From 26bfd339e8e4e720c1f152ae064014583f27db00 Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 9 Aug 2026 16:48:35 +0200 Subject: [PATCH 001/290] fix(visuals): stop the glow eyes from occasionally landing behind the skull AswidVisuals/DvergarVisuals measure which way the head bone faces exactly once, the first time BuildEyes runs for a given character, by reading the bone's live pose at that instant and snapping it to the nearest axis - then cache the result for as long as the eyes exist. Taken while sitting, attached, mid-attack or asleep, the head can be turned away from the body's own forward, and the snap picks whichever axis is closest to that pose - landing the eyes behind the skull instead of on the face, and staying wrong for the rest of the session. ApplyEyes now defers the first build while the player is attached, attached to a ship, mid-attack or asleep, since it runs again on every subsequent UpdateColors anyway. Reduces the obvious bad-timing cases; does not by itself rule out a mistimed read during ordinary idle animation, which would need the measurement moved to the model's bind pose (animation-independent) to close out completely. Also shrinks the Aswid's eyes by 10% (EyeSize 0.062 -> 0.0558), per request. Confirmed improved by playtest. --- JotunnModStub/Aswid/AswidVisuals.cs | 19 +++++++++++++++++-- JotunnModStub/Dvergar/DvergarVisuals.cs | 14 +++++++++++++- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/Aswid/AswidVisuals.cs b/JotunnModStub/Aswid/AswidVisuals.cs index a6a86dc..1afbe7c 100644 --- a/JotunnModStub/Aswid/AswidVisuals.cs +++ b/JotunnModStub/Aswid/AswidVisuals.cs @@ -68,7 +68,7 @@ namespace RacesOfValheim public static readonly float EyeSeparation = 0.032f; // half the distance between them public static readonly float EyeForward = 0.081f; // centre out from the head bone public static readonly float EyeHeight = 0.181f; // up from the head bone - public static readonly float EyeSize = 0.062f; // across, so a 24mm radius at 0.78 + public static readonly float EyeSize = 0.0558f; // 0.062 x 0.9 - across, so a 24mm radius at 0.78 // Carried over from the Dvergar's own tuning on this same rig: the face is not flat, so // two eyes placed symmetrically do not come out looking symmetrical. May need a pass in @@ -147,7 +147,22 @@ namespace RacesOfValheim return; } - if (eyes == null) eyes = BuildEyes(headBone); + if (eyes == null) + { + // BuildEyes measures which way the skull faces from the head bone's pose at this + // exact instant (see the frame comment above it) - a one-time reading, cached for + // as long as the eyes exist. Taken while sitting, attached to something, mid-attack + // or asleep, the head can be tilted or turned away from the body's own forward, and + // the snap-to-axis picks whichever axis is closest to THAT pose - which is how eyes + // ended up behind the skull instead of on the face. Waiting for a plain standing + // pose costs nothing (ApplyEyes runs again on the next UpdateColors either way) and + // this is the only place in the whole flow where the timing actually matters. + if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping()) + { + return; + } + eyes = BuildEyes(headBone); + } if (eyes == null) return; // already logged once by the resolver PlaceEyes(player, headBone, eyes); diff --git a/JotunnModStub/Dvergar/DvergarVisuals.cs b/JotunnModStub/Dvergar/DvergarVisuals.cs index 6d71ec8..51e00a5 100644 --- a/JotunnModStub/Dvergar/DvergarVisuals.cs +++ b/JotunnModStub/Dvergar/DvergarVisuals.cs @@ -159,7 +159,19 @@ namespace RacesOfValheim return; } - if (eyes == null) eyes = BuildEyes(player, headBone); + if (eyes == null) + { + // See AswidVisuals.ApplyEyes for the full reasoning - BuildEyes takes a one-time + // reading of the head bone's pose to work out which way the skull faces, and + // caches it for as long as the eyes exist. Sitting, attached, mid-attack or asleep, + // the head can be turned away from the body's own forward at that instant, which is + // how the snap-to-axis picked the wrong side and left the eyes behind the skull. + if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping()) + { + return; + } + eyes = BuildEyes(player, headBone); + } if (eyes == null) return; // already logged once by the resolver PlaceEyes(player, headBone, eyes); From 9e4778def78ba9408238f0b88b6cd3b893a646cf Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 9 Aug 2026 17:11:25 +0200 Subject: [PATCH 002/290] feat(aswid): let players toggle the Vampiric Aura, move Devour off I The Vampiric Aura had no on/off switch - it always drains/executes nearby targets in every form. I now toggles it (AswidRace.AuraEnabled, on by default), matching the existing toggle pattern already used for Devour. Devour's own toggle moves off I to make room and stays on by default; its keybind is unbound (KeyCode.None) rather than removed outright, so it remains a real Configuration Manager entry for anyone who wants to bind their own key to it. --- JotunnModStub/Aswid/AswidConfig.cs | 10 ++++++++-- JotunnModStub/Aswid/AswidPatches.cs | 7 +++++++ JotunnModStub/Aswid/AswidRace.cs | 8 +++++++- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/Aswid/AswidConfig.cs b/JotunnModStub/Aswid/AswidConfig.cs index a50f8c8..0bdf141 100644 --- a/JotunnModStub/Aswid/AswidConfig.cs +++ b/JotunnModStub/Aswid/AswidConfig.cs @@ -23,6 +23,7 @@ namespace RacesOfValheim public static ConfigEntry MistFormKey; public static ConfigEntry EclipseKey; public static ConfigEntry TameKey; + public static ConfigEntry ToggleAuraKey; public static ConfigEntry ToggleDevourKey; // ─── Passive combat (scales with progression state, doubles at night) ──── @@ -70,8 +71,13 @@ namespace RacesOfValheim new ConfigDescription("Casts Eclipse, tier 6+. Fails silently at night.")); TameKey = config.Bind(keybinds, "Tame", new KeyboardShortcut(KeyCode.U), new ConfigDescription("Tames the creature under your cursor, if your tier allows it.")); - ToggleDevourKey = config.Bind(keybinds, "Toggle Devour Ability", new KeyboardShortcut(KeyCode.I), - new ConfigDescription("Turns the automatic Devour-on-kill behavior on or off.")); + ToggleAuraKey = config.Bind(keybinds, "Toggle Vampiric Aura", new KeyboardShortcut(KeyCode.I), + new ConfigDescription("Turns the passive Vampiric Aura's damage/lifesteal on or off.")); + // Unbound by default: Devour always stays on now that I is the Aura's toggle. Left as + // a real keybind, not removed, so anyone who still wants a switch for it can bind one + // themselves in Configuration Manager. + ToggleDevourKey = config.Bind(keybinds, "Toggle Devour Ability", new KeyboardShortcut(KeyCode.None), + new ConfigDescription("Turns the automatic Devour-on-kill behavior on or off. Unbound by default - Devour stays on unless you assign a key here.")); const string combat = "Aswid - Passive Combat"; DamageBonusPerState = config.Bind(combat, "Damage Bonus Per State", 2f, diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index c3d0dff..ac5c76f 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -529,6 +529,13 @@ namespace RacesOfValheim ZNetView nview = __instance.GetComponent(); if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid") { + if (__instance == Player.m_localPlayer && RaceInput.Allowed && AswidConfig.ToggleAuraKey.Value.IsDownIgnoringHeldKeys()) + { + AswidRace.AuraEnabled = !AswidRace.AuraEnabled; + string msg = AswidRace.AuraEnabled ? "Vampiric Aura: ENABLED" : "Vampiric Aura: DISABLED"; + __instance.Message(MessageHud.MessageType.Center, msg); + } + if (__instance == Player.m_localPlayer && RaceInput.Allowed && AswidConfig.ToggleDevourKey.Value.IsDownIgnoringHeldKeys()) { AswidRace.DevourEnabled = !AswidRace.DevourEnabled; diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index 9293dd4..363fead 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -824,12 +824,18 @@ namespace RacesOfValheim private float damageTickTimer = 0f; + /// Toggled by AswidConfig.ToggleAuraKey (Aswid_PlayerUpdate_Patch); on by default. + public static bool AuraEnabled = true; + /// /// The Vampiric Aura is passive: it drains on its own, in every form, with no key to hold and - /// no icon or message of its own. The form only decides how hard it bites. + /// no icon or message of its own beyond the on/off toggle. The form only decides how hard it + /// bites. /// private void HandleVampiricAura() { + if (!AuraEnabled) return; + damageTickTimer += Time.deltaTime; if (damageTickTimer < AswidConfig.AuraTickInterval.Value) return; From 10e55aff3e0ec33871ab464a03356579a865700a Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 9 Aug 2026 18:31:33 +0200 Subject: [PATCH 003/290] fix(fenrir): source the taunt howl from the real creature's alert bark sfx_wolf_howl/sfx_wolf_alert/sfx_fenring_idle never resolved to anything playable - wolves carry no standalone howl prefab. Reads BaseAI.m_alertedEffects off the live Fenring/Fenring_Cultist prefabs instead, the same effect the creature itself plays going on alert. Still reported silent in testing; leaving it in as a step in the right direction rather than reverting. --- JotunnModStub/Fenrir/FenrirBehaviors.cs | 34 +++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 86045ff..58549a7 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -9,6 +9,36 @@ using UnityEngine.UI; // Added for UI namespace RacesOfValheim { + /// + /// Howl vocalisation, borrowed from the real creature instead of guessed at. Wolves and their + /// kin do not carry a standalone "sfx_wolf_howl"-style prefab that PlaySFX's + /// PrefabManager.Cache lookup could ever find - dumpdverger's own hierarchy dump for + /// Fenring_Cultist shows no ZSFX anywhere on it. + /// + /// BaseAI.m_idleSound was the first guess and was wrong in a quieter way: it is real, but it + /// is the creature's passive ambient noise (DoIdleSound, on a timer while it is doing nothing + /// in particular) - a small grunt, not a howl, and it played back sounding like whatever + /// generic "the form did something" cue the transformation itself already uses. What a + /// creature actually vocalises WHEN IT SPOTS SOMETHING is BaseAI.m_alertedEffects, fired from + /// SetAlerted(true) - reading that off the real "Fenring"/"Fenring_Cultist" prefab and calling + /// Create() plays the same aggressive bark the creature itself makes going on alert. + /// + internal static class FenrirCreatureSound + { + public static void PlayHowl(string sourcePrefabName, Vector3 position) + { + GameObject source = PrefabManager.Cache.GetPrefab(sourcePrefabName); + BaseAI ai = source != null ? source.GetComponent() : null; + if (ai == null || ai.m_alertedEffects == null) + { + Jotunn.Logger.LogWarning($"[FenrirForm] No BaseAI.m_alertedEffects found on '{sourcePrefabName}'."); + return; + } + + ai.m_alertedEffects.Create(position, Quaternion.identity); + } + } + public class FenrirFormBehavior : MonoBehaviour { private Animator playerAnim; @@ -101,7 +131,7 @@ namespace RacesOfValheim fenrirAnim.SetTrigger("attack_taunt"); - PlaySFX("sfx_wolf_howl", "sfx_wolf_alert", "sfx_fenring_idle"); + FenrirCreatureSound.PlayHowl("Fenring", Player.m_localPlayer.transform.position); yield return new WaitForSeconds(2.0f); @@ -386,7 +416,7 @@ namespace RacesOfValheim // Cultist ha una vera e propria animazione di "taunt" cultistAnim.SetTrigger("attack_taunt"); - PlaySFX("sfx_wolf_howl", "sfx_wolf_alert", "sfx_fenring_idle"); + FenrirCreatureSound.PlayHowl("Fenring_Cultist", Player.m_localPlayer.transform.position); // Durata approssimativa dell'animazione di taunt yield return new WaitForSeconds(2.0f); From 66cea69d332f464328883eea82d2403f46b2ca7b Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 9 Aug 2026 18:31:53 +0200 Subject: [PATCH 004/290] fix(compendium): rewrite every race entry against live game code Most GenerateXText methods described mechanics that didn't match what the code actually does, some invented stats that never existed. Went race by race and rewrote each one off the real ConfigEntry/Progression values, verifying tier gates, keybinds and numbers against the actual patches rather than restating old prose. - Aswid: rewritten from scratch. Invented Damage/Armor/Jump-per-state multipliers that don't exist in AswidConfig; Bat Form, Eclipse and Tame were missing entirely; the Vampiric Aura was described as a shield-block channel in bat/mist form when it's actually passive and always-on (toggled with 'I'). - Furling: was a placeholder ("will be revealed soon...") with only tiers 5-8 written and a mojibake dash in the base passive. Filled in Master of Shadows (tier 2), The Wickerman (tier 3) and Dance of the Dead (tier 4), all missing. - Trenta: had no compendium entry at all - no title, no branch, no method. Written from scratch off TrentaConfig/TrentaConfigManagement. Also fixed a real gameplay bug found while cross-checking: Thorns had no tier gate and was live from tier 1 instead of Moder (tier 5), the way its own doc comment and config grouping said it should be. - Skadi/Skeleton: audited line by line, already accurate, untouched. - Dvergar: one stale line (claimed 33% height reduction; the live VisualScale is 22%). - Draugh: substantial rewrite. Removed a "permanent Corpse Run" buff that doesn't exist anywhere in the codebase, corrected base-tier Poison (ordinary until Bonemass, not resistant from tier 1), fixed the Human Meat trigger (any nearby player death, not humanoid kills), fixed a false "no stamina to spend" claim, and added the missing skeleton/draugr/ghost/wraith hostility exemption, Frost immunity and stagger-crit unlocks. --- JotunnModStub/RaceCompendium.cs | 332 ++++++++++++++++++++++---- JotunnModStub/Trenta/TrentaPatches.cs | 1 + 2 files changed, 285 insertions(+), 48 deletions(-) diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs index 0ddbc5f..af5d979 100644 --- a/JotunnModStub/RaceCompendium.cs +++ b/JotunnModStub/RaceCompendium.cs @@ -16,7 +16,8 @@ namespace RacesOfValheim "Furling Secrets", "Trol Secrets", "Draugh Secrets", - "Dvergar Secrets" + "Dvergar Secrets", + "Trenta Secrets" }; public static void UpdateCompendiumText(Player player) @@ -72,20 +73,29 @@ namespace RacesOfValheim { GenerateDvergarText(knownTexts, state); } + else if (currentRace == TrentaConfig.RaceId) + { + GenerateTrentaText(knownTexts, state); + } } /// /// Reads its figures straight out of the live rules rather than restating them, so the - /// entry cannot drift from the code the way a hand-written percentage would. + /// entry cannot drift from the code the way a hand-written percentage would. One prose + /// figure had already drifted before this pass: the height reduction was hand-written as + /// "a third shorter", left over from when DvergarConfig.VisualScale was 0.70 (-30%) - the + /// comment on that field says it was "nudged up" to 0.78 (-22%) once it read too small on + /// screen, and the compendium line was never updated to follow. Reads the live scale now. /// private static void GenerateDvergarText(Dictionary knownTexts, int state) { DvergarProgression.DvergarRules rules = DvergarProgression.GetRules(state); + int heightReductionPercent = Mathf.RoundToInt((1f - DvergarConfig.VisualScale) * 100f); StringBuilder sb = new StringBuilder(); sb.AppendLine("The Dvergar's Craft\n"); - sb.AppendLine($"[Base Passive] Small and Stubborn: You stand a third shorter than a human and carry {rules.HealthMalus:0.#} less health for it. The dvergr hood never leaves your head - wear whatever helm you please and keep every point of its protection, but the runes will always show you as one of the deep folk.\n"); + sb.AppendLine($"[Base Passive] Small and Stubborn: You stand {heightReductionPercent}% shorter than a human and carry {rules.HealthMalus:0.#} less health for it. The dvergr hood never leaves your head - wear whatever helm you please and keep every point of its protection, but the runes will always show you as one of the deep folk.\n"); sb.AppendLine($"[Base Passive] Runic Spark: The runes in your blood earth themselves through whatever you strike. Every blow you land carries +{rules.ElementalDamage:0.#} Lightning damage - a bonus that grows as each boss falls.\n"); @@ -117,33 +127,65 @@ namespace RacesOfValheim knownTexts["Dvergar Secrets"] = sb.ToString(); } + /// + /// Rewritten off the live DraughConfig values, the way Fenrir's and Aswid's entries are. + /// The base passive claimed innate Poison resistance that Draugh_Damage_Patch never + /// grants at tier 1 - the real always-on modifiers are 20% Physical resistance and 50% + /// extra Fire/Spirit damage taken, plus the infinite stamina Draugh shares with Skeleton + /// and Aswid (Player_UseStamina_Patch) - none of which appeared here. "Slowly We Rot" + /// claimed Wet immunity and faster swimming that SE_Wet_Setup_Patch does not grant; it + /// only flips Wet's health regen positive and drops its stamina penalty. "Flesh and the + /// Power It Holds" invented a "Corpse Run buff" that appears nowhere in the codebase and + /// described Human Meat as a kill drop from humanoid enemies, when Draugh_DeathAura_Patch + /// actually drops it from any player dying near a Draugh - and the real tier 4 unlock + /// (Poison Immunity, a stagger crit bonus, no skill drain on death) was missing entirely. + /// Tier 5 never mentioned Frost Immunity, which Draugh_Damage_Patch also grants at that + /// tier alongside the frost nova on parry. Also given the "[Boss Unlock]" tier headers + /// every other race's entry uses, which this one never had. + /// private static void GenerateDraughText(Dictionary knownTexts, int state, Player player) { + int physResistPercent = Mathf.RoundToInt((1f - DraughConfig.PhysicalResistMultiplier.Value) * 100f); + int fireSpiritWeakPercent = Mathf.RoundToInt((DraughConfig.FireSpiritWeaknessMultiplier.Value - 1f) * 100f); + int wetRegenPercent = Mathf.RoundToInt((DraughConfig.WetHealthRegenMultiplier.Value - 1f) * 100f); + int poisonOnHitPercent = Mathf.RoundToInt(DraughConfig.PoisonOnHitPercent.Value * 100f); + int poisonSplashDamage = Mathf.RoundToInt(DraughConfig.PoisonSplashDamage.Value); + int staggerCritPercent = Mathf.RoundToInt((DraughConfig.StaggerCritMultiplier.Value - 1f) * 100f); + int deathAuraRadius = Mathf.RoundToInt(DraughConfig.DeathAuraRadius.Value); + int northWindCooldown = Mathf.RoundToInt(DraughConfig.NorthWindCooldown.Value); + int northWindRadius = Mathf.RoundToInt(DraughConfig.NorthWindRadius.Value); + int northWindDamage = Mathf.RoundToInt(DraughConfig.NorthWindFrostDamage.Value); + int undyingCooldownMinutes = Mathf.RoundToInt(DraughConfig.UndyingWillCooldown.Value / 60f); + int eitrDrainPerSecond = Mathf.RoundToInt(DraughConfig.UndyingWillEitrDrainPerTick.Value / DraughConfig.UndyingWillTickInterval.Value); + int swarmCount = DraughConfig.SwarmSpawnCount.Value; + int swarmCooldown = Mathf.RoundToInt(DraughConfig.SwarmSpawnCooldown.Value); + int stealBreathHealPercent = Mathf.RoundToInt(DraughConfig.StealBreathHealPercent.Value * 100f); + StringBuilder sb = new StringBuilder(); sb.AppendLine("The Draugh's Awakening\n"); - sb.AppendLine("[Base Passive] Born Dead, Buried Alive: You are a decaying undead warrior. You have innate resistance to Poison, but are weak to Fire and Spirit damage. Your digestive system adapts to death, allowing you to consume raw and rotten meat (Neck tail, raw meat, entrails, ooze, etc.).\n"); + sb.AppendLine($"[Base Passive] Born Dead, Buried Alive: You take {physResistPercent}% less Physical (blunt/slash/pierce) damage, but Fire and Spirit strike you {fireSpiritWeakPercent}% harder. Skeletons, draugr, ghosts and wraiths no longer see you as prey. Your digestive system adapts to death, allowing you to consume raw and rotten meat (neck tail, raw meat, entrails, blood, etc.) - proper cooked food and berries disgust you and cannot be eaten.\n"); if (state >= 2) - sb.AppendLine("Slowly We Rot (Passive): You are no longer hindered by water. You gain immunity to the Wet effect, your movement speed in water is greatly increased, and you passively regenerate health while wet or swimming.\n"); - + sb.AppendLine($"[Eikthyr Unlock] Slowly We Rot (Passive): Being Wet no longer saps your stamina regeneration, and it heals rather than does nothing for you - your health regenerates {wetRegenPercent}% faster while wet or swimming.\n"); + if (state >= 3) - sb.AppendLine("Toxic Trace (Passive): Your physical attacks are laced with the swamp's decay. Enemies struck by your physical weapons suffer additional poison damage over time.\n"); - + sb.AppendLine($"[The Elder Unlock] Rotting Edge (Passive/Parry): Your physical attacks are laced with the swamp's decay, adding poison damage worth {poisonOnHitPercent}% of the physical harm you deal. A successful parry also splashes {poisonSplashDamage} poison damage onto whoever you parried.\n"); + if (state >= 4) - sb.AppendLine("Flesh and the Power It Holds (Passive): Slaying humanoid enemies drops Human Meat. Consuming it grants incredible buffs. You also gain the Corpse Run buff permanently.\n"); - + sb.AppendLine($"[Bonemass Unlock] Undead Fortitude (Passive): Poison can no longer touch you at all. Striking a staggered enemy deals {staggerCritPercent}% more physical damage, and death no longer costs you skill experience. Should any player die within {deathAuraRadius}m of you, their fall leaves Human Meat behind - flesh only a Draugh can stomach.\n"); + if (state >= 5) - sb.AppendLine("At the Heart of Winter (Parry Effect): When you successfully parry an attack, you unleash a freezing nova of frost magic around you, pushing back and damaging enemies (20 second cooldown).\n"); - + sb.AppendLine($"[Moder Unlock] Grave Chill (Passive/Parry): Frost can no longer touch you at all. A successful parry now also unleashes a freezing nova, dealing {northWindDamage} Frost damage and pushing back everything within {northWindRadius}m of you - the nova has its own {northWindCooldown} second cooldown, separate from Rotting Edge's poison splash, which still fires on every parry.\n"); + if (state >= 6) - sb.AppendLine("Zombie Ritual (Passive Survival): When you take fatal damage, you do not die. Instead, you enter a ghostly state, becoming immune to all damage. While in this state, your Eitr drains rapidly. If your Eitr hits zero, you truly die.\n"); - + sb.AppendLine($"[Yagluth Unlock] Zombie Ritual (Passive Survival): When you take fatal damage, you do not die. Instead, you enter a ghostly state, immune to all damage, while your Eitr drains at {eitrDrainPerSecond} per second. If your Eitr hits zero before you are saved, you truly die. Once triggered, the ritual cannot save you again for {undyingCooldownMinutes} minutes.\n"); + if (state >= 7) - sb.AppendLine("Swarm of Terror (Retaliation): Whenever you are struck in melee combat, you automatically spawn 2 Seeker Broods to fight for you. They live for 9.5 seconds and have a 10 second cooldown.\n"); - + sb.AppendLine($"[The Queen Unlock] Swarm of Terror (Retaliation): Whenever you are struck in melee combat, you automatically spawn {swarmCount} Seeker Broods to fight for you. They live for {DraughConfig.SwarmBroodLifetime.Value:0.#} seconds, with a {swarmCooldown} second cooldown between spawns.\n"); + if (state >= 8) - sb.AppendLine("Steal Their Breath (Execution): While surviving in the 'Zombie Ritual' ghost state, scoring a killing blow on any enemy will instantly restore 25% of your maximum health, stop the Eitr drain, and save your life, bringing you fully back to the world of the living.\n"); + sb.AppendLine($"[Fader Unlock] Steal Their Breath (Execution): While surviving in the Zombie Ritual's ghost state, scoring a killing blow on any enemy will instantly restore {stealBreathHealPercent}% of your maximum health, stop the Eitr drain, and save your life, bringing you fully back to the world of the living.\n"); knownTexts["Draugh Secrets"] = sb.ToString(); } @@ -153,16 +195,16 @@ namespace RacesOfValheim StringBuilder sb = new StringBuilder(); sb.AppendLine("The Trol's Heritage\n"); - sb.AppendLine($"Base Passive: Physical kills automatically consume enemies (if edible). You are natively 20% larger than a human with immense strength. You have +200 Max Carry Weight and gain +3 Armor per boss defeated.\n"); + sb.AppendLine($"Base Passive: Physical kills automatically consume enemies (if edible). You are natively 20% larger than a human with immense strength. You have +200 Max Carry Weight, gain +3 Armor per boss defeated, and carry a 4th food slot from your very first meal - no boss required.\n"); if (state >= 1) sb.AppendLine("Eikthyr Defeated: Increased XP gain for physical labor and blunt combat (Clubs, Unarmed, Axes, Pickaxes, WoodCutting).\n"); - + if (state >= 2) sb.AppendLine("The Elder Defeated: Unlocked Rock Throwing ability. +10% passive health regeneration.\n"); - + if (state >= 3) - sb.AppendLine("Bonemass Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed, +10 Rock Throwing Damage. Unlocked 4th Food Slot.\n"); + sb.AppendLine("Bonemass Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed, +10 Rock Throwing Damage.\n"); if (state >= 4) sb.AppendLine("Moder Defeated: Unlocked True Form (Transformation ability).\n"); @@ -179,60 +221,133 @@ namespace RacesOfValheim knownTexts["Trol Secrets"] = sb.ToString(); } + /// + /// Rewritten off the live AswidConfig/AswidProgression values, the way Fenrir's and Skadi's + /// entries are. The old text invented a Jump Bonus Per State that doesn't exist (jump actually + /// rides the same SpeedBonusPerState as move speed, in AswidStatusEffects.UpdateStats), used + /// state*3/state*5 multipliers that don't match ArmorBonusPerState=1/DamageBonusPerState=2, and + /// described the Vampiric Aura as a shield-block channel in bat/mist form only - it is actually + /// passive and always-on in every form (AswidRace.HandleVampiricAura), toggled with 'I'. Bat + /// Form, Eclipse, and Tame were missing entirely. + /// private static void GenerateAswidText(Dictionary knownTexts, int state) { - int spd = state * 3; - int jmp = state * 3; - int arm = state * 3; - int dmg = state * 5; + int arm = Mathf.RoundToInt(AswidConfig.ArmorBonusPerState.Value * state); + int dmg = Mathf.RoundToInt(AswidConfig.DamageBonusPerState.Value * state); + int spd = Mathf.RoundToInt(AswidConfig.SpeedBonusPerState.Value * state * 100f); + int lifesteal = state * 2; + int auraRadiusDay = Mathf.RoundToInt(AswidConfig.AuraRadiusDay.Value); + int auraRadiusNight = Mathf.RoundToInt(AswidConfig.AuraRadiusNight.Value); + int auraExecute = Mathf.RoundToInt(AswidConfig.AuraExecuteThreshold.Value * 100f); + int sensesRadius = Mathf.RoundToInt(AswidConfig.SensesRadius.Value); + int eclipseCooldownMin = Mathf.RoundToInt(AswidConfig.EclipseCooldown.Value / 60f); + int eclipseDuration = Mathf.RoundToInt(AswidConfig.EclipseDuration.Value); + int enslaveCooldownMin = Mathf.RoundToInt(AswidConfig.EnslaveCooldown.Value / 60f); + int thrallLifetime = Mathf.RoundToInt(AswidConfig.ThrallLifetime.Value); + int surtlingDmg = Mathf.RoundToInt(AswidConfig.SurtlingFormDamageBonus.Value); StringBuilder sb = new StringBuilder(); sb.AppendLine("The Aswid's Curse\n"); - - sb.AppendLine($"[Base Passive] Benedictus et Afflictus:"); - sb.AppendLine($"Physical kills automatically consume enemies (Vae Victis) granting Blood Magic XP. Your physical stats scale progressively as you defeat Valheim's Bosses: +{arm} Armor, +{dmg} Damage, +{spd}% Speed, and +{jmp}% Jump. All your passive bonuses are doubled during the night. You can cast Blood Magic items with infinite Eitr, and your Blood Magic skill increases twice as fast.\n"); - sb.AppendLine("Vampiric Aura (Like a Bat out of Hell/Weight of Shadows Only): Block with your shield (Mouse 2) while in bat or mist form to channel an AoE magic damage aura against nearby enemies, healing for 20% of the damage dealt and converting them into food when they die.\n"); - if (state >= 1) - { - // Eikthyr - Base passives already covered - } + + sb.AppendLine("[Base Passive] Benedictus et Afflictus:"); + sb.AppendLine($"You take no fall damage, and physical kills automatically devour edible enemies (Vae Victis) for Blood Magic XP. Your physical stats scale with every boss you defeat: +{arm} Armor, +{dmg} Damage, +{spd}% Speed and Jump, and +{lifesteal}% Lifesteal on physical hits. All of these bonuses double during the night. You can cast Blood Magic items with infinite Eitr, and your Blood Magic skill rises {AswidConfig.BloodMagicSkillGainMultiplier.Value:0.#}x as fast.\n"); + + sb.AppendLine("Vampiric Aura (Passive, toggle with 'I'):"); + sb.AppendLine($"Always active, in every form, with no key to hold - only the on/off toggle. Drains a {auraRadiusDay}m radius by day, {auraRadiusNight}m by night, for magic damage that scales with your Blood Magic skill, healing you for the damage dealt. Enemies at or below {auraExecute}% health are executed outright. The aura hits for half in human form, full as a Bat, and double as Mist.\n"); + + if (state >= 2) + sb.AppendLine("[Eikthyr Unlock] Bat Form ('G' Key, night only): Take the shape of a bat.\n"); + + if (state >= 2) + sb.AppendLine("[Eikthyr Unlock] Tame ('U' Key): Tame a boar under your cursor.\n"); + + if (state >= 3) + sb.AppendLine("[The Elder Unlock] Bat Form now answers by day as well as night.\n"); if (state >= 5) { sb.AppendLine("[Moder Unlock] Freezing Blood (Passive):"); - sb.AppendLine("You gain permanent immunity to the Freezing status (mountains/snowstorms) and Poison damage.\n"); - sb.AppendLine("[Moder Unlock] Auspex (Passive):"); - sb.AppendLine("You emit a 10-meter aura that reveals the presence of untamed creatures by wreathing them in ethereal flames.\n"); + sb.AppendLine("You gain permanent immunity to the Freezing status (mountains/snowstorms) and to Poison damage.\n"); + sb.AppendLine("[Moder Unlock] Superhuman Senses (Passive):"); + sb.AppendLine($"You sense every untamed creature within {sensesRadius}m, marking it with a telltale glow.\n"); + sb.AppendLine("[Moder Unlock] Tame ('U' Key): Wolves join the huntable list.\n"); } if (state >= 6) { - sb.AppendLine("[Yagluth Unlock] Dominate (E Key):"); - sb.AppendLine("Press E on non-tameable, non-boss enemies to dominate them for 60 seconds (15-min cooldown). Dominated thralls fight alongside you and drop standard loot.\n"); + sb.AppendLine("[Yagluth Unlock] Eclipse ('J' Key, day only):"); + sb.AppendLine($"A {AswidConfig.EclipseCastTime.Value:0.#}-second cast that forces the night to fall around you for {eclipseDuration} seconds, letting you claim your night-doubled bonuses under the sun. Fails silently if it is already night. {eclipseCooldownMin}-minute cooldown.\n"); + sb.AppendLine("[Yagluth Unlock] Dominate (native Interact key):"); + sb.AppendLine($"Target a non-tameable, non-boss enemy to dominate it for {thrallLifetime} seconds ({enslaveCooldownMin}-min cooldown). Dominated thralls fight alongside you and drop standard loot.\n"); + sb.AppendLine("[Yagluth Unlock] Tame ('U' Key): Lox join the huntable list.\n"); } if (state >= 7) { - sb.AppendLine("[The Queen Unlock] Weight of Shadows (H Key):"); - sb.AppendLine("You transform into an elusive mist. You become immune to physical and poison damage, but weak to fire, frost, and spirit. Your Vampiric Aura deals double damage, but you cannot attack or run. Sunrise breaks the transformation.\n"); + sb.AppendLine("[The Queen Unlock] Weight of Shadows ('H' Key, toggle):"); + sb.AppendLine("You transform into an elusive mist. You become immune to physical (blunt/slash/pierce) and poison damage, and take no fall damage, but you cannot attack, run, or jump. Your Vampiric Aura deals double damage while mist. Sunrise breaks the transformation.\n"); } if (state >= 8) { sb.AppendLine("[Fader Unlock] Asmund (Passive):"); - sb.AppendLine("Your hair and beard turn as dark as the abyss. You become 10% taller and gain a flat +30 to Physical Damage.\n"); + sb.AppendLine($"Your hair and beard turn as dark as the abyss. You become 10% taller and gain a flat +{surtlingDmg} Physical Damage.\n"); + sb.AppendLine("[Fader Unlock] Tame ('U' Key): Asksvin join the huntable list.\n"); } knownTexts["Aswid Secrets"] = sb.ToString(); } + /// + /// This used to be a single hardcoded sentence, the same at every tier - the forms + /// themselves (Wolf/Ulv/Fenring/Cultist, each gated by its own day/night and tier rules in + /// FenrirProgression) never appeared here at all. Rewritten the way Skadi's entry is, off + /// the live FenrirConfig values so it cannot drift from what TryTransformWithRules actually + /// grants at each state. + /// private static void GenerateFenrirText(Dictionary knownTexts, int state) { - int spd = state * 3; - int jmp = state * 3; - int arm = state * 3; - int dmg = state * 5; - knownTexts["Fenrir Secrets"] = $"The secrets of the pack will be revealed soon...\n\nBase Passive: Physical kills automatically consume enemies (if edible). Your physical stats scale progressively as you defeat Valheim's Bosses: +{arm} Armor, +{dmg} Damage, +{spd}% Speed, and +{jmp}% Jump."; + int spd = Mathf.RoundToInt(FenrirConfig.SpeedBonusPerState.Value * state * 100f); + int jmp = Mathf.RoundToInt(FenrirConfig.JumpBonusPerState.Value * state * 100f); + int arm = Mathf.RoundToInt(FenrirConfig.ArmorBonusPerState.Value * state); + int dmg = Mathf.RoundToInt(FenrirConfig.DamageBonusPerState.Value * state); + int fall = Mathf.RoundToInt(-FenrirProgression.GetFallDamageModifier(state) * 100f); + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("The Curse of the Pack\n"); + + sb.AppendLine($"[Base Passive] The Beast Within: Physical kills automatically consume edible enemies. Your physical stats scale with every boss you defeat: +{arm} Armor, +{dmg} Damage, +{spd}% Speed, +{jmp}% Jump, and -{fall}% Fall Damage.\n"); + + if (state >= 3) + sb.AppendLine("[The Elder Unlock] Wolf Form ('G' Key, night only): Take the shape of a wolf. Faster and lighter on your feet, with three claw attacks of growing weight on Left, Right, and Middle Mouse.\n"); + + if (state >= 4) + { + sb.AppendLine("[Bonemass Unlock] Wolf Form now answers by day as well as night.\n"); + sb.AppendLine("[Bonemass Unlock] Ulv Form ('H' Key, night only): A heavier wolf shape - stronger bite attacks, still bound to the dark.\n"); + } + + if (state >= 5) + { + sb.AppendLine("[Moder Unlock] 'G' now calls Ulv Form instead of Wolf, and answers by day as well as night.\n"); + sb.AppendLine("[Moder Unlock] Fenring Form ('H' Key, night only): Stand as a true Fenring - heavy claws and a leaping strike, and the strongest of the four shapes so far.\n"); + } + + if (state >= 6) + sb.AppendLine("[Yagluth Unlock] Cultist Form ('J' Key, night only): A robed shape that claws and channels fire. Lasts 1 minute, 10-minute cooldown.\n"); + + if (state >= 7) + { + sb.AppendLine("[The Queen Unlock] Fenring Form now answers by day as well as night.\n"); + sb.AppendLine("[The Queen Unlock] Cultist Form's cooldown falls to 5 minutes (still night only, still 1 minute).\n"); + } + + if (state >= 8) + sb.AppendLine("[Fader Unlock] Cultist Form now answers by day as well as night, and may be held as long as you wish.\n"); + + sb.AppendLine("Sunrise breaks any night-bound form early and leaves the beast too tired to change shape again for a short while after.\n"); + + knownTexts["Fenrir Secrets"] = sb.ToString(); } private static void GenerateSkadiText(Dictionary knownTexts, int state) @@ -372,13 +487,44 @@ namespace RacesOfValheim knownTexts["Skeleton Secrets"] = sb.ToString(); } + /// + /// Was a placeholder ("will be revealed soon") with a mojibake dash baked into the base + /// passive text and only the tier 5-8 entries actually written - Master of Shadows (tier 2, + /// Eikthyr) and The Wickerman (tier 3, The Elder) were entirely missing, and Dance of the Dead + /// (tier 4, Bonemass) wasn't mentioned at all. Filled in from FurlingPatches.cs/FurlingConfig.cs. + /// private static void GenerateFurlingText(Dictionary knownTexts, int state, Player player) { + int runSpeed = Mathf.RoundToInt(FurlingConfig.RunSpeedBonus.Value * 100f); + int weaponXp = Mathf.RoundToInt(FurlingConfig.WeaponSkillXPMultiplier.Value); + int noiseRange = Mathf.RoundToInt(FurlingConfig.StealthNoiseRangeThreshold.Value); + int fireResist = Mathf.RoundToInt((1f - FurlingConfig.WickermanFireResistMultiplier.Value) * 100f); + int poisonResist = Mathf.RoundToInt((1f - FurlingConfig.PoisonResistMultiplier.Value) * 100f); + int fireArrowDmg = Mathf.RoundToInt(FurlingConfig.FireArrowMinDamage.Value); + StringBuilder sb = new StringBuilder(); - sb.AppendLine("The secrets of the hoard will be revealed soon...\n"); + sb.AppendLine("The Secrets of the Hoard\n"); sb.AppendLine("[Base Passive] Combat Mastery:"); - sb.AppendLine("All weapon and combat skills gain 2x XP permanently. You're short, but very fast — your movement speed is permanently increased by 10%.\n"); + sb.AppendLine($"All weapon and combat skills gain {weaponXp}x XP permanently. You're short, but very fast - your movement speed is permanently increased by {runSpeed}%.\n"); + + if (state >= 2) + { + sb.AppendLine("[Eikthyr Unlock] Master of Shadows (Passive):"); + sb.AppendLine($"Your footsteps and small movements no longer betray you - any noise you make within {noiseRange} meters goes unheard.\n"); + } + + if (state >= 3) + { + sb.AppendLine("[The Elder Unlock] The Wickerman (Passive):"); + sb.AppendLine($"You take {fireResist}% less Fire damage and {poisonResist}% less Poison damage. Your arrows carry at least {fireArrowDmg} Fire damage of their own.\n"); + } + + if (state >= 4) + { + sb.AppendLine("[Bonemass Unlock] Dance of the Dead (Passive):"); + sb.AppendLine("Every mead, potion, wine, bomb, or batch of ammunition you craft comes out doubled - one copy for the recipe, one for free.\n"); + } if (state >= 5) { @@ -412,6 +558,96 @@ namespace RacesOfValheim knownTexts["Furling Secrets"] = sb.ToString(); } + + /// + /// The Trenta had no compendium entry at all - no title in RaceTitles, no branch in + /// UpdateCompendiumText, no method. Written from scratch off TrentaConfig/ + /// TrentaConfigManagement's live values and the tier gates in TrentaAbilities.cs/ + /// TrentaStatusEffects.cs/TrentaPatches.cs. + /// + private static void GenerateTrentaText(Dictionary knownTexts, int state) + { + int stillness = Mathf.RoundToInt(TrentaConfig.PhotosynthesisStillnessSeconds); + int healTicks = TrentaConfig.PhotosynthesisHealSeconds; + int healPercent = Mathf.RoundToInt(TrentaConfig.PhotosynthesisHealPercentPerSecond * 100f); + int restMinutes = Mathf.RoundToInt(TrentaConfig.PhotosynthesisRestBaseMinutes + + TrentaConfig.PhotosynthesisRestMinutesPerBoss * (state - BossProgressionManager.MinState)); + int foodDuration = Mathf.RoundToInt(TrentaConfig.FoodDurationMultiplier); + + int purpleRainRadius = Mathf.RoundToInt(TrentaConfig.PurpleRainRadius); + int purpleRainHeal = Mathf.RoundToInt(TrentaConfig.PurpleRainHealAmount); + int purpleRainPoison = Mathf.RoundToInt(TrentaConfig.PurpleRainPoisonDamage); + int purpleRainCooldown = Mathf.RoundToInt(TrentaConfigManagement.PurpleRainCooldown.Value); + int purpleRainMuspellCooldown = Mathf.RoundToInt(TrentaConfigManagement.MuspellPurpleRainCooldown.Value); + + int lastStandBonus = Mathf.RoundToInt(TrentaConfig.LastStandMaxArmorBonus * 100f); + int thornsPercent = Mathf.RoundToInt(TrentaConfig.ThornsReflectPercent * 100f); + + int portalCooldownMin = Mathf.RoundToInt(TrentaConfig.PortalCooldown / 60f); + int portalLifetime = Mathf.RoundToInt(TrentaConfig.PortalLifetime); + + int hornetsDamage = Mathf.RoundToInt(TrentaConfig.HornetsNestDamagePerTick); + int hornetsInterval = Mathf.RoundToInt(TrentaConfig.HornetsNestTickInterval); + int hornetsRadius = Mathf.RoundToInt(TrentaConfig.HornetsNestEngageRadius); + + int muspellStompDamage = Mathf.RoundToInt(TrentaConfig.MuspellStompDamage); + int muspellSpikeDamage = Mathf.RoundToInt(TrentaConfig.MuspellSpikeDamage); + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("The Secrets of the Heartwood\n"); + + sb.AppendLine("[Base Passive] Heartwood:"); + sb.AppendLine("Sap and heartwood conduct lightning and turn away the dead: you take half damage from Lightning and Spirit. But kindling burns and the woodsman's axe still bites - you take half again as much from Fire and Slash. Meat, fish, eggs and honey are nothing you can stomach; only what grows from the ground sustains you, and it does so for " + foodDuration + "x as long as it would a normal body.\n"); + + sb.AppendLine("[Base Passive] Photosynthesis:"); + sb.AppendLine($"Stand still in daylight, roof over nothing but sky, for {stillness} unbroken seconds, and roots take hold: {healTicks} ticks of healing follow, {healPercent}% of your maximum health apiece, along with a Rested buff lasting {restMinutes} minutes - longer with every boss you have felled.\n"); + + if (state >= TrentaConfig.EikthyrDefeatedState) + { + sb.AppendLine("[Eikthyr Unlock] Awakened Seeds (Passive):"); + sb.AppendLine("Every seed, cone, acorn and self-seeding mushroom you carry has woken up. Eat one on the spot and it consumes itself for the strongest meal its home biome has to offer, health or eitr as the biome favors, instead of sitting idle as planting stock.\n"); + } + + if (state >= TrentaConfig.PurpleRainUnlockState) + { + sb.AppendLine("[The Elder Unlock] Purple Rain ('G' Key):"); + sb.AppendLine($"A spray of toxic pollen bursts out to {purpleRainRadius} meters: every ally caught in it is healed {purpleRainHeal}, every foe is poisoned for {purpleRainPoison}. {purpleRainCooldown}-second cooldown, shortened to {purpleRainMuspellCooldown} seconds while transformed into Muspell.\n"); + } + + if (state >= TrentaConfig.BonemassDefeatedState) + { + sb.AppendLine("[Bonemass Unlock] Deep Roots (Passive):"); + sb.AppendLine("The swamp has nothing left to spoil in you. Poison cannot touch you, the Wet effect cannot land on you, and swimming costs no stamina at all.\n"); + } + + if (state >= TrentaConfig.ModerDefeatedState) + { + sb.AppendLine("[Moder Unlock] Last Stand (Passive):"); + sb.AppendLine($"The closer you come to falling, the harder your bark grows: your armor rises by up to {lastStandBonus}% as your health drops toward zero.\n"); + sb.AppendLine("[Moder Unlock] Thorns (Passive):"); + sb.AppendLine($"Every hit you take returns {thornsPercent}% of its damage to whoever landed it.\n"); + } + + if (state >= TrentaConfig.PortalUnlockState) + { + sb.AppendLine("[Yagluth Unlock] Homecoming Portal ('H' Key):"); + sb.AppendLine($"Open a linked pair of portals - one where you stand, one at your respawn point - for anyone to walk through, no ore or item carried against them. They fade after {portalLifetime} seconds. {portalCooldownMin}-minute cooldown.\n"); + } + + if (state >= TrentaConfig.HornetsNestUnlockState) + { + sb.AppendLine("[The Queen Unlock] Hornet's Nest (Passive):"); + sb.AppendLine($"A swarm of hornets has made its home in your branches and never leaves. Any foe that comes within {hornetsRadius} meters is stung for {hornetsDamage} poison and pierce damage every {hornetsInterval} seconds until it breaks off or falls.\n"); + } + + if (state >= TrentaConfig.MuspellUnlockState) + { + sb.AppendLine("[Fader Unlock] Muspell ('J' Key, toggle):"); + sb.AppendLine($"Take the shape of a young Elder, root and bramble given fury. Left Mouse stomps the ground for {muspellStompDamage} damage in a ring around you, Right Mouse looses a root-spike that pierces for {muspellSpikeDamage} - both rising with your Unarmed skill. Purple Rain still answers your call while transformed, on its shorter cooldown.\n"); + } + + knownTexts["Trenta Secrets"] = sb.ToString(); + } } [HarmonyPatch(typeof(TextsDialog), "Setup")] diff --git a/JotunnModStub/Trenta/TrentaPatches.cs b/JotunnModStub/Trenta/TrentaPatches.cs index 46df88b..4bf50dd 100644 --- a/JotunnModStub/Trenta/TrentaPatches.cs +++ b/JotunnModStub/Trenta/TrentaPatches.cs @@ -175,6 +175,7 @@ namespace RacesOfValheim { if (__instance != Player.m_localPlayer) return; if (!TrentaRace.IsTrenta()) return; + if (BossProgressionManager.GetCurrentProgressionState() < TrentaConfig.ModerDefeatedState) return; if (hit == null || !hit.HaveAttacker()) return; Character attacker = hit.GetAttacker(); From e9f41a86e34024c9bb22c71e4c9fdef2cf4c3c46 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Sun, 9 Aug 2026 21:54:56 +0200 Subject: [PATCH 005/290] warvulture --- JotunnModStub/PieceDensityLimit.cs | 71 ++- JotunnModStub/RacesOfValheim.cs | 4 + JotunnModStub/Skadi/SkadiGolem.cs | 460 ++++++++++++++++++ JotunnModStub/Skadi/SkadiGolemBehaviour.cs | 302 ++++++++++++ JotunnModStub/Skadi/SkadiRace.cs | 1 + JotunnModStub/WarVulture/WarVultureConfig.cs | 109 +++++ JotunnModStub/WarVulture/WarVultureHud.cs | 116 +++++ JotunnModStub/WarVulture/WarVultureItem.cs | 308 ++++++++++++ JotunnModStub/WarVulture/WarVultureMount.cs | 389 +++++++++++++++ JotunnModStub/WarVulture/WarVulturePatches.cs | 193 ++++++++ JotunnModStub/WarVulture/WarVultureVisual.cs | 376 ++++++++++++++ 11 files changed, 2320 insertions(+), 9 deletions(-) create mode 100644 JotunnModStub/Skadi/SkadiGolem.cs create mode 100644 JotunnModStub/Skadi/SkadiGolemBehaviour.cs create mode 100644 JotunnModStub/WarVulture/WarVultureConfig.cs create mode 100644 JotunnModStub/WarVulture/WarVultureHud.cs create mode 100644 JotunnModStub/WarVulture/WarVultureItem.cs create mode 100644 JotunnModStub/WarVulture/WarVultureMount.cs create mode 100644 JotunnModStub/WarVulture/WarVulturePatches.cs create mode 100644 JotunnModStub/WarVulture/WarVultureVisual.cs diff --git a/JotunnModStub/PieceDensityLimit.cs b/JotunnModStub/PieceDensityLimit.cs index b872263..076f246 100644 --- a/JotunnModStub/PieceDensityLimit.cs +++ b/JotunnModStub/PieceDensityLimit.cs @@ -35,6 +35,20 @@ namespace RacesOfValheim private static readonly Dictionary Limits = new Dictionary(); + /// + /// Extra placement rules, one per piece, for the chains whose cap cannot be expressed as + /// "how many of THIS piece stand nearby". + /// + /// The Skadi's golem is the case that forced this: the piece it builds removes itself a frame + /// later and leaves a creature behind, so counting the piece counts nothing, and one of its two + /// caps is per-stonecutter rather than per-area. A gate is handed the same player and the same + /// placement point the simple limit gets, says yes or no, and is responsible for its own + /// refusal message - which is the whole extension: the counting is the chain's business, being + /// the ONE Player.PlacePiece prefix in the mod is still this class's. + /// + private static readonly Dictionary> Gates = + new Dictionary>(); + /// /// The radius of a circle with the given area, so a limit can be written the way it is /// actually discussed - "five per 1.6 square kilometres" - instead of as a magic distance. @@ -61,6 +75,45 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: at most {max} within {radius:0} m."); } + /// + /// Adds a rule of the chain's own to a piece. Same call-once-from-Register() contract as + /// , and a second call replaces the first rather than stacking. + /// + public static void RegisterGate(string piecePrefabName, System.Func gate) + { + if (string.IsNullOrEmpty(piecePrefabName) || gate == null) + { + Jotunn.Logger.LogWarning($"[Density] Refusing a nonsense gate for '{piecePrefabName}'."); + return; + } + + Gates[piecePrefabName] = gate; + Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: a rule of its own runs at placement."); + } + + /// + /// Every ZDO in the world carrying that prefab. False when the world cannot be asked right + /// now, which callers must read as "no information" rather than as "none". + /// + /// ZDOs and not loaded GameObjects, for the reason at the top of this file, and public + /// because the Skadi's golem counts by an anchor written INTO each ZDO rather than by + /// distance - so it needs the ZDOs themselves and not a tally of them. + /// + public static bool Gather(string prefabName, List into) + { + if (ZDOMan.instance == null || into == null) return false; + + int index = 0; + // The iterative sweep hands back a chunk per call and reports true when it is done. The + // guard is so a pathological world cannot spin here forever. + for (int guard = 0; guard < 1000; guard++) + { + if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(prefabName, into, ref index)) break; + } + + return true; + } + /// /// How many of that piece already stand within the radius of a point, or -1 if the world /// cannot be asked right now - in which case callers must let the placement through rather @@ -68,16 +121,8 @@ namespace RacesOfValheim /// public static int Count(string piecePrefabName, Vector3 position, float radius) { - if (ZDOMan.instance == null) return -1; - List zdos = new List(); - int index = 0; - // The iterative sweep hands back a chunk per call and reports true when it is done. The - // guard is so a pathological world cannot spin here forever. - for (int guard = 0; guard < 1000; guard++) - { - if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(piecePrefabName, zdos, ref index)) break; - } + if (!Gather(piecePrefabName, zdos)) return -1; float rangeSq = radius * radius; int count = 0; @@ -96,6 +141,14 @@ namespace RacesOfValheim /// public static bool Allow(Player player, string piecePrefabName, Vector3 position) { + // The chain's own rule first: it is the more specific of the two, so it should be the one + // that gets to explain itself when both would refuse. + if (Gates.TryGetValue(piecePrefabName, out System.Func gate) && + !gate(player, position)) + { + return false; + } + if (!Limits.TryGetValue(piecePrefabName, out Limit limit)) return true; int nearby = Count(piecePrefabName, position, limit.Radius); diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 4b69a34..c04e8d5 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -36,6 +36,9 @@ namespace RacesOfValheim SkeletonConfig.Bind(Config); TrentaConfigManagement.Bind(Config); TrolConfig.Bind(Config); + // Not a race: a summoned mount two races share, so it binds after the races rather + // than inside the alphabetical run above. + WarVultureConfig.Bind(Config); harmony.PatchAll(); gameObject.AddComponent(); gameObject.AddComponent(); @@ -119,6 +122,7 @@ namespace RacesOfValheim DraughRace.Instance.CreateModAssets(); DvergarRace.Instance.CreateModAssets(); TrentaRace.Instance.CreateModAssets(); + WarVultureItem.Register(); } // --- RACE SELECTION UI --- public void ShowRaceSelectionMenu() diff --git a/JotunnModStub/Skadi/SkadiGolem.cs b/JotunnModStub/Skadi/SkadiGolem.cs new file mode 100644 index 0000000..07e6aeb --- /dev/null +++ b/JotunnModStub/Skadi/SkadiGolem.cs @@ -0,0 +1,460 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Skadi station: crystal golems, cut at a stonecutter and bound to it. + /// + /// Eighth of the per-race item-progression chains, and the odd one out in two ways that decide + /// everything else in this file. + /// + /// FIRST, the station is not ours. Every other chain builds its own bench - a trough, a bone pile, + /// a composter - and can therefore hang a MonoBehaviour on it, count its own garrison from it, and + /// mark its thralls when it falls. The stonecutter is vanilla's, and nothing here modifies it: the + /// golem carries the stonecutter's position in its own ZDO and asks the world whether one still + /// stands there. That is why this chain does not use RaisedThrall, which is otherwise exactly the + /// right component - RaisedThrall's wither depends on the station registering itself, and a vanilla + /// piece never will. + /// + /// SECOND, a golem is not a follower. RaisedThrall's whole vocabulary - follow me, stand down, call + /// to arms - is wrong for something that may not leave a twenty metre circle. There is deliberately + /// no Tameable on it either: it is tame, so it will never turn on anyone, but it cannot be named, + /// ordered, or walked away with. It guards the stone that shaped it, and that is all it does. + /// + /// The three limits are the design, not decoration: + /// never further than 20 m from its stonecutter (the vanilla station build range) + /// two per stonecutter + /// ten per square mile + /// The first is enforced on the golem (SkadiGolemGuard), the other two at the moment of building, + /// through PieceDensityLimit's single Player.PlacePiece prefix - refusing later would spend a + /// dragon tear before telling anyone no. + /// + public static class SkadiGolem + { + // ─── Names ─────────────────────────────────────────────────────────── + public const string GolemName = "SkadiCrystalGolem"; + public const string SeedPieceName = "SkadiCrystalGolemSeed"; + public const string DisplayName = "Crystal Golem"; + + private const string SourceGolem = "StoneGolem"; + + /// + /// The seed piece's model, and it is chosen for its BUILD GHOST: the golem itself only exists + /// a frame later, so a standing stone is what the player actually aims with. Everything the + /// ward DOES - the private area above all - is stripped off the clone below; a chain that + /// quietly planted a ward every time you cut a golem would be a much worse bug than a wrong + /// silhouette. + /// + private const string SourcePiece = "guard_stone"; + + public const string StationPrefab = "piece_stonecutter"; + + // ─── The price ─────────────────────────────────────────────────────── + // Moder needs no state check of her own to BUILD one - her drop is in the recipe - but the + // gate asks anyway, because the recipe is not the only way an item reaches an inventory. + public const string GolemTrophy = "TrophySGolem"; + public const string CrystalItem = "Crystal"; + public const int CrystalCost = 10; + public const string ModerDrop = "DragonTear"; + public const int ModerProgressionState = 5; + + // ─── The limits ────────────────────────────────────────────────────── + + /// + /// How far a golem may get from its stonecutter. Twenty metres because that is the + /// stonecutter's own build range in vanilla, so the circle a golem defends is exactly the + /// circle it could have been built in - one number, visible in game, not two that nearly + /// agree. + /// + public const float LeashRange = 20f; + + /// + /// Past this it has stopped walking home and started failing to. A golem that has been pushed + /// into water, or that stands on the wrong side of something it cannot path around, would + /// otherwise sit outside its leash forever - so at half again the leash it is simply put back. + /// It is a failsafe for a stuck pathfinder, not a movement mechanic. + /// + public const float HardLeashRange = 30f; + + public const int MaxPerStation = 2; + + // Ten per square mile. 2.59 km2, the same area the Fenrir's trough is measured in, so the two + // stations are spaced by the same yardstick even though the numbers differ. + public const int MaxInArea = 10; + public const float DensityAreaKm2 = 2.59f; + + /// + /// How long a golem outlives the stonecutter that cut it. Shorter than the Fenrir trough's + /// five minutes because there is nothing to rebuild: a stonecutter costs ten stone and two + /// wood, so "put it back" is a moment's work, and a longer grace would just mean a garrison + /// that survives being moved. + /// + public const float WitherSeconds = 60f; + + /// Slack when asking "is my stonecutter still there" - a station never moves. + public const float StationCheckRange = 2f; + + /// + /// Only asked this close to home, for the reason RaisedThrall's wither carries the same guard: + /// further out the station's zone is probably not loaded, so "nothing stands there" would be a + /// lie. A golem is leashed to 20 m anyway, so this is never the reason one survives. + /// + public const float HomeCheckRange = 40f; + + // ─── Behaviour ─────────────────────────────────────────────────────── + + /// Idle wander around the stonecutter. Half the leash, so it never idles onto it. + private const float WanderRange = 10f; + + /// + /// The station's m_name, read off the stonecutter prefab once at registration. + /// + /// It is NOT the prefab name: CraftingStation.HaveBuildStationInRange compares against + /// m_name, which is a localisation token, while Jotunn's PieceConfig.CraftingStation wants the + /// prefab name. Both spellings are needed and they are not the same string, which is exactly + /// the kind of thing worth reading off the game once instead of guessing at twice. + /// + private static string StationName = "$piece_stonecutter"; + + public static void Register() + { + CacheStationName(); + + if (!RegisterGolem()) return; + RegisterSeedPiece(); + + PieceDensityLimit.RegisterGate(SeedPieceName, MayRaise); + } + + private static void CacheStationName() + { + GameObject station = PrefabManager.Cache.GetPrefab(StationPrefab); + CraftingStation component = station != null ? station.GetComponent() : null; + + if (component == null || string.IsNullOrEmpty(component.m_name)) + { + Jotunn.Logger.LogWarning($"[Skadi] Could not read the stonecutter's station name off " + + $"'{StationPrefab}'; falling back to '{StationName}'."); + return; + } + + StationName = component.m_name; + } + + // ---------------------------------------------------------------- the golem + + /// + /// A vanilla stone golem, tamed, frozen over, and made incapable of the three things it must + /// never do. + /// + /// Health, damage and resistances stay exactly as vanilla has them. A mountain golem is a slow + /// wall with a great deal of health, which is precisely what a defender that cannot leave its + /// circle should be - there is nothing to retune, and nothing here does. + /// + /// What IS written over: + /// - it does not sleep. Vanilla golems start as rocks and wake when something comes near; + /// a guard that has to be woken up is not a guard. + /// - it does not target player-built anything (m_attackPlayerObjects). That is the first + /// half of "never attacks structures"; the second half is the WearNTear guard below, + /// because an area attack aimed at a greydwarf can still land on a wall. + /// - it does not flee. A golem holds its ground or it dies on it. + /// - it gives up a chase past its leash, measured from its own spawn point, which + /// SkadiGolemGuard pins to the stonecutter. That is vanilla's own leash, used as intended + /// rather than reimplemented. + /// - it drops nothing. Two golems per stonecutter that could be farmed for crystals and + /// trophies would be a mint, and the trophy is this chain's own gate item. + /// It never attacks tamed creatures or players for free: Attack.DoMeleeAttack only lets a + /// tamed attacker through to targets its own AI counts as enemies, which is checked in the + /// game's code rather than assumed here. + /// + private static bool RegisterGolem() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(GolemName, SourceGolem); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourceGolem}; {DisplayName} not registered."); + return false; + } + + Character character = prefab.GetComponent(); + if (character != null) character.m_name = DisplayName; + + SkadiIce.Apply(prefab); + + BaseAI ai = prefab.GetComponent(); + if (ai != null) + { + ai.m_randomMoveRange = WanderRange; + ai.m_avoidWater = true; + } + + MonsterAI monster = prefab.GetComponent(); + if (monster != null) + { + monster.m_sleeping = false; + monster.m_attackPlayerObjects = false; + + // It notices what comes into the circle it defends, and nothing outside it. Being + // hit still turns it around - OnDamaged sets a target whatever the alert range says - + // which is the difference between a defender and a statue. + monster.m_alertRange = LeashRange; + monster.m_maxChaseDistance = LeashRange; + monster.m_fleeIfLowHealth = 0f; + monster.m_fleeIfNotAlerted = false; + monster.m_fleeIfHurtWhenTargetCantBeReached = false; + } + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + foreach (Procreation breeding in prefab.GetComponentsInChildren(true)) + { + if (breeding != null) Object.DestroyImmediate(breeding); + } + + // "Ten seconds unhurt, then 2% a second" - the Skeleton's sentry regeneration, which three + // chains now share. A guard that cannot heal between raids is a guard you rebuild. + prefab.AddComponent(); + + prefab.AddComponent(); + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Skadi] {GolemName} from '{SourceGolem}': awake, tame, leashed, " + + "blind to structures, drops nothing."); + return true; + } + + // ---------------------------------------------------------------- the seed piece + + /// + /// The hammer entry, and the same trick SkeletonSentry uses for the same reason: the hammer + /// builds Piece, a golem is a Character, so a piece is placed and swaps itself for one. + /// + private static void RegisterSeedPiece() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SeedPieceName, SourcePiece); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePiece}; {DisplayName} cannot be built."); + return; + } + + // Everything the ward does goes - PrivateArea and its effect areas above all. What is + // wanted is a placeable shell with the right outline, alive for one frame. + foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren(true)) + { + if (behaviour == null) continue; + if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue; + Object.DestroyImmediate(behaviour); + } + + AswidBloodRefinery.StripOffensive(prefab, SeedPieceName); + SkadiIce.Apply(prefab); + + prefab.AddComponent(); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = DisplayName; + piece.m_canBeRemoved = true; + piece.m_groundPiece = true; + piece.m_groundOnly = true; + piece.m_icon = BorrowIcon(CrystalItem); + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = DisplayName, + Description = "Cut at the stone and woken with a tear. It will not follow you, and it " + + "will not leave the stonecutter that shaped it.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + // The stonecutter is the station, so vanilla itself refuses to place one anywhere its + // golem could not then be bound - the gate below never has to be the first to say no. + CraftingStation = CraftingStations.Stonecutter, + Icon = BorrowIcon(CrystalItem), + Requirements = new[] + { + new RequirementConfig(GolemTrophy, 1, 0, true), + new RequirementConfig(CrystalItem, CrystalCost, 0, true), + new RequirementConfig(ModerDrop, 1, 0, true), + } + })); + } + + // ---------------------------------------------------------------- the gate + + /// + /// The two caps that cannot live on the golem, asked at the moment of building. + /// + /// Order matters: race, then boss, then the stonecutter, then its own two, so the first thing + /// a player is told is the thing they can actually do something about. + /// + /// HONEST LIMIT, inherited from PieceDensityLimit and worth repeating: the counts are over + /// ZDOs, which on a remote client are only the ZDOs the server has sent. On the host they are + /// exact. Where a count cannot be taken at all the placement is allowed - refusing on no + /// information is worse than a cap that occasionally misses. + /// + public static bool MayRaise(Player player, Vector3 position) + { + if (player == null) return true; + + if (!SkadiRace.IsLocalSkadi()) + { + player.Message(MessageHud.MessageType.Center, "The stone does not answer to you."); + return false; + } + + if (BossProgressionManager.GetCurrentProgressionState() < ModerProgressionState) + { + player.Message(MessageHud.MessageType.Center, + "The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen."); + return false; + } + + CraftingStation station = FindStonecutter(position); + if (station == null) + { + player.Message(MessageHud.MessageType.Center, "It needs a stonecutter to be cut at."); + return false; + } + + int bound = CountBoundTo(station.transform.position); + if (bound >= MaxPerStation) + { + player.Message(MessageHud.MessageType.Center, + $"That stonecutter already holds {bound}. It will not hold more."); + return false; + } + + int nearby = PieceDensityLimit.Count(GolemName, position, PieceDensityLimit.RadiusForArea(DensityAreaKm2)); + if (nearby >= MaxInArea) + { + player.Message(MessageHud.MessageType.Center, + $"There are already {nearby} of these within a day's walk. The stone is spent."); + return false; + } + + return true; + } + + /// + /// The stonecutter that owns a point, by the station's OWN build range rather than by a number + /// of ours - so the circle a golem may be cut in and the circle it may stand in are the same + /// circle, and stay the same if a game update retunes the station. + /// + public static CraftingStation FindStonecutter(Vector3 position) + { + return CraftingStation.HaveBuildStationInRange(StationName, position); + } + + /// True if a stonecutter still stands at that exact point. + public static bool StonecutterStandsAt(Vector3 position) + { + return CraftingStation.FindClosestStationInRange(StationName, position, StationCheckRange) != null; + } + + /// + /// How many golems already answer to the stonecutter at that point, counted over ZDOs and not + /// over loaded creatures. + /// + /// That distinction is the whole cap: a golem in an unloaded zone is still a golem, and + /// counting only what is loaded would make walking away and coming back the way to hold six. + /// Dead ones are gone from the world entirely, so a slot frees itself with no bookkeeping. + /// + public static int CountBoundTo(Vector3 station) + { + List zdos = new List(); + if (!PieceDensityLimit.Gather(GolemName, zdos)) return 0; + + int count = 0; + foreach (ZDO zdo in zdos) + { + if (zdo == null) continue; + + // A generous epsilon: a station never moves, so this only has to survive float + // round-tripping through the ZDO. + Vector3 anchor = zdo.GetVec3(SkadiGolemGuard.KeyAnchor, Vector3.zero); + if (anchor != Vector3.zero && Vector3.SqrMagnitude(anchor - station) < 0.25f) count++; + } + + return count; + } + + // ---------------------------------------------------------------- known pieces + + /// + /// Learnt by being Skadi, and not by having killed Moder. + /// + /// Deliberate: the entry shows up greyed out with its price on it, which is how every vanilla + /// recipe tells you what to go and get. Gating the entry itself on the boss would hide it + /// until a relog anyway - OnSpawned is the only moment this is asked - so the boss check lives + /// where it can be asked every time instead, in MayRaise. + /// + public static void EnsureKnown(Player player) + { + if (player == null || !SkadiRace.IsLocalSkadi()) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(SeedPieceName); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece == null) return; + + Traverse traverse = Traverse.Create(player); + traverse.Method("AddKnownPiece", piece).GetValue(); + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + + private static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null + ? drop.m_itemData.m_shared.m_icons + : null; + if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0]; + + Jotunn.Logger.LogWarning($"[Skadi] Could not borrow the icon from '{prefabName}'."); + return null; + } + } + + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class SkadiGolemKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + SkadiGolem.EnsureKnown(__instance); + } + } + + /// + /// The second half of "it never attacks structures". + /// + /// m_attackPlayerObjects stops a golem CHOOSING a wall as a target; it does not stop one landing a + /// swing on the wall behind a greydwarf, because Attack.DoMeleeAttack has no tamed check on the + /// destructible path at all - only on the character one. Read off the game's own code rather than + /// assumed, and it is why this patch exists instead of one field being trusted to do both jobs. + /// + /// The signature is spelled out and bound positionally for the reason PieceDensityLimitPatch + /// carries in its own comment: Damage returns VOID, so a prefix returning false is the whole + /// mechanism, and asking for a __result on a void method throws at patch time and takes the rest + /// of the mod's patches down with it. + /// + [HarmonyPatch(typeof(WearNTear), "Damage", new[] { typeof(HitData) })] + public static class SkadiGolemStructureGuardPatch + { + public static bool Prefix(HitData __0) + { + if (__0 == null) return true; + + Character attacker = __0.GetAttacker(); + return attacker == null || attacker.GetComponent() == null; + } + } +} diff --git a/JotunnModStub/Skadi/SkadiGolemBehaviour.cs b/JotunnModStub/Skadi/SkadiGolemBehaviour.cs new file mode 100644 index 0000000..b21621a --- /dev/null +++ b/JotunnModStub/Skadi/SkadiGolemBehaviour.cs @@ -0,0 +1,302 @@ +using System; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// One crystal golem: tame, bound to a stonecutter, and unable to get more than its leash away + /// from it. + /// + /// Same shape as RaisedThrall - an anchor in the creature's own ZDO, a leash pinned to it, a + /// wither clock that starts when the station is gone - and deliberately NOT that class. Two + /// differences make it a copy rather than a reuse, and both are in SkadiGolem's own comment: the + /// station is vanilla's and cannot register itself, and a golem takes no orders, so the follow, + /// stand-down and call-to-arms half of RaisedThrall is not merely unused here but wrong. + /// + /// The leash is three layers, weakest first, because each one covers the case the one before it + /// cannot: + /// - vanilla's own chase limit (m_maxChaseDistance, measured from m_spawnPoint, which is pinned + /// to the stonecutter below) makes it GIVE UP on anything it would have to leave home for; + /// - the patrol point, re-pinned every tick, is what brings it back and what keeps it wandering + /// around the station rather than drifting after it has been pushed or knocked back; + /// - and past half again the leash it is simply put back, because at that distance it is not + /// walking home slowly, it is failing to walk home at all. + /// + public class SkadiGolemGuard : MonoBehaviour + { + public const string KeyAnchor = "RoV_golemAnchor"; + public const string KeyOrphanAt = "RoV_golemOrphanAt"; + + /// + /// One second, and not the two RaisedThrall uses. Vanilla will not drop a target it can still + /// SEE, whatever m_maxChaseDistance says - read off MonsterAI.UpdateTarget, where the give-up + /// test also wants a second of having lost sight of it - so this tick is what actually holds + /// the leash, and how far past twenty metres a golem gets is how far it walks between two of + /// them. A stone golem is slow; at one second that is a stride. + /// + private const float TickSeconds = 1f; + + // SetPatrolPoint(Vector3) is private - only the parameterless overload, which uses the + // creature's current position, is public. Resolved once here rather than per call, exactly as + // RaisedThrall does it. + private static readonly System.Reflection.MethodInfo SetPatrolPointMethod = + AccessTools.Method(typeof(BaseAI), "SetPatrolPoint", new[] { typeof(Vector3) }); + + // m_spawnPoint is protected, and it is the point vanilla measures m_maxChaseDistance from - + // read off MonsterAI.UpdateTarget rather than assumed, because "chase distance" could just as + // easily have meant distance from the target. + private static readonly System.Reflection.FieldInfo SpawnPointField = + AccessTools.Field(typeof(BaseAI), "m_spawnPoint"); + + private Character m_character; + private BaseAI m_ai; + private MonsterAI m_monsterAI; + private ZNetView m_nview; + private Rigidbody m_body; + + private void Awake() + { + m_character = GetComponent(); + m_ai = GetComponent(); + m_monsterAI = GetComponent(); + m_nview = GetComponent(); + m_body = GetComponent(); + + InvokeRepeating("Tick", TickSeconds, TickSeconds); + } + + /// Where the stonecutter that cut this one stands, or null if it was cut by none. + public Vector3? Anchor + { + get + { + if (m_nview == null || !m_nview.IsValid()) return null; + + Vector3 anchor = m_nview.GetZDO().GetVec3(KeyAnchor, Vector3.zero); + return anchor == Vector3.zero ? (Vector3?)null : anchor; + } + } + + /// + /// Called once, by the seed piece that placed it. Tames it, marks whose stonecutter it is, and + /// sends it home - all three, so nothing else has to remember to do any of them. + /// + public void Bind(Vector3 anchor) + { + if (m_nview == null || !m_nview.IsValid()) return; + + m_nview.GetZDO().Set(KeyAnchor, anchor); + + if (m_monsterAI != null) m_monsterAI.MakeTame(); + if (m_character != null) m_character.SetTamed(true); + + GoHome(); + } + + // ---------------------------------------------------------------- the tick + + private void Tick() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + if (m_character == null || m_character.IsDead()) return; + + if (TickWither()) return; + + Vector3? anchor = Anchor; + if (anchor == null) return; + + float distance = Vector3.Distance(transform.position, anchor.Value); + + if (distance > SkadiGolem.LeashRange) + { + // Whatever it was going after is outside the circle it defends, so it stops going + // after it. Vanilla would drop the target itself a second or so later through + // m_maxChaseDistance; doing it here as well means the leash does not depend on that + // one field surviving a game update. + ClearTarget(); + } + + if (distance > SkadiGolem.HardLeashRange) SnapHome(anchor.Value); + + // Every tick, and not only when it has strayed: this is also what pins m_spawnPoint after + // a zone reload, where Bind is never called again. + GoHome(); + } + + /// + /// Starts the clock when the stonecutter is gone, and stops the golem when it runs out. + /// Returns true once it has done so, so the caller stops bothering with it. + /// + /// Without some form of this a stonecutter is a duplication exploit: cut two golems, take the + /// stonecutter down, put it up somewhere else, and keep both from every round. + /// + private bool TickWither() + { + Vector3? anchor = Anchor; + if (anchor == null || ZNet.instance == null) return false; + + long stamp = m_nview.GetZDO().GetLong(KeyOrphanAt, 0L); + + if (stamp == 0L) + { + // Only asked from close to home - see SkadiGolem.HomeCheckRange. Being leashed to + // twenty metres, a golem is essentially always close enough, so this guard is about + // the moment after a zone loads rather than about distance. + if (Vector3.SqrMagnitude(transform.position - anchor.Value) > + SkadiGolem.HomeCheckRange * SkadiGolem.HomeCheckRange) return false; + + if (SkadiGolem.StonecutterStandsAt(anchor.Value)) return false; + + MarkOrphaned(); + return false; + } + + // Put back in time, on the same spot: the clock is cleared and the golem lives. It opens + // no exploit - a stonecutter on the same spot owns these golems by anchor anyway. + if (SkadiGolem.StonecutterStandsAt(anchor.Value)) + { + m_nview.GetZDO().Set(KeyOrphanAt, 0L); + return false; + } + + double elapsed = (ZNet.instance.GetTime() - new DateTime(stamp)).TotalSeconds; + if (elapsed < SkadiGolem.WitherSeconds) return false; + + Crumble(); + return true; + } + + /// Starts the wither clock, once. Idempotent, so it cannot be restarted and keep an + /// orphan alive forever. + private void MarkOrphaned() + { + if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return; + if (m_nview.GetZDO().GetLong(KeyOrphanAt, 0L) != 0L) return; + + m_nview.ClaimOwnership(); + m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks); + + if (Player.m_localPlayer != null && + Vector3.Distance(Player.m_localPlayer.transform.position, transform.position) < 30f) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, + "The stonecutter is gone. What it cut will not outlast it by long."); + } + } + + /// + /// Pins the patrol point - and the spawn point vanilla measures its own chase limit from - + /// back onto the stonecutter. Cheap enough to call on a timer, and calling it repeatedly is + /// what stops a golem drifting after it has been pushed or knocked back. + /// + private void GoHome() + { + Vector3? anchor = Anchor; + if (anchor == null || m_ai == null) return; + + if (SpawnPointField != null) SpawnPointField.SetValue(m_ai, anchor.Value); + + if (SetPatrolPointMethod != null) + { + SetPatrolPointMethod.Invoke(m_ai, new object[] { anchor.Value }); + } + else + { + // Fall back to writing the two fields the private method writes. + Traverse traverse = Traverse.Create(m_ai); + traverse.Field("m_patrolPoint").SetValue(anchor.Value); + traverse.Field("m_patrol").SetValue(true); + } + } + + /// Forgets whatever it was going after, creature or otherwise. + private void ClearTarget() + { + if (m_monsterAI == null) return; + + Traverse traverse = Traverse.Create(m_monsterAI); + traverse.Field("m_targetCreature").SetValue(null); + traverse.Field("m_targetStatic").SetValue(null); + } + + /// + /// The failsafe, and only that. A golem that is this far out has not wandered - it has been + /// pushed somewhere it cannot path back from, and the alternative to putting it back is one + /// that stands in a lake until its stonecutter falls. + /// + private void SnapHome(Vector3 anchor) + { + Vector2 offset = UnityEngine.Random.insideUnitCircle * 3f; + Vector3 destination = anchor + new Vector3(offset.x, 0.5f, offset.y); + + transform.position = destination; + if (m_body != null) m_body.linearVelocity = Vector3.zero; + + ClearTarget(); + + Jotunn.Logger.LogWarning($"[Skadi] A golem was {SkadiGolem.HardLeashRange:0} m or more from its " + + "stonecutter and could not walk back; it was put back."); + } + + private void Crumble() + { + if (m_character == null || m_character.IsDead()) return; + + HitData hit = new HitData(); + hit.m_damage.m_damage = 1E+10f; + hit.m_hitType = HitData.HitType.Undefined; + m_character.ApplyDamage(hit, true, false); + } + } + + /// + /// Lives for one frame: swaps itself for the golem and goes. Owner only, so in multiplayer exactly + /// one golem stands up rather than one per client. + /// + /// The stonecutter is looked up again here rather than handed over by the placement gate, and that + /// is deliberate: both call SkadiGolem.FindStonecutter with the same point, so both get the same + /// answer, and there is no piece of state between them that can go stale or arrive out of order. + /// + /// If the lookup comes back empty the materials are lost, and that is the honest outcome rather + /// than an oversight: it can only happen if the stonecutter was taken down between the gate saying + /// yes and this frame, and the alternative - a golem anchored to nothing - would wither in a + /// minute anyway while looking like a bug. + /// + public class SkadiGolemSeed : MonoBehaviour + { + private void Start() + { + ZNetView nview = GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + GameObject prefab = ZNetScene.instance != null + ? ZNetScene.instance.GetPrefab(SkadiGolem.GolemName) + : null; + + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skadi] No '{SkadiGolem.GolemName}' in ZNetScene; nothing was cut."); + ZNetScene.instance.Destroy(gameObject); + return; + } + + CraftingStation station = SkadiGolem.FindStonecutter(transform.position); + if (station == null) + { + Jotunn.Logger.LogWarning("[Skadi] No stonecutter in range at the moment of cutting; " + + "nothing was raised."); + ZNetScene.instance.Destroy(gameObject); + return; + } + + GameObject spawned = Instantiate(prefab, transform.position, transform.rotation); + + // Bind tames it, marks whose stonecutter it is, and sends it home - all three. + SkadiGolemGuard guard = spawned.GetComponent(); + if (guard != null) guard.Bind(station.transform.position); + + ZNetScene.instance.Destroy(gameObject); + } + } +} diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index 75e2602..9d1084c 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -56,6 +56,7 @@ namespace RacesOfValheim // bench - and the staff's recipe references it by name too. SkadiFrostHeart.Register(); SkadiNokkel.Register(); + SkadiGolem.Register(); var se = ScriptableObject.CreateInstance(); se.name = "SE_SkadiStats"; diff --git a/JotunnModStub/WarVulture/WarVultureConfig.cs b/JotunnModStub/WarVulture/WarVultureConfig.cs new file mode 100644 index 0000000..1903f4a --- /dev/null +++ b/JotunnModStub/WarVulture/WarVultureConfig.cs @@ -0,0 +1,109 @@ +using BepInEx.Configuration; + +namespace RacesOfValheim +{ + /// + /// Every tunable number behind the War Vulture, bound as BepInEx ConfigEntry so it shows up in + /// Configuration Manager - same shape as TrolConfig, which is the house model for this. + /// + /// The three numbers most likely to need a pass in game are deliberately here rather than in + /// code: MountSize, MountOffsetY and MountOffsetZ. Where a bird sits under a rider is the one + /// thing the last attempt lost three rounds to (section 16.6 of the design doc: measure a + /// relation, never pick a number in metres from the armchair), and a value that can be dragged + /// in the menu while standing in the world beats another compile. + /// + /// No keybind is bound here on purpose. The mount answers to LEFT CLICK on the item and to the + /// vanilla run key, so there is nothing new to learn and nothing new to rebind. + /// + public static class WarVultureConfig + { + // ─── Access ──────────────────────────────────────────────────────────── + public static ConfigEntry AllowedRaces; + + // ─── Flight ──────────────────────────────────────────────────────────── + public static ConfigEntry CruiseSpeed; + public static ConfigEntry SprintSpeed; + public static ConfigEntry SprintSeconds; + public static ConfigEntry RechargeSeconds; + public static ConfigEntry LandingSpeed; + + // ─── Model ───────────────────────────────────────────────────────────── + public static ConfigEntry HandModelScale; + public static ConfigEntry MountSize; + public static ConfigEntry SeatBone; + public static ConfigEntry SeatNudgeY; + public static ConfigEntry SeatNudgeZ; + + // ─── Interface ───────────────────────────────────────────────────────── + public static ConfigEntry ShowStaminaBar; + + public static void Bind(ConfigFile config) + { + const string access = "War Vulture - Access"; + AllowedRaces = config.Bind(access, "Allowed races", "Furling,Dvergar", + new ConfigDescription("Comma separated list of race ids that can call the vulture. " + + "In anyone else's hands the item is an inert trophy on a stick. " + + "Leave empty to let every race ride.")); + + const string flight = "War Vulture - Flight"; + // 7 and 13 are not proposals: they are m_flySlowSpeed and m_flyFastSpeed read off the + // vanilla Volture at runtime (design doc 15.13). A number read from the game survives a + // Valheim patch; a number invented here does not. + CruiseSpeed = config.Bind(flight, "Cruise speed", 7f, + new ConfigDescription("Metres per second with the run key up. This one is unlimited - " + + "vultures stay up for hours.")); + SprintSpeed = config.Bind(flight, "Sprint speed", 13f, + new ConfigDescription("Metres per second while the run key is held and the bird still " + + "has wind in it.")); + SprintSeconds = config.Bind(flight, "Sprint seconds", 10f, + new ConfigDescription("How long full speed lasts before the bird drops back to cruise.")); + RechargeSeconds = config.Bind(flight, "Recharge seconds", 10f, + new ConfigDescription("How long a spent bird takes to fill up again. It recharges in the " + + "air as soon as the run key is released - landing is not required.")); + LandingSpeed = config.Bind(flight, "Landing speed", 12f, + new ConfigDescription("Metres per second of the automatic descent after the dismount " + + "click. The controls are ignored until the ground arrives.")); + + const string model = "War Vulture - Model"; + HandModelScale = config.Bind(model, "Hand model scale", 0.6f, + new ConfigDescription("Size of the vulture trophy carried in hand, as a fraction of the " + + "real trophy. 0.6 is the 40% smaller that was asked for.")); + MountSize = config.Bind(model, "Mount size", 7.75f, + new ConfigDescription("Largest dimension of the bird under the rider, in metres. 7.75 is " + + "the vanilla Volture's own mesh, wings included.")); + // The rider is glued to a BONE, not to a height: the bird's back rises and falls with + // every wingbeat, and any offset in metres can only be right on one frame of that. + SeatBone = config.Bind(model, "Seat bone", "", + new ConfigDescription("Name (or part of a name) of the bone on the vulture's skeleton the " + + "rider sits on. Empty picks the last spine/chest bone automatically, " + + "which is what the bird actually flies with.")); + SeatNudgeY = config.Bind(model, "Seat nudge Y", 0f, + new ConfigDescription("Fine adjustment up (+) or down (-) from the seat bone, in metres. " + + "Zero means exactly on the bone.")); + SeatNudgeZ = config.Bind(model, "Seat nudge Z", 0f, + new ConfigDescription("Fine adjustment forward (+) or back (-) from the seat bone, in metres.")); + + const string ui = "War Vulture - Interface"; + ShowStaminaBar = config.Bind(ui, "Show stamina bar", true, + new ConfigDescription("Draws the bird's own wind as a bar under the player's stamina, " + + "cloned from vanilla's mount stamina bar.")); + } + + /// + /// Whether a race id may call the bird. An empty list means everyone, which is the honest + /// reading of "no restriction" and is also what makes this testable on any character. + /// + public static bool RaceAllowed(string race) + { + string list = AllowedRaces != null ? AllowedRaces.Value : null; + if (string.IsNullOrEmpty(list)) return true; + if (string.IsNullOrEmpty(race)) return false; + + foreach (string entry in list.Split(',')) + { + if (entry.Trim().Equals(race.Trim(), System.StringComparison.OrdinalIgnoreCase)) return true; + } + return false; + } + } +} diff --git a/JotunnModStub/WarVulture/WarVultureHud.cs b/JotunnModStub/WarVulture/WarVultureHud.cs new file mode 100644 index 0000000..0f63814 --- /dev/null +++ b/JotunnModStub/WarVulture/WarVultureHud.cs @@ -0,0 +1,116 @@ +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The bird's wind, as a bar under the player's stamina. + /// + /// It is a CLONE of vanilla's own mount stamina bar, not a bar drawn from scratch, for two + /// reasons: it is already skinned, sized and animated like every other bar in the game, and it + /// is semantically the same thing - Hud.UpdateMount drives that bar from Sadle.GetStamina for + /// the asksvin. Ours is the same idea with a different animal underneath. + /// + /// Vanilla's copy cannot simply be borrowed where it stands: Hud.UpdateMount switches the whole + /// mount panel off on every frame in which the player is not on a Sadle, and it would take the + /// bar with it. The clone is reparented out of that panel, so vanilla never touches it again. + /// + /// Everything here is reflection because GuiBar lives in assembly_guiutils, which this project + /// does not reference - and adding a reference to the csproj is a bigger change than a bar is + /// worth. Every step is null-checked: a bar that fails to build costs the bar and nothing else, + /// which is the right trade for an ornament on a flying mount. + /// + public class WarVultureHud + { + private const float BelowStaminaPixels = 24f; + + private readonly WarVultureMount mount; + private readonly GameObject barObject; + private readonly Component guiBar; + private readonly MethodInfo setValue; + + private WarVultureHud(WarVultureMount mount, GameObject barObject, Component guiBar, MethodInfo setValue) + { + this.mount = mount; + this.barObject = barObject; + this.guiBar = guiBar; + this.setValue = setValue; + } + + public static WarVultureHud Create(WarVultureMount mount) + { + Hud hud = Hud.instance; + if (hud == null) return null; + + Component template = Traverse.Create(hud).Field("m_mountStaminaBar").GetValue(); + RectTransform staminaRoot = hud.m_staminaBar2Root; + if (template == null || staminaRoot == null || staminaRoot.parent == null) + { + Jotunn.Logger.LogWarning("[WarVulture] The vanilla mount stamina bar or the stamina bar root " + + "could not be found, so the bird flies without a gauge."); + return null; + } + + GameObject clone = Object.Instantiate(template.gameObject, staminaRoot.parent); + clone.name = "WarVultureWindBar"; + + // Anchored off the stamina bar rather than off the screen: the stamina bar moves with + // the player's HUD layout, and anything positioned against the screen would drift away + // from it the moment that layout changes. + RectTransform rect = clone.GetComponent(); + if (rect != null) + { + rect.anchorMin = staminaRoot.anchorMin; + rect.anchorMax = staminaRoot.anchorMax; + rect.pivot = staminaRoot.pivot; + rect.anchoredPosition = staminaRoot.anchoredPosition + new Vector2(0f, -BelowStaminaPixels); + rect.localScale = staminaRoot.localScale; + } + + clone.SetActive(true); + + Component bar = clone.GetComponent("GuiBar"); + MethodInfo setter = bar != null + ? bar.GetType().GetMethod("SetValue", new[] { typeof(float) }) + : null; + + if (setter == null) + { + Jotunn.Logger.LogWarning("[WarVulture] The cloned bar has no GuiBar.SetValue(float) to drive, " + + "so it would have sat there full forever; it was removed."); + Object.Destroy(clone); + return null; + } + + TintBrown(bar); + + return new WarVultureHud(mount, clone, bar, setter); + } + + /// + /// Optional, and treated as such: if GuiBar ever loses SetColor the bar simply keeps + /// vanilla's colour instead of costing an exception every summon. + /// + private static void TintBrown(Component bar) + { + MethodInfo setColor = bar.GetType().GetMethod("SetColor", new[] { typeof(Color) }); + if (setColor == null) return; + + setColor.Invoke(bar, new object[] { new Color(0.72f, 0.55f, 0.32f, 1f) }); + } + + public void Refresh() + { + if (barObject == null || guiBar == null || setValue == null) return; + if (mount == null) return; + + setValue.Invoke(guiBar, new object[] { mount.WindFraction }); + } + + public void Dispose() + { + if (barObject != null) Object.Destroy(barObject); + } + } +} diff --git a/JotunnModStub/WarVulture/WarVultureItem.cs b/JotunnModStub/WarVulture/WarVultureItem.cs new file mode 100644 index 0000000..03d105c --- /dev/null +++ b/JotunnModStub/WarVulture/WarVultureItem.cs @@ -0,0 +1,308 @@ +using HarmonyLib; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The War Vulture item: a Dead Raiser with the skeleton taken out of it and a vulture trophy + /// hung in its place. Clicked, it puts the player on a flying bird; clicked again, it brings + /// them down and takes the bird away. + /// + /// Why a staff and not a trinket: the game lets a WEAPON be used without any trickery. Cloning + /// StaffSkeleton buys the click, the cast gesture and the effects for free - which is exactly + /// the reasoning that produced SkadiNokkel, and this file is deliberately that file's twin. If + /// one of them ever needs a fix, the other almost certainly needs the same one. + /// + /// Three things are removed from the vanilla staff, and each is removed TWICE on purpose: + /// - the eitr, health and stamina costs are zeroed on the clone AND forced to zero in the + /// getters every cost check flows through (WarVultureFreeCastPatch). The eitr cost is not + /// cosmetic: it is checked BEFORE the attack starts, so a player without eitr would never + /// reach the code that summons; + /// - the summon is nulled on the clone AND the attack trigger itself is taken over, so + /// vanilla's spawn code is not merely defused but unreachable (WarVultureCastPatch); + /// - the staff's model is replaced by the trophy under the item's "attach" child, which is + /// the ONLY child VisEquipment draws - a model hung anywhere else is present, correct and + /// invisible (design doc 15.11, half an hour paid for once already). + /// + public static class WarVultureItem + { + public const string PrefabName = "WarVulture"; + public const string DisplayName = "War Vulture"; + + private const string SourcePrefab = "StaffSkeleton"; + private const string TrophyPrefab = "TrophyVolture"; + private const string Label = "WarVulture"; + + public static void Register() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[{Label}] Could not clone {SourcePrefab}; {DisplayName} not registered."); + return; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) + { + Jotunn.Logger.LogWarning($"[{Label}] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered."); + return; + } + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = DisplayName; + shared.m_description = "A vulture's head, kept. Raise it and the bird comes back under you, " + + "and it will carry you as long as you care to stay up - though it only " + + "has so much haste in it before it settles into a glide."; + shared.m_useDurability = false; + + // ItemType is left exactly as the vanilla staff has it: it decides the equip slot and + // which animation set the arms use, and the cast gesture is the whole reason this is a + // staff rather than a trinket. + + Strip(shared); + SwapHandModel(prefab); + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + + // Built HERE and not at the summon, and the comment on WarVultureVisual explains why in + // full: this is a context where components may be destroyed immediately, and the summon + // is not. Getting that wrong once put a live Ashlands predator in the player's world. + WarVultureVisual.BuildTemplate(); + + // No recipe, on purpose and for now: the item is spawned from the console + // ("spawn WarVulture") while the flight is being proven. A recipe costs nothing to add + // later and would only be materials invented before anyone knows what this is worth. + Jotunn.Logger.LogInfo($"[{Label}] {DisplayName} registered: no eitr, no health, no stamina, no skeleton."); + } + + /// + /// Takes the skeleton staff apart. Every field is zeroed on BOTH attacks, because the + /// secondary is a separate Attack carrying its own copy of every cost. + /// + /// The summon hangs off a SpawnAbility on a prefab referenced by the attack, and WHICH + /// field carries it is not knowable from the game files - so all three candidates go. + /// Nulling three fields that might each be the culprit costs nothing; guessing wrong costs + /// a skeleton on every click. + /// + /// The animation is the one thing deliberately left alone. It is the whole point: the + /// player raises the trophy, and the bird answers. + /// + private static void Strip(ItemDrop.ItemData.SharedData shared) + { + StripAttack(shared.m_attack); + StripAttack(shared.m_secondaryAttack); + } + + private static void StripAttack(Attack attack) + { + if (attack == null) return; + + attack.m_attackEitr = 0f; + attack.m_drawEitrDrain = 0f; + attack.m_reloadEitrDrain = 0f; + + attack.m_attackHealth = 0f; + attack.m_attackHealthPercentage = 0f; + attack.m_attackHealthLowBlockUse = false; + attack.m_attackHealthReturnHit = 0f; + + attack.m_attackStamina = 0f; + attack.m_drawStaminaDrain = 0f; + attack.m_reloadStaminaDrain = 0f; + + attack.m_attackProjectile = null; + attack.m_spawnOnTrigger = null; + attack.m_spawnOnHit = null; + attack.m_spawnOnHitChance = 0f; + } + + /// + /// Puts the vulture trophy in the hand where the staff's model was. + /// + /// "attach" is not a name picked for tidiness: VisEquipment instantiates that child and + /// nothing else, so this is the only place a held model can live. + /// + /// The size is a MULTIPLIER rather than a measurement in metres, which is the opposite of + /// what ModelBorrow does and is right here for one reason: the brief was "the trophy, 40% + /// smaller". The trophy's own size is the measurement; 0.6 is the relation applied to it. + /// + private static void SwapHandModel(GameObject prefab) + { + Transform attach = FindChild(prefab.transform, "attach"); + if (attach == null) + { + Jotunn.Logger.LogWarning($"[{Label}] The {SourcePrefab} clone has no 'attach' child, so the " + + "held model was left as the vanilla staff. VisEquipment draws " + + "nothing else, so there was nowhere else to put it."); + return; + } + + GameObject trophy = PrefabManager.Cache.GetPrefab(TrophyPrefab); + if (trophy == null) + { + Jotunn.Logger.LogWarning($"[{Label}] No '{TrophyPrefab}' to borrow; the item keeps the " + + "skeleton staff's look."); + return; + } + + // The old staff mesh goes first, or the hand holds both. + for (int i = attach.childCount - 1; i >= 0; i--) + { + Object.DestroyImmediate(attach.GetChild(i).gameObject); + } + foreach (Renderer renderer in attach.GetComponents()) + { + if (renderer != null) Object.DestroyImmediate(renderer); + } + + // Instantiate into a holder that is ALREADY INACTIVE - the one line ModelBorrow exists + // for. A trophy is an ItemDrop, and Instantiate runs Awake first: waking one for a + // single frame drops a real trophy on the floor. + GameObject holder = new GameObject("WarVultureTrophy"); + holder.transform.SetParent(attach, false); + holder.SetActive(false); + + GameObject copy = Object.Instantiate(trophy, holder.transform); + copy.name = "model"; + copy.transform.localPosition = Vector3.zero; + copy.transform.localRotation = Quaternion.identity; + copy.transform.localScale = Vector3.one * WarVultureConfig.HandModelScale.Value; + + StripToMeshesOnly(copy); + + holder.SetActive(true); + } + + /// + /// The trophy reduced to nothing but its shape. + /// + /// This used to be a BLACKLIST - scripts, colliders, rigidbodies, ZNetView - and it let + /// through exactly what a blacklist always lets through: the things nobody thought to name. + /// A vanilla item prefab carries the sparkle that makes dropped loot findable in long grass, + /// and that lives in ParticleSystems, ParticleSystemRenderers and Lights. None of those is a + /// MonoBehaviour, so all of them survived, and the item glittered in the player's hand like + /// something they had just thrown away. + /// + /// So it is a whitelist now, the same shape as WarVultureVisual's: MeshFilter, + /// MeshRenderer, SkinnedMeshRenderer, Transform. Note it is deliberately NARROWER than the + /// mount's whitelist - "Renderer" would be wrong here, because ParticleSystemRenderer IS a + /// Renderer and it is half of what we are trying to be rid of. + /// + /// Passes, because Unity refuses to destroy a component another one still requires, and the + /// refusal only unblocks once the dependent is gone. + /// + private static void StripToMeshesOnly(GameObject copy) + { + for (int pass = 0; pass < 6; pass++) + { + bool destroyedSomething = false; + + foreach (Component component in copy.GetComponentsInChildren(true)) + { + if (component == null) continue; + if (component is Transform) continue; + if (component is MeshFilter) continue; + if (component is MeshRenderer) continue; + if (component is SkinnedMeshRenderer) continue; + + Object.DestroyImmediate(component); + + if (component == null) destroyedSomething = true; + } + + if (!destroyedSomething) break; + } + } + + private static Transform FindChild(Transform root, string name) + { + if (root.name == name) return root; + for (int i = 0; i < root.childCount; i++) + { + Transform found = FindChild(root.GetChild(i), name); + if (found != null) return found; + } + return null; + } + + public static bool IsWarVulture(ItemDrop.ItemData item) + { + return item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == PrefabName; + } + + /// + /// True when a cost being asked about belongs to this item. + /// + /// The fallback on the equipped weapon is necessary rather than belt-and-braces: the cost + /// getters are called from Attack.Start and m_weapon is not guaranteed to be assigned yet. + /// It is only consulted when m_weapon is null, so a creature's own attack cannot be zeroed + /// just because the player happens to be holding the trophy at the time. + /// + public static bool IsWarVultureContext(ItemDrop.ItemData weapon) + { + if (weapon != null) return IsWarVulture(weapon); + + Player local = Player.m_localPlayer; + return local != null && IsWarVulture(local.GetCurrentWeapon()); + } + } + + /// + /// The click. Attack.OnAttackTrigger is used rather than Attack.Start because it takes NO + /// parameters - its signature cannot drift - and it fires when the animation reaches its + /// release point, which is when a summon should land. + /// + /// A Prefix returning FALSE, so for this item vanilla's attack-trigger code never runs at all. + /// m_weapon and m_character are private on Attack and arrive through Harmony's triple + /// underscore injection, which is checked at patch time: a rename becomes a startup error + /// instead of a silent null on every click. + /// + [HarmonyPatch(typeof(Attack), "OnAttackTrigger")] + public static class WarVultureCastPatch + { + public static bool Prefix(ItemDrop.ItemData ___m_weapon, Humanoid ___m_character) + { + if (!WarVultureItem.IsWarVulture(___m_weapon)) return true; + + // Still returns false while riding, so vanilla's trigger never runs - but the dismount + // is NOT taken from here. In the saddle this event is unreliable: the cast clip loses + // to the sitting pose before its event fires. WarVultureMount reads the button itself. + WarVultureMount.Toggle(___m_character as Player); + return false; + } + } + + /// + /// The item costs nothing, guaranteed. + /// + /// Zeroing the fields on the clone ought to be enough by every reading of the game's own code. + /// On the Skadi staff the cost came back in game anyway, which means the write to a clone's + /// SharedData does not survive something - so relying on it alone is relying on a mechanism + /// already observed to fail. These three getters are the single funnel every cost check flows + /// through: Attack.Start asks them before it will start, and the tooltip asks them for what to + /// print. All three are private and take no parameters, so they are addressed by name. + /// + [HarmonyPatch] + public static class WarVultureFreeCastPatch + { + [HarmonyTargetMethods] + private static System.Collections.Generic.IEnumerable TargetMethods() + { + yield return AccessTools.Method(typeof(Attack), "GetAttackEitr"); + yield return AccessTools.Method(typeof(Attack), "GetAttackHealth"); + yield return AccessTools.Method(typeof(Attack), "GetAttackStamina"); + } + + [HarmonyPostfix] + private static void Postfix(ItemDrop.ItemData ___m_weapon, ref float __result) + { + if (__result == 0f) return; + if (!WarVultureItem.IsWarVultureContext(___m_weapon)) return; + + __result = 0f; + } + } +} diff --git a/JotunnModStub/WarVulture/WarVultureMount.cs b/JotunnModStub/WarVulture/WarVultureMount.cs new file mode 100644 index 0000000..027a540 --- /dev/null +++ b/JotunnModStub/WarVulture/WarVultureMount.cs @@ -0,0 +1,389 @@ +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The ride itself. Lives on the local player while they are mounted, and nowhere else. + /// + /// THE ONE IDEA THIS FILE IS BUILT ON: the PLAYER flies, the bird is how it looks from outside. + /// That inversion is what makes a flying mount a small feature instead of a large one - it + /// removes the ZDO owner problem, the AI, the taming, the passivity and the whole saddle, all + /// of which cost a session each the first time round. The flight itself is the Aswid's bat + /// form: Player.m_debugFly, and nothing else. + /// + /// THE ONE TRAP: a real attach and a self-driven player are enemies in vanilla, and the game + /// says so twice. + /// - Player.SetControls: if the player is attached, has no doodad controller and presses ANY + /// movement key, vanilla calls AttachStop. That is how you stand up from a chair. + /// - Player.SetDoodadControlls: giving it a doodad controller instead is worse - it zeroes + /// moveDir, run and autoRun unconditionally after handing them to the controller, so the + /// rider could not move at all. + /// Both were read out of the assembly, not guessed. The way through is the third door: the + /// attach point is the PLAYER'S OWN TRANSFORM, so Player.UpdateAttach - which copies position + /// and rotation from the attach point every frame, and would otherwise nail the rider in place + /// - provably copies the player onto themselves and does nothing. The bird hangs off the + /// player, not the other way round. The one remaining conflict, the AttachStop above, is + /// switched off for the duration in WarVultureControlsPatch. + /// + /// What the attach is still there FOR, after all that, is the pose: AttachStart ends with + /// m_zanim.SetBool(attachAnimation, true), and ZSyncAnimation replicates it - so every other + /// player sees the rider sitting, for free, with no code of ours involved. + /// + public class WarVultureMount : MonoBehaviour + { + /// The ZDO flag other clients watch to know they should draw a bird under this player. + public const string MountedKey = "WarVulture_Mounted"; + + private const string Label = "WarVulture"; + private const string HolderName = "WarVultureMountModel"; + + /// How long after the summon a click is ignored, so one press cannot do both. + private const float ClickGuardSeconds = 0.6f; + + /// The one live mount. There is at most one: this is the local player's own ride. + public static WarVultureMount Active { get; private set; } + + private Player player; + private WarVultureRig rig; + private Transform seat; + private WarVultureHud hud; + + private float wind; // seconds of full speed left in the bird + private bool landing; // dismount asked for; coming down before it takes effect + private float landingStartedAt; + private float summonedAt; + + // ---------------------------------------------------------------- public surface + + public static bool IsRiding(Player candidate) + { + return Active != null && candidate != null && Active.player == candidate; + } + + /// Fraction of the bird's wind left, for the bar. 1 = fresh, 0 = spent. + public float WindFraction + { + get + { + float max = Mathf.Max(0.01f, WarVultureConfig.SprintSeconds.Value); + return Mathf.Clamp01(wind / max); + } + } + + /// + /// The SUMMON, and only the summon. Called from WarVultureCastPatch, which has already + /// established that the thing being swung is ours and that the player is not already up. + /// + /// The dismount used to come through here too, and it did not work: the click fires + /// Attack.OnAttackTrigger, which the game raises from an animation event partway through + /// the cast clip - and in the saddle that clip loses to the sitting pose before it ever + /// gets there. The rider was trapped in the air with a click that did nothing. The dismount + /// is now read straight off the button in Update, where no animation can swallow it. + /// + public static void Toggle(Player caster) + { + if (caster == null || caster != Player.m_localPlayer) return; + if (Active != null && Active.player == caster) return; + + Summon(caster); + } + + /// + /// The dismount button, read from the device rather than from the animation. + /// + /// RaceInput.Allowed is the same gate every ability in this mod uses, and it is here for a + /// reason worth remembering: it reads Player.TakeInput, which is FALSE while the console is + /// open. A dismount that "does not work" during a test session is usually the console. + /// + private static bool DismountPressed() + { + if (!RaceInput.Allowed) return false; + return ZInput.GetButtonDown("Attack") || ZInput.GetButtonDown("JoyAttack"); + } + + // ---------------------------------------------------------------- summon + + private static void Summon(Player rider) + { + string race = null; + if (rider.m_customData != null) rider.m_customData.TryGetValue("Race", out race); + + if (!WarVultureConfig.RaceAllowed(race)) + { + rider.Message(MessageHud.MessageType.Center, "The bird does not know you."); + return; + } + + if (!WarVultureVisual.Ready) + { + rider.Message(MessageHud.MessageType.Center, "The vulture does not answer."); + Jotunn.Logger.LogWarning($"[{Label}] Call refused: the stripped model template was never built, " + + "so there is no bird to show. The reason is logged at startup - and " + + "refusing is deliberate, because the alternative is putting an unstripped " + + "creature prefab in the world."); + return; + } + + ZNetView nview = rider.GetComponent(); + if (nview == null || !nview.IsValid()) + { + Jotunn.Logger.LogWarning($"[{Label}] Call refused: the player has no valid ZNetView yet, so " + + "the flight state could not be published and no one else would see " + + "the bird."); + return; + } + + WarVultureMount mount = rider.gameObject.AddComponent(); + mount.player = rider; + mount.Begin(nview); + } + + private void Begin(ZNetView nview) + { + Active = this; + summonedAt = Time.time; + wind = WarVultureConfig.SprintSeconds.Value; + + // No lift, and that is the point: the rider is not raised above anything. The bird is + // moved so that its BACK BONE arrives under the rider, every frame, in WarVultureRig. + rig = WarVultureVisual.Spawn(player.transform, HolderName); + Seat(); + SetFlying(nview, true); + nview.GetZDO().Set(MountedKey, true); + + if (WarVultureConfig.ShowStaminaBar.Value) hud = WarVultureHud.Create(this); + } + + /// + /// The attach, and the reason it is harmless: the seat is a child of the player sitting + /// exactly on the player's own origin, so UpdateAttach's every-frame "put the rider on the + /// attach point" is the identity. + /// + /// The pose string is READ from the lox's own Sadle rather than typed from memory - the + /// same rule as prefab names, applied to an animation. + /// + /// hideWeapons is false on purpose: hiding the hand items unequips them, and the item in + /// that hand is the only way back down. + /// + private void Seat() + { + seat = new GameObject("WarVultureSeat").transform; + seat.SetParent(player.transform, false); + seat.localPosition = Vector3.zero; + seat.localRotation = Quaternion.identity; + + player.AttachStart(seat, null, false, false, false, ReadSaddlePose(), Vector3.zero, null); + } + + private static string ReadSaddlePose() + { + GameObject lox = PrefabManager.Cache.GetPrefab("Lox"); + Sadle sadle = lox != null ? lox.GetComponentInChildren(true) : null; + if (sadle != null && !string.IsNullOrEmpty(sadle.m_attachAnimation)) return sadle.m_attachAnimation; + + Jotunn.Logger.LogWarning($"[{Label}] Could not read the lox saddle's attach animation; " + + "falling back to 'attach_chair'. The rider may sit oddly."); + return "attach_chair"; + } + + // ---------------------------------------------------------------- per frame + + private void Update() + { + if (player == null || player != Player.m_localPlayer) { Dismount(); return; } + if (player.IsDead()) { Dismount(); return; } + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) + { + // Not an ordinary way down: the rider's own networking went away mid-flight, so it + // is worth a line even though the dismount itself is silent. + Jotunn.Logger.LogWarning($"[{Label}] The rider's ZNetView went away mid-flight; dismounting."); + Dismount(); + return; + } + + // Held on every frame rather than set once: the same thing BatFormBehavior does, for + // the same reason - anything else in the game (or in this mod) that clears debug fly + // would otherwise drop the rider out of the sky without a word. + SetFlying(nview, true); + + DriveAnimator(); + + // The guard is not superstition: the summoning click is still physically down on the + // frame the mount is created, and without it the bird would be called and dismissed by + // the same press. + if (Time.time - summonedAt > ClickGuardSeconds && DismountPressed()) + { + // A second click during the descent lets go there and then. + if (landing) Dismount(); + else BeginLanding(); + return; + } + + if (landing) UpdateLanding(); + + if (hud != null) hud.Refresh(); + } + + private void DriveAnimator() + { + if (rig == null) return; + + Vector3 velocity = player.GetVelocity(); + rig.Drive(new Vector3(velocity.x, 0f, velocity.z).magnitude); + } + + /// + /// The descent. The rider's own controls are not disabled - they are simply overruled in + /// ApplyFlight, which writes the velocity last and therefore wins. + /// + private void BeginLanding() + { + landing = true; + landingStartedAt = Time.time; + player.Message(MessageHud.MessageType.Center, "The vulture spirals down."); + } + + private void UpdateLanding() + { + Vector3 position = player.transform.position; + + float floor = -10000f; + if (ZoneSystem.instance != null) + { + // Over open water the solid height is the seabed, which would mean a long swim + // down. The surface is the floor there. + floor = Mathf.Max(ZoneSystem.instance.GetSolidHeight(position), ZoneSystem.instance.m_waterLevel); + } + + if (position.y - floor <= 0.6f) { Dismount(); return; } + + // A descent that never ends is worse than a hard landing: if the ground cannot be + // found at all, let go anyway rather than trap the rider in a falling animation. + if (Time.time - landingStartedAt > 20f) + { + Jotunn.Logger.LogWarning($"[{Label}] The descent found no ground in 20s; letting go anyway."); + Dismount(); + } + } + + // ---------------------------------------------------------------- flight, called from the physics step + + /// + /// Called from WarVultureFlightPatch, right after vanilla's UpdateDebugFly has written the + /// rider's velocity for this physics step. + /// + /// Speed is applied as a FACTOR on what vanilla just computed rather than as a fresh + /// velocity, and that is deliberate: vanilla lerps towards its target, so scaling the + /// result keeps every bit of its smoothing - the ramp up, the ease off, the standstill at + /// zero input - and only changes how fast the whole thing runs. Writing a velocity of our + /// own would have thrown all of that away. + /// + /// The wind is spent here, in the physics step, because this is the only place that knows + /// the rider is actually flying. + /// + public void ApplyFlight(bool runHeld, ref Vector3 currentVelocity, Rigidbody body) + { + float dt = Time.fixedDeltaTime; + + if (landing) + { + currentVelocity = Vector3.down * WarVultureConfig.LandingSpeed.Value; + if (body != null) body.linearVelocity = currentVelocity; + return; + } + + bool sprinting = runHeld && wind > 0f && currentVelocity.sqrMagnitude > 0.01f; + + if (sprinting) + { + wind = Mathf.Max(0f, wind - dt); + if (wind <= 0f) + { + player.Message(MessageHud.MessageType.Center, "The vulture settles into a glide."); + } + } + else if (wind < WarVultureConfig.SprintSeconds.Value) + { + // Refills in the air the moment the run key is released. A vulture can stay up for + // hours; what it cannot do is keep stooping. + float perSecond = WarVultureConfig.SprintSeconds.Value / + Mathf.Max(0.01f, WarVultureConfig.RechargeSeconds.Value); + wind = Mathf.Min(WarVultureConfig.SprintSeconds.Value, wind + perSecond * dt); + } + + float wanted = sprinting ? WarVultureConfig.SprintSpeed.Value : WarVultureConfig.CruiseSpeed.Value; + + // What vanilla aimed for this step: m_debugFlySpeed, times 2.5 when the run key is + // down. Read from the game rather than assumed, so a Valheim retune cannot silently + // double our speeds. + float vanilla = WarVultureFlightPatch.DebugFlySpeed * (runHeld ? 2.5f : 1f); + if (vanilla <= 0.01f) return; + + currentVelocity *= wanted / vanilla; + if (body != null) body.linearVelocity = currentVelocity; + } + + // ---------------------------------------------------------------- dismount + + private void Dismount() + { + Player rider = player; + + if (rider != null) + { + ZNetView nview = rider.GetComponent(); + if (nview != null && nview.IsValid()) + { + SetFlying(nview, false); + nview.GetZDO().Set(MountedKey, false); + } + else + { + // No ZDO to write to, but the local field still has to come off or the player + // keeps flying on foot. + Traverse.Create(rider).Field("m_debugFly").SetValue(false); + } + + rider.AttachStop(); + } + + if (hud != null) { hud.Dispose(); hud = null; } + // Destroy, never DestroyImmediate: a dismount can be a click, which arrives from an + // animation event callback where immediate destruction is refused. The whole reason + // this feature had a live vulture in it once. + if (rig != null) { Destroy(rig.gameObject); rig = null; } + if (seat != null) { Destroy(seat.gameObject); seat = null; } + + if (Active == this) Active = null; + + Destroy(this); + } + + private void OnDestroy() + { + // Belt and braces for a component torn off by something other than Dismount (a scene + // change, a reload). Leaving debug fly on would be the worst possible parting gift. + if (Active != this) return; + Active = null; + + if (player == null) return; + Traverse.Create(player).Field("m_debugFly").SetValue(false); + } + + /// + /// Both halves of debug fly. The field is what the local rider's own physics reads; the ZDO + /// var is what every OTHER client reads (Character.IsDebugFlying consults the ZDO when it + /// is not the owner). BatFormBehavior only ever wrote the field, which is why a bat looked + /// wrong to everyone else - this writes both. + /// + private void SetFlying(ZNetView nview, bool flying) + { + Traverse.Create(player).Field("m_debugFly").SetValue(flying); + nview.GetZDO().Set(ZDOVars.s_debugFly, flying); + } + } +} diff --git a/JotunnModStub/WarVulture/WarVulturePatches.cs b/JotunnModStub/WarVulture/WarVulturePatches.cs new file mode 100644 index 0000000..73bc532 --- /dev/null +++ b/JotunnModStub/WarVulture/WarVulturePatches.cs @@ -0,0 +1,193 @@ +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The one patch that makes a seated player able to fly. + /// + /// Player.SetControls opens with: if the player is attached and presses any movement key, and + /// there is no doodad controller, call AttachStop. That is vanilla's "stand up from the chair", + /// read straight out of the assembly - and against a rider who drives themselves it fires on + /// the first tap of W. + /// + /// Giving the game a doodad controller instead is not the way out: SetDoodadControlls zeroes + /// moveDir, run and autoRun unconditionally afterwards, so the rider would stay attached and + /// be unable to move. Both doors are shut, which is why this one is a patch. + /// + /// So m_attached is lifted for the duration of SetControls and put straight back. Nothing else + /// in that method reads it (checked instruction by instruction), and everything else in the + /// game still sees an attached player - including ZSyncAnimation, which is what keeps the + /// sitting pose on everyone else's screen. + /// + /// AND THE SECOND HALF, added after the first flight. Lifting m_attached hands the rider back + /// every action a standing player has, and three of them have no business happening in a + /// saddle: jump, dodge and crouch each played their own animation for half a second before the + /// sitting pose snapped back, which is what a rider trying to gain height actually saw. + /// + /// They are suppressed here, at the source, and it costs nothing that was wanted: vanilla's + /// UpdateDebugFly does NOT read these arguments. It reads ZInput directly - GetButton("Jump") + /// to climb and KeyCode.LeftControl to descend - so taking them out of SetControls removes the + /// jump and keeps the climb. Same for the click: while riding, the dismount is read straight + /// off ZInput in WarVultureMount, so the attack is suppressed here rather than left to fight + /// the saddle pose for an animation it was never going to win. + /// + /// It costs one boolean read per frame when nobody is riding. + /// + [HarmonyPatch(typeof(Player), "SetControls")] + public static class WarVultureControlsPatch + { + public static void Prefix(Player __instance, ref bool ___m_attached, + ref bool attack, ref bool attackHold, + ref bool secondaryAttack, ref bool secondaryAttackHold, + ref bool jump, ref bool crouch, ref bool dodge, + out bool __state) + { + __state = false; + if (!WarVultureMount.IsRiding(__instance)) return; + + attack = false; + attackHold = false; + secondaryAttack = false; + secondaryAttackHold = false; + jump = false; + crouch = false; + dodge = false; + + if (!___m_attached) return; + + ___m_attached = false; + __state = true; + } + + public static void Postfix(ref bool ___m_attached, bool __state) + { + if (__state) ___m_attached = true; + } + } + + /// + /// The speed of the ride, and the bird's wind. + /// + /// Character.UpdateDebugFly has just written this physics step's velocity when this runs, so + /// this is the last word on it. The mount scales what vanilla computed rather than replacing + /// it - see WarVultureMount.ApplyFlight for why that keeps the flight feeling smooth. + /// + /// m_currentVel, m_body and m_run are all private on Character and arrive through Harmony's + /// field injection, which is verified when the patch is applied: a Valheim rename becomes a + /// startup error instead of a mount that silently stops working. + /// + [HarmonyPatch(typeof(Character), "UpdateDebugFly")] + public static class WarVultureFlightPatch + { + private static readonly FieldInfo DebugFlySpeedField = AccessTools.Field(typeof(Character), "m_debugFlySpeed"); + private static bool warnedAboutSpeedField; + + /// + /// Vanilla's own debug fly speed, read live rather than cached: the game exposes it as a + /// static that can be retuned, and a stale copy here would quietly scale the whole ride. + /// + public static float DebugFlySpeed + { + get + { + if (DebugFlySpeedField != null) return System.Convert.ToSingle(DebugFlySpeedField.GetValue(null)); + + if (!warnedAboutSpeedField) + { + warnedAboutSpeedField = true; + Jotunn.Logger.LogWarning("[WarVulture] Character.m_debugFlySpeed could not be found, so the " + + "mount's speeds are being scaled against an assumed 10 m/s. If the " + + "bird flies wrong, this line is why."); + } + return 10f; + } + } + + public static void Postfix(Character __instance, ref Vector3 ___m_currentVel, Rigidbody ___m_body, bool ___m_run) + { + WarVultureMount mount = WarVultureMount.Active; + if (mount == null) return; + + Player player = __instance as Player; + if (player == null || !WarVultureMount.IsRiding(player)) return; + + mount.ApplyFlight(___m_run, ref ___m_currentVel, ___m_body); + } + } + + /// + /// Gives every player a watcher, so a rider on someone else's screen gets a bird under them. + /// + /// A second Player.Awake postfix alongside the one in ZdoVisualSync rather than an edit to it: + /// that file belongs to the shared race visuals, this belongs to the vulture, and Harmony is + /// perfectly happy to hold both. + /// + [HarmonyPatch(typeof(Player), "Awake")] + public static class WarVulturePlayerAwakePatch + { + public static void Postfix(Player __instance) + { + if (__instance.GetComponent() == null) + { + __instance.gameObject.AddComponent(); + } + } + } + + /// + /// The bird as everyone ELSE sees it. + /// + /// The rider's own client draws its bird from WarVultureMount; this draws one for every other + /// player who has the flag set on their ZDO. It never touches flight, attachment or input - + /// remote players are moved by their own owner and the pose replicates itself through + /// ZSyncAnimation, so there is nothing here but a model that appears and disappears. + /// + public class WarVultureRemoteVisual : MonoBehaviour + { + private const string HolderName = "WarVultureRemoteModel"; + + private Player player; + private WarVultureRig rig; + + private void Awake() + { + player = GetComponent(); + } + + private void Update() + { + if (player == null) return; + + // The local rider is drawn by their own mount; two birds is one too many. + if (player == Player.m_localPlayer) { Hide(); return; } + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) { Hide(); return; } + + bool mounted = nview.GetZDO().GetBool(WarVultureMount.MountedKey, false) && !player.IsDead(); + + if (mounted && rig == null) rig = WarVultureVisual.Spawn(player.transform, HolderName); + else if (!mounted && rig != null) Hide(); + + if (rig != null) + { + Vector3 velocity = player.GetVelocity(); + rig.Drive(new Vector3(velocity.x, 0f, velocity.z).magnitude); + } + } + + private void Hide() + { + if (rig == null) return; + Destroy(rig.gameObject); + rig = null; + } + + private void OnDestroy() + { + Hide(); + } + } +} diff --git a/JotunnModStub/WarVulture/WarVultureVisual.cs b/JotunnModStub/WarVulture/WarVultureVisual.cs new file mode 100644 index 0000000..cf42a91 --- /dev/null +++ b/JotunnModStub/WarVulture/WarVultureVisual.cs @@ -0,0 +1,376 @@ +using UnityEngine; +using Jotunn.Managers; + +namespace RacesOfValheim +{ + /// + /// The bird's body: built dead once, then copied. + /// + /// WHY IT IS BUILT AT REGISTRATION AND NOT AT THE SUMMON. The first version borrowed the model + /// the way ModelBorrow does it - instantiate into an inactive holder, then DestroyImmediate + /// everything that is not a renderer. That is correct at registration time and wrong at summon + /// time, and the game says so out loud: + /// + /// Destroying components immediately is not permitted during physics trigger/contact, + /// animation event callbacks, rendering callbacks or OnValidate. + /// + /// The summon runs from Attack.OnAttackTrigger, which the game calls from CharacterAnimEvent - + /// an animation event callback. Every DestroyImmediate was refused, the model kept its + /// Character, its MonsterAI and its ZNetView, and the moment the holder was switched on Awake + /// ran and a real Ashlands predator was born under the player. A live rigidbody ignores its + /// parent transform, so it flew off. Eleven refusal lines sat in the log directly above the + /// "Borrowed 'Volture'" line, which is exactly how it was found. + /// + /// So: the stripping happens once, during CreateAllModAssets, where DestroyImmediate is legal. + /// What is kept is a TEMPLATE - an inactive, script-free carcass held in DontDestroyOnLoad - + /// and a summon is a plain Instantiate of it. Instantiate is allowed in any context. + /// + /// And it is CHECKED, not assumed. If a single MonoBehaviour survives the strip, the template + /// is thrown away and the item refuses to summon. A bird that does not appear is a bug report; + /// a bird that appears with an AI is a predator in the player's world with a saved ZDO. + /// + public static class WarVultureVisual + { + private const string SourcePrefab = "Volture"; + private const string Label = "WarVulture"; + + // The three parameters DrakeFormBehavior drives, which is the only animated borrowed + // creature in this mod known to look right. + private const string FlyingParam = "flying"; + private const string GroundParam = "onGround"; + private const string SpeedParam = "forward_speed"; + + private static GameObject template; + private static float templateSize = 1f; + + public static bool Ready => template != null; + + // ---------------------------------------------------------------- the template + + /// + /// Called once from WarVultureItem.Register, i.e. from CreateAllModAssets, i.e. from a + /// context where components may be destroyed immediately. + /// + public static void BuildTemplate() + { + if (template != null) return; + + GameObject source = PrefabManager.Cache.GetPrefab(SourcePrefab); + if (source == null) + { + Jotunn.Logger.LogWarning($"[{Label}] No '{SourcePrefab}' prefab to copy; the mount will refuse " + + "to summon rather than put an invisible rider in the sky."); + return; + } + + // Inactive BEFORE the Instantiate - the one line that keeps Awake from running on a + // live predator. Everything else here depends on it. + GameObject root = new GameObject("WarVultureTemplate"); + root.SetActive(false); + Object.DontDestroyOnLoad(root); + + GameObject copy = Object.Instantiate(source, root.transform); + copy.name = "VoltureModel"; + copy.transform.localPosition = Vector3.zero; + copy.transform.localRotation = Quaternion.identity; + copy.transform.localScale = Vector3.one; + + int refused = StripToRenderers(copy); + + int alive = CountBehaviours(copy); + if (alive > 0) + { + Jotunn.Logger.LogError($"[{Label}] {alive} script(s) survived the strip on '{SourcePrefab}' " + + $"({refused} destroy calls were refused). The template is being thrown " + + "away and the War Vulture will not summon - a half-stripped creature " + + "prefab is a live animal, not a model."); + Object.DestroyImmediate(root); + return; + } + + PrepareAnimator(copy); + templateSize = Mathf.Max(0.01f, LargestDimension(copy)); + template = copy; + } + + /// + /// Everything that is not geometry or animation, removed in passes. + /// + /// Passes rather than one sweep because Unity refuses to destroy a component another + /// component still requires, and the refusal is silent as far as the caller is concerned - + /// it logs and moves on. Repeating until a pass changes nothing lets a dependency chain + /// unwind in whatever order it needs to. + /// + /// Returns how many destroy calls were refused on the last pass, purely so the failure + /// above can say something useful. + /// + private static int StripToRenderers(GameObject copy) + { + int stubborn = 0; + + for (int pass = 0; pass < 6; pass++) + { + bool destroyedSomething = false; + stubborn = 0; + + foreach (Component component in copy.GetComponentsInChildren(true)) + { + if (component == null) continue; + if (IsKept(component)) continue; + + Object.DestroyImmediate(component); + + if (component == null) destroyedSomething = true; + else stubborn++; + } + + if (!destroyedSomething) break; + } + + return stubborn; + } + + /// + /// The whitelist. Anything not on it goes - colliders, rigidbodies, ZNetView, Character, + /// MonsterAI, the lot. Keeping a list of what to KEEP rather than a list of what to remove + /// is the difference between a model and an animal: a new component in a future Valheim + /// patch is removed by default instead of surviving by omission. + /// + /// The two MESH renderers by name rather than Renderer as a family, which looks like + /// pedantry and is not: ParticleSystemRenderer is a Renderer, and "keep every Renderer" is + /// how the trophy in the player's hand ended up carrying the sparkle vanilla puts on + /// dropped loot. Meshes and the animator that poses them - nothing else. + /// + private static bool IsKept(Component component) + { + return component is Transform + || component is MeshFilter + || component is MeshRenderer + || component is SkinnedMeshRenderer + || component is Animator + || component is LODGroup; + } + + private static int CountBehaviours(GameObject copy) + { + int alive = 0; + foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) + { + if (behaviour != null) alive++; + } + return alive; + } + + /// + /// Three settings, each preventing one specific failure rather than tidying anything. + /// + /// applyRootMotion: clips authored to walk a creature through the world would walk the + /// model out from under its rider. + /// + /// cullingMode: the default stops animating when no renderer is on screen, and this bird + /// lives half off the bottom of the screen - a frozen mid-flap reads as a bug. + /// + /// fireEvents: the flight clips carry animation events aimed at CharacterAnimEvent, which + /// has just been stripped off. Left on, every wingbeat would log "has no receiver". + /// + private static void PrepareAnimator(GameObject copy) + { + Animator animator = copy.GetComponentInChildren(true); + if (animator == null) + { + Jotunn.Logger.LogWarning($"[{Label}] The stripped '{SourcePrefab}' has no Animator, so the bird " + + "will hang in its bind pose - wings out, legs straight."); + return; + } + + animator.applyRootMotion = false; + animator.cullingMode = AnimatorCullingMode.AlwaysAnimate; + animator.fireEvents = false; + animator.enabled = true; + } + + // ---------------------------------------------------------------- summoning a copy + + /// + /// Hangs a copy of the template under a rider and returns the rig that keeps it there. + /// Null when the template could not be built, which the caller must treat as "do not + /// summon" rather than "summon an invisible bird". + /// + public static WarVultureRig Spawn(Transform rider, string holderName) + { + if (template == null || rider == null) return null; + + GameObject holder = new GameObject(holderName); + holder.transform.SetParent(rider, false); + holder.transform.localPosition = Vector3.zero; + holder.transform.localRotation = Quaternion.identity; + + GameObject model = Object.Instantiate(template, holder.transform); + model.name = "model"; + model.transform.localPosition = Vector3.zero; + model.transform.localRotation = Quaternion.identity; + model.transform.localScale = Vector3.one * (WarVultureConfig.MountSize.Value / templateSize); + model.SetActive(true); + + WarVultureRig rig = holder.AddComponent(); + rig.Bind(rider, model); + return rig; + } + + // ---------------------------------------------------------------- animation + + /// + /// One frame of flight, told to the animator. Any parameter this controller does not have + /// is skipped, so a Valheim animator rename costs a stiff-looking bird rather than a wall + /// of errors every frame. + /// + public static void Drive(Animator animator, float forwardSpeed) + { + if (animator == null || animator.runtimeAnimatorController == null) return; + + if (Has(animator, FlyingParam, AnimatorControllerParameterType.Bool)) animator.SetBool(FlyingParam, true); + if (Has(animator, GroundParam, AnimatorControllerParameterType.Bool)) animator.SetBool(GroundParam, false); + if (Has(animator, SpeedParam, AnimatorControllerParameterType.Float)) animator.SetFloat(SpeedParam, forwardSpeed); + } + + private static bool Has(Animator animator, string name, AnimatorControllerParameterType type) + { + foreach (AnimatorControllerParameter parameter in animator.parameters) + { + if (parameter.type == type && parameter.name == name) return true; + } + return false; + } + + // ---------------------------------------------------------------- the seat bone + + /// + /// The bone the rider sits on. + /// + /// A bone rather than an offset in metres, because that is the difference between sitting + /// on the bird and hovering above it: the back moves with every wingbeat, and a fixed + /// offset can only ever be right on one frame of the animation. + /// + /// The name is guessed from a priority list and can be overridden in config, because the + /// rig's bone names are not knowable from outside the game. The automatic pick was the right + /// one in play, so the startup dump that found it has been retired. + /// + public static Transform FindSeatBone(GameObject model) + { + if (model == null) return null; + + Transform[] bones = model.GetComponentsInChildren(true); + + string wanted = WarVultureConfig.SeatBone.Value; + if (!string.IsNullOrEmpty(wanted)) + { + Transform named = Match(bones, wanted); + if (named != null) return named; + + Jotunn.Logger.LogWarning($"[{Label}] No bone matching '{wanted}' on the vulture; falling back " + + "to the automatic pick. The bone list is in the log from startup."); + } + + // Deliberately in this order: the back of a bird is its spine and chest, and the hips + // and root are last-ditch so that SOMETHING is anchored rather than nothing. + foreach (string candidate in new[] { "spine", "chest", "back", "torso", "body", "pelvis", "hip", "root" }) + { + Transform found = Match(bones, candidate); + if (found != null) return found; + } + + return null; + } + + /// + /// Last match rather than first, on purpose: rigs number their spines outward from the + /// hips, so the last "spine" is the one furthest along the back - which is where a saddle + /// goes, not where the tail joins. + /// + private static Transform Match(Transform[] bones, string needle) + { + Transform best = null; + foreach (Transform bone in bones) + { + if (bone.name.IndexOf(needle, System.StringComparison.OrdinalIgnoreCase) >= 0) best = bone; + } + return best; + } + + // ---------------------------------------------------------------- measuring + + private static float LargestDimension(GameObject model) + { + bool any = false; + Bounds bounds = new Bounds(); + + foreach (Renderer renderer in model.GetComponentsInChildren(true)) + { + Mesh mesh = renderer is SkinnedMeshRenderer skinned + ? skinned.sharedMesh + : renderer.GetComponent()?.sharedMesh; + if (mesh == null) continue; + + Bounds local = mesh.bounds; + Matrix4x4 toModel = model.transform.worldToLocalMatrix * renderer.transform.localToWorldMatrix; + + for (int corner = 0; corner < 8; corner++) + { + Vector3 point = toModel.MultiplyPoint3x4(local.center + new Vector3( + (corner & 1) == 0 ? -local.extents.x : local.extents.x, + (corner & 2) == 0 ? -local.extents.y : local.extents.y, + (corner & 4) == 0 ? -local.extents.z : local.extents.z)); + + if (!any) { bounds = new Bounds(point, Vector3.zero); any = true; } + else bounds.Encapsulate(point); + } + } + + return any ? Mathf.Max(bounds.size.x, Mathf.Max(bounds.size.y, bounds.size.z)) : 1f; + } + } + + /// + /// Keeps the bird under its rider, one bone at a time. + /// + /// In LateUpdate, after the animator has posed the skeleton for this frame, the whole model is + /// slid so that the seat bone lands exactly on the rider's own origin. That is what "sitting on + /// the bird's back" means as a piece of code, and it is why there is no height offset anywhere + /// in this feature any more: the back tells us where it is, every frame, including while it + /// rises and falls with the wingbeat. + /// + /// Shared by the rider's own copy and by the copy other players see, so the bird cannot sit in + /// two different places depending on who is looking. + /// + public class WarVultureRig : MonoBehaviour + { + private Transform rider; + private Transform model; + private Transform seatBone; + private Animator animator; + + public void Bind(Transform rider, GameObject model) + { + this.rider = rider; + this.model = model.transform; + seatBone = WarVultureVisual.FindSeatBone(model); + animator = model.GetComponentInChildren(true); + } + + public void Drive(float forwardSpeed) + { + WarVultureVisual.Drive(animator, forwardSpeed); + } + + private void LateUpdate() + { + if (rider == null || model == null) return; + + Vector3 seat = rider.position + rider.rotation * new Vector3( + 0f, WarVultureConfig.SeatNudgeY.Value, WarVultureConfig.SeatNudgeZ.Value); + + if (seatBone != null) model.position += seat - seatBone.position; + else model.position = seat; + } + } +} From 0294d6a71b2b64019717bc19fd07275bd0bc94fa Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Tue, 11 Aug 2026 07:55:23 +0200 Subject: [PATCH 006/290] feat(skadi): remove Skadis Nokkel and the hidden hollow The staff opened a pair of client-side portals into a claimed troll cave, and that whole mechanism broke in multiplayer. The two Harmony patches it needed were the sharpest edge: SkadiNokkelCastPatch prefixed Attack.OnAttackTrigger and SkadiNokkelFreeCastPatch postfixed the three cost getters, so every attack by every character in the game went through mod code before being filtered. Nothing is put in its place, on purpose. The Crystal Golem is the Skadi's station now and the balance was already settled around it, and the part of the hollow that was actually worth having - Skadi and Trol building inside any troll cave - lives in RaceCaveBuilding and is untouched. Removed: SkadiNokkel.cs, SkadiHollow.cs, SkadiHollowPortal.cs, the "Skadi - Hidden Hollow" config section, the HOLLOW_COOLDOWN_SE status effect, the F8 dump, and the "Nothing takes root here" rule in PieceDensityLimit, which existed only for the hollow. Kept: SkadiIce, which the staff's file happened to host but the Frost Heart and the golem both use - moved to its own file. Greater Frost Heart stays on sale from the Fenring_Cultist at 1500 as it was. Co-Authored-By: Claude Opus 5 --- .../Factions/FactionMerchantCatalog.cs | 2 +- JotunnModStub/PieceDensityLimit.cs | 21 - JotunnModStub/RacesOfValheim.csproj | 7 +- JotunnModStub/Skadi/SkadiConfig.cs | 16 - JotunnModStub/Skadi/SkadiHollow.cs | 256 ----------- JotunnModStub/Skadi/SkadiHollowPortal.cs | 234 ----------- JotunnModStub/Skadi/SkadiIce.cs | 55 +++ JotunnModStub/Skadi/SkadiNokkel.cs | 396 ------------------ JotunnModStub/Skadi/SkadiRace.cs | 18 +- JotunnModStub/WarVulture/WarVultureItem.cs | 5 +- 10 files changed, 67 insertions(+), 943 deletions(-) delete mode 100644 JotunnModStub/Skadi/SkadiHollow.cs delete mode 100644 JotunnModStub/Skadi/SkadiHollowPortal.cs create mode 100644 JotunnModStub/Skadi/SkadiIce.cs delete mode 100644 JotunnModStub/Skadi/SkadiNokkel.cs diff --git a/JotunnModStub/Factions/FactionMerchantCatalog.cs b/JotunnModStub/Factions/FactionMerchantCatalog.cs index 2847b82..440aef4 100644 --- a/JotunnModStub/Factions/FactionMerchantCatalog.cs +++ b/JotunnModStub/Factions/FactionMerchantCatalog.cs @@ -194,7 +194,7 @@ namespace RacesOfValheim Items = new List { new CatalogEntry("JuteRed", 2), - new CatalogEntry("GreaterFrostHeart", 1500), // gates the Skadi's hidden hollow + new CatalogEntry("GreaterFrostHeart", 1500), // the Skadi's bought reagent new CatalogEntry("TrophyCultist", 1500), } }; diff --git a/JotunnModStub/PieceDensityLimit.cs b/JotunnModStub/PieceDensityLimit.cs index 076f246..ee01fe4 100644 --- a/JotunnModStub/PieceDensityLimit.cs +++ b/JotunnModStub/PieceDensityLimit.cs @@ -194,28 +194,7 @@ namespace RacesOfValheim { if (__instance != Player.m_localPlayer || __0 == null) return true; - if (!HollowAllowsPiece(__instance, __0)) return false; - return PieceDensityLimit.Allow(__instance, Utils.GetPrefabName(__0.gameObject), __1); } - - /// - /// "You may build in your hollow, but nothing takes root there." Rides along on this prefix - /// rather than adding a second one, which is the whole reason this class exists. - /// - /// Worth knowing that the refusal is about the MESSAGE, not about making the impossible - /// impossible: a Plant needs cultivated ground and a matching biome (Plant.m_needCultivated- - /// Ground, Plant.m_biome), and five kilometres above the sea there is no terrain to cultivate - /// and no biome to match, so a seed would have failed anyway - with a vanilla error that says - /// nothing useful about why. - /// - private static bool HollowAllowsPiece(Player player, Piece piece) - { - if (!SkadiHollow.IsInside(player)) return true; - if (piece.GetComponentInChildren(true) == null) return true; - - player.Message(MessageHud.MessageType.Center, "Nothing takes root here."); - return false; - } } } diff --git a/JotunnModStub/RacesOfValheim.csproj b/JotunnModStub/RacesOfValheim.csproj index 497541d..58ed010 100644 --- a/JotunnModStub/RacesOfValheim.csproj +++ b/JotunnModStub/RacesOfValheim.csproj @@ -34,9 +34,10 @@ ..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\assembly_valheim.dll - + ..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\SoftReferenceableAssets.dll diff --git a/JotunnModStub/Skadi/SkadiConfig.cs b/JotunnModStub/Skadi/SkadiConfig.cs index 7910560..81134c3 100644 --- a/JotunnModStub/Skadi/SkadiConfig.cs +++ b/JotunnModStub/Skadi/SkadiConfig.cs @@ -48,12 +48,6 @@ namespace RacesOfValheim // ─── Passive combat ────────────────────────────────────────────────── public static ConfigEntry BonusFrostDamagePerState; - // ─── Skadis Nokkel / the hidden hollow ─────────────────────────────── - public static ConfigEntry HollowCooldown; - public static ConfigEntry HollowPortalCloseDelay; - public static ConfigEntry HollowPortalSpawnDistance; - public static ConfigEntry HollowEntryHeight; - // ─── Dragon forms: scale ───────────────────────────────────────────── public static ConfigEntry DrakeScale; public static ConfigEntry ModerScale; @@ -108,16 +102,6 @@ namespace RacesOfValheim BonusFrostDamagePerState = config.Bind(combat, "Bonus Frost Damage Per State", 2f, new ConfigDescription("Flat frost damage added to every hit the player lands, multiplied by the current progression state.", new AcceptableValueRange(0f, 10f))); - const string hollow = "Skadi - Hidden Hollow"; - HollowCooldown = config.Bind(hollow, "Cooldown", 120f, - new ConfigDescription("Seconds between openings of the hollow. This is the only brake on Skadis Nokkel - it costs no stamina, eitr or health - and it never applies to LEAVING: stepping in and changing your mind must not lock you in.", new AcceptableValueRange(0f, 600f))); - HollowPortalCloseDelay = config.Bind(hollow, "Portal Close Delay", 5f, - new ConfigDescription("Seconds the portal pair lingers after the player comes back out. Until then both ends simply stand there - unlike the Trenta portal, this one has no lifetime of its own.", new AcceptableValueRange(0f, 60f))); - HollowPortalSpawnDistance = config.Bind(hollow, "Portal Spawn Distance", 2f, - new ConfigDescription("Metres in front of the player the outside end of the portal appears.", new AcceptableValueRange(0.5f, 10f))); - HollowEntryHeight = config.Bind(hollow, "Entry Height", 1f, - new ConfigDescription("Height above the claimed troll cave's own origin that the inner portal stands at. Raise it if arriving ever puts the player inside the ground.", new AcceptableValueRange(0f, 20f))); - const string spell = "Skadi - Cold Spell"; SpellStaminaCost = config.Bind(spell, "Stamina Cost", 20f, new ConfigDescription("Stamina spent per cast.", new AcceptableValueRange(0f, 100f))); diff --git a/JotunnModStub/Skadi/SkadiHollow.cs b/JotunnModStub/Skadi/SkadiHollow.cs deleted file mode 100644 index 6f9f498..0000000 --- a/JotunnModStub/Skadi/SkadiHollow.cs +++ /dev/null @@ -1,256 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// Where Skadis Nokkel takes you: a troll cave that already exists in the world, the same one - /// every time, claimed the first time the staff is used. - /// - /// THIRD AND FINAL SHAPE, and it is by far the smallest. What used to be here - instantiating a - /// cave shell, learning where its interior was, emptying it of trolls, standing three benches up - /// in it - is all gone. Four things that could each fail, and between them always did. - /// - /// What makes the cave usable now is not here at all: RaceCaveBuilding lets a Skadi (and a Trol) - /// build inside ANY troll cave, by lifting the one restriction that mattered. So this file has - /// nothing left to arrange. It picks a cave, it remembers which, and it opens a door to it. - /// - /// The three failed designs are on the record in Skadi_PortaleGhiaccio.txt sections 0c to 0g, in - /// particular the two facts that killed them: DestroyImmediate is forbidden inside an animation - /// event callback (and the cast runs in one), and a location's m_position is its MOUTH rather - /// than its inside - which is why the portal kept putting the player out on the hillside. - /// - public static class SkadiHollow - { - /// - /// Confirmed present in a live world, along with TrollCave (interior radius 0, so no use to - /// us), MountainCave01, MountainCave02 and Hildir_cave. - /// - public const string SourceLocation = "TrollCave02"; - - // ─── Which cave ─────────────────────────────────────────────────────── - // - // "Half way out, and away from the north." Half of the world's ~10 km radius is 5000, and the - // band is generous because a Black Forest troll cave has to actually exist in it. - private const float ClaimRadiusMin = 3500f; - private const float ClaimRadiusMax = 6500f; - - /// - /// Everything with a positive Z is thrown out, which is the whole northern half of the map. - /// Cruder than a bearing test and that is deliberate: it cannot accidentally admit the Deep - /// North, which is where the first design landed. - /// - private const float MaxNorthing = 0f; - - /// - /// How far from the cave counts as "at my hollow" - used only by the no-planting rule now. - /// Wide, because the cave's origin is its mouth and the inside is some way past it. - /// - public const float Radius = 72f; - - // The claim is written down rather than recomputed. It depends on where this world's troll - // caves are and on the order the candidates come back in, so recomputing it after any change - // to either would hand the player a different cave and orphan everything built in the old one. - private const string CaveKey = "Skadi_HollowCave"; - private const string ReturnPointKey = "Skadi_HollowReturn"; - - private static float lastCastTime = -100000f; - - // ─── Claiming ───────────────────────────────────────────────────────── - - /// - /// This player's cave, if they have claimed one. Does not allocate: it is called from the - /// build prefix, which runs on every attempted placement. - /// - public static bool TryGetCave(Player player, out Vector3 cave) - { - cave = Vector3.zero; - if (player == null || player.m_customData == null) return false; - return TryReadVector(player, CaveKey, out cave); - } - - public static bool IsInside(Player player) - { - if (player == null) return false; - if (!TryGetCave(player, out Vector3 cave)) return false; - return (player.transform.position - cave).sqrMagnitude <= Radius * Radius; - } - - private static bool TryClaimCave(Player player, out Vector3 cave) - { - if (TryGetCave(player, out cave)) return true; - - List candidates = FindCandidateCaves(); - if (candidates.Count == 0) - { - Jotunn.Logger.LogWarning($"[Skadi] No '{SourceLocation}' found in the Black Forest between " + - $"{ClaimRadiusMin:0} m and {ClaimRadiusMax:0} m of the centre, south of the equator. " + - "The hollow cannot be claimed in this world."); - return false; - } - - // Sorted before indexing, because GetLocationList() makes no promise about order and an - // unstable order would mean an unstable claim on the very first cast. - candidates.Sort((a, b) => a.x != b.x ? a.x.CompareTo(b.x) : a.z.CompareTo(b.z)); - - cave = candidates[(int)(HashOf(player) % (uint)candidates.Count)]; - player.m_customData[CaveKey] = FormatVector(cave); - - Jotunn.Logger.LogInfo($"[Skadi] Hollow claimed for '{player.GetPlayerName()}': {SourceLocation} at {cave} " + - $"({BiomeAt(cave)}, {new Vector2(cave.x, cave.z).magnitude:0} m from the centre) " + - $"- chosen from {candidates.Count} candidates."); - return true; - } - - private static List FindCandidateCaves() - { - List found = new List(); - if (ZoneSystem.instance == null) return found; - - foreach (ZoneSystem.LocationInstance instance in ZoneSystem.instance.GetLocationList()) - { - if (instance.m_location == null) continue; - if (instance.m_location.m_prefabName != SourceLocation) continue; - - Vector3 position = instance.m_position; - if (position.z > MaxNorthing) continue; - - float distance = new Vector2(position.x, position.z).magnitude; - if (distance < ClaimRadiusMin || distance > ClaimRadiusMax) continue; - - if (BiomeAt(position) != Heightmap.Biome.BlackForest) continue; - - found.Add(position); - } - return found; - } - - private static Heightmap.Biome BiomeAt(Vector3 point) - { - if (WorldGenerator.instance == null) return Heightmap.Biome.None; - return WorldGenerator.instance.GetBiome(new Vector3(point.x, 0f, point.z)); - } - - private static uint HashOf(Player player) - { - long id = player != null ? player.GetPlayerID() : 0L; - if (id == 0L) - { - string name = player != null ? player.GetPlayerName() : null; - id = string.IsNullOrEmpty(name) ? 1L : name.GetStableHashCode(); - } - // Knuth's multiplicative hash, so two ids one apart do not pick neighbouring caves. - return (uint)(id ^ (id >> 32)) * 2654435761u; - } - - // ─── The cast ───────────────────────────────────────────────────────── - - /// - /// What Skadis Nokkel does. Outside, it opens the pair; inside, it takes the player straight - /// back out. The cooldown applies to going IN only - stepping in and changing your mind must - /// not lock you in a cave for two minutes. - /// - /// The far end stands at the cave's mouth, and the player walks in from there. That is not a - /// compromise any more: since building works in the cave itself, there is nothing waiting - /// inside that has to be lined up with, so the one point we can name honestly is the right - /// one to use. - /// - public static void Cast(Player player) - { - if (player == null || player != Player.m_localPlayer) return; - - if (IsInside(player)) - { - Leave(player); - return; - } - - float cooldown = SkadiConfig.HollowCooldown.Value; - float waited = Time.time - lastCastTime; - if (waited < cooldown) - { - int remaining = Mathf.CeilToInt(cooldown - waited); - player.Message(MessageHud.MessageType.Center, $"The frost has not gathered again ({remaining}s)."); - return; - } - - if (!TryClaimCave(player, out Vector3 cave)) - { - player.Message(MessageHud.MessageType.Center, "No hollow answers you."); - return; - } - - lastCastTime = Time.time; - SkadiRace.ApplyCooldownIcon(SkadiRace.HOLLOW_COOLDOWN_SE, SkadiConfig.HollowCooldown.Value); - - // Remembered across a logout, so casting from inside always has somewhere to put them. - player.m_customData[ReturnPointKey] = FormatVector(player.transform.position); - - Vector3 castPoint = player.transform.position - + player.transform.forward * SkadiConfig.HollowPortalSpawnDistance.Value; - - SkadiHollowPortal.Open(castPoint, player.transform.rotation, - cave + Vector3.up * SkadiConfig.HollowEntryHeight.Value); - } - - private static void Leave(Player player) - { - player.TeleportTo(ReturnPointFor(player), player.transform.rotation, true); - SkadiHollowPortal.CloseSoon(); - } - - /// - /// Called by the portal when the player walks through. Going in changes nothing - the pair - /// stands as long as they are inside. Coming out starts the collapse. - /// - public static void OnTraversed(bool intoHollow) - { - if (!intoHollow) SkadiHollowPortal.CloseSoon(); - } - - private static Vector3 ReturnPointFor(Player player) - { - if (TryReadVector(player, ReturnPointKey, out Vector3 stored) - && TryGetCave(player, out Vector3 cave) - && (stored - cave).sqrMagnitude > Radius * Radius) // a point inside would strand them - { - return stored; - } - - // Same fallback the Trenta portal uses for its home end, and for the same reason: the - // respawn point is the one place the game itself considers always valid. - PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null; - if (profile != null) - { - return profile.HaveCustomSpawnPoint() ? profile.GetCustomSpawnPoint() : PlayerProfile.m_originalSpawnPoint; - } - return PlayerProfile.m_originalSpawnPoint; - } - - // ─── customData helpers ─────────────────────────────────────────────── - - private static string FormatVector(Vector3 v) - { - return $"{v.x:R};{v.y:R};{v.z:R}"; - } - - private static bool TryReadVector(Player player, string key, out Vector3 value) - { - value = Vector3.zero; - if (player == null || player.m_customData == null) return false; - if (!player.m_customData.TryGetValue(key, out string stored) || string.IsNullOrEmpty(stored)) return false; - - string[] parts = stored.Split(';'); - if (parts.Length != 3) return false; - - System.Globalization.CultureInfo invariant = System.Globalization.CultureInfo.InvariantCulture; - const System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Float; - if (!float.TryParse(parts[0], style, invariant, out float x)) return false; - if (!float.TryParse(parts[1], style, invariant, out float y)) return false; - if (!float.TryParse(parts[2], style, invariant, out float z)) return false; - - value = new Vector3(x, y, z); - return true; - } - } -} diff --git a/JotunnModStub/Skadi/SkadiHollowPortal.cs b/JotunnModStub/Skadi/SkadiHollowPortal.cs deleted file mode 100644 index cdf91f3..0000000 --- a/JotunnModStub/Skadi/SkadiHollowPortal.cs +++ /dev/null @@ -1,234 +0,0 @@ -using System.Collections; -using Jotunn.Managers; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// One end of the pair of portals Skadis Nokkel opens. Deliberately a copy of - /// TrentaPortalLink rather than a shared abstraction: the two diverge on colour, on who is - /// allowed through, and above all on when they close (the Trenta pair dies on a timer, this - /// one waits for the player to come back out), and three differences in a forty-line class is - /// cheaper duplicated than parameterised. - /// - /// Everything the Trenta version earned is kept: a plain GameObject with no ZNetView, so it is - /// unregistered and purely local - which is most of "only the player can go in", since remote - /// clients never learn the thing exists - plus its own trigger, its own teleport call, and the - /// same guard against the same-frame ping-pong. - /// - public class SkadiHollowPortalLink : MonoBehaviour - { - public SkadiHollowPortalLink Other; - - /// True on the end that stands inside the hollow. - public bool IsHollowSide; - - // Without this, a player who arrives is still standing in the destination's own trigger and - // gets bounced straight back the way they came, forever. - private float reentryBlockedUntil = -1f; - - private void OnTriggerEnter(Collider other) - { - if (Other == null || Time.time < reentryBlockedUntil) return; - - Player player = other.GetComponentInParent(); - if (player == null) return; - - // The requirement spelled out, even though the portal being local already means no - // other player can reach this line: only the owner walks through. - if (player != Player.m_localPlayer) return; - - Vector3 destination = Other.transform.position + Other.transform.forward * 1.5f; - player.TeleportTo(destination, Other.transform.rotation, true); - - Other.reentryBlockedUntil = Time.time + 1.5f; - - // Going in leaves the pair standing; coming out starts the collapse. - SkadiHollow.OnTraversed(intoHollow: !IsHollowSide); - } - } - - public static class SkadiHollowPortal - { - private static Material cachedVfxMaterial; - private static bool vfxMaterialResolved; - - private static GameObject outsideEnd; - private static GameObject hollowEnd; - private static Coroutine closing; - - public static bool IsOpen => outsideEnd != null || hollowEnd != null; - - /// - /// Spawns the pair: one where the Skadi is standing, one inside their hollow. Neither end - /// has a lifetime - they stand until CloseSoon is called. - /// - public static void Open(Vector3 outsidePoint, Quaternion outsideRotation, Vector3 hollowPoint) - { - CloseNow(); - - outsideEnd = SpawnEnd(outsidePoint, outsideRotation, isHollowSide: false); - hollowEnd = SpawnEnd(hollowPoint, Quaternion.identity, isHollowSide: true); - - SkadiHollowPortalLink outsideLink = outsideEnd.GetComponent(); - SkadiHollowPortalLink hollowLink = hollowEnd.GetComponent(); - outsideLink.Other = hollowLink; - hollowLink.Other = outsideLink; - } - - /// - /// Takes both ends down after the configured grace period. Called when the player leaves the - /// hollow - by walking out or by casting from inside - which is the only thing that closes - /// this pair. - /// - public static void CloseSoon() - { - if (!IsOpen || closing != null) return; - if (SkadiRace.Instance == null) { CloseNow(); return; } - - closing = SkadiRace.Instance.StartCoroutine( - CloseAfter(SkadiConfig.HollowPortalCloseDelay.Value)); - } - - /// No grace period, no animation. For reopening, and for shutting down. - public static void CloseNow() - { - if (closing != null && SkadiRace.Instance != null) - { - SkadiRace.Instance.StopCoroutine(closing); - } - closing = null; - - if (outsideEnd != null) Object.Destroy(outsideEnd); - if (hollowEnd != null) Object.Destroy(hollowEnd); - outsideEnd = null; - hollowEnd = null; - } - - private static GameObject SpawnEnd(Vector3 position, Quaternion rotation, bool isHollowSide) - { - GameObject portal = new GameObject(isHollowSide ? "SkadiHollowPortal_In" : "SkadiHollowPortal_Out"); - portal.transform.position = position; - portal.transform.rotation = rotation; - - CapsuleCollider trigger = portal.AddComponent(); - trigger.isTrigger = true; - trigger.height = 3f; - trigger.radius = 1.2f; - trigger.center = new Vector3(0, 1.5f, 0); - - SkadiHollowPortalLink link = portal.AddComponent(); - link.IsHollowSide = isHollowSide; - - BuildSwirlVfx(portal.transform); - - return portal; - } - - /// - /// The swirl only, no wooden frame - same shape and same reasoning as the Trenta portal's: - /// borrow a particle material off the real portal prefab by READING it (never instantiating - /// it, so none of the real portal's gameplay components ever get a chance to run), then - /// drive shape, emission and colour from here. The one change is the colour, which is - /// Skadi's ice instead of the Trenta's toxic purple. - /// - private static void BuildSwirlVfx(Transform parent) - { - if (!vfxMaterialResolved) - { - vfxMaterialResolved = true; - GameObject source = PrefabManager.Cache.GetPrefab("portal_wood"); - if (source != null) - { - ParticleSystemRenderer sourceRenderer = source.GetComponentInChildren(true); - if (sourceRenderer != null) cachedVfxMaterial = sourceRenderer.material; - } - if (cachedVfxMaterial == null) - { - Jotunn.Logger.LogWarning("[Skadi] Hollow portal: no particle material on 'portal_wood'; using the default particle material."); - } - } - - GameObject vfx = new GameObject("Swirl"); - vfx.transform.SetParent(parent, false); - vfx.transform.localPosition = new Vector3(0, 1.2f, 0); - - ParticleSystem ps = vfx.AddComponent(); - var main = ps.main; - main.loop = true; - main.startLifetime = 1.5f; - main.startSpeed = 0f; - main.startSize = new ParticleSystem.MinMaxCurve(0.15f, 0.3f); - main.maxParticles = 200; - main.simulationSpace = ParticleSystemSimulationSpace.Local; - - var emission = ps.emission; - emission.rateOverTime = 80f; - - var shape = ps.shape; - shape.shapeType = ParticleSystemShapeType.Circle; - shape.radius = 1f; - shape.radiusThickness = 0.1f; // hollow ring, not a filled disc - - var rotationOverLifetime = ps.rotationOverLifetime; - rotationOverLifetime.enabled = true; - rotationOverLifetime.z = new ParticleSystem.MinMaxCurve(90f); - - ParticleSystemRenderer renderer = ps.GetComponent(); - if (cachedVfxMaterial != null) renderer.material = cachedVfxMaterial; - - var colorOverLifetime = ps.colorOverLifetime; - colorOverLifetime.enabled = true; - Gradient grad = new Gradient(); - grad.SetKeys( - new GradientColorKey[] { new GradientColorKey(SkadiIce.PortalSwirl, 0f), new GradientColorKey(SkadiIce.PortalSwirl, 1f) }, - new GradientAlphaKey[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(0.9f, 0.3f), new GradientAlphaKey(0.9f, 0.7f), new GradientAlphaKey(0f, 1f) } - ); - colorOverLifetime.color = grad; - - ps.Play(); - } - - private static IEnumerator CloseAfter(float seconds) - { - yield return new WaitForSeconds(seconds); - - GameObject a = outsideEnd; - GameObject b = hollowEnd; - outsideEnd = null; - hollowEnd = null; - closing = null; - - yield return Collapse(a); - yield return Collapse(b); - } - - /// - /// Link and trigger die first, so nothing can walk through mid-collapse, then a one-second - /// shrink stands in for a closing animation - vanilla portals are simply present or absent, - /// so there is no real one to borrow. - /// - private static IEnumerator Collapse(GameObject portal) - { - if (portal == null) yield break; - - SkadiHollowPortalLink link = portal.GetComponent(); - if (link != null) Object.Destroy(link); - - CapsuleCollider trigger = portal.GetComponent(); - if (trigger != null) Object.Destroy(trigger); - - float t = 0f; - Vector3 startScale = portal.transform.localScale; - while (t < 1f) - { - if (portal == null) yield break; - t += Time.deltaTime; - portal.transform.localScale = Vector3.Lerp(startScale, Vector3.zero, t); - yield return null; - } - - if (portal != null) Object.Destroy(portal); - } - } -} diff --git a/JotunnModStub/Skadi/SkadiIce.cs b/JotunnModStub/Skadi/SkadiIce.cs new file mode 100644 index 0000000..a8405c7 --- /dev/null +++ b/JotunnModStub/Skadi/SkadiIce.cs @@ -0,0 +1,55 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The one ice palette the whole Skadi chain shares. Taken from the Fader recolour in + /// SkadiRace.ExecuteTransformation rather than picked fresh, so the reagent and the crystal golem + /// are the same ice as the Skeleton Dragon the race turns into at tier 8. + /// + /// It lived in SkadiNokkel.cs until that staff was removed; it is its own file now because the + /// two things still using it have nothing else to do with each other. + /// + public static class SkadiIce + { + public static readonly Color Albedo = new Color(0.6f, 0.8f, 1f, 1f); + public static readonly Color Emission = new Color(0f, 0.5f, 1f, 1f); + + /// + /// Multiplies the ice tint over whatever the base texture already carries instead of + /// overwriting it, so the model keeps its detail and reads as frozen bone rather than as a + /// flat blue silhouette. Same approach as AswidSpectralClaw.ApplySpectralVisual, and like + /// that one it copies each material first so the vanilla asset is never touched. + /// + public static void Apply(GameObject root) + { + if (root == null) return; + + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null || renderer is ParticleSystemRenderer) continue; + + Material[] source = renderer.sharedMaterials; + Material[] tinted = new Material[source.Length]; + for (int i = 0; i < source.Length; i++) + { + if (source[i] == null) continue; + + Material material = new Material(source[i]); + if (material.HasProperty("_Color")) + { + Color baseColor = material.GetColor("_Color"); + material.SetColor("_Color", new Color(baseColor.r * Albedo.r, + baseColor.g * Albedo.g, + baseColor.b * Albedo.b, + baseColor.a)); + } + if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Emission); + + tinted[i] = material; + } + renderer.sharedMaterials = tinted; + } + } + } +} diff --git a/JotunnModStub/Skadi/SkadiNokkel.cs b/JotunnModStub/Skadi/SkadiNokkel.cs deleted file mode 100644 index f4a32b4..0000000 --- a/JotunnModStub/Skadi/SkadiNokkel.cs +++ /dev/null @@ -1,396 +0,0 @@ -using HarmonyLib; -using Jotunn.Configs; -using Jotunn.Entities; -using Jotunn.Managers; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// The one ice palette the whole Skadi chain shares. Taken from the Fader recolour in - /// SkadiRace.ExecuteTransformation rather than picked fresh, so the staff, the reagent and the - /// portal are all the same ice as the Skeleton Dragon the race turns into at tier 8. - /// - public static class SkadiIce - { - public static readonly Color Albedo = new Color(0.6f, 0.8f, 1f, 1f); - public static readonly Color Emission = new Color(0f, 0.5f, 1f, 1f); - public static readonly Color PortalSwirl = new Color(0.55f, 0.85f, 1f, 1f); - - /// - /// Multiplies the ice tint over whatever the base texture already carries instead of - /// overwriting it, so the model keeps its detail and reads as frozen bone rather than as a - /// flat blue silhouette. Same approach as AswidSpectralClaw.ApplySpectralVisual, and like - /// that one it copies each material first so the vanilla asset is never touched. - /// - public static void Apply(GameObject root) - { - if (root == null) return; - - foreach (Renderer renderer in root.GetComponentsInChildren(true)) - { - if (renderer == null || renderer is ParticleSystemRenderer) continue; - - Material[] source = renderer.sharedMaterials; - Material[] tinted = new Material[source.Length]; - for (int i = 0; i < source.Length; i++) - { - if (source[i] == null) continue; - - Material material = new Material(source[i]); - if (material.HasProperty("_Color")) - { - Color baseColor = material.GetColor("_Color"); - material.SetColor("_Color", new Color(baseColor.r * Albedo.r, - baseColor.g * Albedo.g, - baseColor.b * Albedo.b, - baseColor.a)); - } - if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Emission); - - tinted[i] = material; - } - renderer.sharedMaterials = tinted; - } - } - } - - /// - /// Skadis Nokkel - "Skadi's key". A StaffSkeleton with the skeleton taken out of it: it costs no - /// eitr, no health and no stamina, it summons nothing, and what it does instead is open a portal - /// into the player's own hidden hollow (SkadiHollow). - /// - /// The name is the point. It is not a weapon that happens to open a door, it is a key - and a - /// reproducible one: losing it costs a trip to the forge, not the hollow. - /// - /// Two layers keep the vanilla staff's behaviour from leaking through, deliberately overlapping: - /// - every field that could carry a cost or a summon is zeroed on the clone (Strip below); - /// - the attack trigger itself is intercepted and vanilla's never runs for this staff - /// (SkadiNokkelCastPatch). Nulling a projectile field would leave vanilla walking into it; - /// taking over the method means that code path is not merely defused, it is unreachable. - /// - public static class SkadiNokkel - { - public const string PrefabName = "SkadiNokkel"; - public const string DisplayName = "Skadis Nokkel"; - private const string SourcePrefab = "StaffSkeleton"; - - private const string ModerDrop = "DragonTear"; - private const string SkullTrophy = "TrophySkeleton"; - - public static void Register() - { - GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab); - if (prefab == null) - { - Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePrefab}; {DisplayName} not registered."); - return; - } - - ItemDrop drop = prefab.GetComponent(); - if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) - { - Jotunn.Logger.LogWarning($"[Skadi] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered."); - return; - } - - ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; - shared.m_name = DisplayName; - shared.m_description = "A staff of frozen bone. It raises nothing. Used, it opens the way to a hollow " + - "that is yours and no one else's - and used again, it lets you out."; - shared.m_useDurability = false; - - // ItemType is left exactly as the vanilla staff has it, on purpose: it decides the - // equip slot and which animation set the character uses, and the cast gesture is the - // whole reason this is a staff and not a trinket. - - Strip(shared); - SkadiIce.Apply(prefab); - - ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); - - LogCosts("straight after registering", shared); - - ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig - { - Item = PrefabName, - Amount = 1, - CraftingStation = CraftingStations.Forge, - Requirements = new[] - { - new RequirementConfig(SkadiFrostHeart.PrefabName, 1, 0, true), - new RequirementConfig(ModerDrop, 1, 0, true), - new RequirementConfig(SkullTrophy, 1, 0, true), - }, - })); - - Jotunn.Logger.LogInfo($"[Skadi] {DisplayName} registered: no eitr, no health, no summon."); - } - - /// - /// Takes the skeleton staff apart. Every field is zeroed on BOTH attacks, because the - /// secondary is a separate Attack with its own copy of every cost. - /// - /// The summon is the interesting one: it comes from a SpawnAbility component (verified class, - /// field GameObject[] m_spawnPrefab) which does not live on the item but on a prefab hung off - /// the attack. WHICH field hangs it - m_attackProjectile or m_spawnOnTrigger - is not - /// knowable from the game files, so all of them go. Nulling three fields that might each be - /// the culprit costs nothing; guessing wrong costs a skeleton every cast. - /// - /// m_attackStamina goes to zero too, and that is a decision, not thoroughness: the moment - /// someone wants to flee into their hollow is exactly the moment they have no stamina left. - /// The only brake on this staff is its cooldown. - /// - private static void Strip(ItemDrop.ItemData.SharedData shared) - { - StripAttack(shared.m_attack); - StripAttack(shared.m_secondaryAttack); - } - - private static void StripAttack(Attack attack) - { - if (attack == null) return; - - attack.m_attackEitr = 0f; - attack.m_drawEitrDrain = 0f; - attack.m_reloadEitrDrain = 0f; - - attack.m_attackHealth = 0f; - attack.m_attackHealthPercentage = 0f; - attack.m_attackHealthLowBlockUse = false; - attack.m_attackHealthReturnHit = 0f; - - attack.m_attackStamina = 0f; - attack.m_drawStaminaDrain = 0f; - attack.m_reloadStaminaDrain = 0f; - - attack.m_attackProjectile = null; - attack.m_spawnOnTrigger = null; - attack.m_spawnOnHit = null; - attack.m_spawnOnHitChance = 0f; - - // The animation stays. It is the summoning gesture, which is the right gesture for - // opening a way, and it is the same one TrentaAbilities plays by hand for its portal. - } - - /// - /// Runs on the cast. Race-gated: the hollow belongs to the Skadi, so in anyone else's hands - /// this is an inert stick - the same shape as Aswid_SpectralClawDamage_Patch, which asks - /// AswidRace.IsAswid() before doing anything at all. - /// - public static void OnCast(Player player) - { - if (player == null || player != Player.m_localPlayer) return; - - if (!SkadiRace.IsLocalSkadi()) - { - player.Message(MessageHud.MessageType.Center, "The staff is cold and answers to someone else."); - return; - } - - SkadiHollow.Cast(player); - } - - public static bool IsNokkel(ItemDrop.ItemData item) - { - return item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == PrefabName; - } - - /// - /// True when a cost being asked about belongs to this staff. - /// - /// The fallback on the equipped weapon is not belt-and-braces, it is necessary: the cost - /// getters are called from Attack.Start, and m_weapon is not guaranteed to have been assigned - /// by the time the cost is checked. It is deliberately only consulted when m_weapon is null, - /// so a creature's own attack cannot be zeroed just because the player happens to be holding - /// the staff at the time. - /// - public static bool IsNokkelContext(ItemDrop.ItemData weapon) - { - if (weapon != null) return IsNokkel(weapon); - - Player local = Player.m_localPlayer; - return local != null && IsNokkel(local.GetCurrentWeapon()); - } - - /// - /// Prints what the clone's attack actually costs, so "the eitr cost came back" stops being a - /// mystery and becomes a number with a timestamp. Called once at registration and again from - /// the F8 dump, which between them say whether the zeroes were never written or were written - /// and then overwritten by something else. - /// - public static void LogCosts(string when, ItemDrop.ItemData.SharedData shared) - { - if (shared == null) { Jotunn.Logger.LogWarning($"[Skadi] Nokkel costs {when}: no shared data."); return; } - - Attack primary = shared.m_attack; - Attack secondary = shared.m_secondaryAttack; - - Jotunn.Logger.LogInfo($"[Skadi] Nokkel costs {when}: " + - $"primary eitr={Describe(primary, a => a.m_attackEitr)} " + - $"health={Describe(primary, a => a.m_attackHealth)} " + - $"health%={Describe(primary, a => a.m_attackHealthPercentage)} " + - $"stamina={Describe(primary, a => a.m_attackStamina)} | " + - $"secondary eitr={Describe(secondary, a => a.m_attackEitr)} " + - $"stamina={Describe(secondary, a => a.m_attackStamina)}"); - } - - private static string Describe(Attack attack, System.Func read) - { - return attack == null ? "" : read(attack).ToString("0.##"); - } - - /// - /// What the F8 dump prints for this chain. Two unknowns, both settled by reading them once - /// off a running game: which field of the vanilla staff carries the summon, and what the - /// troll cave location is really called in this build. - /// - public static void DumpSource() - { - Jotunn.Logger.LogInfo("=== SKADI NOKKEL SOURCE DUMP ==="); - - GameObject staff = PrefabManager.Cache.GetPrefab(SourcePrefab); - ItemDrop staffDrop = staff != null ? staff.GetComponent() : null; - if (staffDrop == null) - { - Jotunn.Logger.LogWarning($"{SourcePrefab} not found."); - } - else - { - Attack attack = staffDrop.m_itemData.m_shared.m_attack; - Jotunn.Logger.LogInfo($" m_attackType : {attack.m_attackType}"); - Jotunn.Logger.LogInfo($" m_attackAnimation : {attack.m_attackAnimation}"); - Jotunn.Logger.LogInfo($" m_attackProjectile : {(attack.m_attackProjectile != null ? attack.m_attackProjectile.name : "")}"); - Jotunn.Logger.LogInfo($" m_spawnOnTrigger : {(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "")}"); - Jotunn.Logger.LogInfo($" m_attackEitr : {attack.m_attackEitr}"); - Jotunn.Logger.LogInfo($" m_attackHealth : {attack.m_attackHealth} / {attack.m_attackHealthPercentage}%"); - - foreach (GameObject candidate in new[] { attack.m_attackProjectile, attack.m_spawnOnTrigger }) - { - if (candidate == null) continue; - foreach (SpawnAbility ability in candidate.GetComponentsInChildren(true)) - { - string spawns = ""; - if (ability.m_spawnPrefab != null && ability.m_spawnPrefab.Length > 0) - { - string[] names = new string[ability.m_spawnPrefab.Length]; - for (int i = 0; i < names.Length; i++) - { - names[i] = ability.m_spawnPrefab[i] != null ? ability.m_spawnPrefab[i].name : ""; - } - spawns = string.Join(", ", names); - } - Jotunn.Logger.LogInfo($" SpawnAbility on '{candidate.name}' spawns: {spawns}"); - } - } - } - - // The clone as the game currently holds it, not as Register() left it. If these are not - // zero, the write in Strip() did not survive - which is the whole reason - // SkadiNokkelFreeCastPatch exists, and this line is how we find out whether it is still - // needed or whether the fields hold after all. - GameObject clone = PrefabManager.Cache.GetPrefab(PrefabName); - ItemDrop cloneDrop = clone != null ? clone.GetComponent() : null; - if (cloneDrop == null) - { - Jotunn.Logger.LogWarning($" {PrefabName} is not in the prefab cache."); - } - else - { - LogCosts("as the game holds it now", cloneDrop.m_itemData.m_shared); - Jotunn.Logger.LogInfo($" shared data instance is {(ReferenceEquals(cloneDrop.m_itemData.m_shared, staffDrop != null ? staffDrop.m_itemData.m_shared : null) ? "THE SAME OBJECT as the vanilla staff's - that is the bug" : "its own copy, as expected")}"); - } - - // The other half: is 'TrollCave02' actually what it is called here? - Jotunn.Logger.LogInfo($"--- locations matching 'cave' (looking for {SkadiHollow.SourceLocation}) ---"); - if (ZoneSystem.instance == null || ZoneSystem.instance.m_locations == null) - { - Jotunn.Logger.LogWarning(" ZoneSystem not up yet; load a world first."); - } - else - { - // m_locations, not GetLocationList(): the latter is public but returns the locations - // PLACED in this world, and the hollow needs the definition, not an instance. - foreach (ZoneSystem.ZoneLocation location in ZoneSystem.instance.m_locations) - { - if (location == null || string.IsNullOrEmpty(location.m_prefabName)) continue; - if (location.m_prefabName.IndexOf("cave", System.StringComparison.OrdinalIgnoreCase) < 0) continue; - - Jotunn.Logger.LogInfo($" {location.m_prefabName} (biome {location.m_biome}, " + - $"interior r{location.m_interiorRadius}, clearArea {location.m_clearArea})"); - } - } - - Jotunn.Logger.LogInfo("=== END SKADI NOKKEL SOURCE DUMP ==="); - } - } - - /// - /// The cast hook, and the second half of "remove the unwanted components". - /// - /// Attack.OnAttackTrigger() is used rather than Attack.Start because it takes NO parameters - - /// its signature cannot drift and cannot be got wrong, which matters here because Attack.Start's - /// parameter types could not even be loaded for inspection outside the game. It also fires at - /// the moment the animation reaches its release point, which is exactly when a cast should land. - /// - /// It is a Prefix returning FALSE, not a postfix, and that is the whole trick: for this staff - /// vanilla's attack-trigger code never executes at all. The summon and the projectile are not - /// just defused by the zeroed fields, they are unreachable - and vanilla cannot trip over the - /// nulls we left behind either, which a postfix would have been at the mercy of. - /// - /// m_weapon and m_character are both PRIVATE on Attack, so they arrive through Harmony's triple - /// underscore field injection rather than off __instance - which is also why they are spelled - /// out here instead of being read with Traverse: the injection is checked at patch time, so a - /// rename shows up as a startup error instead of a silent null every cast. - /// - [HarmonyPatch(typeof(Attack), "OnAttackTrigger")] - public static class SkadiNokkelCastPatch - { - public static bool Prefix(ItemDrop.ItemData ___m_weapon, Humanoid ___m_character) - { - if (!SkadiNokkel.IsNokkel(___m_weapon)) return true; - - SkadiNokkel.OnCast(___m_character as Player); - return false; - } - } - - /// - /// The staff costs nothing, guaranteed - and this is what guarantees it. - /// - /// Zeroing m_attackEitr, m_attackHealth and m_attackStamina on the clone is still done in - /// Strip(), and by every reading of the game's own code it ought to be enough: those three, plus - /// the two drain fields, are the ONLY eitr costs that exist anywhere on Attack, and SharedData - /// carries none at all (checked field by field). In game the cost came back anyway, which means - /// the write to the clone's own SharedData does not survive something - so relying on that write - /// is relying on a mechanism that has already been observed to fail. - /// - /// These three getters are the single funnel every cost check flows through: Attack.Start asks - /// them before it will start, and the tooltip asks them for what to print. Forcing them to zero - /// makes the staff free no matter what any field says, which is the same reasoning as the prefix - /// above - do not defuse the code path, remove it. - /// - /// All three are PRIVATE and take no parameters, so they are addressed by name through - /// AccessTools and share one postfix. - /// - [HarmonyPatch] - public static class SkadiNokkelFreeCastPatch - { - [HarmonyTargetMethods] - private static System.Collections.Generic.IEnumerable TargetMethods() - { - yield return AccessTools.Method(typeof(Attack), "GetAttackEitr"); - yield return AccessTools.Method(typeof(Attack), "GetAttackHealth"); - yield return AccessTools.Method(typeof(Attack), "GetAttackStamina"); - } - - [HarmonyPostfix] - private static void Postfix(ItemDrop.ItemData ___m_weapon, ref float __result) - { - if (__result == 0f) return; - if (!SkadiNokkel.IsNokkelContext(___m_weapon)) return; - - __result = 0f; - } - } -} diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index 9d1084c..63fe55c 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -33,7 +33,6 @@ namespace RacesOfValheim // rebuild - see CONFIGURATION-MANAGER-HOWTO.md. public const string SPELL_COOLDOWN_SE = "SE_SkadiSpellCooldown"; public const string ATTACK_COOLDOWN_SE = "SE_SkadiAttackCooldown"; - public const string HOLLOW_COOLDOWN_SE = "SE_SkadiHollowCooldown"; private static float SPELL_STAMINA_COST => SkadiConfig.SpellStaminaCost.Value; private static float SPELL_COOLDOWN => SkadiConfig.SpellCooldown.Value; @@ -53,9 +52,8 @@ namespace RacesOfValheim { // The reagent goes first: the faction merchant catalogue resolves its entries by prefab // name, so Greater Frost Heart has to exist before a Fenring_Cultist is ever set up as a - // bench - and the staff's recipe references it by name too. + // bench. SkadiFrostHeart.Register(); - SkadiNokkel.Register(); SkadiGolem.Register(); var se = ScriptableObject.CreateInstance(); @@ -109,13 +107,6 @@ namespace RacesOfValheim attackCd.m_tooltip = "Your dragon shape must ready itself to strike again."; attackCd.m_icon = GetItemIcon("TrophyHatchling") ?? dragonIcon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(attackCd, fixReference: false)); - - var hollowCd = ScriptableObject.CreateInstance(); - hollowCd.name = HOLLOW_COOLDOWN_SE; - hollowCd.m_name = "Skadis Nokkel"; - hollowCd.m_tooltip = "The way to your hollow must freeze over again before it will open."; - hollowCd.m_icon = GetItemIcon("StaffIceShards") ?? dragonIcon; - ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(hollowCd, fixReference: false)); } // Drives the HUD countdown: Valheim prints the remaining time on any status effect whose @@ -152,8 +143,8 @@ namespace RacesOfValheim } /// - /// The same check, reachable without an Instance - which the Nokkel's Harmony patch and the - /// hollow both need, since they run from static context. + /// The same check, reachable without an Instance - which the golem and the cave-building + /// watcher both need, since they run from static context. /// public static bool IsLocalSkadi() { @@ -255,8 +246,7 @@ namespace RacesOfValheim DumpPrefabDebugInfo("Dragon"); DumpPrefabDebugInfo("Hatchling"); DumpPrefabDebugInfo("Fader"); - SkadiNokkel.DumpSource(); - if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader + Nokkel debug info to console!"); + if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader debug info to console!"); } } diff --git a/JotunnModStub/WarVulture/WarVultureItem.cs b/JotunnModStub/WarVulture/WarVultureItem.cs index 03d105c..8ba29ad 100644 --- a/JotunnModStub/WarVulture/WarVultureItem.cs +++ b/JotunnModStub/WarVulture/WarVultureItem.cs @@ -12,8 +12,9 @@ namespace RacesOfValheim /// /// Why a staff and not a trinket: the game lets a WEAPON be used without any trickery. Cloning /// StaffSkeleton buys the click, the cast gesture and the effects for free - which is exactly - /// the reasoning that produced SkadiNokkel, and this file is deliberately that file's twin. If - /// one of them ever needs a fix, the other almost certainly needs the same one. + /// the reasoning that produced Skadis Nokkel, whose file this one was written as a twin of. The + /// Nokkel has since been removed - it opened a portal pair, which broke in multiplayer - so this + /// file is now the only copy of that pattern and there is no sibling to keep it in step with. /// /// Three things are removed from the vanilla staff, and each is removed TWICE on purpose: /// - the eitr, health and stamina costs are zeroed on the clone AND forced to zero in the From 3095198539bd676d87e0ac2dee8e206ae630c4f2 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Tue, 11 Aug 2026 07:55:33 +0200 Subject: [PATCH 007/290] docs(readme): add the Sverm, the War Vulture and the v1.5.0 changelog The Sverm goes in as the tenth race, with its own progression block and a description of the colony. The War Vulture gets a section of its own, including the fact that it has no recipe yet and is console-spawned while the flight is being proven - documenting it as craftable would have been false. The v1.5.0 changelog covers everything landed since v1.4.0: the race, the mount, and the per-race station chains for all nine other races, plus the merchant catalogue entries that gate them, the piece spacing rules and the ObjectDB duplicate-item crash fix. Skadis Nokkel is not mentioned anywhere: it never shipped, so its removal is not a changelog entry. The version is deliberately NOT bumped - manifest.json and PluginVersion still read 1.4.0. More bugfixes are due before the release. Co-Authored-By: Claude Opus 5 --- README.md | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 41fb9d0..4cca570 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A comprehensive Valheim mod allowing you to play as unique races, each providing ## Features -**Races of Valheim introduces 9 custom playable races:** +**Races of Valheim introduces 10 custom playable races:** ### 1. Skeleton ![Skeleton](https://wiki.aledanidev.ovh/assets/images/corna_scheletro.gif) @@ -67,6 +67,14 @@ A comprehensive Valheim mod allowing you to play as unique races, each providing - **Forest Camouflage:** Animals/monsters do not see you as an enemy. - **Root and Rot:** Late game: emit healing pollen, open portals, summon hornet companions, take Elder’s shape. +### 10. Sverm +- **Chitin Plating:** You never dress. Chest, legs and helm are carapace that never comes off, worth a full set of the biome ahead of you at every tier — best quality, weightless, no movement penalty. Only cloak and trinket may still be worn. +- **Vilebone Maulclaws:** Your hands are the weapon, and they cannot be taken from you. Draw a sword and the claws wait; sheathe it and they are back. +- **Hive Pheromones:** No invertebrate attacks you — leeches, ticks, deathsquitos, seekers and bees all ignore you, from tier zero. +- **Toxin Immunity:** Poison cannot touch you. Blunt weapons and fire hit you 40% harder — until Fader, when the fire weakness burns out and comes back as a resistance. +- **The Colony:** After the Elder, build a Brood Mound, feed it whole stacks of food, wood or resin, and spend the digested biomass on a roster of insect troops, a Hive Market, blister ticks and captured beehives. +- **Stinger Morph:** After Yagluth, become a deathsquito — real flight and the creature's own sting, on a body made of paper. + --- ## Installation @@ -179,6 +187,23 @@ Right Mouse toggles flight. Glide towards aim, W = forward/climb, Shift+W = use +
+Sverm Progression + +- **Base:** Chitin Plating (carapace armour, full next-biome set at every tier, weightless, no speed penalty; only cloak and trinket wearable). Toxin Immunity — poison cannot touch you, but +40% blunt and +40% fire damage taken. Hive Pheromones — no invertebrate attacks you. Insect Metabolism — eats everything, honey counts double, alchemical blood is the one refusal. Vilebone Maulclaws — unarmed blows land at a share of the claws' full weight, rising with every tier. +- **Eikthyr:** Metabolic Surge – running and jumping cost less, and you jump higher. Ventral Pouches – +100 carry weight. +- **Elder:** Grinding Mandibles – seeds are food (raw nourishment, no garden buffs). Sensory Antennae – feel what lives around you, through stone and soil. **The colony wakes:** Brood Mound unlocked. +- **Bonemass:** Venom Glands – every blow carries bonus poison, growing per tier. Acid Hemolymph – melee attackers take poison back. +- **Moder:** Vestigial Wings – no fall damage, and small wings appear. +- **Yagluth:** Stinger Morph (configurable key) – become a deathsquito: real flight and its sting, on a fragile body. +- **Queen:** Surrenal Glands – 10% larger, and the carapace takes its greatest leap. +- **Fader:** Carapace Regeneration – 0.5 health a second, always. Annealed Chitin and Emberform – fire stops hurting you and becomes a 40% resistance; the chitin goes black with a red heat under it. + +**The Colony (from the Elder onward):** +Build a **Brood Mound** with the hammer — no more than two within its density radius. Press it to feed it a whole stack from your pack (any food, any wood, any resin; honey and royal jelly are medicine and are refused). Feeding is not instant: it digests into the nest's bank at a fixed rate, and only what has arrived can be spent. The nest lays **brood eggs** on a timer and holds a few at a time; every troop costs an egg as well as biomass — the egg grows back, the biomass does not. A **Hive Market** raised within ten meters is where everything is bought, out of that nest's bank. Growing the nest through its four stages costs that stage's whole tankful and opens the next rung of the troop roster. Blister ticks buy a slot forever and regrow free. Raise vanilla beehives inside the nest's ten meters and the colony takes them over: twice the speed, three times the honey, and royal jelly once Yagluth is down. Press honey or royal jelly on one of your own insects to heal it. + +
+
Trenta Progression @@ -209,6 +234,21 @@ Right Mouse toggles flight. Glide towards aim, W = forward/climb, Shift+W = use --- +## The War Vulture (Flying Mount) + +A vulture's head kept on a stick. Raise it and the bird comes back under you. + +- **Who can call it:** Furling and Dvergar by default. The list is a config entry (`War Vulture - Access`) — add races to it, or leave it empty to let everyone ride. In anyone else's hands the item is an inert trophy. +- **Summon and dismount:** Left click the item to call the bird. Left click again and the vulture starts a controlled descent, ignoring your input until the ground arrives; a third click lets go on the spot. +- **Flying:** Same feel as the Aswid's bat form — you steer where you look. Cruise speed is unlimited, because a vulture stays up for hours. +- **Sprint:** Hold the vanilla run key for full speed. The bird only has so much wind in it (10s by default) before it settles back to a glide, and it refills in the air as soon as you let go — landing is not required. The reserve is drawn as a bar under your own stamina. +- **Seen by others:** Everyone else sees you sitting on a real vulture; the bird and the riding pose are network-synced. +- **Not craftable yet.** There is deliberately no recipe while the flight is being proven — the item is spawned from the console (`spawn WarVulture`). A recipe will land once it is clear what the ride is worth in materials. + +Speeds, sprint duration, recharge, mount size and seat position are all in Configuration Manager under `War Vulture`. + +--- + ## The Race Menu Ward - Build (2 Wood, Hammer/Misc, no crafting station). First placed near Sacrificial Stones in every new world. @@ -237,6 +277,8 @@ Skadi, Fenrir, Dvergar / at peace with Drake, Wolf, Ulv, Fenring/Cultist, Dverge **Swamp:** Aswid, Draugh, Skeleton / at peace with Ghost, Skeleton, Draugr, Wraith, Leech, Abomination, Blob. +The **Sverm** belongs to no faction. Its Hive Pheromones make every invertebrate in the game ignore it instead — leeches, ticks, deathsquitos, seekers and bees — with no boss gate and no trading. + --- ## Development & Feedback @@ -248,6 +290,25 @@ Bug reports, feedback, ideas: [https://discord.gg/gbBEK2VTE](https://discord.gg/ ## Changelog +### v1.5.0 + +- **NEW - Sverm Race:** The tenth race. Wears carapace instead of armour (never removable, always worth the next biome's full set, weightless), fights with permanent claws, is immune to poison but takes 40% more from blunt and fire, and is ignored by every invertebrate in the game from tier zero. After the Elder it stops being one body and becomes a colony. +- **NEW - The Colony (Sverm):** Build a Brood Mound and feed it whole stacks of food, wood or resin. Feeding is not instant — it digests into the nest's bank at a fixed rate. Spend that biomass, plus brood eggs the nest lays on a timer, on a roster of insect troops that follow you, walk home when dismissed and mend themselves. A Hive Market raised nearby is where everything is bought; growing the nest through its four stages opens the next rung of the roster. Vanilla beehives raised inside the nest's ten meters are taken over by the colony: twice the speed, three times the honey, royal jelly after Yagluth. Honey and royal jelly heal your insects instead of feeding the nest. +- **NEW - War Vulture (Flying Mount):** A vulture trophy on a stick that puts you on a real, network-visible flying bird. Left click to call it, click again for a controlled descent. Unlimited cruise, a limited sprint reserve on the run key that refills in mid-air, and its own bar under your stamina. Furling and Dvergar by default, configurable. No recipe yet while the flight is being proven — spawn it from the console. +- **NEW - Race Stations and Item Chains:** Every race now has a buildable station of its own, gated by a reagent bought from its faction's merchant. Servants across all of them share one system: they follow when asked, walk home when dismissed, and knit their own wounds shut. + - **Aswid:** Blood Refinery — refines Blood Essence, Superior Blood Essence and Blood Core. + - **Trenta:** Composter — rots raw flesh into Fertilizer, which grows any plant on the spot. Heartwood Grove — a tree that fertilises what surrounds it, stings what approaches it, and fills a chest with honey. + - **Draugh:** Cursed Body Pile — eats raw flesh and answers with tamed draugr. Draugr and Elite trophies are worth a whole batch. Anyone can build it, but only a Draugh gives the draugr orders; for everyone else it is a grave that defends its own ten meters. + - **Skeleton:** Bound Bone Pile — pay once per slot and that slot refills itself forever, because skeletons are fragile and an army you re-buy after every fight is one nobody takes out of the house. Bound Sentry — a bound archer that cannot walk, regenerates when left alone, and hands its parts back when it falls. + - **Trol:** War Totem — hires warbands of trolls and greydwarves for coin. Race locked: the hammer refuses it to anyone who is not a Trol. A dead warband is money spent. + - **Dvergar:** Contract Bank — coin on the table, a professional crew signs on; they keep their race's truce, so a hired band walking into a dvergr outpost does not start a war with the shopkeeper. Rune Barrel — pour a vanilla potion into it and the crew standing around it drinks. + - **Fenrir:** Pack Trough — Ulvsblod and Greater Ulvsblod buy a roster of Pack Wolves, Ulvs and Fenrir. + - **Skadi:** Crystal Golem — a stonecutter-bound guardian on a leash. Skadi (and Trol) may now build inside any troll cave in the world. + - **Furling:** Five crops. Copper, Tin and Iron Flax grow metal out of poisoned soil; Stoneberry and Flintberry bushes give stone and flint. +- **Factions:** The merchant catalogue now carries the reagents that gate every one of the chains above, and hostility rules were reworked alongside it. +- **Building:** Stations of the same kind can no longer be packed on top of each other — each one has its own minimum spacing. +- **Fix - Crash:** Duplicate items in ObjectDB are deduplicated by name hash before the registers update, which fixes a crash on world load. + ### v1.4.0 - **NEW - Factions:** Each race is at peace with a faction of vanilla mobs; many now trade with you if you match. Goblins (Fuling) peace/trade now works properly. - **NEW - Config Manager:** All abilities, cooldowns and keybinds now configurable for each race. From 1d66b003745db66cc60205cff5e80eafdf080d29 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Tue, 11 Aug 2026 16:30:20 +0200 Subject: [PATCH 008/290] warvulture --- JotunnModStub/ModelBorrow.cs | 31 +- JotunnModStub/RaceCompendium.cs | 156 +++- JotunnModStub/RaceHostilityManager.cs | 32 + JotunnModStub/RaceScale.cs | 7 +- JotunnModStub/RacesOfValheim.cs | 56 ++ JotunnModStub/Sverm/SvermAntennae.cs | 170 ++++ JotunnModStub/Sverm/SvermBeehive.cs | 197 +++++ JotunnModStub/Sverm/SvermBiomass.cs | 243 ++++++ JotunnModStub/Sverm/SvermBlisterTick.cs | 289 +++++++ JotunnModStub/Sverm/SvermBrood.cs | 293 +++++++ JotunnModStub/Sverm/SvermCarapace.cs | 133 ++++ JotunnModStub/Sverm/SvermClawSlot.cs | 283 +++++++ JotunnModStub/Sverm/SvermClaws.cs | 154 ++++ JotunnModStub/Sverm/SvermConfig.cs | 535 +++++++++++++ JotunnModStub/Sverm/SvermConfigManagement.cs | 271 +++++++ JotunnModStub/Sverm/SvermFood.cs | 273 +++++++ JotunnModStub/Sverm/SvermHive.cs | 621 +++++++++++++++ JotunnModStub/Sverm/SvermHiveGoods.cs | 499 ++++++++++++ JotunnModStub/Sverm/SvermHiveStage.cs | 106 +++ JotunnModStub/Sverm/SvermHiveStore.cs | 518 ++++++++++++ JotunnModStub/Sverm/SvermHiveVfx.cs | 150 ++++ JotunnModStub/Sverm/SvermMedicine.cs | 114 +++ JotunnModStub/Sverm/SvermPatches.cs | 337 ++++++++ JotunnModStub/Sverm/SvermProgression.cs | 116 +++ JotunnModStub/Sverm/SvermRace.cs | 102 +++ JotunnModStub/Sverm/SvermStatusEffects.cs | 161 ++++ JotunnModStub/Sverm/SvermStingerForm.cs | 375 +++++++++ JotunnModStub/Sverm/SvermVisuals.cs | 780 +++++++++++++++++++ JotunnModStub/Sverm/SvermWorker.cs | 238 ++++++ 29 files changed, 7236 insertions(+), 4 deletions(-) create mode 100644 JotunnModStub/Sverm/SvermAntennae.cs create mode 100644 JotunnModStub/Sverm/SvermBeehive.cs create mode 100644 JotunnModStub/Sverm/SvermBiomass.cs create mode 100644 JotunnModStub/Sverm/SvermBlisterTick.cs create mode 100644 JotunnModStub/Sverm/SvermBrood.cs create mode 100644 JotunnModStub/Sverm/SvermCarapace.cs create mode 100644 JotunnModStub/Sverm/SvermClawSlot.cs create mode 100644 JotunnModStub/Sverm/SvermClaws.cs create mode 100644 JotunnModStub/Sverm/SvermConfig.cs create mode 100644 JotunnModStub/Sverm/SvermConfigManagement.cs create mode 100644 JotunnModStub/Sverm/SvermFood.cs create mode 100644 JotunnModStub/Sverm/SvermHive.cs create mode 100644 JotunnModStub/Sverm/SvermHiveGoods.cs create mode 100644 JotunnModStub/Sverm/SvermHiveStage.cs create mode 100644 JotunnModStub/Sverm/SvermHiveStore.cs create mode 100644 JotunnModStub/Sverm/SvermHiveVfx.cs create mode 100644 JotunnModStub/Sverm/SvermMedicine.cs create mode 100644 JotunnModStub/Sverm/SvermPatches.cs create mode 100644 JotunnModStub/Sverm/SvermProgression.cs create mode 100644 JotunnModStub/Sverm/SvermRace.cs create mode 100644 JotunnModStub/Sverm/SvermStatusEffects.cs create mode 100644 JotunnModStub/Sverm/SvermStingerForm.cs create mode 100644 JotunnModStub/Sverm/SvermVisuals.cs create mode 100644 JotunnModStub/Sverm/SvermWorker.cs diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs index 097f44d..b064361 100644 --- a/JotunnModStub/ModelBorrow.cs +++ b/JotunnModStub/ModelBorrow.cs @@ -40,6 +40,33 @@ namespace RacesOfValheim public static GameObject Attach(Transform parent, string holderName, string sourcePrefab, Vector3 localPosition, Quaternion localRotation, float targetSize, string label) + { + GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab(sourcePrefab); + if (source == null) + { + Jotunn.Logger.LogWarning($"[{label}] No '{sourcePrefab}' to borrow a model from; nothing was attached."); + + GameObject empty = new GameObject(holderName); + empty.transform.SetParent(parent, false); + empty.transform.localPosition = localPosition; + return empty; + } + + return Attach(parent, holderName, source, localPosition, localRotation, targetSize, label); + } + + /// + /// The same, for a source that has already been found by hand. + /// + /// Not every borrowable model is a top-level prefab. The Seeker's wing, for one, is a + /// child of the creature's death effect rather than a prefab of its own, so no name lookup + /// can reach it and the caller has to walk to it first. Everything past the lookup - the + /// inactive holder, the component strip, the measure-and-ground - is identical, which is + /// exactly why this is an overload and not a second copy. + /// + public static GameObject Attach(Transform parent, string holderName, GameObject source, + Vector3 localPosition, Quaternion localRotation, float targetSize, + string label) { GameObject holder = new GameObject(holderName); holder.transform.SetParent(parent, false); @@ -48,14 +75,14 @@ namespace RacesOfValheim // BEFORE the Instantiate below. This single line is the whole point of the class. holder.SetActive(false); - GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab(sourcePrefab); if (source == null) { - Jotunn.Logger.LogWarning($"[{label}] No '{sourcePrefab}' to borrow a model from; nothing was attached."); + Jotunn.Logger.LogWarning($"[{label}] No source model handed to '{holderName}'; nothing was attached."); holder.SetActive(true); return holder; } + string sourcePrefab = source.name; GameObject copy = Object.Instantiate(source, holder.transform); copy.name = "model"; copy.transform.localPosition = Vector3.zero; diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs index 0ddbc5f..1004049 100644 --- a/JotunnModStub/RaceCompendium.cs +++ b/JotunnModStub/RaceCompendium.cs @@ -16,7 +16,8 @@ namespace RacesOfValheim "Furling Secrets", "Trol Secrets", "Draugh Secrets", - "Dvergar Secrets" + "Dvergar Secrets", + "Sverm Secrets" }; public static void UpdateCompendiumText(Player player) @@ -72,6 +73,142 @@ namespace RacesOfValheim { GenerateDvergarText(knownTexts, state); } + else if (currentRace == SvermConfig.RaceId) + { + GenerateSvermText(knownTexts, state); + } + + // The War Vulture is not a racial power and does not belong inside any one race's + // generator: it is an item whose access list is a config entry. Appended here, once, + // to whichever page was just written - so adding a race to that list in Configuration + // Manager puts the paragraph on that race's page without a line of code changing. + AppendWarVulture(knownTexts, currentRace); + } + + /// + /// The War Vulture's half-page, added to any race allowed to call the bird. + /// + /// Asks WarVultureConfig instead of naming Furling and Dvergar, because the allowed list is + /// a config entry and a hard-coded pair would be wrong the moment anyone edits it. The + /// speeds are read the same way, so the page cannot promise a number the bird does not fly. + /// + private static void AppendWarVulture(Dictionary knownTexts, string race) + { + // Before Bind runs there are no numbers to print. RaceAllowed already survives a null + // config; the speeds below would not. + if (WarVultureConfig.CruiseSpeed == null) return; + if (!WarVultureConfig.RaceAllowed(race)) return; + + string key = race + " Secrets"; + if (!knownTexts.TryGetValue(key, out string page)) return; + + StringBuilder sb = new StringBuilder(page); + sb.AppendLine("\n-- THE WAR VULTURE --\n"); + + sb.AppendLine("A vulture's head kept on a stick, and the bird answers to it. Raise it and the vulture comes back under you. Raise it again and it carries you down, deaf to you until the ground arrives - and a third time lets go of it where you are.\n"); + + sb.AppendLine($"It goes where you look, and it goes as long as you care to stay up: {WarVultureConfig.CruiseSpeed.Value:0.#} meters a second costs it nothing at all. Hold your run key and it gives you {WarVultureConfig.SprintSpeed.Value:0.#} for {WarVultureConfig.SprintSeconds.Value:0} seconds and not a moment longer - there is only so much haste in a bird. Let go and the wind comes back into it in {WarVultureConfig.RechargeSeconds.Value:0} seconds, in the air. You never have to land for it.\n"); + + if (WarVultureConfig.ShowStaminaBar.Value) + sb.AppendLine("What the bird has left is the bar under your own.\n"); + + knownTexts[key] = sb.ToString(); + } + + /// + /// The Sverm's entry, in two halves because the race is two halves: a body that grows on its + /// own, and a colony that has to be built. Figures are read from the live rules and from the + /// colony's own tables rather than restated, so the page cannot drift from the code. + /// + private static void GenerateSvermText(Dictionary knownTexts, int state) + { + SvermProgression.SvermRules rules = SvermProgression.GetRules(state); + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("The Sverm's Colony\n"); + + sb.AppendLine("[Base Passive] Chitin Plating: You do not dress. Chest, legs and helm are carapace and never come off, and at every tier they are worth the full set of the biome ahead of you - at its best quality, weightless, and without the slowness that armour costs anyone else. Cloak and trinket are the only things you may still wear.\n"); + + sb.AppendLine($"[Base Passive] Toxin Immunity: Poison cannot touch you. What can is the club and the torch: you take {rules.BluntWeakness * 100f:0}% more from blunt blows{(rules.FireWeakness > 0f ? $" and {rules.FireWeakness * 100f:0}% more from fire" : ", and fire has stopped being a weakness")}.\n"); + + sb.AppendLine("[Base Passive] Hive Pheromones: No invertebrate will attack you - not leeches, not ticks, not deathsquitos, not seekers, not the bees. Bonemass is not an insect and does not care.\n"); + + sb.AppendLine("[Base Passive] Insect Metabolism: You eat everything anyone else eats, and honey is worth double to you. Alchemical blood is the one thing you will not swallow.\n"); + + sb.AppendLine($"[Base Passive] Vilebone Maulclaws: Your hands are the weapon. Bare-handed blows land at {rules.ClawDamagePercent * 100f:0}% of the claws' full weight, and they cannot be taken from you - draw a sword and they wait, sheathe it and they are back.\n"); + + if (rules.MetabolicSurge) + sb.AppendLine("[Eikthyr Unlock] Metabolic Surge: Running and jumping cost you less, and you jump higher.\n"); + + if (rules.CarryWeightBonus > 0f) + sb.AppendLine($"[Eikthyr Unlock] Ventral Pouches: You carry {rules.CarryWeightBonus:0} more.\n"); + + if (rules.SeedsEdible) + sb.AppendLine("[Elder Unlock] Grinding Mandibles: Seeds are food. Raw nourishment and nothing more - the garden's blessings belong to somebody else.\n"); + + if (rules.SensoryAntennae) + sb.AppendLine("[Elder Unlock] Sensory Antennae: You feel what lives around you, through stone and through soil.\n"); + + if (rules.VenomOnHit > 0f) + sb.AppendLine($"[Bonemass Unlock] Venom Glands: Every blow you land carries +{rules.VenomOnHit:0.#} poison.\n"); + + if (rules.AcidHemolymph > 0f) + sb.AppendLine($"[Bonemass Unlock] Acid Hemolymph: Whoever strikes you in melee takes {rules.AcidHemolymph:0.#} poison back for the trouble.\n"); + + if (rules.FallDamageModifier <= 0f) + sb.AppendLine("[Moder Unlock] Vestigial Wings: Small wings, and no ground hard enough to hurt you.\n"); + + if (rules.StingerMorph) + sb.AppendLine($"[Yagluth Unlock] Stinger Morph ('{SvermConfigManagement.StingerKey.Value}' Key): Become a deathsquito. Real flight and the creature's own sting - and a body made of paper. It is how you kill, not how you travel.\n"); + + if (rules.BodyScale > 1f) + sb.AppendLine("[Queen Unlock] Surrenal Glands: You stand a tenth larger, and the carapace takes its greatest leap.\n"); + + if (rules.CarapaceRegenPerSecond > 0f) + sb.AppendLine($"[Fader Unlock] Carapace Regeneration: You knit yourself back together, {rules.CarapaceRegenPerSecond:0.##} health a second, always.\n"); + + if (rules.Emberform) + sb.AppendLine("[Fader Unlock] Annealed Chitin and Emberform: Eight tiers of burning have turned the flaw into armour - fire no longer hurts you, and the chitin goes black with a red heat under it.\n"); + + // ── The colony + sb.AppendLine("\n-- THE COLONY --\n"); + + if (state < SvermConfig.HiveUnlockState) + { + sb.AppendLine("The colony will not wake until the Elder falls. Until then you are a body, and the body is enough.\n"); + } + else + { + sb.AppendLine($"Brood Mound (Hammer): Your nest, and no more than two of them may stand within {SvermConfig.HiveDensityRadius:0} meters of each other. Press it, or the hive at its foot, to feed it a whole stack out of your pack: any food, any wood, any resin. Honey and royal jelly are medicine now and it will not take them.\n"); + + sb.AppendLine($"Digestion: what you feed it is not yours to spend yet. It seeps into the nest's bank at {SvermConfigManagement.DigestRate:0.#} a second, and only what has arrived can be spent.\n"); + + sb.AppendLine($"Brood Eggs: the nest lays one every {SvermConfig.EggInterval:0} seconds and holds {SvermConfig.EggCapBase + 1} of them at its first stage, one more at each stage after. Every troop costs an egg as well as biomass - the egg grows back, the biomass does not.\n"); + + sb.AppendLine("Hive Market (Hammer): a counter raised within ten meters of a nest. Everything the colony buys is bought here, out of that nest's bank.\n"); + + sb.AppendLine($"Growth: {SvermHiveStage.NameOf(2)} {SvermHiveStage.PriceToLeave(1):0}, {SvermHiveStage.NameOf(3)} {SvermHiveStage.PriceToLeave(2):0}, {SvermHiveStage.NameOf(4)} {SvermHiveStage.PriceToLeave(3):0}. Each one costs that stage's whole tankful and opens the next rung of the roster.\n"); + + StringBuilder roster = new StringBuilder(); + foreach (SvermBrood.Kind kind in SvermBrood.Roster) + { + roster.Append($"{kind.Display} {kind.Price:0} (from {SvermHiveStage.NameOf(kind.Stage)}, at most {kind.Cap}). "); + } + sb.AppendLine($"Troops: {roster}They follow when you ask, walk home when you let them go, and mend themselves.\n"); + + string haulers = state >= SvermConfig.HaulerUnlockState + ? $", and up to {SvermConfigManagement.Haulers} haulers come out of the nest to carry food back into it" + : ", and the haulers who carry food back into it will not hatch until Bonemass falls"; + sb.AppendLine($"Seeker Workers: free, and always free - no biomass, no egg, and a new one when an old one dies. Two trades that never share hands: up to {SvermConfigManagement.Farmers} farmers come out of the infected beehives to work the ground{haulers}. They are half a Seeker in size, in health and in reach, they take no orders and they never follow - they stay where they were born and defend what stands there.\n"); + + sb.AppendLine($"Blister Tick {SvermConfig.TickPrice:0}: buys a slot forever. It runs at what you are fighting and bursts, and the nest grows another one {SvermConfig.TickRespawnSeconds:0} seconds later, free.\n"); + + sb.AppendLine("Surrenal Glands 800 and Hyperplasia 1600: everything hatched after them is born with one star, then two.\n"); + + sb.AppendLine($"The beehives: raise vanilla hives inside the nest's ten meters and the colony takes them over after a minute - twice the speed, three times the honey, and royal jelly instead once Yagluth is down. Press honey or royal jelly on one of your own insects to heal it: {SvermConfig.HoneyHealing:0} and {SvermConfig.RoyalJellyHealing:0}.\n"); + } + + knownTexts["Sverm Secrets"] = sb.ToString(); } /// @@ -296,6 +433,23 @@ namespace RacesOfValheim sb.AppendLine("The bones of a dragon rise at your call, wreathed in frost. It rends with bite and claw, sweeps all around it with a spinning tail (Right Mouse), and its breath carries thrice the fury of Moder's.\n"); } + // ── The station. Figures come from SkadiGolem's own constants, which are also what + // MayRaise enforces, so the page and the refusal message can never disagree. + sb.AppendLine("\n-- THE CRYSTAL GOLEM --\n"); + + if (state < SkadiGolem.ModerProgressionState) + { + sb.AppendLine("The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.\n"); + } + else + { + sb.AppendLine($"Cut one at a stonecutter for a stone golem's trophy, {SkadiGolem.CrystalCost} crystal and a dragon tear. The stone answers to no one who is not Skadi, so what you raise is yours and stays yours.\n"); + + sb.AppendLine($"It is bound to the stonecutter that shaped it and may never leave the {SkadiGolem.LeashRange:0} meters around it - the same circle the station itself builds in. It cannot be named, cannot be ordered and will not follow you. It guards the stone that cut it, and that is the whole of what it does.\n"); + + sb.AppendLine($"One stonecutter holds {SkadiGolem.MaxPerStation} of them, and no more than {SkadiGolem.MaxInArea} may stand within a day's walk of each other. Break the stonecutter and what it cut goes still {SkadiGolem.WitherSeconds:0} seconds later.\n"); + } + knownTexts["Skadi Secrets"] = sb.ToString(); } diff --git a/JotunnModStub/RaceHostilityManager.cs b/JotunnModStub/RaceHostilityManager.cs index 2bd09b4..a60aa07 100644 --- a/JotunnModStub/RaceHostilityManager.cs +++ b/JotunnModStub/RaceHostilityManager.cs @@ -93,6 +93,38 @@ namespace RacesOfValheim __result = false; } } + + // Sverm Race Logic - Hive Pheromones. No progression gate at all, unlike + // Aswid's escalating list: an invertebrate is kin from the first minute. + // + // That absence of a gate is doing real work rather than saving a few lines. + // Every invertebrate in the game lives from the Swamp onward, so a gated + // version would have handed the race nothing until Bonemass; ungated, a + // newborn Sverm walks through leeches and deathsquitoes, which is the whole + // of its early game. + // + // Bonemass is deliberately NOT here. It is a mass of ooze and it would + // qualify, but a boss that ignores the player is not a boss. + if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == SvermConfig.RaceId) + { + string prefabName = monster.gameObject.name.ToLower(); + + // "blob" covers Blob, BlobElite, BlobTar and the Ashlands lava blob + // whatever it turns out to be called - which is why the one prefab name + // still unconfirmed in the design doc costs nothing here. + // "seeker" covers Seeker, SeekerBrood, SeekerBrute and SeekerQueen. + bool isKin = prefabName.Contains("blob") + || prefabName.Contains("leech") + || prefabName.Contains("tick") + || prefabName.Contains("deathsquito") + || prefabName.Contains("gjall") + || prefabName.Contains("seeker"); + + if (isKin && !prefabName.Contains("bonemass")) + { + __result = false; + } + } } } } diff --git a/JotunnModStub/RaceScale.cs b/JotunnModStub/RaceScale.cs index f471666..bdbdde7 100644 --- a/JotunnModStub/RaceScale.cs +++ b/JotunnModStub/RaceScale.cs @@ -20,7 +20,12 @@ namespace RacesOfValheim "Trol", "Furling", DvergarConfig.RaceId, - TrentaConfig.RaceId + TrentaConfig.RaceId, + // Sverm sizes itself only from the Queen on (Surrenal Glands, +10%). It is listed here + // for every tier all the same: below that tier its own ApplyScale asks for 1, which is + // the same answer another race's reset would give, and being on the list is what stops + // those resets from fighting it once the +10% does arrive. + SvermConfig.RaceId }; public static bool ManagesOwnScale(string race) diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index c04e8d5..70dc814 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -34,6 +34,7 @@ namespace RacesOfValheim FurlingConfig.Bind(Config); SkadiConfig.Bind(Config); SkeletonConfig.Bind(Config); + SvermConfigManagement.Bind(Config); TrentaConfigManagement.Bind(Config); TrolConfig.Bind(Config); // Not a race: a summoned mount two races share, so it binds after the races rather @@ -49,6 +50,7 @@ namespace RacesOfValheim gameObject.AddComponent(); gameObject.AddComponent(); gameObject.AddComponent(); + gameObject.AddComponent(); // Not a race: a perk two races share (Skadi and Trol build inside troll caves), so it // gets its own component rather than living inside either one's Update. gameObject.AddComponent(); @@ -122,6 +124,7 @@ namespace RacesOfValheim DraughRace.Instance.CreateModAssets(); DvergarRace.Instance.CreateModAssets(); TrentaRace.Instance.CreateModAssets(); + SvermRace.Instance.CreateModAssets(); WarVultureItem.Register(); } // --- RACE SELECTION UI --- @@ -266,6 +269,7 @@ namespace RacesOfValheim // Row 3 (y = -140) CreateRaceButtonWithConfirm("Dvergar", new Vector2(-450, -140), GetDvergarIcon(), "Small, stubborn smiths of the deep. Frail of frame, but masters of metal, mine and market.", SelectDvergar); CreateRaceButtonWithConfirm("Trenta", new Vector2(-150, -140), GetTrentaIcon(), "Tree-born folk, kin to root and leaf. Patient and hard to fell.", SelectTrenta); + CreateRaceButtonWithConfirm("Sverm", new Vector2(150, -140), GetSvermIcon(), "Chitin-born swarm kin. Armoured from birth and never slowed, venomous, at peace with every crawling thing - but blunt trauma and fire find the seams.", SelectSverm); GUIManager.BlockInput(true); } @@ -632,6 +636,58 @@ namespace RacesOfValheim } } + private void SelectSverm() + { + if (Player.m_localPlayer != null) + { + Player.m_localPlayer.m_customData["Race"] = SvermConfig.RaceId; + ZNetView nview = Player.m_localPlayer.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", SvermConfig.RaceId); + + Player.m_localPlayer.GetSEMan().AddStatusEffect(SvermConfig.StatsSE.GetStableHashCode(), true); + + // The carapace seals chest, legs and helmet, so whatever the player was wearing in + // those slots has to come off before the visual rebuild - otherwise the old chest + // stays on screen underneath a carapace that the equip patch will refuse to remove + // later, because the refusal is on EQUIPPING, not on unequipping. + Humanoid humanoid = Player.m_localPlayer; + foreach (ItemDrop.ItemData.ItemType slot in SvermConfig.SealedSlots) + { + ItemDrop.ItemData worn = null; + foreach (ItemDrop.ItemData item in humanoid.GetInventory().GetEquippedItems()) + { + if (item != null && item.m_shared != null && item.m_shared.m_itemType == slot) { worn = item; break; } + } + if (worn != null) humanoid.UnequipItem(worn, false); + } + + VisEquipment visEq = Player.m_localPlayer.GetComponent(); + if (visEq != null) + { + visEq.GetType().GetMethod("UpdateVisuals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); + } + + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Sverm."); + CloseRaceSelectionMenu(); + } + } + + private Sprite GetSvermIcon() + { + GameObject prefab = PrefabManager.Cache.GetPrefab("TrophySeekerBrute")?.gameObject; + if (prefab == null) prefab = PrefabManager.Cache.GetPrefab("TrophySeeker")?.gameObject; + if (prefab == null) prefab = PrefabManager.Cache.GetPrefab("Chitin")?.gameObject; + if (prefab != null) + { + ItemDrop drop = prefab.GetComponent(); + if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0) + { + return drop.m_itemData.m_shared.m_icons[0]; + } + } + return null; + } + private Sprite GetDvergarIcon() { GameObject prefab = PrefabManager.Cache.GetPrefab("HelmetDverger")?.gameObject; diff --git a/JotunnModStub/Sverm/SvermAntennae.cs b/JotunnModStub/Sverm/SvermAntennae.cs new file mode 100644 index 0000000..f256670 --- /dev/null +++ b/JotunnModStub/Sverm/SvermAntennae.cs @@ -0,0 +1,170 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Sensory Antennae: from The Elder on, a Sverm feels every living thing around it and reads + /// what each one is by colour. + /// + /// This is the Aswid's Auspex (AswidRace, the sensesCheckTimer loop) with one thing added: the + /// Aswid marks everything green because it only wants to know that something is THERE. An + /// insect's antennae are a chemical sense, and a chemical sense tells kin from prey from + /// threat - so the light is the same trick and the colour carries the information. + /// + /// red - hostile + /// yellow - invertebrate: kin, and by Hive Pheromones already harmless to you + /// azure - yours: tamed, and in due course the colony's own brood + /// green - alive and indifferent + /// + /// NOTHING HERE IS REPLICATED. A Light created on this client and parented to a creature costs + /// other players nothing and never touches the ZDO - the same reason the Aswid and the Dvergar + /// both mark with lights rather than with anything the server would have to carry. + /// + /// The cost that IS real is local: this is a passive with no cooldown, so in a busy forest it + /// can hold a dozen or more point lights at once, and Valheim renders few per pixel. If it + /// ever misbehaves the lever is the radius, not the mechanism. + /// + public static class SvermAntennae + { + private const string LightName = "SvermAntennaeLight"; + + private static readonly Dictionary lights = new Dictionary(); + private static readonly List stale = new List(); + + private static float nextSweep; + + public static void Tick(Player player) + { + bool active = player != null + && player == Player.m_localPlayer + && SvermVisuals.IsSvermPlayer(player) + && !player.IsDead() + && SvermProgression.Current.SensoryAntennae; + + if (!active) + { + ClearAll(); + return; + } + + if (Time.time < nextSweep) return; + nextSweep = Time.time + SvermConfig.AntennaeInterval; + + Sweep(player); + } + + private static void Sweep(Player player) + { + Vector3 centre = player.transform.position; + float radius = SvermConfig.AntennaeRadius; + + HashSet inRange = new HashSet(); + + foreach (Character c in Character.GetAllCharacters()) + { + if (c == null || c == player || c.IsDead()) continue; + if (Vector3.Distance(c.transform.position, centre) > radius) continue; + + inRange.Add(c); + + Color colour = ColourFor(player, c); + + if (lights.TryGetValue(c, out GameObject existing) && existing != null) + { + // Already lit. Only the colour can have changed - a boar that turns hostile, + // a creature that gets tamed - and re-colouring is cheaper than rebuilding. + Light live = existing.GetComponent(); + if (live != null && live.color != colour) live.color = colour; + continue; + } + + lights[c] = BuildLight(c, colour); + } + + // Anything no longer in range, or dead, or gone. Collected first and removed after: + // deleting from a dictionary while enumerating it throws. + stale.Clear(); + foreach (KeyValuePair pair in lights) + { + if (pair.Key == null || !inRange.Contains(pair.Key)) stale.Add(pair.Key); + } + + foreach (Character gone in stale) + { + if (lights.TryGetValue(gone, out GameObject go) && go != null) Object.Destroy(go); + lights.Remove(gone); + } + } + + /// + /// Order matters more than the colours do. + /// + /// Tamed is checked FIRST because a tamed wolf is still an enemy of nothing and a friend of + /// yours, and asking IsEnemy first would paint your own animals as threats. Invertebrates + /// come next because Hive Pheromones has already made them harmless, so calling them + /// hostile would contradict the rest of the race. Only then does the hostile test run, and + /// everything left over is simply alive. + /// + private static Color ColourFor(Player player, Character c) + { + if (c.IsTamed()) return SvermConfig.AntennaeKinColor; + + if (IsInvertebrate(c)) return SvermConfig.AntennaeInvertebrateColor; + + if (BaseAI.IsEnemy(player, c)) return SvermConfig.AntennaeHostileColor; + + return SvermConfig.AntennaePassiveColor; + } + + /// + /// The same substring test RaceHostilityManager uses for Hive Pheromones, and deliberately + /// so: whatever counts as kin for the truce has to count as kin for the antennae, or the + /// player is told one thing and shown another. + /// + private static bool IsInvertebrate(Character c) + { + string prefabName = c.gameObject.name.ToLowerInvariant(); + + if (prefabName.Contains("bonemass")) return false; + + return prefabName.Contains("blob") + || prefabName.Contains("leech") + || prefabName.Contains("tick") + || prefabName.Contains("deathsquito") + || prefabName.Contains("gjall") + || prefabName.Contains("seeker"); + } + + private static GameObject BuildLight(Character c, Color colour) + { + GameObject go = new GameObject(LightName); + go.transform.SetParent(c.transform); + go.transform.position = c.GetCenterPoint(); + + Light light = go.AddComponent(); + light.type = LightType.Point; + light.color = colour; + light.range = SvermConfig.AntennaeLightRange; + light.intensity = SvermConfig.AntennaeLightIntensity; + + // No shadows, ever. A dozen shadow-casting point lights in a forest is a slideshow, + // and none of these lights is meant to light the world - only to say "here". + light.shadows = LightShadows.None; + + return go; + } + + /// Puts out every light. Called when the perk stops applying, and on death. + public static void ClearAll() + { + if (lights.Count == 0) return; + + foreach (KeyValuePair pair in lights) + { + if (pair.Value != null) Object.Destroy(pair.Value); + } + lights.Clear(); + } + } +} diff --git a/JotunnModStub/Sverm/SvermBeehive.cs b/JotunnModStub/Sverm/SvermBeehive.cs new file mode 100644 index 0000000..bd0ad1e --- /dev/null +++ b/JotunnModStub/Sverm/SvermBeehive.cs @@ -0,0 +1,197 @@ +using System.Collections.Generic; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The takeover of the ordinary beehives standing inside a nest's aura. + /// + /// A minute inside the aura and a hive stops being the player's and becomes the colony's: an + /// egg pushes out through the roof, and from then on it fills twice as fast and holds three + /// times as much. After Yagluth what comes out is royal jelly instead of honey. + /// + /// NOTHING IS CLONED AND NOTHING IS REPLACED. The vanilla Beehive component is retuned in + /// place on that one instance, and the state lives on that instance's ZDO - so an infected + /// hive stays infected across a reload, other players see the same thing, and a hive outside + /// any aura is never touched. The egg is a borrowed model parented to the hive, exactly the + /// way the crest is worn on a bone. + /// + /// Retuning a COMPONENT is safe where retuning m_shared would not be: m_secPerUnit lives on + /// the instance, not on shared item data, so one hive changing does not change every hive in + /// the world. + /// + public static class SvermBeehive + { + /// Written on the hive's own ZDO, so the takeover survives a reload. + private const string InfectedKey = "RacesOfValheim_SvermInfected"; + + /// When this hive first came under an aura, so the minute can be counted. + private const string ClaimedAtKey = "RacesOfValheim_SvermClaimedAt"; + + private const string EggName = "SvermHiveEgg"; + + /// Values captured before we touched them, so a hive can be handed back intact. + private static readonly Dictionary originalSecPerUnit = new Dictionary(); + + // ─── The sweep ─────────────────────────────────────────────────────── + + /// + /// Called by the nest, on a timer. Claims what is in range and ripens what has waited. + /// + public static void SweepAura(Vector3 nest) + { + foreach (Beehive hive in Find(nest)) + { + ZNetView nview = hive.GetComponent(); + if (nview == null || !nview.IsValid()) continue; + + if (nview.GetZDO().GetBool(InfectedKey, false)) + { + Apply(hive, nview); + continue; + } + + // First sighting starts the clock. Stored as world time rather than counted in a + // field, because a nest that unloads and comes back must not restart the minute. + double claimedAt = nview.GetZDO().GetFloat(ClaimedAtKey, 0f); + if (claimedAt <= 0.0) + { + nview.GetZDO().Set(ClaimedAtKey, (float)ZNet.instance.GetTimeSeconds()); + continue; + } + + if (ZNet.instance.GetTimeSeconds() - claimedAt < SvermConfig.BeehiveInfectionSeconds) continue; + + nview.GetZDO().Set(InfectedKey, true); + Apply(hive, nview); + + Jotunn.Logger.LogInfo("[Sverm] A beehive has been taken over by the colony."); + } + } + + /// + /// Retunes one infected hive and makes sure it is wearing its egg. + /// + /// Re-applied on every sweep rather than once at infection: Valheim rebuilds these + /// components when the zone reloads, and a hive that came back at vanilla speed would + /// quietly undo the whole feature with nothing in the log to say so. + /// + private static void Apply(Beehive hive, ZNetView nview) + { + if (!originalSecPerUnit.ContainsKey(hive)) originalSecPerUnit[hive] = hive.m_secPerUnit; + + float wanted = originalSecPerUnit[hive] / SvermConfig.BeehiveSpeedMultiplier; + if (!Mathf.Approximately(hive.m_secPerUnit, wanted)) hive.m_secPerUnit = wanted; + + int wantedMax = Mathf.RoundToInt(SvermConfig.BeehiveBaseMaxHoney * SvermConfig.BeehiveCapacityMultiplier); + if (hive.m_maxHoney != wantedMax) hive.m_maxHoney = wantedMax; + + // After Yagluth the colony stops making honey and starts making royal jelly. Read from + // ObjectDB rather than held as a reference, because the item has to exist first. + string wantedItem = BossProgressionManager.GetCurrentProgressionState() >= SvermConfig.RoyalJellyHiveState + ? SvermConfig.RoyalJellyPrefab + : "Honey"; + + if (hive.m_honeyItem == null || hive.m_honeyItem.gameObject.name != wantedItem) + { + ItemDrop replacement = PrefabManager.Cache.GetPrefab(wantedItem); + if (replacement != null) hive.m_honeyItem = replacement; + } + + EnsureEgg(hive.transform); + } + + /// + /// The egg on the roof: a permanent mark, and the only way to tell an infected hive from an + /// ordinary one at a glance. + /// + /// Borrowed through ModelBorrow, so it arrives stripped of its ItemDrop and its networking + /// and cannot be picked up, walked into, or dropped on the floor. + /// + private static void EnsureEgg(Transform hive) + { + if (hive.Find(EggName) != null) return; + + ModelBorrow.Attach( + hive, + EggName, + SvermConfig.HiveEggPrefab, + Vector3.up * SvermConfigManagement.EggHeight, + Quaternion.identity, + SvermConfigManagement.EggSize, + "Sverm"); + } + + // ─── Lookups ───────────────────────────────────────────────────────── + + /// Every beehive standing inside a nest's aura. + public static List Find(Vector3 nest) + { + List found = new List(); + + foreach (Collider collider in Physics.OverlapSphere(nest, SvermConfig.HiveAuraRadius)) + { + if (collider == null) continue; + + Beehive hive = collider.GetComponentInParent(); + if (hive != null && !found.Contains(hive)) found.Add(hive); + } + + return found; + } + + public static int CountInAura(Vector3 nest) => Find(nest).Count; + + public static int CountInfectedInAura(Vector3 nest) + { + int count = 0; + foreach (Beehive hive in Find(nest)) + { + if (IsInfected(hive)) count++; + } + return count; + } + + /// + /// Puts the colony's marks on every taken hive in range: flies always, green gas only when + /// the hive is FULL and has nothing left to do but wait for someone to empty it. + /// + /// Called by the nest on every client, not from the owner's sweep - particles are local, and + /// a hive that only smoked on the host's screen would be half a feature. + /// + public static void DressInfected(Vector3 nest) + { + float scale = SvermConfigManagement.BeehiveVfxScale; + + foreach (Beehive hive in Find(nest)) + { + if (!IsInfected(hive)) continue; + + SvermHiveVfx.EnsureFlies(hive.transform, scale); + SvermHiveVfx.SetGas(hive.transform, IsFull(hive), scale); + } + } + + /// + /// Whether the hive has no room left for honey. + /// + /// GetHoneyLevel is private in the assembly this project compiles against - like + /// Container.Save and Inventory.FindEmptySlot - so it is read through Traverse rather than + /// called, and rather than second-guessed by reading the ZDO key by hand. + /// + private static bool IsFull(Beehive hive) + { + if (hive == null) return false; + + int level = HarmonyLib.Traverse.Create(hive).Method("GetHoneyLevel").GetValue(); + return level >= hive.m_maxHoney; + } + + public static bool IsInfected(Beehive hive) + { + ZNetView nview = hive != null ? hive.GetComponent() : null; + return nview != null && nview.IsValid() && nview.GetZDO().GetBool(InfectedKey, false); + } + } +} diff --git a/JotunnModStub/Sverm/SvermBiomass.cs b/JotunnModStub/Sverm/SvermBiomass.cs new file mode 100644 index 0000000..e951543 --- /dev/null +++ b/JotunnModStub/Sverm/SvermBiomass.cs @@ -0,0 +1,243 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The nest's tank, and the rule for what may go into it. + /// + /// The number lives on the nest's own ZDO rather than in a field, so it survives a reload, a + /// zone unload, and a different player walking up to the same nest. + /// + /// WHAT COUNTS AS FUEL is the part worth reading. Anything the Sverm could eat, at half its + /// nutritional sum, plus a flat rate for wood and resin - EXCEPT honey and royal jelly, which + /// stopped being fuel the moment they became medicine. Feeding the colony its own healing + /// supply would be the worst kind of bug: quiet, expensive, and entirely the mod's fault. + /// + public static class SvermBiomass + { + // ─── What burns ────────────────────────────────────────────────────── + + public static bool IsFuel(ItemDrop.ItemData item) + { + if (item == null || item.m_shared == null) return false; + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : ""; + + // The medicine. Explicitly first, so no later rule can accidentally readmit it. + if (prefabName == "Honey" || prefabName == SvermConfig.RoyalJellyPrefab) return false; + + if (IsWood(prefabName)) return true; + + return item.m_shared.m_food + item.m_shared.m_foodStamina + item.m_shared.m_foodEitr > 0f; + } + + /// + /// Wood and resin, at a flat rate regardless of biome. Ashwood is out. + /// + /// Flat because a per-biome table for firewood is a lot of bookkeeping for a resource whose + /// whole job is to be the bulk filler while food is the concentrate. + /// + private static bool IsWood(string prefabName) + { + if (string.IsNullOrEmpty(prefabName)) return false; + if (prefabName.ToLowerInvariant().Contains("ash")) return false; // ashwood excluded + + return prefabName == "Wood" + || prefabName == "RoundLog" + || prefabName == "FineWood" + || prefabName == "ElderBark" + || prefabName == "YggdrasilWood" + || prefabName == "Resin"; + } + + /// What one of this item is worth in the tank. + public static float ValueOf(ItemDrop.ItemData item) + { + if (!IsFuel(item)) return 0f; + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : ""; + if (IsWood(prefabName)) return SvermConfig.WoodBiomassValue; + + return (item.m_shared.m_food + item.m_shared.m_foodStamina + item.m_shared.m_foodEitr) * 0.5f; + } + + // ─── The tank ──────────────────────────────────────────────────────── + // + // THREE NUMBERS, NOT ONE, and the middle one is the whole point of the shop. What the hive + // has just been handed is not what the hive can spend: everything it eats lands in + // DIGESTION and seeps into the BANK at a fixed rate, and only the bank ever pays for + // anything. CAPACITY is the stage's ceiling and it covers both together, because a stomach + // that is full is full whether or not the last meal has gone down yet. + + // The bank keeps the key the tank has always had, so a hive standing in somebody's world + // reads back with its biomass intact rather than at zero. + private const string BankKey = "RacesOfValheim_SvermBiomass"; // spendable + private const string DigestKey = "RacesOfValheim_SvermDigesting"; // eaten, not yet spendable + private const string ClockKey = "RacesOfValheim_SvermDigestedAt"; // world second of the last digest + + /// What the hive can actually spend. + public static float Bank(Transform nest) + { + ZDO zdo = Zdo(nest); + return zdo != null ? zdo.GetFloat(BankKey, 0f) : 0f; + } + + /// Eaten but not yet spendable. + public static float Digesting(Transform nest) + { + ZDO zdo = Zdo(nest); + return zdo != null ? zdo.GetFloat(DigestKey, 0f) : 0f; + } + + public static float Capacity(Transform nest) + { + return SvermHiveStage.Capacity(SvermHiveStage.Of(nest)); + } + + /// How much more the hive can hold, digested or not. + public static float Space(Transform nest) + { + return Mathf.Max(0f, Capacity(nest) - Bank(nest) - Digesting(nest)); + } + + /// Adds one item's worth. Returns what actually fitted. + public static float Deposit(Transform nest, ItemDrop.ItemData item) + { + return Swallow(nest, ValueOf(item)); + } + + /// + /// Puts raw biomass into digestion, clamped to what is left of the tank. Returns what fitted. + /// + /// EVERYTHING the hive eats comes through here - the shop's one button and the haulers' + /// chest round alike. A meal that arrived by way of a chest is still a meal, and giving the + /// haulers a shortcut straight into the bank would make the wait the shop imposes + /// avoidable by anyone who owns a box. + /// + public static float Swallow(Transform nest, float amount) + { + if (amount <= 0f) return 0f; + + ZNetView nview = Claim(nest); + if (nview == null) return 0f; + + float accepted = Mathf.Min(amount, Space(nest)); + if (accepted <= 0f) return 0f; + + ZDO zdo = nview.GetZDO(); + + // The clock is started by the first mouthful and not before: an untouched hive has no + // "last digested" second, and reading a missing key as zero would hand it every second + // since the world began the moment it was finally fed. + // + // WHOLE SECONDS IN A LONG FIELD, deliberately and everywhere. ZDO.Set takes a long as + // readily as a float, and a clock written through one overload and read through the + // other is a key that always answers with its default - which here means an elapsed + // time of zero, forever, and a hive that digests nothing at all. + if (zdo.GetFloat(DigestKey, 0f) <= 0f) zdo.Set(ClockKey, WorldSecond()); + + zdo.Set(DigestKey, zdo.GetFloat(DigestKey, 0f) + accepted); + return accepted; + } + + /// + /// Moves what time has earned from digestion into the bank. + /// + /// Measured against the WORLD clock rather than frames, so a hive nobody is standing next + /// to still digests: come back to it in the morning and the meal has gone down. The owner + /// calls this on a timer - see SvermHiveBehaviour. + /// + public static void Digest(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + ZDO zdo = nview.GetZDO(); + float digesting = zdo.GetFloat(DigestKey, 0f); + if (digesting <= 0f) return; + + long now = WorldSecond(); + long last = zdo.GetLong(ClockKey, now); + long elapsed = now - last; + + // Whole seconds only, and the clock only moves by what was actually consumed, so the + // fraction left over is not quietly lost on every tick. + if (elapsed <= 0L) return; + + float moved = Mathf.Min(digesting, SvermConfigManagement.DigestRate * elapsed); + zdo.Set(ClockKey, now); + if (moved <= 0f) return; + + zdo.Set(DigestKey, digesting - moved); + zdo.Set(BankKey, zdo.GetFloat(BankKey, 0f) + moved); + } + + /// + /// Puts spent biomass straight back in the bank, past the digestion. + /// + /// Only ever for a purchase that was paid for and then could not be delivered. It skips the + /// digestion on purpose: the hive already digested this once, and making the player wait + /// again for a thing they did not get would be a second punishment for our own race. + /// + public static void Refund(Transform nest, float amount) + { + if (amount <= 0f) return; + + ZNetView nview = Claim(nest); + if (nview == null) return; + + ZDO zdo = nview.GetZDO(); + zdo.Set(BankKey, Mathf.Min(zdo.GetFloat(BankKey, 0f) + amount, Capacity(nest))); + } + + /// Takes from the bank if there is enough. All or nothing. + public static bool Spend(Transform nest, float amount) + { + ZNetView nview = Claim(nest); + if (nview == null) return false; + + ZDO zdo = nview.GetZDO(); + float bank = zdo.GetFloat(BankKey, 0f); + if (bank < amount) return false; + + zdo.Set(BankKey, bank - amount); + return true; + } + + // ─── Plumbing ──────────────────────────────────────────────────────── + + private static ZDO Zdo(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + return nview != null && nview.IsValid() ? nview.GetZDO() : null; + } + + /// + /// The nest's view, owned by us before we write to it. + /// + /// A write to a ZDO somebody else owns survives until their copy comes back over the wire + /// and overwrites it - which reads, to the player who just sold half their larder, as the + /// hive having eaten it and forgotten. + /// + private static ZNetView Claim(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return null; + if (!nview.IsOwner()) nview.ClaimOwnership(); + return nview; + } + + /// + /// The world clock in whole seconds. + /// + /// The world's own time and not Time.time, so the answer means the same thing to a hive + /// that has just loaded as to one that has been standing there all evening. Zero when there + /// is no net yet, which only happens before a world is up - and Digest reads a missing + /// clock as "now", so nothing is ever handed a windfall. + /// + private static long WorldSecond() + { + return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L; + } + } +} diff --git a/JotunnModStub/Sverm/SvermBlisterTick.cs b/JotunnModStub/Sverm/SvermBlisterTick.cs new file mode 100644 index 0000000..f8c0869 --- /dev/null +++ b/JotunnModStub/Sverm/SvermBlisterTick.cs @@ -0,0 +1,289 @@ +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Blister Tick: fifty biomass buys a SLOT, and the slot is forever. + /// + /// SECTION 12, and it is the one troop that does not behave like the others. It runs at what the + /// colony is fighting and bursts. It leaves nothing behind, it heals nothing, and it does not + /// need to: thirty seconds after it dies the nest grows another one, free - no egg, no biomass. + /// The slot that was paid for is permanent, exactly like the Skeleton's chains, and ten of them + /// coming back every half minute is a continuous stream of explosions rather than a squad. That + /// is the whole point of the unit and the reason its damage is borrowed from two bombs the game + /// already balanced instead of from a number somebody invented. + /// + /// THE DAMAGE IS READ, NOT COPIED: the poison blob's own projectile prefab is asked what it + /// hits for, once, at registration. Ooze up to the second stage of the nest, the elite blob + /// after that - section 12's "BombOoze then BombBile" expressed in the two projectiles this + /// build actually ships. + /// + public static class SvermBlisterTick + { + public const string PrefabName = "SvermBlisterTick"; + public const string DisplayName = "Blister Tick"; + private const string SourcePrefab = "Tick"; + + /// How many slots this nest has bought. Permanent, and the respawn reads it. + private const string SlotKey = "RacesOfValheim_SvermTickSlots"; + + /// The blast, in rising order of nastiness. Both are verified manifest names. + private const string EarlyBlast = "BombBlob_Poison_projectile"; + private const string LateBlast = "BombBlob_PoisonElite_projectile"; + private const string BlastEffect = "BombBlob_explode_poison"; + + private static HitData.DamageTypes earlyDamage; + private static HitData.DamageTypes lateDamage; + private static float blastRadius = 4f; + + // ─── Registration ──────────────────────────────────────────────────── + + public static void Register() + { + GameObject source = PrefabManager.Cache.GetPrefab(SourcePrefab); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{SourcePrefab}' to build the Blister Tick from; no ticks."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, source); + if (prefab == null) return; + + Character character = prefab.GetComponent(); + if (character != null) character.m_name = DisplayName; + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = SvermConfig.TroopLeashRange; + + // Nothing to farm off something that respawns for free forever. This one matters more + // than on the other troops for exactly that reason. + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = PrefabName; + thrall.m_commandingRace = SvermConfig.RaceId; + thrall.m_maxFollowers = -1; + thrall.m_witherSeconds = SvermConfig.TroopWitherSeconds; + thrall.m_homeCheckRange = SvermConfig.TroopHomeCheckRange; + thrall.m_refusalMessage = "It does not smell your colony on you."; + + // No SkeletonSentryBehaviour. A tick that healed itself would be a tick that never gets + // round to exploding, which is its entire job. + prefab.AddComponent(); + + ReadBlastDamage(); + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Sverm] Registered '{PrefabName}' from '{SourcePrefab}'."); + } + + /// + /// Asks the two blob projectiles what they hit for, once. A missing one leaves its stage on + /// the fallback rather than on zero - a tick that exploded for nothing would look like it + /// was working. + /// + private static void ReadBlastDamage() + { + earlyDamage = DamageOf(EarlyBlast, SvermConfig.TickFallbackDamage); + lateDamage = DamageOf(LateBlast, SvermConfig.TickFallbackDamage * 2f); + } + + private static HitData.DamageTypes DamageOf(string projectileName, float fallbackPoison) + { + GameObject prefab = PrefabManager.Cache.GetPrefab(projectileName); + Projectile projectile = prefab != null ? prefab.GetComponent() : null; + + if (projectile == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{projectileName}' to price the Blister Tick's blast; " + + $"it falls back to {fallbackPoison:0} poison."); + return new HitData.DamageTypes { m_poison = fallbackPoison }; + } + + if (projectile.m_aoe > 0f) blastRadius = projectile.m_aoe; + return projectile.m_damage; + } + + /// What one blast does, at this nest's stage. Section 12's two tiers. + public static HitData.DamageTypes BlastFor(int stage) + { + return stage >= SvermConfig.TickLateBlastStage ? lateDamage : earlyDamage; + } + + public static float BlastRadius => blastRadius; + + public static GameObject BlastVfx() + { + return PrefabManager.Cache.GetPrefab(BlastEffect); + } + + // ─── The slots ─────────────────────────────────────────────────────── + + public static int SlotsOf(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return 0; + + return Mathf.Clamp(nview.GetZDO().GetInt(SlotKey, 0), 0, SvermConfigManagement.BlisterTick); + } + + public static void BuySlot(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(SlotKey, SlotsOf(nest) + 1); + } + + /// How many are alive right now, counted off the nest the way the roster is. + public static int CountAlive(SvermHiveBehaviour hive) + { + if (hive == null) return 0; + + int count = 0; + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(hive.transform.position)) + { + if (thrall != null && thrall.Kind == PrefabName) count++; + } + return count; + } + + /// + /// Fills the empty slots, free. Called by the nest on its own timer, owner only. + /// + /// One per call rather than all at once: ten ticks arriving in the same frame after a fight + /// would be a wall of bodies, and a slot every half minute is what the design asks for. + /// + public static void Replace(SvermHiveBehaviour hive) + { + if (hive == null) return; + + int slots = SlotsOf(hive.transform); + if (slots <= 0 || CountAlive(hive) >= slots) return; + + Hatch(hive); + } + + public static bool Hatch(SvermHiveBehaviour hive) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(PrefabName) : null; + if (prefab == null) return false; + + Vector3 offset = Random.insideUnitSphere * 2f; + offset.y = 0f; + GameObject spawned = Object.Instantiate(prefab, hive.transform.position + offset + Vector3.up * 0.5f, + Quaternion.Euler(0f, Random.Range(0, 360), 0f)); + if (spawned == null) return false; + + Character character = spawned.GetComponent(); + if (character != null) + { + int stars = SvermBroodStars.Of(hive.transform); + if (stars > 0) character.SetLevel(1 + stars); + } + + RaisedThrall thrall = spawned.GetComponent(); + if (thrall != null) thrall.Bind(hive.transform.position); + + return true; + } + } + + /// + /// One tick's short life: get close to something the colony is fighting, and burst. + /// + /// It goes off on ITS OWN TARGET and not on anything that happens to be near. A tick that + /// exploded because a boar walked past would clear its own base of livestock, and one that went + /// off next to the player it was following would be a trap rather than a weapon - so the blast + /// spares everything tame, the player included. + /// + public class SvermBlisterTickBehaviour : MonoBehaviour + { + private Character m_character; + private MonsterAI m_ai; + private ZNetView m_nview; + private bool m_bursting; + + private void Awake() + { + m_character = GetComponent(); + m_ai = GetComponent(); + m_nview = GetComponent(); + + InvokeRepeating("TickCheck", 1f, 0.5f); + } + + private void TickCheck() + { + if (m_bursting) return; + if (m_character == null || m_character.IsDead()) return; + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + if (m_ai == null) return; + + Character target = m_ai.GetTargetCreature(); + if (target == null || target.IsDead()) return; + + if (Vector3.Distance(transform.position, target.transform.position) > SvermConfig.TickBurstRange) return; + + Burst(); + } + + private void Burst() + { + m_bursting = true; + + Vector3 where = transform.position + Vector3.up * 0.3f; + + GameObject vfx = SvermBlisterTick.BlastVfx(); + if (vfx != null) Object.Instantiate(vfx, where, Quaternion.identity); + + // The stage of whichever nest it belongs to. A tick whose nest has been torn down still + // bursts - at the early damage, which is the honest answer when there is nobody left to + // ask. + int stage = SvermHiveStage.First; + RaisedThrall thrall = GetComponent(); + Vector3? anchor = thrall != null ? thrall.Anchor : null; + if (anchor != null) + { + SvermHiveBehaviour nest = SvermHive.NearestNest(anchor.Value, 2f); + if (nest != null) stage = SvermHiveStage.Of(nest.transform); + } + + HitData.DamageTypes damage = SvermBlisterTick.BlastFor(stage); + + foreach (Collider collider in Physics.OverlapSphere(where, SvermBlisterTick.BlastRadius)) + { + if (collider == null) continue; + + Character victim = collider.GetComponentInParent(); + if (victim == null || victim == m_character || victim.IsDead()) continue; + + // Everything of ours walks away from this: the player, their tames, and every other + // thing the colony has hatched. + if (victim.IsPlayer() || victim.IsTamed()) continue; + + HitData hit = new HitData(); + hit.m_damage = damage; + hit.m_point = victim.GetCenterPoint(); + hit.m_dir = (victim.transform.position - where).normalized; + hit.SetAttacker(m_character); + victim.Damage(hit); + } + + // Its own death is the cost of the attack, and it is what the free respawn is measured + // from: the nest sees an empty slot and grows another. + // + // Killed through RaisedThrall.Kill rather than by writing health to zero, because that + // is the one path in this mod already proven to take a summoned creature all the way + // through the game's own death sequence. + if (thrall != null) thrall.Kill(); + else m_character.SetHealth(0f); + } + } +} diff --git a/JotunnModStub/Sverm/SvermBrood.cs b/JotunnModStub/Sverm/SvermBrood.cs new file mode 100644 index 0000000..1d52a0e --- /dev/null +++ b/JotunnModStub/Sverm/SvermBrood.cs @@ -0,0 +1,293 @@ +using System.Collections.Generic; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The army: four creatures, hatched at the market, bound to the nest that paid for them. + /// + /// TWO RESOURCES IN PARALLEL, which is section 10.2 and the whole shape of the colony. The EGG + /// is the slot and it grows back on its own; the BIOMASS is the price and it does not. A troop + /// needs both, so a hive with a full tank and no eggs waits, and a hive full of eggs and no + /// biomass waits differently. + /// + /// Nothing here is new machinery. A troop is a RaisedThrall - the same component the Draugh's + /// spawner, the Dvergar's bank and the Fenrir's trough hang their rosters on - so the follow and + /// stay orders, the leash, the walk home and the withering when the station falls all come for + /// free and behave exactly like every other summoned thing in the mod. The self-healing is + /// SkeletonSentryBehaviour, reused whole, which is section 11.2 word for word. + /// + public static class SvermBrood + { + /// + /// What every troop prefab's name starts with. One place, because two things ask the + /// question "is this creature one of ours" - the roster and the medicine. + /// + public const string PrefabPrefix = "SvermTroop_"; + + /// One rung of the ladder, from section 11's table. + public class Kind + { + public string Id; + public string Display; + public string Source; // the vanilla creature it is cloned from + public string Icon; + public float Price; + public int Stage; // the nest stage it becomes available at + public float Cooldown; // seconds between two of these + + public string PrefabName => PrefabPrefix + Source; + public int Cap => CapOf(Id); + } + + /// + /// Section 11's table, prices and caps and stage gates unchanged. + /// + /// The cooldowns are section 20.4's: ten minutes for a Gjall and "the others scaled + /// accordingly", which is read here as scaled BY PRICE - a Brood is a tenth of a Gjall in + /// biomass, so it is a tenth of a Gjall in patience too. + /// + public static readonly List Roster = new List + { + new Kind { Id = "brood", Display = "Brood", Source = "SeekerBrood", Icon = "TrophySeeker", Price = 100f, Stage = 1, Cooldown = 60f }, + new Kind { Id = "seeker", Display = "Seeker", Source = "Seeker", Icon = "TrophySeeker", Price = 250f, Stage = 2, Cooldown = 150f }, + new Kind { Id = "soldier", Display = "Soldier", Source = "SeekerBrute", Icon = "TrophySeekerBrute", Price = 500f, Stage = 3, Cooldown = 300f }, + new Kind { Id = "gjall", Display = "Gjall", Source = "Gjall", Icon = "TrophyGjall", Price = 1000f, Stage = 4, Cooldown = 600f }, + }; + + private static int CapOf(string id) + { + switch (id) + { + case "brood": return SvermConfigManagement.Brood; + case "seeker": return SvermConfigManagement.Seeker; + case "soldier": return SvermConfigManagement.Soldier; + case "gjall": return SvermConfigManagement.Gjall; + default: return 0; + } + } + + // ─── Registration ──────────────────────────────────────────────────── + + public static void Register() + { + foreach (Kind kind in Roster) RegisterOne(kind); + } + + /// + /// One troop prefab: the vanilla creature, tamed at spawn, leashed, healing, worth nothing dead. + /// + /// The drop table goes for the reason it always goes here - a troop that dropped seeker parts + /// would turn the colony into a trophy farm, and the biomass would be paying for itself. + /// + private static void RegisterOne(Kind kind) + { + GameObject source = PrefabManager.Cache.GetPrefab(kind.Source); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{kind.Source}' to build the {kind.Display} from; " + + "that rung of the roster is missing."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source); + if (prefab == null) return; + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = SvermConfig.TroopLeashRange; + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = kind.PrefabName; + thrall.m_commandingRace = SvermConfig.RaceId; + thrall.m_maxFollowers = -1; // the cap is the colony's, counted at the nest, not per player + thrall.m_witherSeconds = SvermConfig.TroopWitherSeconds; + thrall.m_homeCheckRange = SvermConfig.TroopHomeCheckRange; + thrall.m_refusalMessage = "It does not smell your colony on you."; + + // Section 11.2, reused whole: ten seconds untouched, then two percent a second. Healing + // and not respawning - a dead troop is dead, and the egg it cost is already back. + prefab.AddComponent(); + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Sverm] Registered '{kind.PrefabName}' for the {kind.Display}."); + } + + // ─── Counting and hatching ─────────────────────────────────────────── + + /// + /// How many of this kind this nest has alive. + /// + /// Counted off the thralls bound to the nest, which is the same answer every other station in + /// the mod gives - and carries the same honest limit: it can only see creatures that are + /// loaded. A troop in an unloaded zone is not counted, so a cap can be briefly exceeded by + /// hatching a replacement for something that is still alive far away. + /// + public static int CountAlive(SvermHiveBehaviour hive, Kind kind) + { + if (hive == null || kind == null) return 0; + + int count = 0; + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(hive.transform.position)) + { + if (thrall != null && thrall.Kind == kind.PrefabName) count++; + } + return count; + } + + /// + /// Puts one on the ground beside the nest, bound to it and born at whatever star the colony + /// has bought. + /// + public static bool Hatch(SvermHiveBehaviour hive, Kind kind) + { + if (hive == null || kind == null) return false; + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(kind.PrefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{kind.PrefabName}' in ZNetScene; the {kind.Display} " + + "could not be hatched."); + return false; + } + + Vector3 offset = Random.insideUnitSphere * 2f; + offset.y = 0f; + Vector3 where = hive.transform.position + offset + Vector3.up * 0.5f; + + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f)); + if (spawned == null) return false; + + // The stars, and this is the ONLY thing the two star upgrades do: they are read here, at + // birth, so everything bought before them stays as it was born. Section 14's "valgono su + // tutto quello che nasce DOPO l'acquisto", enforced by the fact that nothing goes back + // and re-levels anyone. + Character character = spawned.GetComponent(); + if (character != null) + { + int stars = SvermBroodStars.Of(hive.transform); + if (stars > 0) character.SetLevel(1 + stars); + } + + RaisedThrall thrall = spawned.GetComponent(); + if (thrall != null) thrall.Bind(hive.transform.position); + + return true; + } + } + + /// + /// The brood eggs: the slot half of the price, section 10.2. + /// + /// One every twenty seconds up to five plus the stage, and it is worked out from the WORLD CLOCK + /// rather than ticked - the same trick the digestion uses. A nest nobody is standing next to + /// still fills its clutch, and there is no timer to lose when a zone unloads. + /// + public static class SvermBroodEggs + { + private const string EggKey = "RacesOfValheim_SvermEggs"; + private const string ClockKey = "RacesOfValheim_SvermEggAt"; + + public static int Cap(Transform nest) + { + return SvermConfig.EggCapBase + SvermHiveStage.Of(nest); + } + + /// What the clutch holds right now, without writing anything. + public static int Count(Transform nest) + { + ZNetView nview = View(nest); + if (nview == null) return 0; + + ZDO zdo = nview.GetZDO(); + int stored = zdo.GetInt(EggKey, 0); + long clock = zdo.GetLong(ClockKey, 0L); + + // A clutch that has never been settled has no elapsed time to claim. Reading a missing + // clock as zero would hand a brand new nest every egg since the world began. + if (clock <= 0L) return Mathf.Clamp(stored, 0, Cap(nest)); + + long elapsed = WorldSecond() - clock; + int laid = elapsed > 0L ? (int)(elapsed / SvermConfig.EggInterval) : 0; + + return Mathf.Clamp(stored + laid, 0, Cap(nest)); + } + + /// + /// Writes down what time has laid and restarts the clock. The owner calls this on a timer so + /// the number the other clients read is never far behind. + /// + public static void Settle(Transform nest) + { + ZNetView nview = View(nest); + if (nview == null || !nview.IsOwner()) return; + + ZDO zdo = nview.GetZDO(); + int now = Count(nest); + + zdo.Set(EggKey, now); + zdo.Set(ClockKey, WorldSecond()); + } + + /// Takes eggs out of the clutch. All or nothing. + public static bool Take(Transform nest, int howMany) + { + ZNetView nview = View(nest); + if (nview == null) return false; + + int have = Count(nest); + if (have < howMany) return false; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(EggKey, have - howMany); + nview.GetZDO().Set(ClockKey, WorldSecond()); + return true; + } + + private static ZNetView View(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + return nview != null && nview.IsValid() ? nview : null; + } + + private static long WorldSecond() + { + return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L; + } + } + + /// + /// Surrenal Glands and Hyperplasia: what star the colony's troops are born at. + /// + /// One number on the nest, 0 to 2, and it is read at the moment a troop is hatched and never + /// again. Everything already walking around keeps the stars it was born with, which is the + /// document's own rule and also the only version that does not need to find and re-level a + /// garrison spread over half the map. + /// + public static class SvermBroodStars + { + private const string StarKey = "RacesOfValheim_SvermStars"; + + public static int Of(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return 0; + + return Mathf.Clamp(nview.GetZDO().GetInt(StarKey, 0), 0, 2); + } + + public static void Set(Transform nest, int stars) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(StarKey, Mathf.Clamp(stars, 0, 2)); + } + } +} diff --git a/JotunnModStub/Sverm/SvermCarapace.cs b/JotunnModStub/Sverm/SvermCarapace.cs new file mode 100644 index 0000000..03b74d7 --- /dev/null +++ b/JotunnModStub/Sverm/SvermCarapace.cs @@ -0,0 +1,133 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The carapace: chest, legs and helmet, permanently, at every tier. + /// + /// WHAT IT IS WORTH IS NOT WRITTEN DOWN. Each tier names a vanilla set in SvermConfig, and the + /// armour value is that set's three pieces read off ObjectDB and priced at quality 4. The race + /// therefore tracks vanilla's own balance forever: if a game patch buffs iron, the Sverm's + /// third tier is buffed with it, and nobody has to remember this file exists. + /// + /// The lookup is cached per state and not per frame on purpose - GetBodyArmor runs from the + /// HUD and from every damage calculation, and ObjectDB.GetItemPrefab is a dictionary hit plus + /// a GetComponent on each of three prefabs. + /// + /// Resolution is deferred rather than done at startup: ObjectDB is not populated when the + /// plugin wakes, so the first caller inside a world is what fills the cache. A missing prefab + /// contributes zero and logs once, so a renamed vanilla item costs a warning and a soft tier + /// rather than a null-reference in the damage path. + /// + public static class SvermCarapace + { + private static readonly float[] armorCache = new float[BossProgressionManager.MaxState + 1]; + private static readonly bool[] armorCached = new bool[BossProgressionManager.MaxState + 1]; + + private static float eitrRegenReference = -1f; + + /// + /// Total armour the carapace is worth at this tier: the three reference pieces at quality + /// 4, plus the hand-picked Fader bonus, which is the one number in the race that is chosen + /// rather than derived - there is no biome after the Ashlands to read a set from. + /// + public static float GetArmor(int state) + { + state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState); + if (armorCached[state]) return armorCache[state]; + + if (ObjectDB.instance == null) return 0f; // too early; do not poison the cache + + float total = 0f; + string[] set = SvermConfig.ArmorReferenceSets[state]; + if (set != null) + { + foreach (string prefabName in set) + { + total += ArmorOf(prefabName); + } + } + + if (state >= SvermConfig.AnnealedChitinState) total += SvermConfig.FaderArmorBonus; + + armorCache[state] = total; + armorCached[state] = true; + + Jotunn.Logger.LogInfo($"[Sverm] Carapace tier {state} priced at {total:0.#} armour " + + $"from {(set == null ? "nothing" : string.Join(" + ", set))} at quality " + + $"{SvermConfig.ArmorReferenceQuality}."); + return total; + } + + /// Armour of one vanilla piece at the reference quality, or 0 with a warning. + private static float ArmorOf(string prefabName) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No item '{prefabName}' to price the carapace from; " + + "it contributes nothing to this tier."); + return 0f; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return 0f; + + // Valheim's own formula: armour + (quality - 1) * armourPerLevel. + return drop.m_itemData.m_shared.m_armor + + (SvermConfig.ArmorReferenceQuality - 1) * drop.m_itemData.m_shared.m_armorPerLevel; + } + + /// + /// Eitr regeneration the carapace hands back, from Eitr Sacs on. + /// + /// The eitr-weave set gives REGENERATION, not maximum eitr - the maximum comes from food, + /// which the Sverm eats like anyone else. So sealing the armour slots never blocked magic; + /// it only slowed the recovery, and this gives back a fraction of it. Deliberately a + /// fraction: eitr-weave is light armour and pays for its regeneration in defence, and a + /// Sverm carrying a biome set at quality 4 AND the full regeneration would simply be a + /// better mage than a mage. + /// + public static float GetEitrRegenBonus(int state) + { + if (state < SvermConfig.EitrSacsState) return 0f; + if (ObjectDB.instance == null) return 0f; + + if (eitrRegenReference < 0f) + { + float total = 0f; + foreach (string prefabName in SvermConfig.EitrReferenceSet) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName); + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null) + { + total += drop.m_itemData.m_shared.m_eitrRegenModifier; + } + } + eitrRegenReference = total; + Jotunn.Logger.LogInfo($"[Sverm] Eitr Sacs reference: eitr-weave set regenerates {total:0.##}, " + + $"carapace returns {SvermConfig.EitrRegenFraction:P0} of it."); + } + + return eitrRegenReference * SvermConfig.EitrRegenFraction; + } + + /// True when this slot is taken by the carapace and cannot hold anything else. + public static bool IsSealedSlot(ItemDrop.ItemData.ItemType type) + { + foreach (ItemDrop.ItemData.ItemType sealedType in SvermConfig.SealedSlots) + { + if (sealedType == type) return true; + } + return false; + } + + /// The tint the carapace, the helmet and the claws all share at this tier. + public static Color GetTint(int state) + { + state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState); + return SvermConfig.CarapaceTintByState[state]; + } + } +} diff --git a/JotunnModStub/Sverm/SvermClawSlot.cs b/JotunnModStub/Sverm/SvermClawSlot.cs new file mode 100644 index 0000000..11b911c --- /dev/null +++ b/JotunnModStub/Sverm/SvermClawSlot.cs @@ -0,0 +1,283 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Maulclaws as a REAL equipped weapon, sitting in the inventory in plain sight and + /// refusing to be moved. + /// + /// WHY THIS REPLACED THE COSMETIC VERSION. Bolting a model to the hand bones worked, but the + /// carapace beside it did not: the game rebuilds equipment visuals from what is ACTUALLY in + /// the slots, so every unequip wiped the lot and something had to put it back, one frame late + /// and visibly. A real item in a real slot removes the whole class of problem - there is + /// nothing to put back, because nothing was ever faked. + /// + /// The trade, accepted deliberately: a real weapon occupies the right hand, so drawing a sword + /// puts the claws away. Three rules make that read as intended rather than as a bug: + /// + /// 1. sheathe anything else and the claws come straight back (UnequipItem postfix); + /// 2. the holster key cannot put the claws away - a Sverm is never empty-handed + /// (HideHandItems prefix); + /// 3. the claws cannot be dragged, moved or dropped (SetupDragItem prefix, quest-item flag). + /// + /// VISIBLE, NOT HIDDEN, and that is the second design this file has had. The first reserved + /// the rightmost column and switched its slots off in the inventory window - which meant + /// patching InventoryGrid.UpdateGui, a method that runs for every chest and every grid in the + /// game, to hide something in exactly one of them. It also cost the player four slots. + /// Showing the claws and refusing to let them move is less code, touches no UI, and tells the + /// player something true: they are carrying them, and they always will be. + /// + /// The last resort behind all three rules is that Maintain re-issues the claws whenever they + /// are missing. However they get lost - a tombstone, a mod, a bug in this file - they are back + /// within half a second. + /// + public static class SvermClawSlot + { + public const string ItemName = "SvermMaulclaws"; + public const string ItemDisplayName = "Vilebone Maulclaws"; + + /// Row in the reserved column the claws sit on. The other three await the carapace. + private const int ClawRow = 0; + + private static bool registered; + + // ─── Registration ──────────────────────────────────────────────────── + + /// + /// Clones whichever of the four candidate prefabs this build actually has. Deferred until + /// ObjectDB is up, so it is driven from the first player spawn rather than from Awake. + /// + public static void EnsureRegistered() + { + if (registered) return; + + if (ObjectDB.instance != null && ObjectDB.instance.GetItemPrefab(ItemName) != null) + { + registered = true; + return; + } + + GameObject source = SvermClaws.GetPrefab(); + if (source == null) return; // already logged once by the resolver + + GameObject clone = PrefabManager.Instance.CreateClonedPrefab(ItemName, source); + if (clone == null) + { + Jotunn.Logger.LogWarning($"[Sverm] Could not clone '{source.name}'; the claws stay unregistered."); + return; + } + + ItemDrop drop = clone.GetComponent(); + if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null) + { + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = ItemDisplayName; + shared.m_description = "Grown, not forged. They do not come off."; + + // Quest item: Valheim refuses to drop, trade or stack these. It is the cheapest + // honest way to say "this is part of your body" without a patch per verb. + shared.m_questItem = true; + shared.m_teleportable = true; + shared.m_weight = 0f; + shared.m_maxQuality = 1; + + // No recipe and no station: this item is never crafted, only issued. + } + + ItemManager.Instance.AddItem(new Jotunn.Entities.CustomItem(clone, fixReference: false)); + registered = true; + Jotunn.Logger.LogInfo($"[Sverm] Registered '{ItemName}' from '{source.name}'."); + } + + // ─── Issue and re-equip ────────────────────────────────────────────── + + /// + /// Makes sure the player owns exactly one pair and is holding them whenever both hands are + /// free. Safe to call on a timer: every step checks first. + /// + /// + /// Guards against re-entry, and it is not belt-and-braces - it is the fix for a crash. + /// + /// Maintain equips the claws. Humanoid.EquipItem unequips the right hand first, which + /// fires the UnequipItem postfix, which calls Maintain, which equips the claws... Mono + /// answers an unbounded recursion by killing the process outright, with no exception and a + /// log file that ends mid-word. Switching race was enough to trigger it every time. + /// + /// The null check in the postfix closes the specific door; this closes the corridor. + /// + private static bool maintaining; + + public static void Maintain(Player player) + { + if (maintaining) return; + if (player == null || player != Player.m_localPlayer) return; + if (!SvermVisuals.IsSvermPlayer(player)) return; + + maintaining = true; + try { MaintainInner(player); } + finally { maintaining = false; } + } + + private static void MaintainInner(Player player) + { + EnsureRegistered(); + + Inventory inventory = player.GetInventory(); + if (inventory == null) return; + + ItemDrop.ItemData claws = Find(inventory); + + if (claws == null) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(ItemName) : null; + if (prefab == null) return; + + // The GameObject overload, deliberately: it is the one that is public in the + // shipped assembly. The overloads that take a grid position are private there, and + // the project compiles against the shipped assembly rather than the publicized + // copy - so anything else would build on this machine and not on a clean one. + if (!inventory.AddItem(prefab, 1)) return; + + claws = Find(inventory); + if (claws == null) return; + + // Tidied into the bottom-right corner IF that corner is free, and left wherever + // the inventory put them otherwise. Nothing of the player's is ever displaced to + // make room: an item that cannot be moved has no business shoving one that can. + Vector2i corner = new Vector2i(inventory.GetWidth() - 1, inventory.GetHeight() - 1); + if (corner.x >= 0 && ItemAt(inventory, corner.x, corner.y) == null) + { + claws.m_gridPos = corner; + } + + Jotunn.Logger.LogInfo("[Sverm] Issued the Maulclaws."); + } + + // Empty-handed means clawed. Anything else in the right hand wins until it is put + // away, which is the whole compromise. + ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field("m_rightItem").Value; + if (held == null && !player.InAttack() && !player.IsDead()) + { + player.EquipItem(claws, false); + } + } + + /// + /// What is sitting at this grid position, read from the items themselves. + /// + /// Inventory.GetItemAt is private in the shipped assembly, and every item already carries + /// its own m_gridPos, so a scan over GetAllItems answers the same question with nothing + /// but public members. An inventory holds a few dozen items; this is not a hot path. + /// + private static ItemDrop.ItemData ItemAt(Inventory inventory, int x, int y) + { + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_gridPos.x == x && item.m_gridPos.y == y) return item; + } + return null; + } + + public static ItemDrop.ItemData Find(Inventory inventory) + { + if (inventory == null) return null; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return item; + if (item != null && item.m_shared != null && item.m_shared.m_name == ItemDisplayName) return item; + } + return null; + } + + public static bool IsClaws(ItemDrop.ItemData item) + { + if (item == null || item.m_shared == null) return false; + if (item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return true; + return item.m_shared.m_name == ItemDisplayName; + } + } + + // ─── Patches ───────────────────────────────────────────────────────────── + + /// + /// Put anything else away and the claws come straight back. + /// + /// A postfix rather than doing it inside UnequipItem's own flow: the game is mid-way through + /// tearing down the old item's visuals when the prefix would run, and equipping there leaves + /// the new item without a model. + /// + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.UnequipItem))] + public static class Sverm_UnequipItem_Patch + { + public static void Postfix(Humanoid __instance, ItemDrop.ItemData item) + { + // NULL IS THE IMPORTANT CASE. Humanoid.EquipItem calls UnequipItem(m_rightItem) before + // putting a weapon in the hand, and an empty hand means that argument is null. Without + // this line the postfix treats "nothing was unequipped" as "something was unequipped", + // calls Maintain, which equips the claws, which unequips null again - and Mono kills + // the process on the recursion, instantly and silently. + if (item == null) return; + + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return; + if (!SvermVisuals.IsSvermPlayer(player)) return; + if (SvermClawSlot.IsClaws(item)) return; // do not re-equip what was just taken off + + SvermClawSlot.Maintain(player); + } + } + + /// + /// The holster key cannot put the claws away. + /// + /// HideHandItems is what R calls. Refused only while the claws ARE the thing in hand: holding + /// a sword, R sheathes the sword normally, and the unequip postfix above hands the claws back + /// on the same action. So the key keeps working and simply never leaves a Sverm empty-handed. + /// + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.HideHandItems))] + public static class Sverm_HideHandItems_Patch + { + public static bool Prefix(Humanoid __instance) + { + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return true; + if (!SvermVisuals.IsSvermPlayer(player)) return true; + + ItemDrop.ItemData held = Traverse.Create(__instance).Field("m_rightItem").Value; + return !SvermClawSlot.IsClaws(held); + } + } + + /// + /// The claws cannot be picked up with the mouse. + /// + /// SetupDragItem is the single door every manual move goes through - within the inventory, out + /// to a chest, onto the ground, into a crafting slot. Refusing here closes all of them with + /// one prefix, instead of one patch per destination, and leaves every OTHER item's handling + /// completely untouched. + /// + /// It replaces an earlier design that hid the rightmost column outright. That one had to patch + /// InventoryGrid.UpdateGui - a method that runs for every chest and every grid in the game - + /// in order to change exactly one of them, and it cost the player four slots. The claws are + /// visible now, which is also more honest: they are part of the character, and the character + /// can see them. + /// + [HarmonyPatch(typeof(InventoryGui), "SetupDragItem")] + public static class Sverm_SetupDragItem_Patch + { + public static bool Prefix(ItemDrop.ItemData item) + { + if (!SvermClawSlot.IsClaws(item)) return true; + + if (Player.m_localPlayer != null) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands."); + } + return false; + } + } +} diff --git a/JotunnModStub/Sverm/SvermClaws.cs b/JotunnModStub/Sverm/SvermClaws.cs new file mode 100644 index 0000000..88acd56 --- /dev/null +++ b/JotunnModStub/Sverm/SvermClaws.cs @@ -0,0 +1,154 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Vilebone Maulclaws: attached to the hands for good, and never equipped. + /// + /// WHY NOT A REAL WEAPON. Valheim has one weapon slot. A claw that is genuinely equipped locks + /// the Sverm out of every sword, bow and staff in the game for the whole run, which is not + /// what "permanent claws" is supposed to mean. So the feature is split: + /// + /// the MODEL is cosmetic - two copies bolted to the hand bones, visible always, including + /// while holding a two-hander (SvermVisuals does the mounting); + /// the DAMAGE is unarmed - a bare-handed Sverm punches for the claws of its tier. Pick up a + /// sword and you swing the sword; the claws are still on your hands. + /// + /// So the race is never disarmed and never restricted, and the two halves can be tuned apart. + /// + /// THE PREFAB NAME IS NOT TRUSTED. The install's manifest carries four near-identical names - + /// FistBjornUndeadClaw, FistBjornClawUndead, FistUnbjornClaw, FistBjornClaw - and only some of + /// them have a recipe, which means the item and the mesh may not share a name. Guessing wrong + /// costs two empty hands and no error at all, so the resolve walks the list and logs the + /// winner. A warning beats a silent nothing. + /// + public static class SvermClaws + { + private static GameObject resolved; + private static bool resolveAttempted; + + private static HitData.DamageTypes referenceDamage; + private static bool referenceRead; + + /// + /// The claw prefab, or null. Resolution happens once, inside a world, because ObjectDB is + /// empty when the plugin wakes. + /// + public static GameObject GetPrefab() + { + if (resolved != null) return resolved; + + foreach (string name in SvermConfig.ClawPrefabFallbacks) + { + // PrefabManager's cache first, ObjectDB second, and that order is what lets this + // run at OnVanillaPrefabsAvailable - which is the only moment Jotunn will accept a + // new item. ObjectDB is still empty then. + GameObject candidate = Jotunn.Managers.PrefabManager.Cache.GetPrefab(name); + if (candidate == null && ObjectDB.instance != null) + { + candidate = ObjectDB.instance.GetItemPrefab(name); + } + + if (candidate != null) + { + resolved = candidate; + Jotunn.Logger.LogInfo($"[Sverm] Maulclaws resolved to '{name}'."); + return resolved; + } + } + + // Warned once, but NOT latched: a later call may run when more of the game is loaded, + // and a race with no hands is worth retrying for. + if (!resolveAttempted) + { + resolveAttempted = true; + Jotunn.Logger.LogWarning("[Sverm] None of " + string.Join(", ", SvermConfig.ClawPrefabFallbacks) + + " resolved yet; retrying as the game loads."); + } + return null; + } + + /// + /// The vanilla weapon's damage at quality 4, read once. This is the ceiling the tier + /// percentages are a fraction of, and state 7 is 100% of it - the real Maulclaws. + /// + private static HitData.DamageTypes GetReferenceDamage() + { + if (referenceRead) return referenceDamage; + + GameObject prefab = GetPrefab(); + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) + { + return referenceDamage; // all zeroes; referenceRead stays false so a later world can retry + } + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + + HitData.DamageTypes at1 = shared.m_damages; + HitData.DamageTypes perLevel = shared.m_damagesPerLevel; + int steps = SvermConfig.ArmorReferenceQuality - 1; + + referenceDamage = new HitData.DamageTypes + { + m_blunt = at1.m_blunt + perLevel.m_blunt * steps, + m_slash = at1.m_slash + perLevel.m_slash * steps, + m_pierce = at1.m_pierce + perLevel.m_pierce * steps, + m_chop = at1.m_chop + perLevel.m_chop * steps, + m_pickaxe = at1.m_pickaxe + perLevel.m_pickaxe * steps, + m_fire = at1.m_fire + perLevel.m_fire * steps, + m_frost = at1.m_frost + perLevel.m_frost * steps, + m_lightning = at1.m_lightning + perLevel.m_lightning * steps, + m_poison = at1.m_poison + perLevel.m_poison * steps, + m_spirit = at1.m_spirit + perLevel.m_spirit * steps, + }; + + referenceRead = true; + Jotunn.Logger.LogInfo($"[Sverm] Maulclaws at quality {SvermConfig.ArmorReferenceQuality}: " + + $"slash {referenceDamage.m_slash:0.#}, pierce {referenceDamage.m_pierce:0.#}, " + + $"blunt {referenceDamage.m_blunt:0.#}."); + return referenceDamage; + } + + /// Fraction of the reference damage the bare hands hit for at this tier. + public static float GetDamagePercent(int state) + { + state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState); + return SvermConfig.ClawDamagePercentByState[state]; + } + + /// + /// Rewrites a bare-handed blow into a claw blow. Called from the Character.Damage prefix, + /// and only when the attacker really is punching: an unarmed hit in Valheim carries a tiny + /// blunt figure, which is REPLACED here rather than added to, so the tier percentage means + /// what it says. + /// + public static void ApplyToUnarmedHit(HitData hit, int state) + { + if (hit == null) return; + + HitData.DamageTypes reference = GetReferenceDamage(); + float percent = GetDamagePercent(state); + if (percent <= 0f) return; + + float slash = reference.m_slash * percent; + float pierce = reference.m_pierce * percent; + float blunt = reference.m_blunt * percent; + + // Nothing to give: the reference item did not resolve. Leave vanilla's fist alone + // rather than zeroing the player's only attack. + if (slash + pierce + blunt <= 0f) return; + + hit.m_damage.m_slash = slash; + hit.m_damage.m_pierce = pierce; + hit.m_damage.m_blunt = blunt; + + // Annealed Chitin lights the claws too. A fraction of the physical total rather than a + // flat number, so it scales with whatever the reference weapon turns out to be worth. + if (state >= SvermConfig.AnnealedChitinState) + { + hit.m_damage.m_fire += (slash + pierce + blunt) * SvermConfig.ClawFireFraction; + } + } + } +} diff --git a/JotunnModStub/Sverm/SvermConfig.cs b/JotunnModStub/Sverm/SvermConfig.cs new file mode 100644 index 0000000..e75684a --- /dev/null +++ b/JotunnModStub/Sverm/SvermConfig.cs @@ -0,0 +1,535 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Every tunable number the Sverm uses, in one place. + /// + /// Same contract as DvergarConfig: nothing here is baked into the logic. SvermProgression reads + /// these to build its per-tier rules and the patches read the rules, never a literal. Retuning + /// the race means editing this file only. + /// + /// Two of these numbers are NOT numbers but prefab names, and that is deliberate. The carapace + /// is worth "whatever the vanilla set of that biome is worth", and the claws hit for "whatever + /// the vanilla weapon hits for" - both read off ObjectDB at runtime rather than transcribed + /// here. A game patch that rebalances iron armour rebalances the Sverm with it, and nobody has + /// to remember that this file existed. + /// + public static class SvermConfig + { + // ─── Identity ──────────────────────────────────────────────────────── + // Stored in m_customData["Race"] and on the ZDO, so renaming it after players have chosen + // the race would orphan their characters. See DvergarRace.MigrateLegacyRaceId for what + // that costs to undo. + public const string RaceId = "Sverm"; + + public const string StatsSE = "SE_SvermStats"; + public const string StingerSE = "SE_SvermStingerForm"; + public const string StingerCdSE = "SE_SvermStingerCooldown"; + + // Mirrors the ZDO key layout the other races use, so remote clients can work out the tier + // without having the local player's progression state. + public const string StateZdoKey = "RacesOfValheim_SvermState"; + + // ─── Damage taken ──────────────────────────────────────────────────── + // Chitin burns and chitin cracks. Expressed as a plain multiplier rather than + // HitData.DamageModifier.Weak because that enum is discrete - Weak is a flat +50% and + // there is no rung at +40%. Applied in a Character.Damage prefix, the way Aswid, Draugh + // and Dvergar already scale damage. + public static readonly float BluntWeakness = 0.40f; + public static readonly float FireWeakness = 0.40f; + + // Annealed Chitin: at Fader the weakness inverts. 0.40 means fire lands at 60% of its + // value, i.e. roughly one rung of DamageModifier.Resistant, arrived at by the same knob + // that hurt for eight tiers. + public const int AnnealedChitinState = 8; + public static readonly float FireResistanceAtFader = 0.40f; + + // ─── Chitin Plating: the carapace ──────────────────────────────────── + // Reference sets, one per progression state. The carapace is worth the SUM of these three + // pieces AT QUALITY 4, read from ObjectDB. Every name here was verified against the + // install's own SoftRef manifest, so a null means the game changed, not that we guessed. + // + // Index 0 is unused: progression states run 1..8 and indexing by state is worth one wasted + // slot to avoid an off-by-one in every caller. + public static readonly string[][] ArmorReferenceSets = + { + null, // unused + new[] { "ArmorLeatherChest", "ArmorLeatherLegs", "HelmetLeather" }, // 1 + new[] { "ArmorBronzeChest", "ArmorBronzeLegs", "HelmetBronze" }, // 2 Eikthyr + new[] { "ArmorIronChest", "ArmorIronLegs", "HelmetIron" }, // 3 Elder + new[] { "ArmorWolfChest", "ArmorWolfLegs", "HelmetDrake" }, // 4 Bonemass + new[] { "ArmorPaddedCuirass", "ArmorPaddedGreaves", "HelmetPadded" }, // 5 Moder + new[] { "ArmorCarapaceChest", "ArmorCarapaceLegs", "HelmetCarapace" }, // 6 Yagluth + new[] { "ArmorFlametalChest", "ArmorFlametalLegs", "HelmetFlametal" }, // 7 Queen + new[] { "ArmorFlametalChest", "ArmorFlametalLegs", "HelmetFlametal" }, // 8 Fader + }; + + /// Quality the reference set is priced at. Valheim: armor + (q-1) * armorPerLevel. + public const int ArmorReferenceQuality = 4; + + /// + /// Added on top at Fader only. There is no biome after the Ashlands to read a set from, so + /// state 8 is the one tier whose number is chosen rather than derived - and it is a flat + /// bonus rather than a multiplier precisely so it reads as "chosen" in the log. + /// + public static readonly float FaderArmorBonus = 10f; + + /// Slots the carapace occupies and therefore forbids. + public static readonly ItemDrop.ItemData.ItemType[] SealedSlots = + { + ItemDrop.ItemData.ItemType.Chest, + ItemDrop.ItemData.ItemType.Legs, + ItemDrop.ItemData.ItemType.Helmet, + }; + + /// What the carapace LOOKS like, at every tier. The value changes, the shape does not. + public const string CarapaceChestVisual = "ArmorCarapaceChest"; + public const string CarapaceLegsVisual = "ArmorCarapaceLegs"; + public const string CarapaceHelmetVisual = "HelmetCarapace"; + + // ─── Vilebone Maulclaws ────────────────────────────────────────────── + // FOUR near-identical names exist in the manifest and only some carry a recipe, so the + // prefab is resolved by trying them in order and logging which one answered. A wrong guess + // here fails soft and silently - two empty hands - which is exactly the failure this + // chain exists to make loud. + public static readonly string[] ClawPrefabFallbacks = + { + "FistBjornUndeadClaw", + "FistBjornClawUndead", + "FistUnbjornClaw", + "FistBjornClaw", + }; + + /// Length in METRES from the back of the hand to the tip. ModelBorrow sizes in metres. + public static readonly float ClawLength = 0.22f; + + /// + /// Fraction of the vanilla weapon's quality-4 damage the bare hands hit for, per state. + /// State 7 is the ceiling - the real Maulclaws - and state 8 adds fire on top rather than + /// going past it. Index 0 unused, as above. + /// + public static readonly float[] ClawDamagePercentByState = + { + 0f, 0.35f, 0.45f, 0.55f, 0.70f, 0.85f, 0.95f, 1.00f, 1.00f + }; + + /// Fire added at Fader, as a fraction of the claws' physical total. + public static readonly float ClawFireFraction = 0.30f; + + // ─── Insect Metabolism ─────────────────────────────────────────────── + /// Raw meat is worth this much of its cooked counterpart. + public static readonly float RawMeatFraction = 0.70f; + + /// Honey and royal jelly: bonus and duration both multiplied by this. + public static readonly float HoneyMultiplier = 2f; + + /// Seeds become food from this state on (The Elder). + public const int SeedsEdibleState = 3; + + // Royal jelly, made edible from scratch. These are the FINAL values, already doubled - + // they are not multiplied again by HoneyMultiplier. + public const string RoyalJellyPrefab = "RoyalJelly"; + public static readonly float RoyalJellyHealth = 90f; + public static readonly float RoyalJellyStamina = 90f; + public static readonly float RoyalJellyEitr = 90f; + public static readonly float RoyalJellyDuration = 2400f; + public static readonly float RoyalJellyRegen = 5f; + + // ─── Perk unlock states ────────────────────────────────────────────── + public const int MetabolicSurgeState = 2; + public const int VentralPouchesState = 2; + public const int GrindingMandiblesState = 3; + public const int SensoryAntennaeState = 3; + public const int VenomGlandsState = 4; + public const int AcidHemolymphState = 4; + public const int VestigialWingsState = 5; + public const int StingerMorphState = 6; + public const int EitrSacsState = 6; + public const int MajesticCarapaceState = 7; + public const int SurrenalGlandsState = 7; + public const int FullWingspanState = 7; + public const int CarapaceRegenState = 8; + + // ─── Metabolic Surge (state 2) ─────────────────────────────────────── + public static readonly float RunStaminaDiscount = 0.20f; // -20% on running + public static readonly float JumpStaminaDiscount = 0.20f; + public static readonly float JumpBonus = 0.15f; // +15% jump force + + // ─── Ventral Pouches (state 2) ─────────────────────────────────────── + public static readonly float CarryWeightBonus = 100f; + + // ─── Sensory Antennae (state 3) ────────────────────────────────────── + // Passive and always on, so the radius is the only real brake on how many point lights can + // be alive at once. Raise it with that in mind. + public static readonly float AntennaeRadius = 30f; + public static readonly float AntennaeInterval = 2f; + public static readonly float AntennaeLightRange = 4f; + public static readonly float AntennaeLightIntensity = 1.4f; + + // What each colour means, and the meaning is the whole feature: the Aswid's Auspex marks + // everything the same because it only asks "is something there". A chemical sense answers + // "what is it". + public static readonly Color AntennaeHostileColor = new Color(1f, 0.15f, 0.10f, 1f); // red + public static readonly Color AntennaePassiveColor = new Color(0.25f, 1f, 0.30f, 1f); // green + public static readonly Color AntennaeInvertebrateColor = new Color(1f, 0.90f, 0.20f, 1f); // yellow + public static readonly Color AntennaeKinColor = new Color(0.35f, 0.75f, 1f, 1f); // azure + + // ─── Venom Glands (state 4) ────────────────────────────────────────── + /// Poison added to every blow, per state above the unlock. + public static readonly float VenomPerState = 6f; + + // ─── Acid Hemolymph (state 4) ──────────────────────────────────────── + /// Poison dealt back to whoever lands a melee blow, per state above the unlock. + public static readonly float HemolymphPerState = 5f; + public static readonly float HemolymphRange = 4f; + + // ─── Dorsal Spines (state 5) / Full Crest (state 7) ────────────────── + // Wings were the first design and they lost on cost. Wing_gib turned out not to be a + // prefab at all - it is a child inside a death effect, reachable only by walking somebody + // else's hierarchy and hoping the parent list is right - and animated wings on a static + // mount never look like anything but a prop. A ribcage worn spine-up is STATIC by nature, + // it is a real prefab that resolves by name, and it reads as xenomorph spines rather than + // as a bird. + public const string SpinesPrefab = "UndeadBjornRibcage"; + public static readonly float SpineSizeSmall = 0.45f; // metres, state 5-6 + public static readonly float SpineSizeFull = 0.80f; // metres, state 7+ + /// + /// Which bone they ride. Spine3 and ONLY Spine3 - no fallback chain. + /// + /// The earlier version tried Spine2, then Spine1, then Spine, on the theory that a missing + /// bone should degrade rather than disappear. On this rig all three exist, so the fallback + /// never fired for the right reason and only ever meant "somewhere on the back, roughly" - + /// which is not good enough for a crest that was positioned by eye. One bone, or nothing. + /// + public const string SpineBoneName = "Spine3"; + + // Found in game with the crest on screen. A ribcage is authored lying around a body, so + // standing it up out of a back is a quarter turn on two axes - not something anybody was + // going to derive on paper. + public static readonly float SpineRotationX = 0f; + public static readonly float SpineRotationY = -90f; + public static readonly float SpineRotationZ = 90f; + + /// + /// What holds a falling Sverm up: the Mistlands' own fireflies, swarming under the body. + /// + /// Note the capital F in the middle. "Fireflies" resolves to nothing and fails silently, + /// which is the whole reason every prefab name in this race is checked against the game's + /// manifest before it is written down. + /// + public const string GlideMotesPrefab = "FireFlies"; + + // ─── Eitr Sacs (state 6) ───────────────────────────────────────────── + /// Fraction of the eitr-weave set's regeneration the carapace gives back. + public static readonly float EitrRegenFraction = 0.50f; + public static readonly string[] EitrReferenceSet = { "ArmorMageChest", "ArmorMageLegs", "HelmetMage" }; + + // ─── Surrenal Glands (state 7) ─────────────────────────────────────── + public static readonly float BodyScaleAtQueen = 1.10f; + + // ─── Carapace Regeneration (state 8) ───────────────────────────────── + public static readonly float CarapaceRegenPerSecond = 0.5f; + + // ─── Stinger Morph (state 6) ───────────────────────────────────────── + public const string StingerCreature = "Deathsquito"; + public static readonly float StingerDurationSeconds = 120f; + public static readonly float StingerCooldownSeconds = 480f; + + /// + /// Multiplier on every point of damage taken while in form. 2.5 means a blow that the + /// carapace would shrug off very nearly ends you. + /// + /// This is the entire cost of the ability and it has to be steep: in form you deal the + /// hardest single hit in the Plains and you can leave any fight by going straight up. The + /// balance is not the cooldown, it is that a single arrow answers you. + /// + public static readonly float StingerFragility = 2.5f; + + // ─── The escort ────────────────────────────────────────────────────── + /// + /// Two deathsquitoes called up with the form, and they OUTLIVE it on purpose. + /// + /// Three minutes against the form's two. The extra minute is the whole idea: the form ends + /// wherever it ends, usually in the air, and the Sverm comes back to being a slow armoured + /// thing halfway through a fall. The escort is what covers that minute. Then it dies too. + /// + public const int EscortCount = 2; + public static readonly float EscortLifetimeSeconds = 180f; + public static readonly float EscortSpawnSpread = 2.5f; + + // ─── Transformation effects ────────────────────────────────────────── + // The Seeker's own spawn and death bursts, verified in the manifest. vfx_boar_death is the + // fallback because it is what the Aswid uses and is certain to exist. + public static readonly string[] MorphInEffects = { "fx_seeker_spawn", "vfx_boar_death" }; + public static readonly string[] MorphOutEffects = { "fx_seeker_death", "vfx_boar_death" }; + + // ─── Palette ───────────────────────────────────────────────────────── + // Read off a Seeker Soldier. The exposed skin is almost black and matte: what makes the + // look is the CONTRAST against the amber plates, not the skin colour itself. + public static readonly Color SkinColor = Hex(0x24, 0x1B, 0x15); + public static readonly Color MembraneColor = Hex(0xB8, 0x5F, 0x5C); + + /// + /// The tint ramp IS the visual progression. Same carapace silhouette at every tier, aged + /// by colour: pale washed sand, then full amber, then dark amber, then black with a red + /// burn at Fader. Zero new assets. Index 0 unused. + /// + /// + /// A YOUNG insect is not a small adult, and the ramp says so. The early tiers are violet - + /// the soft, pale, not-yet-hardened shell of something freshly moulted - and the amber of + /// the reference photograph is where the race ARRIVES rather than where it starts. The + /// last two tiers darken out of amber into near black, which is what gives Emberform's red + /// something to burn through. + /// + /// Index 0 unused. + /// + public static readonly Color[] CarapaceTintByState = + { + Color.white, + Hex(0xB0, 0xA3, 0xC8), // 1 pale violet - newly moulted, soft + Hex(0x9B, 0x88, 0xB8), // 2 + Hex(0x86, 0x70, 0x9F), // 3 violet, deepening + Hex(0x7C, 0x60, 0x79), // 4 mauve: the turn towards amber begins + Hex(0x8A, 0x62, 0x49), // 5 + Hex(0x8B, 0x5E, 0x34), // 6 full amber - the colour of the photograph + Hex(0x4A, 0x32, 0x20), // 7 dark amber + Hex(0x14, 0x10, 0x0C), // 8 near black; Emberform adds the red + }; + + // ─── Emberform ─────────────────────────────────────────────────────── + // The hue at full strength, dimmed by EmberGlowStrength below. Split in two for the same + // reason AswidVisuals splits its eye colour: the hue and the brightness are tuned against + // different things, and mixing them into one HDR value makes every adjustment a guess. + // + // The first version shipped this at (3.2, 0.30, 0.06) applied directly, and it came out + // blinding - which is the Aswid's lesson arriving late and at ten times the surface area. + // Two glowing spheres on a face can carry an HDR value past 3; a whole chest, both legs + // and a helmet cannot. Past the bloom threshold the extra brightness buys a bigger white + // area and LESS red, so the fix is downward, not sideways. + public static readonly Color EmberEmission = new Color(3.2f, 0.30f, 0.06f, 1f); + + /// + /// How much of that hue actually reaches the material. + /// + /// Tuned downward twice, in game, and the trend is the whole lesson: full HDR was blinding, + /// 0.25 was still too strong, and 0.0625 is where it stopped looking like a lamp. That puts + /// the red at 0.2 - well under the clip - which on a surface the size of a whole body is + /// plenty. Two glowing eyes and a glowing torso are not the same problem and do not take + /// the same number. + /// + /// Live from the .cfg, because this is a number only an eye can settle. + /// + public static readonly float EmberGlowStrength = 0.0625f; + + // Glowing eyes, same geometry as the Aswid's. Placement constants live in the head bone's + // own local space, which is why the state-7 +10% needs no special case: a child transform + // rides its parent's scale for free. + public static readonly Color EyeColor = new Color(3.4f, 0.12f, 0.08f, 1f); + public static readonly float EyeGlowStrength = 0.22f; + + // ─── The colony (stub - see SvermHive when that half is written) ───── + /// Two nests per square mile. A square mile is 2.59 km2; the circle of equal area has r = 908 m. + public static readonly float HiveDensityRadius = 908f; + public const int HiveDensityMax = 2; + + /// The Elder. Before that the Sverm is a body and nothing else. + public const int HiveUnlockState = 3; + + // ─── Colony caps ───────────────────────────────────────────────────── + // The DEFAULTS. What is actually enforced comes from SvermConfigManagement, which binds + // these into the .cfg so a machine that cannot carry nineteen creatures can say so without + // a rebuild. Only the nest density stays out of reach - two per square mile is a rule + // about the world, not a comfort setting. + public const int CapBrood = 8; + public const int CapSeeker = 6; + public const int CapSoldier = 3; + public const int CapGjall = 2; + public const int CapBlisterTick = 10; + + /// Two separate pools, nine workers alive at most. Farmers come from the infected + /// beehives, haulers from the nest after Bonemass, and neither can starve the other. + public const int CapFarmers = 6; + public const int CapHaulers = 3; + + // ─── The aura and the beehives in it ───────────────────────────────── + public static readonly float HiveAuraRadius = 10f; + public const int HiveAuraBeehiveMax = 10; + + /// Not every frame: it walks a sphere of colliders and nothing here is urgent. + public static readonly float HiveAuraSweepInterval = 5f; + + /// How long a beehive must stand in the aura before the colony takes it. + public static readonly float BeehiveInfectionSeconds = 60f; + + public static readonly float BeehiveSpeedMultiplier = 2f; // twice as fast + public static readonly float BeehiveCapacityMultiplier = 3f; // three times the honey + + /// + /// Vanilla's own cap, written down because m_maxHoney is an instance field and by the time + /// we read it on a hive we may already have changed it. Multiplying what we find would + /// treble the trebled number on the next sweep. + /// + public const int BeehiveBaseMaxHoney = 4; + + /// After Yagluth the colony makes royal jelly instead of honey. + public const int RoyalJellyHiveState = 6; + + // The mark of a taken hive. SeekerEgg is a real prefab - unlike Wing_gib, which was not. + // The first pass shipped a 35 cm egg at 90 cm and nobody could see it: too small, and high + // enough above the hive's origin to float clear of the roof instead of sitting on it. Both + // numbers are in the .cfg now, because where a thing sits on another thing is decided by + // an eye and not by arithmetic. + public const string HiveEggPrefab = "SeekerEgg"; + public static readonly float HiveEggSize = 0.55f; // metres + public static readonly float HiveEggHeight = 0.45f; // above the hive's own origin + + /// The nest's own size. 0.75 is the quarter off that the first placement asked for. + public static readonly float HiveScale = 0.75f; + + // ─── What the colony looks like from outside ───────────────────────── + // How big the swarm of flies and the green reek are on each thing that wears them. Metres, + // near enough - the holder is scaled by these and the particles ride it. Both are first + // guesses and both are in the .cfg, because nobody can settle a cloud of flies on paper. + public static readonly float NestVfxScale = 1.5f; + public static readonly float BeehiveVfxScale = 0.5f; + + // The two hives bolted to the nest: the stomach at its foot, the market up top. Sizes are + // in metres and heights are metres up the trunk from the ground. Both sizes are also the + // width of the sphere you press, so a mouth that is too small is a mouth that is hard to + // point at as well as hard to see - the stomach is the bigger of the two because it is the + // one you use every time you come home. + public static readonly float StomachSize = 1.4f; + public static readonly float StomachHeight = 0f; + /// + /// The Hive Market bench's own scale. It is a BUILDING now, not a mouth on the nest. + /// + /// Two heights were tried while it still hung on the trunk and neither could work: the + /// measured crown put it eight metres over the player's head, and the number that replaced + /// it lost to the zero already written in everyone's .cfg, which dropped it inside the + /// stomach's own sphere. A counter you raise where you like has no such argument to lose. + /// + public static readonly float MarketSize = 1.6f; // metres, the borrowed model's largest side + + // ─── Seeker Worker ─────────────────────────────────────────────────── + public const string WorkerDisplayName = "Seeker Worker"; + public static readonly float WorkerScale = 0.5f; + public static readonly float WorkerHealthFraction = 0.5f; + public static readonly float WorkerDamageFraction = 0.5f; + + /// One out of every infected beehive on this timer, until the pool is full. + public static readonly float WorkerSpawnInterval = 120f; + + /// Haulers only start after Bonemass. + public const int HaulerUnlockState = 4; + + /// Ten metres. Also the radius it keeps in repair. + public static readonly float WorkerLeashRange = 10f; + + /// How far a worker reaches to mend, and how often it mends one thing. + public static readonly float WorkerRepairRange = 10f; + public static readonly float WorkerRepairInterval = 5f; + + /// How far from its anchor a worker looks for chests. + public static readonly float WorkerChestRange = 3f; + + /// How often a worker does a round of its trade. + public static readonly float WorkerRoundInterval = 4f; + + /// Plants per infected beehive, once the farmer's job lands. + public const int PlantsPerBeehive = 15; + + // ─── Biomass ───────────────────────────────────────────────────────── + public static readonly float BiomassTankBase = 1000f; + + /// Section 10.1: 1000 / 1500 / 2000 / 2500 across the four stages. + public static readonly float BiomassTankPerStage = 500f; + + /// + /// Headroom over the document's tank, on every stage: 1500 / 2000 / 2500 / 3000. + /// + /// FOUND IN PLAY, and it is a real hole rather than a balance opinion. A stage costs exactly + /// the tankful of the stage below it, so with the tank and the price being the same number + /// the hive had to be full TO THE GRAM before it could grow - and it never was. Biomass + /// arrives in whole items: with three units of room left, a log worth five does not fit, so + /// the last few points can never be filled and the price is never reached. + /// + /// The prices are untouched. This is the room above them. + /// + public static readonly float BiomassTankHeadroom = 500f; + + public static readonly float WoodBiomassValue = 5f; + + /// + /// How big the nest is at the last stage, as a multiple of how it was built. + /// + /// SECTION 9 SAYS TRIPLE and triple was wrong on screen: the trunk measures about eight + /// metres as placed, so a Hive Citadel stood twenty-four metres tall and read as a bug + /// rather than as a building. 1.75 keeps the growth legible - each stage is visibly bigger + /// than the last - without the last one swallowing the base. In the .cfg because this is a + /// number only an eye can settle. + /// + public static readonly float HiveStageGrowth = 1.75f; + + /// Section 20.4's day between purchases, in game days. + public static readonly float UpgradeCooldownDays = 1f; + + // ─── Brood eggs and troops ─────────────────────────────────────────── + /// Section 10.2: one egg every twenty seconds, five plus the stage in the clutch. + public static readonly float EggInterval = 20f; + public const int EggCapBase = 5; + + /// How far a troop wanders from the nest when nobody is leading it. + public static readonly float TroopLeashRange = 12f; + + /// How long a troop outlives the nest that hatched it, in seconds. + public static readonly float TroopWitherSeconds = 60f; + + /// How close a troop has to be to see whether its nest is still standing. + public static readonly float TroopHomeCheckRange = 25f; + + // ─── Blister Tick ──────────────────────────────────────────────────── + /// Section 12: fifty a slot, and the slot is permanent. + public static readonly float TickPrice = 50f; + + /// How close it gets before it bursts, in metres. + public static readonly float TickBurstRange = 2.5f; + + /// How long the nest waits before growing a replacement, in seconds. + public static readonly float TickRespawnSeconds = 30f; + + /// From this nest stage on, the blast is the elite blob's. Section 12's two tiers. + public const int TickLateBlastStage = 3; + + /// Only used if the blob projectiles are not in this build - see SvermBlisterTick. + public static readonly float TickFallbackDamage = 30f; + + // ─── Medicine ──────────────────────────────────────────────────────── + /// + /// Section 19.4: what a jar heals when it is given to one of the colony's insects instead of + /// eaten. They stopped counting as biomass to become this. + /// + public static readonly float HoneyHealing = 40f; + public static readonly float RoyalJellyHealing = 90f; + + // No Venom Coil numbers. Section 13's turret was built, seen and rejected, so its price, its + // Bonemass gate and its scale are gone with it rather than left here looking pending. + + /// + /// How much biomass moves from digestion into the spendable bank each second. + /// + /// NOT A NUMBER FROM THE DESIGN DOCUMENT - the digestion is described there, its speed is + /// not. Five a second empties a full stage-one tank in a little over three minutes, which + /// is long enough that a hive cannot be filled and spent in the same breath and short + /// enough that nobody stands there waiting. It is in the .cfg because it is the first thing + /// a play test will want to argue with. + /// + public static readonly float BiomassDigestRate = 5f; + + // ─── Helpers ───────────────────────────────────────────────────────── + private static Color Hex(int r, int g, int b) + { + return new Color(r / 255f, g / 255f, b / 255f, 1f); + } + } +} diff --git a/JotunnModStub/Sverm/SvermConfigManagement.cs b/JotunnModStub/Sverm/SvermConfigManagement.cs new file mode 100644 index 0000000..0480f26 --- /dev/null +++ b/JotunnModStub/Sverm/SvermConfigManagement.cs @@ -0,0 +1,271 @@ +using BepInEx.Configuration; + +namespace RacesOfValheim +{ + /// + /// The BepInEx-configurable slice of the Sverm's numbers, bound as ConfigEntry so they can be + /// retuned without a rebuild - see CONFIGURATION-MANAGER-HOWTO.md. Bound once, from + /// RacesOfValheim.Awake(). + /// + /// Configuration Manager is a convenience, not a requirement: these land in + /// BepInEx/config/com.nandor.racesofvalheim.cfg as plain text and can be edited with a text + /// editor and picked up on the next launch. + /// + /// WHAT IS IN HERE AND WHAT IS NOT, on the same boundary DvergarConfigManagement draws: + /// SvermConfig keeps the identity constants that must never change once a character exists + /// (RaceId, status effect names) and the per-tier tables. What lives here is the handful of + /// numbers that can only be judged by looking at them on screen - where the claws sit on the + /// hand, how wide the wings open - because those are guesses until someone sees them, and a + /// guess that needs a rebuild to correct is a guess that gets corrected slowly. + /// + public static class SvermConfigManagement + { + // No claw entries. They were here for one build, while the claws were a model bolted to + // the hand bones and their angle was a guess only an eye could settle. They are a real + // equipped item now (SvermClawSlot), so the game's own attach point decides where they sit + // and there is nothing left to tune. + + // ─── Dorsal spines ─────────────────────────────────────────────────── + public static ConfigEntry SpineSizeSmall; + public static ConfigEntry SpineSizeFull; + public static ConfigEntry SpineBoneName; + public static ConfigEntry SpineRotationX; + public static ConfigEntry SpineRotationY; + public static ConfigEntry SpineRotationZ; + + // ─── Emberform ─────────────────────────────────────────────────────── + public static ConfigEntry EmberGlowStrength; + + // ─── Keybinds ──────────────────────────────────────────────────────── + public static ConfigEntry StingerKey; + + // ─── Stinger Morph, the model ──────────────────────────────────────── + public static ConfigEntry StingerScaleMultiplier; + public static ConfigEntry StingerYawDegrees; + + // ─── Colony caps ───────────────────────────────────────────────────── + // Every ceiling on how many things the colony can have alive at once, in one section, so + // the "is this too many creatures for my machine" question has exactly one place to be + // answered - and can be answered without a rebuild. + // + // The nest density limit is deliberately NOT here. Two per square mile is a rule about + // what the world may look like rather than a comfort setting, and PieceDensityLimit reads + // it once when the piece registers. + public static ConfigEntry CapBrood; + public static ConfigEntry CapSeeker; + public static ConfigEntry CapSoldier; + public static ConfigEntry CapGjall; + public static ConfigEntry CapBlisterTick; + public static ConfigEntry CapFarmers; + public static ConfigEntry CapHaulers; + public static ConfigEntry CapBeehives; + + // ─── The nest and its mark ─────────────────────────────────────────── + public static ConfigEntry WorkerChestRangeValue; + public static ConfigEntry WorkerDebugValue; + public static ConfigEntry HiveScaleValue; + public static ConfigEntry EggSizeValue; + public static ConfigEntry EggHeightValue; + public static ConfigEntry DigestRateValue; + public static ConfigEntry StomachSizeValue; + public static ConfigEntry StomachHeightValue; + public static ConfigEntry MarketSizeValue; + public static ConfigEntry StageGrowthValue; + public static ConfigEntry NestVfxScaleValue; + public static ConfigEntry BeehiveVfxScaleValue; + + public static void Bind(ConfigFile config) + { + const string spines = "Sverm - Dorsal Spines"; + const string ember = "Sverm - Emberform"; + const string keybinds = "Sverm - Keybinds"; + + // G, like every other first transformation in the mod - the Aswid's bat, the Fenrir's + // wolf, the Dvergar's ping. A character only ever has one race, so they never collide. + StingerKey = config.Bind(keybinds, "Stinger Morph", new KeyboardShortcut(UnityEngine.KeyCode.G), + "Turns into a Deathsquito, and back. Unlocked at Yagluth."); + + const string stinger = "Sverm - Stinger Morph"; + + StingerScaleMultiplier = config.Bind(stinger, "Scale", 1f, + "Multiplies the deathsquito model's OWN authored scale. 1 means 'the size the " + + "game draws one'. Raise it if the insect reads as too small to be you."); + + const string nest = "Sverm - Nest"; + + HiveScaleValue = config.Bind(nest, "Nest Scale", SvermConfig.HiveScale, + "How big the nest is. Only affects nests placed AFTER the change - the ones already " + + "standing keep the size they were built at, like every other building."); + + EggSizeValue = config.Bind(nest, "Infection Egg Size", SvermConfig.HiveEggSize, + "How big the egg on a taken beehive is, in metres. The first pass used 0.35 and it " + + "was invisible in play."); + + EggHeightValue = config.Bind(nest, "Infection Egg Height", SvermConfig.HiveEggHeight, + "How far above the beehive's own origin the egg sits, in metres. Too high and it " + + "floats clear of the roof; too low and it sinks into the mesh."); + + // The two hives you press. Sizes are also how wide the sphere you point at is, so these + // decide how easy each mouth is to hit as much as how it looks. Read once, when the + // piece is registered: a change here shows up on the next launch, not on nests already + // standing. + StomachSizeValue = config.Bind(nest, "Stomach Size", SvermConfig.StomachSize, + "How big the hive at the foot of the nest is, in metres. It is the one you feed: " + + "press E on it and a whole stack goes in."); + + StomachHeightValue = config.Bind(nest, "Stomach Height", SvermConfig.StomachHeight, + "How far up the trunk the stomach sits, in metres. Zero puts it on the ground."); + + // NOT "Market Size" - that key already exists in everyone's .cfg holding the size of the + // mouth that used to hang on the trunk, and a key that is read back from a file laughs + // at a changed default. The market is a building of its own now and this is its scale, + // so it gets a name of its own too; the two old lines are orphans and are ignored. + StageGrowthValue = config.Bind(nest, "Growth At Last Stage", SvermConfig.HiveStageGrowth, + "How big a Hive Citadel is compared to the Brood Mound it started as, with the two " + + "middle stages spread evenly between. Applies to nests already standing, since it " + + "is worked out from the stage rather than baked in at placement."); + + NestVfxScaleValue = config.Bind(nest, "Nest Swarm Scale", SvermConfig.NestVfxScale, + "How big the cloud of flies over the nest is, and the green reek it gives off while " + + "it is digesting. The reek only shows when there is something going down."); + + BeehiveVfxScaleValue = config.Bind(nest, "Beehive Swarm Scale", SvermConfig.BeehiveVfxScale, + "The same two marks on a taken beehive, which wants a smaller cloud than the nest. " + + "Its gas shows when the hive is full of honey."); + + MarketSizeValue = config.Bind(nest, "Market Bench Size", SvermConfig.MarketSize, + "How big the Hive Market bench is, in metres. It is a building you raise inside a " + + "hive's ten metres, not a part of the nest."); + + DigestRateValue = config.Bind(nest, "Digestion Rate", SvermConfig.BiomassDigestRate, + "How much biomass moves from digestion into the hive's spendable bank each second. " + + "What you sell the hive is not spendable until it has gone down. At the default a " + + "full stage-one tank takes a little over three minutes. Measured against the world " + + "clock, so a hive nobody is watching digests at the same speed."); + + const string workers = "Sverm - Workers"; + + WorkerChestRangeValue = config.Bind(workers, "Chest Range", SvermConfig.WorkerChestRange, + "How far from the nest or the beehive a worker will look for a chest, in metres. " + + "Three is the design figure; widen it if your storage will not fit that close."); + + WorkerDebugValue = config.Bind(workers, "Log Rounds", false, + "Writes a line to the log when a worker finishes a round and found nothing to do. " + + "Off by default because a worker works every few seconds and would bury the log."); + + const string caps = "Sverm - Colony Caps"; + + CapBrood = config.Bind(caps, "Brood", SvermConfig.CapBrood, + "How many Seeker Brood the colony can keep alive at once."); + CapSeeker = config.Bind(caps, "Seeker", SvermConfig.CapSeeker, + "How many Seekers the colony can keep alive at once."); + CapSoldier = config.Bind(caps, "Soldier", SvermConfig.CapSoldier, + "How many Seeker Soldiers the colony can keep alive at once."); + CapGjall = config.Bind(caps, "Gjall", SvermConfig.CapGjall, + "How many Gjall the colony can keep alive at once."); + + CapBlisterTick = config.Bind(caps, "Blister Ticks", SvermConfig.CapBlisterTick, + "How many bomb ticks the colony can keep alive at once. They respawn for free, so " + + "this number is also how many explosions are in the air at any moment."); + + CapFarmers = config.Bind(caps, "Worker - Farmers", SvermConfig.CapFarmers, + "Seeker Workers produced by infected beehives, the ones that plant and harvest. " + + "Separate pool from the haulers."); + CapHaulers = config.Bind(caps, "Worker - Haulers", SvermConfig.CapHaulers, + "Seeker Workers produced by the nest after Bonemass, the ones that carry food from " + + "nearby chests into the hive. Separate pool from the farmers."); + + CapBeehives = config.Bind(caps, "Beehives per Aura", SvermConfig.HiveAuraBeehiveMax, + "How many beehives may stand in one nest's ten metres. Every one of them ends up " + + "infected and producing a worker, so this is the number that really decides how " + + "busy a base gets."); + + StingerYawDegrees = config.Bind(stinger, "Yaw", 180f, + "Turns the model on the vertical axis, in degrees. The creature's forward is not " + + "the player's, so without this it flies looking back at you. 180 is the usual " + + "answer; try 90 or -90 if it comes out sideways."); + + EmberGlowStrength = config.Bind(ember, "Glow Strength", SvermConfig.EmberGlowStrength, + "How hot the chitin burns at Fader. This multiplies an HDR colour and it is applied " + + "to the chest, the legs and the helmet at once, so it goes a very long way. Settled " + + "in game at 0.0625 after 1.0 blinded and 0.25 was still too bright. Above the bloom " + + "threshold more brightness buys a bigger white area and less red, so tune downward."); + + SpineSizeSmall = config.Bind(spines, "Size Vestigial", SvermConfig.SpineSizeSmall, + "How tall the dorsal spines stand, in metres, from Moder to the Queen."); + + SpineSizeFull = config.Bind(spines, "Size Full", SvermConfig.SpineSizeFull, + "How tall they stand from the Queen on."); + + SpineBoneName = config.Bind(spines, "Bone", SvermConfig.SpineBoneName, + "Which bone the spines ride. This bone and no other - there is no fallback, so a " + + "name that is not in the rig means no crest at all. Leave it blank to use " + + "Spine3."); + + // Defaults are the values found in game with the crest on screen, not zeroes: changing + // nothing here now reproduces the placement that was actually approved. + SpineRotationX = config.Bind(spines, "Rotation X", SvermConfig.SpineRotationX, "Pitch of the spines, in degrees."); + SpineRotationY = config.Bind(spines, "Rotation Y", SvermConfig.SpineRotationY, "Yaw of the spines, in degrees."); + SpineRotationZ = config.Bind(spines, "Rotation Z", SvermConfig.SpineRotationZ, "Roll of the spines, in degrees."); + } + + // ─── Live reads ────────────────────────────────────────────────────── + // Null-guarded so the placement code works whether or not Bind has run - the main-menu + // character preview can build a body before Awake has finished on a slow load. + + public static UnityEngine.Quaternion SpineRotation() + { + return UnityEngine.Quaternion.Euler( + SpineRotationX?.Value ?? SvermConfig.SpineRotationX, + SpineRotationY?.Value ?? SvermConfig.SpineRotationY, + SpineRotationZ?.Value ?? SvermConfig.SpineRotationZ); + } + + public static float EmberStrength => EmberGlowStrength?.Value ?? SvermConfig.EmberGlowStrength; + + public static int Brood => CapBrood?.Value ?? SvermConfig.CapBrood; + public static int Seeker => CapSeeker?.Value ?? SvermConfig.CapSeeker; + public static int Soldier => CapSoldier?.Value ?? SvermConfig.CapSoldier; + public static int Gjall => CapGjall?.Value ?? SvermConfig.CapGjall; + public static int BlisterTick => CapBlisterTick?.Value ?? SvermConfig.CapBlisterTick; + public static int Farmers => CapFarmers?.Value ?? SvermConfig.CapFarmers; + public static int Haulers => CapHaulers?.Value ?? SvermConfig.CapHaulers; + public static int Beehives => CapBeehives?.Value ?? SvermConfig.HiveAuraBeehiveMax; + + public static float ChestRange => WorkerChestRangeValue?.Value ?? SvermConfig.WorkerChestRange; + public static bool WorkerDebug => WorkerDebugValue?.Value ?? false; + + public static float HiveScale => HiveScaleValue?.Value ?? SvermConfig.HiveScale; + public static float EggSize => EggSizeValue?.Value ?? SvermConfig.HiveEggSize; + public static float EggHeight => EggHeightValue?.Value ?? SvermConfig.HiveEggHeight; + public static float DigestRate => DigestRateValue?.Value ?? SvermConfig.BiomassDigestRate; + public static float StomachSize => StomachSizeValue?.Value ?? SvermConfig.StomachSize; + public static float StomachHeight => StomachHeightValue?.Value ?? SvermConfig.StomachHeight; + public static float MarketSize => MarketSizeValue?.Value ?? SvermConfig.MarketSize; + public static float StageGrowth => StageGrowthValue?.Value ?? SvermConfig.HiveStageGrowth; + public static float NestVfxScale => NestVfxScaleValue?.Value ?? SvermConfig.NestVfxScale; + public static float BeehiveVfxScale => BeehiveVfxScaleValue?.Value ?? SvermConfig.BeehiveVfxScale; + + public static float StingerScale => StingerScaleMultiplier?.Value ?? 1f; + public static float StingerYaw => StingerYawDegrees?.Value ?? 180f; + + public static float SizeSmall => SpineSizeSmall?.Value ?? SvermConfig.SpineSizeSmall; + public static float SizeFull => SpineSizeFull?.Value ?? SvermConfig.SpineSizeFull; + /// + /// The bone name, never blank. + /// + /// An empty string is not "no preference": FindBone's loose match asks whether a bone's + /// name CONTAINS the wanted string, and every string contains the empty one - so a blank + /// entry silently mounted the crest on the first bone of the armature. Clearing the field + /// while experimenting is an obvious thing to do, so it has to mean "the default". + /// + public static string Bone + { + get + { + string configured = SpineBoneName?.Value; + return string.IsNullOrWhiteSpace(configured) ? SvermConfig.SpineBoneName : configured; + } + } + } +} diff --git a/JotunnModStub/Sverm/SvermFood.cs b/JotunnModStub/Sverm/SvermFood.cs new file mode 100644 index 0000000..dad338b --- /dev/null +++ b/JotunnModStub/Sverm/SvermFood.cs @@ -0,0 +1,273 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Insect Metabolism: raw meat is nearly as good as cooked, seeds are food, and honey and royal + /// jelly are worth twice what anyone else gets out of them. + /// + /// THE ONE RULE THAT SHAPES THIS FILE: never write to a vanilla item's m_shared. That object is + /// shared by every instance of the item in the game, for every player and every race - setting + /// RoyalJelly.m_food would make royal jelly edible for a Skeleton too, permanently, and a + /// Sverm's 70% raw meat would be everyone's 70% raw meat. + /// + /// So each edible gets a HIDDEN CLONE carrying the Sverm's numbers. When a Sverm right-clicks + /// the real item, the clone is what gets eaten and one of the real item is removed. The player + /// never sees the clone and the vanilla item is never touched. This is DraughFoodPatches' + /// EdibleUncooked_ trick, and it is here for the same reason it is there. + /// + public static class SvermFood + { + private const string ClonePrefix = "SvermMeal_"; + + /// Every real prefab we intercept, mapped to the clone that carries our numbers. + private static readonly Dictionary meals = new Dictionary(); + + /// Seeds are gated behind The Elder, everything else is live from tier 1. + private static readonly HashSet gatedSeeds = new HashSet(); + + private static bool registered; + + // ─── The tables ────────────────────────────────────────────────────── + + /// + /// Seeds by biome, and the numbers are deliberately modest. + /// + /// This is grinding, not cooking: raw bulk with no buff attached. The buff on a seed is + /// Trenta's whole feature (TrentaConfig.AwakenedSeedFood), and two races eating the same + /// ingredient for the same reward would cost one of them its identity. + /// + /// AncientSeed is deliberately absent. It is the offering that summons The Elder, not a + /// seed, and eating one would be an expensive accident. + /// + private struct SeedFood + { + public string Prefab; + public float Health, Stamina, Eitr, Duration, Regen; + + public SeedFood(string prefab, float health, float stamina, float eitr, float duration, float regen) + { + Prefab = prefab; Health = health; Stamina = stamina; Eitr = eitr; Duration = duration; Regen = regen; + } + } + + private static readonly SeedFood[] Seeds = + { + // Meadows - the weakest thing that still counts as a meal + new SeedFood("CarrotSeeds", 8f, 12f, 0f, 900f, 1f), + new SeedFood("TurnipSeeds", 8f, 12f, 0f, 900f, 1f), + new SeedFood("BeechSeeds", 8f, 10f, 0f, 900f, 1f), + new SeedFood("BirchSeeds", 8f, 10f, 0f, 900f, 1f), + + // Black Forest - nuts and cones, denser + new SeedFood("Acorn", 12f, 16f, 0f, 1000f, 1f), + new SeedFood("FirCone", 12f, 16f, 0f, 1000f, 1f), + new SeedFood("PineCone", 12f, 16f, 0f, 1000f, 1f), + + // Plains + new SeedFood("OnionSeeds", 16f, 20f, 0f, 1200f, 1f), + + // Mistlands - the only seeds with eitr in them, which is what makes going that far pay + new SeedFood("VineberrySeeds",20f, 24f, 8f, 1200f, 2f), + new SeedFood("VineGreenSeeds",20f, 24f, 8f, 1200f, 2f), + }; + + // ─── Registration ──────────────────────────────────────────────────── + + /// + /// Builds every clone. Driven from SvermRace.CreateModAssets, which runs on + /// PrefabManager.OnVanillaPrefabsAvailable - the one moment Jotunn accepts new items. + /// + public static void Register() + { + if (registered) return; + registered = true; + + // RAW MEAT. The raw-to-cooked table is Draugh's, borrowed on purpose rather than + // copied: which raw item becomes which cooked one is a fact about Valheim, not an + // opinion of either race, and a second copy would only drift out of step with the + // first the next time the game adds a meat. + foreach (KeyValuePair pair in DraughFoodPatches.rawToCookedMapping) + { + ItemDrop.ItemData.SharedData cooked = SharedOf(pair.Value); + if (cooked == null) continue; + + BuildMeal(pair.Key, + cooked.m_food * SvermConfig.RawMeatFraction, + cooked.m_foodStamina * SvermConfig.RawMeatFraction, + cooked.m_foodEitr * SvermConfig.RawMeatFraction, + cooked.m_foodBurnTime, + cooked.m_foodRegen, + "raw meat"); + } + + // SEEDS. Gated behind The Elder in the UseItem hook, not here: the clone can exist all + // along, it simply is not reachable before tier 3. + foreach (SeedFood seed in Seeds) + { + if (BuildMeal(seed.Prefab, seed.Health, seed.Stamina, seed.Eitr, seed.Duration, seed.Regen, "seed")) + { + gatedSeeds.Add(seed.Prefab); + } + } + + // HONEY, doubled. Read at runtime and multiplied rather than transcribed, so a patch + // that rebalances honey rebalances the Sverm with it. + ItemDrop.ItemData.SharedData honey = SharedOf("Honey"); + if (honey != null) + { + BuildMeal("Honey", + honey.m_food * SvermConfig.HoneyMultiplier, + honey.m_foodStamina * SvermConfig.HoneyMultiplier, + honey.m_foodEitr * SvermConfig.HoneyMultiplier, + honey.m_foodBurnTime * SvermConfig.HoneyMultiplier, + honey.m_foodRegen, + "honey"); + } + + // ROYAL JELLY. Not a food in vanilla at all - it is crafting material - so there is + // nothing to double and the numbers are the ones the design settled on. They are + // already the doubled figures; they are not multiplied again. + BuildMeal(SvermConfig.RoyalJellyPrefab, + SvermConfig.RoyalJellyHealth, + SvermConfig.RoyalJellyStamina, + SvermConfig.RoyalJellyEitr, + SvermConfig.RoyalJellyDuration, + SvermConfig.RoyalJellyRegen, + "royal jelly"); + + Jotunn.Logger.LogInfo($"[Sverm] Insect Metabolism: {meals.Count} edibles registered."); + } + + private static ItemDrop.ItemData.SharedData SharedOf(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + return drop != null && drop.m_itemData != null ? drop.m_itemData.m_shared : null; + } + + /// + /// One hidden clone of one real item, carrying the Sverm's numbers. + /// + /// The clone is made a Consumable whatever the original was - a seed is Material in vanilla + /// and would otherwise be refused by EatFood before it got to look at the numbers. + /// + private static bool BuildMeal(string sourcePrefab, float health, float stamina, float eitr, + float duration, float regen, string label) + { + GameObject source = PrefabManager.Cache.GetPrefab(sourcePrefab); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{sourcePrefab}' to build a {label} from; skipped."); + return false; + } + + string cloneName = ClonePrefix + sourcePrefab; + GameObject clone = PrefabManager.Instance.CreateClonedPrefab(cloneName, source); + if (clone == null) return false; + + ItemDrop drop = clone.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable; + shared.m_food = health; + shared.m_foodStamina = stamina; + shared.m_foodEitr = eitr; + shared.m_foodBurnTime = duration; + shared.m_foodRegen = regen; + + // The name is what Player.Food compares on when it decides whether you are eating the + // same thing twice, so it must stay the ORIGINAL's name - otherwise raw meat and its + // clone would occupy two food slots at once. + // m_maxStackSize left alone; nothing ever holds one of these. + + ItemManager.Instance.AddItem(new CustomItem(clone, fixReference: false)); + meals[sourcePrefab] = cloneName; + return true; + } + + // ─── Eating ────────────────────────────────────────────────────────── + + /// Which clone answers for this item, or null when we do not cover it. + private static string MealFor(ItemDrop.ItemData item, int state) + { + if (item == null || item.m_shared == null) return null; + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; + if (string.IsNullOrEmpty(prefabName)) return null; + + if (gatedSeeds.Contains(prefabName) && state < SvermConfig.SeedsEdibleState) return null; + + return meals.TryGetValue(prefabName, out string clone) ? clone : null; + } + + public static bool IsGatedSeed(string prefabName) => gatedSeeds.Contains(prefabName); + + /// + /// Swaps the real item for its clone at the moment of eating. + /// + /// A prefix on UseItem rather than on EatFood, and that is what lets seeds and royal jelly + /// work at all: they are Material in vanilla, so by the time EatFood is reached the game + /// has already decided they are not food. UseItem runs before that judgement. + /// + [HarmonyPatch(typeof(Humanoid), "UseItem")] + public static class Sverm_UseItem_Patch + { + public static bool Prefix(Humanoid __instance, Inventory inventory, ItemDrop.ItemData item) + { + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return true; + if (!SvermVisuals.IsSvermPlayer(player)) return true; + if (item == null || item.m_shared == null) return true; + + // MEDICINE BEFORE FOOD, and called from here rather than from a prefix of its own: + // honey and royal jelly are both a meal and the colony's medicine, and which one a + // press means is decided by whether the player is looking at one of our insects. + // Two prefixes both wanting to answer that first would be a coin toss. + if (SvermMedicine.TryAdminister(player, item)) return false; + + // The one thing a Sverm may not eat. Blocked here rather than left to fail + // silently, so the refusal says why. + if (item.m_dropPrefab != null && item.m_dropPrefab.name.StartsWith("SvermMeal_") == false + && IsAswidBlood(item)) + { + player.Message(MessageHud.MessageType.Center, "Alchemical blood is not food."); + return false; + } + + string cloneName = MealFor(item, BossProgressionManager.GetCurrentProgressionState()); + if (cloneName == null) return true; + + GameObject clonePrefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(cloneName) : null; + ItemDrop cloneDrop = clonePrefab != null ? clonePrefab.GetComponent() : null; + if (cloneDrop == null) return true; // registration failed; let vanilla decide + + if (!player.EatFood(cloneDrop.m_itemData)) return false; // full, or too soon - vanilla already said so + + if (inventory != null) inventory.RemoveItem(item, 1); + + EffectList consume = Traverse.Create(player).Field("m_consumeItemEffects").Value; + if (consume != null) consume.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1); + + ZSyncAnimation anim = Traverse.Create(player).Field("m_zanim").Value; + if (anim != null) anim.SetTrigger("eat"); + + return false; // handled + } + + /// + /// The Aswid's alchemical blood, recognised without a hard dependency on that race's + /// tables: everything it makes carries its own prefix. + /// + private static bool IsAswidBlood(ItemDrop.ItemData item) + { + string name = item.m_dropPrefab != null ? item.m_dropPrefab.name : ""; + return name.StartsWith("Aswid") || name == "BloodEssence" || name.Contains("BloodPotion"); + } + } + } +} diff --git a/JotunnModStub/Sverm/SvermHive.cs b/JotunnModStub/Sverm/SvermHive.cs new file mode 100644 index 0000000..f5ed0ca --- /dev/null +++ b/JotunnModStub/Sverm/SvermHive.cs @@ -0,0 +1,621 @@ +using System.Collections.Generic; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The nest itself: the piece, its gate, and the ten metres of ground it claims. + /// + /// GATED ON THE ELDER, and that gate is the whole point of the revision. The colony used to + /// open at tier 1 and arrive all at once; now the early game is spent as a body, and the first + /// nest is a thing you earn. What the boss decides is WHEN you may plant one - how fast it + /// grows after that is still bought with biomass, four stages at the shop, exactly as before. + /// + /// THE AURA is what makes it read as a colony rather than as a machine. Inside ten metres the + /// Sverm may raise up to ten vanilla beehives, and they cost only wood - no queen bee, because + /// a colony that has to go hunting for someone else's queen is telling the wrong story. Left + /// alone for a minute, each hive is taken over: an egg pushes out through the roof, and from + /// then on it works twice as fast and holds three times as much. + /// + /// This file owns the piece and the aura. Biomass, eggs, troops and the shop are + /// SvermHiveBehaviour's; the workers are SvermWorker's. + /// + public static class SvermHive + { + public const string PieceName = SvermHiveNames.PieceName; + public const string DisplayName = SvermHiveNames.PieceDisplayName; + + /// + /// What the nest borrows its body from, best first. + /// + /// "Hive" WAS the first entry and it was a disaster. The name is in the game's manifest and + /// it sounds exactly right, so it went in unchecked - and it turned out to carry a + /// Character. Building it did not place a nest, it SPAWNED A CREATURE, and because a Piece + /// and a WearNTear had been bolted on top without removing anything, the health the console + /// tried to take off was not the health holding it up. A giant immortal Bonemass, from a + /// name that read as scenery. + /// + /// Everything in this list now is a CreepProp - the game's own word for "this is a prop" - + /// and IsSafeScenery below refuses anything alive whatever the list says. + /// + private static readonly string[] SourceCandidates = + { + "CreepProp_pillar01", + "CreepProp_egg_hanging01", + "Creeppillar", + "CreepProp_hanging01", + }; + + public static void Register() + { + GameObject prefab = null; + string sourcePrefab = null; + + foreach (string candidate in SourceCandidates) + { + GameObject source = PrefabManager.Cache.GetPrefab(candidate); + if (source == null) continue; + + if (!IsSafeScenery(source, candidate)) continue; + + prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source); + if (prefab == null) continue; + + sourcePrefab = candidate; + break; + } + + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Sverm] No safe scenery to build the nest from (" + + string.Join(", ", SourceCandidates) + "); the nest is not registered. " + + "Not registering is the correct outcome: a nest nobody can build beats " + + "a nest that turns out to be alive."); + return; + } + + // Belt as well as braces: anything that could still make this act like a creature comes + // off the COPY. The guard above should mean there is nothing to find, and this is what + // makes that true rather than hoped for. + StripLife(prefab); + + // Set on the PREFAB, so every nest ever placed comes out this size and the value is + // baked into the piece rather than chased at runtime. It follows that changing it in + // the .cfg only affects nests placed afterwards - the ones already standing keep the + // size they were built at, which is how every other building in the game behaves. + float scale = SvermConfigManagement.HiveScale; + prefab.transform.localScale = new Vector3(scale, scale, scale); + + // A hive in the world is scenery, not a building: it arrives with no Piece and no + // WearNTear, and the hammer needs both. Added rather than assumed - the clone is + // whatever the game shipped, and asking for a component that is not there is how a + // station ends up unplaceable with no error. + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_name = DisplayName; + piece.m_description = "The colony begins here. Everything else grows out of it."; + piece.m_groundPiece = true; + piece.m_groundOnly = true; + piece.m_cultivatedGroundOnly = false; + piece.m_canBeRemoved = true; + + if (prefab.GetComponent() == null) + { + WearNTear wear = prefab.AddComponent(); + wear.m_health = 1500f; + wear.m_noRoofWear = true; + wear.m_noSupportWear = true; + wear.m_destroyedEffect = new EffectList(); + wear.m_hitEffect = new EffectList(); + } + + if (prefab.GetComponent() == null) prefab.AddComponent(); + prefab.AddComponent(); + + MountMouths(prefab); + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = DisplayName, + Description = piece.m_description, + PieceTable = PieceTables.Hammer, + Category = "Crafting", + + // NOT OPTIONAL. Jotunn refuses a piece with no icon outright - "CustomPiece has no + // icon" followed by "is not valid" - and the piece simply never reaches the + // hammer. Borrowed off a trophy, the way SkeletonBonePile does. + Icon = BorrowIcon("TrophySeekerBrute") ?? BorrowIcon("TrophySeeker") ?? BorrowIcon("Honey"), + Requirements = new[] + { + new RequirementConfig { Item = "Wood", Amount = 40, Recover = true }, + new RequirementConfig { Item = "Resin", Amount = 20, Recover = true }, + }, + })); + + // Two per square mile, as before. The radius is 908 m because that is the circle of + // equal area, and PieceDensityLimit counts over ZDOs rather than loaded objects. + PieceDensityLimit.Register(PieceName, SvermConfig.HiveDensityRadius, SvermConfig.HiveDensityMax, + "There is already a hive holding this ground."); + + // The gate. Race first, then the boss - two separate refusals, because "you are not a + // Sverm" and "you have not killed The Elder" are different problems and a player who + // gets the wrong message goes looking in the wrong place. + PieceDensityLimit.RegisterGate(PieceName, (player, position) => + { + if (player == null) return false; + + if (!SvermVisuals.IsSvermPlayer(player)) + { + player.Message(MessageHud.MessageType.Center, "Only the Sverm can raise a hive."); + return false; + } + + if (BossProgressionManager.GetCurrentProgressionState() < SvermConfig.HiveUnlockState) + { + player.Message(MessageHud.MessageType.Center, "The colony will not wake until the Elder falls."); + return false; + } + + return true; + }); + + Jotunn.Logger.LogInfo($"[Sverm] Registered '{PieceName}' from '{sourcePrefab}'."); + } + + /// + /// What the two mouths borrow their look from, best first. SCENERY ONLY. + /// + /// "Hive" WAS ON THIS LIST for one build, on the reasoning that ModelBorrow strips a copy + /// down to its renderers so borrowing a living prefab is safe. IT IS NOT, and the game said + /// so in one line nobody had asked it for: + /// + /// Can't remove Humanoid (Script) because CharacterDrop (Script) depends on it + /// + /// ModelBorrow's strip is a single pass in component order. Unity REFUSES to destroy a + /// component another one still requires, so Humanoid survived on both mouths - and from then + /// on every placement ghost woke a Humanoid, registered it in Character.s_characters and + /// tore it down again, until Character.GetCharactersInRange threw on the wreckage inside + /// Player.UpdatePlacementGhost. The hammer stopped working. FOR EVERY PIECE IN THE GAME, not + /// just this one. + /// + /// Which is house rule one, twice over: ask the prefab whether it has a Character, and do + /// not trust a helper to have asked for you. IsSafeScenery below now runs on the source + /// BEFORE anything is borrowed from it. + /// + private static readonly string[] MouthCandidates = + { + "TheHive", + "CreepProp_egg_hanging01", + "CreepProp_egg_hanging02", + "SeekerEgg", + "CreepProp_hanging01", + }; + + /// + /// The stomach: the hive at the nest's foot that a press feeds. + /// + /// A MOUTH AND NOT A MENU, at the player's call, after a sell panel inside the vanilla store + /// came up empty and unclickable in game. Feeding is a press on a thing you can see, which + /// needs no UI to be right. + /// + /// THERE WAS A SECOND MOUTH UP THE TRUNK, the shop, and it is gone: it never had a height + /// that worked. On the measured crown it was eight metres over the player's head; at the + /// number that replaced it the .cfg still held the old zero, so it sat inside the stomach's + /// own sphere and the ray always found the stomach first. The shop is its own building now - + /// SvermHiveMarketPiece - which is how the Dvergar bench and the Trol totem already do it. + /// + /// The mouth gets a SPHERE OF ITS OWN because Player.FindHoverObject picks what you are + /// pointing at from the first collider the ray meets and reads the Hoverable off THAT + /// collider's own GameObject. A mouth sharing the trunk's collider would not be a mouth. The + /// sphere is as wide as the model, so it stands clear of the trunk rather than hiding inside + /// it - the one thing that would make it unreachable. + /// + private static void MountMouths(GameObject prefab) + { + // Measured BEFORE the mouths are hung, or it would be measuring them too. This is the + // trunk's own height, in the piece's local space, and it is what "up top" means when + // nobody has typed a number into the .cfg. + float trunk = ModelBorrow.HeightOf(prefab); + + GameObject source = null; + string sourceName = null; + foreach (string candidate in MouthCandidates) + { + GameObject found = PrefabManager.Cache.GetPrefab(candidate); + if (found == null) continue; + + // The same question the piece itself has to answer, asked again here: a model is + // borrowed from this, and a borrowed model that turns out to be alive is what broke + // the hammer. + if (!IsSafeScenery(found, candidate)) continue; + + source = found; + sourceName = candidate; + break; + } + + if (source == null) + { + Jotunn.Logger.LogWarning("[Sverm] No safe scenery to borrow the nest's mouths from (" + + string.Join(", ", MouthCandidates) + "); they are mounted " + + "anyway, invisible but pressable, rather than leaving the " + + "nest with no way to be fed."); + } + + // The trunk is REPORTED and not used as a height: it measured 10.59 m, which is the + // number that made the old market unreachable. Kept in the log because it is the only + // way anyone can tell where there is room to put something on this piece. + Jotunn.Logger.LogInfo($"[Sverm] Nest stomach borrowed from '{sourceName ?? "nothing"}'; the trunk " + + $"measures {trunk:0.##} m and the stomach sits at " + + $"{SvermConfigManagement.StomachHeight:0.##} m."); + + MountMouth(prefab, source, "SvermHiveStomach", + SvermConfigManagement.StomachSize, SvermConfigManagement.StomachHeight); + } + + private static void MountMouth(GameObject prefab, GameObject source, string holderName, + float size, float height) where T : SvermHiveMouth + { + GameObject holder = ModelBorrow.Attach(prefab.transform, holderName, source, + new Vector3(0f, height, 0f), Quaternion.identity, size, "Sverm"); + + // The piece's own layer, because that is the layer the player's interact raycast looks + // at. A GameObject built from scratch comes up on Default, and Default is not it. + holder.layer = prefab.layer; + + // Centred half a size up: ModelBorrow grounds a borrowed model on the holder's origin, + // so the holder's origin is the model's FOOT and not its middle. + SphereCollider ball = holder.AddComponent(); + ball.center = new Vector3(0f, size * 0.5f, 0f); + ball.radius = size * 0.5f; + + holder.AddComponent(); + } + + /// + /// Refuses to build a building out of anything that is alive. + /// + /// This is the check that was missing, and its absence cost a giant immortal Bonemass in + /// somebody's base. A name in the asset manifest says nothing about what a prefab DOES - + /// "Hive" carried a Character - and the only way to know is to ask the prefab itself. + /// + /// It logs what it found rather than failing quietly, because the next person to add a + /// station from a borrowed prefab needs to be told which one to stop trusting. + /// + internal static bool IsSafeScenery(GameObject source, string name) + { + if (source.GetComponentInChildren(true) != null) + { + Jotunn.Logger.LogWarning($"[Sverm] '{name}' carries a Character - it is a CREATURE, not scenery. " + + "Refusing to make a building out of it."); + return false; + } + + if (source.GetComponentInChildren(true) != null) + { + Jotunn.Logger.LogWarning($"[Sverm] '{name}' carries a BaseAI; refusing to make a building out of it."); + return false; + } + + if (source.GetComponentInChildren(true) != null) + { + Jotunn.Logger.LogWarning($"[Sverm] '{name}' is a spawner; refusing to make a building out of it."); + return false; + } + + return true; + } + + /// + /// Takes everything that could still behave like a creature off the copy. + /// + /// Order matters for the same reason it does in ModelBorrow: behaviours first, then the + /// things they hold references to. + /// + internal static void StripLife(GameObject copy) + { + foreach (BaseAI ai in copy.GetComponentsInChildren(true)) + { + if (ai != null) Object.DestroyImmediate(ai); + } + foreach (Character character in copy.GetComponentsInChildren(true)) + { + if (character != null) Object.DestroyImmediate(character); + } + foreach (CharacterDrop drop in copy.GetComponentsInChildren(true)) + { + if (drop != null) Object.DestroyImmediate(drop); + } + foreach (SpawnArea spawner in copy.GetComponentsInChildren(true)) + { + if (spawner != null) Object.DestroyImmediate(spawner); + } + foreach (Rigidbody body in copy.GetComponentsInChildren(true)) + { + if (body != null) Object.DestroyImmediate(body); + } + } + + /// + /// The nest this point belongs to, or null. + /// + /// Loaded objects and not ZDOs, deliberately: the only caller is the market bench, which is + /// standing inside the nest's ten metres or it would not have been allowed to exist. A nest + /// that close is loaded by definition, and the cheap answer is the right one. + /// + internal static SvermHiveBehaviour NearestNest(Vector3 position, float radius) + { + SvermHiveBehaviour closest = null; + float best = radius; + + foreach (SvermHiveBehaviour nest in Object.FindObjectsOfType()) + { + if (nest == null) continue; + + float distance = Vector3.Distance(nest.transform.position, position); + if (distance > best) continue; + + best = distance; + closest = nest; + } + + return closest; + } + + /// An item's inventory icon, or null. Same helper shape as SkeletonBonePile's. + internal static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return null; + if (drop.m_itemData.m_shared.m_icons == null || drop.m_itemData.m_shared.m_icons.Length == 0) return null; + return drop.m_itemData.m_shared.m_icons[0]; + } + } + + /// + /// The nest's own upkeep. Today that is the aura and the beehives inside it; biomass, eggs, + /// troops and the shop land here next. + /// + public class SvermHiveBehaviour : MonoBehaviour, Hoverable, Interactable + { + /// + /// The trunk feeds, exactly like the stomach at its foot. + /// + /// IT USED TO TAKE WHAT WAS IN YOUR HAND, which could not be made to work: food is a + /// consumable, it never reaches the weapon slot, and the meat the player thought they were + /// offering was simply eaten by the player. It reads the inventory now. + /// + /// The trunk is the widest thing to point at, so it does the thing you do most rather than + /// being a dead spot between the two mouths. The store has one way in and it is the hive up + /// top - see SvermHiveMarket. + /// + public bool Interact(Humanoid user, bool hold, bool alt) + { + if (hold) return false; + + Player player = user as Player; + if (player == null || player != Player.m_localPlayer) return false; + + if (!SvermVisuals.IsSvermPlayer(player)) + { + player.Message(MessageHud.MessageType.Center, "The hive does not know you."); + return true; + } + + return SvermHiveStore.FeedOneStack(this, player); + } + + public bool UseItem(Humanoid user, ItemDrop.ItemData item) => false; + + /// + /// What the nest says when you look at it. + /// + /// The tank had no readout at all in the first pass, which made every other part of the + /// colony unfalsifiable: a hauler that was not working and a hauler that was working + /// looked exactly the same. A number on the hive is the cheapest possible test of the + /// whole chain. + /// + public string GetHoverText() + { + int beehives = SvermBeehive.CountInAura(transform.position); + int infected = SvermBeehive.CountInfectedInAura(transform.position); + + // Both numbers, always, even when nothing is going down. A line that appears and + // disappears is one the player has to notice twice before they believe it. + return $"{SvermHiveStage.NameOf(SvermHiveStage.Of(transform))}\n" + + SvermHiveReadout.Tank(transform) + + $"Beehives {infected} taken of {beehives} in range\n" + + "[$KEY_Use] Feed it a stack"; + } + + public string GetHoverName() => SvermHiveStage.NameOf(SvermHiveStage.Of(transform)); + + private ZNetView nview; + private float nextSweep; + private float nextHauler; + private float nextDigest; + private float nextTick; + private float nextVfx; + + /// + /// The size this nest was built at, before any growth is applied on top. + /// + /// Read at Awake and kept, rather than taken from the config each time: the piece is + /// registered at the configured scale, so what the transform holds when it loads IS the size + /// this particular nest was placed at - which is the promise the config makes, that changing + /// it never resizes nests already standing. + /// + private Vector3 builtScale = Vector3.one; + private float shownScale = -1f; + + private void Awake() + { + nview = GetComponent(); + builtScale = transform.localScale; + + // A station, in the same sense the Draugh spawner and the Dvergar bank are: this is what + // the troops bound to it look for to decide they are not orphans. Without it the whole + // garrison would wither a minute after it hatched. + RaisedThrall.RegisterStation(transform); + + // Before the first frame is drawn, or a grown nest pops from small to large in front of + // whoever is standing there when it loads. + ApplyStageScale(); + } + + private void OnDestroy() + { + // StationStandsAt cleans destroyed transforms out of its own list, so this is belt as + // well as braces - but a nest that is torn down should stop being a home the same frame, + // not the next time somebody asks. + RaisedThrall.UnregisterStation(transform); + } + + /// + /// Puts the stage on screen. Every client does this off the ZDO, so nobody has to own the + /// nest to see it the right size - section 9.1's "la scala va sul ZDO", by derivation rather + /// than by a second synced field. + /// + private void ApplyStageScale() + { + if (nview == null || !nview.IsValid()) return; + + // The SCALE and not the stage is what is remembered, so that retuning the growth in the + // .cfg moves the nests already standing instead of waiting for a stage they may never + // buy again. + float wanted = SvermHiveStage.ScaleOf(SvermHiveStage.Of(transform)); + if (Mathf.Approximately(wanted, shownScale)) return; + + shownScale = wanted; + transform.localScale = builtScale * wanted; + } + + private void Update() + { + // ABOVE the owner check, and that is the point of it: the client who bought the stage is + // not necessarily the client who owns the nest, and everyone has to see it grow. + ApplyStageScale(); + + // Same reason, same place. The flies hang over the nest always; the green reek only + // while there is something going down, which makes the digestion a thing you can see + // from across the field instead of a number on a hover text. + if (Time.time >= nextVfx) + { + nextVfx = Time.time + 2f; + + float scale = SvermConfigManagement.NestVfxScale; + SvermHiveVfx.EnsureFlies(transform, scale); + SvermHiveVfx.SetGas(transform, SvermBiomass.Digesting(transform) > 0f, scale); + + // The taken beehives wear the same two marks, smaller. Driven from here rather than + // from the sweep because the sweep is the OWNER's round and these have to show up on + // every client. + SvermBeehive.DressInfected(transform.position); + } + + // Only the owner runs the colony. Every client seeing this nest would otherwise infect + // the same beehives over and over, each writing its own answer to the same ZDO. + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + // Ahead of the sweep gate and on a clock of its own: the sweep walks a sphere of + // colliders and can afford to wait five seconds, while a number the player is standing + // there watching should move about as often as they can see it move. What is actually + // digested comes from the world clock, so this interval only decides how smooth the + // readout is, never how fast the hive works. + if (Time.time >= nextDigest) + { + nextDigest = Time.time + 1f; + SvermBiomass.Digest(transform); + + // Eggs work themselves out from the world clock, so this only writes down what has + // already happened - which is what keeps the number the other clients read close to + // the truth. + SvermBroodEggs.Settle(transform); + } + + // The ticks' free respawn, on its own half-minute clock: an empty paid slot grows a new + // one, one per pass, so a wiped-out swarm trickles back rather than arriving all at once. + if (Time.time >= nextTick) + { + nextTick = Time.time + SvermConfig.TickRespawnSeconds; + SvermBlisterTick.Replace(this); + } + + if (Time.time < nextSweep) return; + nextSweep = Time.time + SvermConfig.HiveAuraSweepInterval; + + SvermBeehive.SweepAura(transform.position); + + Haul(); + + // Haulers come out of the NEST, and only after Bonemass. The farmers are the beehives' + // business, not the nest's - see SvermBeehive. + if (BossProgressionManager.GetCurrentProgressionState() >= SvermConfig.HaulerUnlockState && + Time.time >= nextHauler && + SvermWorker.HasRoom(SvermWorker.Job.Hauler)) + { + nextHauler = Time.time + SvermConfig.WorkerSpawnInterval; + SvermWorker.Spawn(SvermWorker.Job.Hauler, transform); + } + } + + /// + /// The nest eats out of the chests around it, once per living hauler per sweep. + /// + /// THE WORK MOVED HERE FROM THE WORKERS, and that is the fix rather than a shortcut. A + /// hauler is a creature: it wanders, it picks fights, it dies, and every one of those took + /// the whole supply chain with it - chests stayed full and the tank stayed at zero with + /// nothing to point at. The nest never moves and is always exactly where the chests are. + /// + /// The haulers still matter: no hauler, no hauling. They are the reason the nest can do + /// it, and they defend the chests they feed from - which is what they were always meant to + /// be doing. What they are no longer is a single point of failure for the economy. + /// + private void Haul() + { + int hands = SvermWorker.Count(SvermWorker.Job.Hauler); + if (hands <= 0) return; + + float range = SvermConfigManagement.ChestRange; + + foreach (Container container in Object.FindObjectsOfType()) + { + if (container == null) continue; + if (Vector3.Distance(container.transform.position, transform.position) > range) continue; + + Inventory inventory = container.GetInventory(); + if (inventory == null) continue; + + foreach (ItemDrop.ItemData item in new List(inventory.GetAllItems())) + { + if (item == null || item.m_shared == null) continue; + if (!SvermBiomass.IsFuel(item)) continue; + + float taken = SvermBiomass.Deposit(transform, item); + if (taken <= 0f) return; // tank full: leave everything where it is + + inventory.RemoveItem(item, 1); + + // Container.Save is private in the shipped assembly, so the write is pushed + // through reflection. Without it the chest empties on this client and refills + // from the server's copy, which reads as nothing having happened. + ZNetView cview = container.GetComponent(); + if (cview != null && cview.IsValid()) + { + HarmonyLib.Traverse.Create(container).Method("Save").GetValue(); + } + + if (--hands <= 0) return; + } + } + } + + /// How many beehives are already claimed by this nest. Used by the build gate. + public int CountBeehives() + { + return SvermBeehive.CountInAura(transform.position); + } + } +} diff --git a/JotunnModStub/Sverm/SvermHiveGoods.cs b/JotunnModStub/Sverm/SvermHiveGoods.cs new file mode 100644 index 0000000..7962d3c --- /dev/null +++ b/JotunnModStub/Sverm/SvermHiveGoods.cs @@ -0,0 +1,499 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// What the Hive Market sells, and the column it is sold from. + /// + /// THE VANILLA BUY LIST CANNOT CARRY THIS. StoreGui's own column is a list of + /// Trader.TradeItem, every one of which is an ItemDrop that lands in your inventory when you pay + /// coin for it. The hive sells no items: it sells a stage of growth, which is a number on its + /// own ZDO. So the goods hang in a column of our own, cloned from the store's list element - + /// exactly what TrolTotemStore does for its warbands, down to sitting at m_listRoot's own + /// position and switching itself off when the window belongs to somebody else. + /// + /// That position matters and it is the correction of a failed attempt: the first version of the + /// hive's panel put its column at m_listRoot's position PLUS 260 px, which is outside the panel + /// that clips it. It drew perfectly and nobody could see or click a single row of it. + /// + /// PRICES ARE THE DOCUMENT'S, unchanged: 1000, 1500, 2000, each one the full tank of the stage + /// it buys you out of, so growing always empties the hive. + /// + public static class SvermHiveGoods + { + /// One thing the market sells. + public class Good + { + public string Id; + public string Name; + public float Price; + public string Icon; + public string Description; + + /// Why this cannot be bought right now, or null when it can. + public Func Refusal; + + /// Hands over the goods. Only ever called after the price has been taken. + public Action Deliver; + + /// + /// How long before another of these, in seconds. A function and not a number because the + /// upgrades wait a GAME DAY, and how long a game day is belongs to the world rather than + /// to this table. + /// + public Func Cooldown; + } + + /// + /// The shelf: three stages, two stars, four troops. + /// + /// NO VENOM COIL. Section 13's serpent turret was built and then taken out again at the + /// player's call - it is not on this shelf, there is no prefab for it, and it is not a thing + /// waiting to be finished. If it ever comes back it comes back as a new decision. + /// + /// Stages first, because they are what unlocks the rest of the list. + /// + public static readonly List Shelf = BuildShelf(); + + private static List BuildShelf() + { + List shelf = new List + { + StageUpgrade(2, "TrophySeeker"), + StageUpgrade(3, "TrophySeekerBrute"), + StageUpgrade(4, "TrophySeekerQueen"), + + Star(1, "Surrenal Glands", 800f, "TrophySeeker", + "Every troop hatched from now on is born with one star.\n\n" + + "It does nothing for the ones already walking around: what is born is born."), + + Star(2, "Hyperplasia", 1600f, "TrophySeekerQueen", + "Every troop hatched from now on is born with two stars.\n\n" + + "The colony has to have grown the glands first."), + }; + + foreach (SvermBrood.Kind kind in SvermBrood.Roster) shelf.Add(Troop(kind)); + + shelf.Add(BlisterTick()); + + return shelf; + } + + /// + /// The bomb tick, which is the only thing on this shelf you buy ONCE and keep having. + /// Section 12: fifty biomass and an egg buy a slot, the slot is permanent, and whatever + /// stands in it comes back for free half a minute after it bursts. + /// + private static Good BlisterTick() + { + return new Good + { + Id = "blistertick", + Name = SvermBlisterTick.DisplayName, + Price = SvermConfig.TickPrice, + Icon = "TrophyTick", + Description = "Buys a PERMANENT slot in the colony. What stands in it runs at whatever " + + "the colony is fighting and bursts, and thirty seconds later the nest " + + "grows another one - no egg, no biomass, forever.\n\n" + + "The blast spares you, your tames and the rest of the colony.", + + Refusal = hive => + { + int slots = SvermBlisterTick.SlotsOf(hive.transform); + if (slots >= SvermConfigManagement.BlisterTick) + { + return $"The colony already keeps {slots} of them."; + } + + if (SvermBroodEggs.Count(hive.transform) < 1) return "No brood egg ready."; + + return null; + }, + + Deliver = hive => + { + if (!SvermBroodEggs.Take(hive.transform, 1)) + { + SvermBiomass.Refund(hive.transform, SvermConfig.TickPrice); + return; + } + + SvermBlisterTick.BuySlot(hive.transform); + SvermBlisterTick.Hatch(hive); + }, + + // The tick has no queue of its own: the wait is the thirty seconds it takes to come + // back, and that is enforced at the nest rather than at the counter. + Cooldown = () => 0f, + }; + } + + /// + /// One step up the four stages. The price is the tank it empties, from section 10.1. + /// + private static Good StageUpgrade(int target, string icon) + { + int from = target - 1; + + return new Good + { + Id = "stage" + target, + Name = SvermHiveStage.NameOf(target), + Price = SvermHiveStage.PriceToLeave(from), + Icon = icon, + Description = $"Grows the nest into a {SvermHiveStage.NameOf(target)}: it holds " + + $"{SvermHiveStage.Capacity(target):0} biomass instead of " + + $"{SvermHiveStage.Capacity(from):0}, and stands half again as tall.\n\n" + + "It costs this stage's whole tankful, so it leaves the hive all but " + + "empty. Grow or field an army - never both in the same breath.", + + Refusal = hive => + { + int stage = SvermHiveStage.Of(hive.transform); + if (stage > from) return "Already grown past this."; + if (stage < from) return $"The nest has to be a {SvermHiveStage.NameOf(from)} first."; + return null; + }, + + Deliver = hive => SvermHiveStage.Advance(hive.transform), + + Cooldown = () => DayLength() * SvermConfig.UpgradeCooldownDays, + }; + } + + /// + /// One of the two permanent star upgrades. They are a ladder: the glands before the + /// hyperplasia. + /// + /// THE LADDER IS AN INVENTION. The document prices them separately and says nothing about + /// needing one for the other - but without it the cheap path to two stars is to skip the + /// eight hundred entirely, which makes the first upgrade a thing only a mistake buys. + /// + private static Good Star(int stars, string name, float price, string icon, string description) + { + return new Good + { + Id = "stars" + stars, + Name = name, + Price = price, + Icon = icon, + Description = description, + + Refusal = hive => + { + int have = SvermBroodStars.Of(hive.transform); + if (have >= stars) return "The colony already breeds like this."; + if (have < stars - 1) return "One star at a time."; + return null; + }, + + Deliver = hive => SvermBroodStars.Set(hive.transform, stars), + + Cooldown = () => DayLength() * SvermConfig.UpgradeCooldownDays, + }; + } + + /// + /// One rung of the roster on sale. Costs biomass AND a brood egg, which is section 10.2's + /// two resources in parallel: the egg is the slot and grows back, the biomass is the price + /// and does not. + /// + private static Good Troop(SvermBrood.Kind kind) + { + return new Good + { + Id = "troop_" + kind.Id, + Name = kind.Display, + Price = kind.Price, + Icon = kind.Icon, + Description = $"Hatches a {kind.Display}, bound to this nest: it follows when you ask, " + + $"walks home when you let it go, and mends itself.\n\n" + + $"Costs one brood egg as well as the biomass. At most {kind.Cap} of them alive at once.", + + Refusal = hive => + { + int stage = SvermHiveStage.Of(hive.transform); + if (stage < kind.Stage) + { + return $"The nest has to be a {SvermHiveStage.NameOf(kind.Stage)} first."; + } + + int alive = SvermBrood.CountAlive(hive, kind); + if (alive >= kind.Cap) return $"The colony is already keeping {alive} of them."; + + if (SvermBroodEggs.Count(hive.transform) < 1) return "No brood egg ready."; + + return null; + }, + + Deliver = hive => + { + // The egg is taken here rather than in Buy, because it is this good's price and + // not every good's: an upgrade costs biomass and nothing else. + // + // And if the egg is gone between the refusal check and this line - which only two + // players at one nest can manage - the biomass goes back. A purchase that took + // the price and handed over nothing is the one outcome worth writing code for. + if (!SvermBroodEggs.Take(hive.transform, 1)) + { + SvermBiomass.Refund(hive.transform, kind.Price); + return; + } + + if (!SvermBrood.Hatch(hive, kind)) + { + SvermBiomass.Refund(hive.transform, kind.Price); + } + }, + + Cooldown = () => kind.Cooldown, + }; + } + + // ─── Buying ────────────────────────────────────────────────────────── + + /// + /// Why this good is greyed out, or null when it can be bought. + /// + /// The order of the questions is the order the player would ask them: can I have it at all, + /// is it too soon, can I afford it. + /// + public static string RefusalFor(Good good, SvermHiveBehaviour hive) + { + if (good == null || hive == null) return "No hive."; + + string ownRefusal = good.Refusal != null ? good.Refusal(hive) : null; + if (ownRefusal != null) return ownRefusal; + + long waitingSeconds = CooldownLeft(hive.transform, good); + if (waitingSeconds > 0L) + { + return waitingSeconds >= 60L + ? $"The hive is still working on the last one ({waitingSeconds / 60}m)." + : $"The hive is still working on the last one ({waitingSeconds}s)."; + } + + if (SvermBiomass.Bank(hive.transform) < good.Price) return "Not enough biomass in the bank."; + + return null; + } + + public static bool Buy(Good good, SvermHiveBehaviour hive, Player player) + { + string refusal = RefusalFor(good, hive); + if (refusal != null) + { + player?.Message(MessageHud.MessageType.Center, refusal); + return false; + } + + // Paid first and delivered second, and never the other way round: Spend is the only + // thing here that can fail on a race with another client, and a hive that hands over a + // stage it was not paid for cannot be undone. + if (!SvermBiomass.Spend(hive.transform, good.Price)) + { + player?.Message(MessageHud.MessageType.Center, "Not enough biomass in the bank."); + return false; + } + + good.Deliver?.Invoke(hive); + StampCooldown(hive.transform, good.Id); + + player?.Message(MessageHud.MessageType.Center, good.Name); + return true; + } + + // ─── The day between purchases ─────────────────────────────────────── + + /// + /// How long this good still has to wait, on the world clock. + /// + /// Section 20.4 asks for two different clocks and this is both of them: a GAME DAY between + /// upgrades, and a wait of its own for every troop - ten minutes for a Gjall, the rest + /// scaled by price. On the three stage upgrades nobody will ever see it, since each of them + /// can only be bought once; on the troops it is the pacing. + /// + private static long CooldownLeft(Transform nest, Good good) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return 0L; + + long stamped = nview.GetZDO().GetLong(CooldownKey(good.Id), 0L); + if (stamped <= 0L) return 0L; + + float wait = good.Cooldown != null ? good.Cooldown() : 0f; + if (wait <= 0f) return 0L; + + long ready = stamped + (long)wait; + long now = WorldSecond(); + return now >= ready ? 0L : ready - now; + } + + private static void StampCooldown(Transform nest, string id) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(CooldownKey(id), WorldSecond()); + } + + private static string CooldownKey(string id) => "RacesOfValheim_SvermBought_" + id; + + /// A day of game time in seconds. The world's own setting, not a hardcoded 1800. + private static float DayLength() + { + return EnvMan.instance != null ? EnvMan.instance.m_dayLengthSec : 1800f; + } + + private static long WorldSecond() + { + return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L; + } + } + + // ─── The column ────────────────────────────────────────────────────────── + + [HarmonyPatch(typeof(StoreGui), "Awake")] + public static class SvermHiveGoodsSetupPatch + { + public static void Postfix(StoreGui __instance) => SvermHiveGoodsPanel.Create(__instance); + } + + [HarmonyPatch(typeof(StoreGui), "FillList")] + public static class SvermHiveGoodsFillPatch + { + public static void Postfix(StoreGui __instance) => SvermHiveGoodsPanel.Refresh(__instance); + } + + [HarmonyPatch(typeof(StoreGui), "Hide")] + public static class SvermHiveGoodsHidePatch + { + public static void Postfix() => SvermHiveGoodsPanel.Clear(); + } + + /// + /// The market's shelf on screen. Built the way TrolTotemStore builds the war totem's, which is + /// the one column in this mod that is known to draw where a player can see it. + /// + public static class SvermHiveGoodsPanel + { + private static RectTransform _root; + private static readonly List _rows = new List(); + + public static void Create(StoreGui gui) + { + if (gui == null || gui.m_listRoot == null) + { + Jotunn.Logger.LogWarning("[Sverm] StoreGui has no m_listRoot; the market's shelf cannot be built."); + return; + } + if (_root != null) return; + + GameObject clone = UnityEngine.Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent); + clone.name = "SvermHiveGoodsList"; + _root = clone.GetComponent(); + + // The vanilla list's OWN position. An offset from it - 260 px was the first guess - puts + // the column outside the panel that clips it, where it draws perfectly and invisibly. + _root.anchoredPosition = gui.m_listRoot.anchoredPosition; + + foreach (Transform child in _root) UnityEngine.Object.Destroy(child.gameObject); + _root.gameObject.SetActive(false); + } + + public static void Clear() + { + foreach (GameObject row in _rows) if (row != null) UnityEngine.Object.Destroy(row); + _rows.Clear(); + + if (_root != null) _root.gameObject.SetActive(false); + } + + public static void Refresh(StoreGui gui) + { + Clear(); + + SvermHiveBehaviour hive = SvermHiveStore.ActiveHive(gui); + if (hive == null) return; // an ordinary merchant, or the war totem. Not ours. + + if (_root == null) + { + Jotunn.Logger.LogWarning("[Sverm] The market's shelf was never built (did the patch on " + + "StoreGui.Awake fail?), so nothing can be drawn into it."); + return; + } + + _root.gameObject.SetActive(true); + + int row = 0; + foreach (SvermHiveGoods.Good good in SvermHiveGoods.Shelf) + { + BuildRow(gui, hive, good, row++); + } + + float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue(); + _root.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Max(baseSize, row * gui.m_itemSpacing)); + } + + private static void BuildRow(StoreGui gui, SvermHiveBehaviour hive, SvermHiveGoods.Good good, int rowIndex) + { + GameObject element = UnityEngine.Object.Instantiate(gui.m_listElement, _root); + element.SetActive(true); + + RectTransform rt = (RectTransform)element.transform; + float offset = (_root.rect.width - rt.rect.width) / 2f; + rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset); + + string refusal = SvermHiveGoods.RefusalFor(good, hive); + bool available = refusal == null; + + Sprite icon = SvermHive.BorrowIcon(good.Icon) ?? SvermHive.BorrowIcon("Honey"); + Image iconImage = element.transform.Find("icon").GetComponent(); + if (icon != null) iconImage.sprite = icon; + iconImage.color = available ? Color.white : Color.grey; + + TMP_Text nameLabel = element.transform.Find("name").GetComponent(); + nameLabel.text = good.Name; + nameLabel.color = available ? Color.white : Color.grey; + + TMP_Text price = FindDescendant(element.transform, "price"); + if (price != null) + { + price.text = good.Price.ToString("0"); + price.color = available ? Color.white : Color.grey; + } + + UITooltip tooltip = element.GetComponent(); + if (tooltip != null) + { + string body = available ? good.Description : refusal + "\n\n" + good.Description; + tooltip.Set(good.Name, body, gui.m_tooltipAnchor, default(Vector2)); + } + + Button button = element.GetComponent + // With an item in hand every outcome counts as handled, refusals included: false makes + // Humanoid.UseItem cover our own message with the generic "$msg_cantuseon". private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + return Use(user, item) || item != null; + } + + private bool Use(Humanoid user, ItemDrop.ItemData item) { if (user == null) return false; diff --git a/README.md b/README.md index 56c3a61..11e2bba 100644 --- a/README.md +++ b/README.md @@ -415,6 +415,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact - **Fix - Faction merchants would not open their shop:** Valheim 1.0 added a name, tooltip, buy effects and unlock keys to every shop item, and the shop window reads some of them without checking they are there. The merchants' goods were missing them, so pressing E threw a `NullReferenceException` and nothing opened. Buying is covered too — it would have hit the same wall on the buy effects. Thanks to the tester who tracked this down. - **Fix - Haldor and Hildir's Dvergar discount broke their shops:** the discounted copies of their goods were rebuilt with only the old fields, so a Dvergar hit the same shop error, and items that unlock something when bought (like Haldor's extra inventory row) lost what they unlock. The discount now copies the whole item and changes only the price. - **Fix - The Trol totem's own messages were replaced by "Can't use X on Y":** using Yagluth's drop on a totem that already has one, or before Yagluth has fallen, or using any other item on it, now shows the totem's message instead of the generic one. Thanks to the tester who spotted it. +- **Fix - The same "Can't use X on Y" was covering the messages of nine other race buildings:** using an item on the Bone Servant table, the Dvergar barrel and contract bank, the Fenrir trough, the Draugr and Skeleton piles, the Aswid Blood Refinery, the Trenta Grove and Composter now shows their own answer — "It's full", "It has already had one.", "Still rotting.", the boss gates and the rest — instead of the generic one. - **Fix - The Fenrir was 100% faster than intended:** the curse's speed bonus was applied as a multiplier on top of normal speed instead of as a bonus, so every Fenrir moved at double speed plus the bonus (103% faster after one boss instead of 3%). It is now the +3% per boss the race has always listed. - **Changed - New Discord link:** [https://discord.gg/jJzuKBZNC](https://discord.gg/jJzuKBZNC). - 1.4.17 was 1.4.16 republished on Thunderstore with only the version number changed; there is no separate 1.4.17 changelog. From 834d6647fd676cb96e42b1efc192a06a6a33aad9 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Sun, 20 Sep 2026 08:26:22 +0200 Subject: [PATCH 049/290] chore(release): v1.4.19 - eye height, remote forms, food refresh, faction retaliation Race body scale moved the model and not the camera: Character.m_eye hangs off the unscaled root, so a Trol or a Dvergar changed height for everyone but themselves. RaceEyeHeight moves the eye by whatever scale the Visual is wearing, for every player, so aim rays follow too. Remote copies of a Fenrir form had no one writing to their Animator and stood in the controller's default state, sliding. RemoteFenrirAnimator mirrors the four local behaviours off the player's own replicated animator, the way RemoteSkadiAnimator already did for Skadi. Player.Food.m_time is time remaining, not time elapsed: the Aswid, Trenta and Draugh repeat-meal branches all set it to 0 and expired the slot they meant to renew, and left the nutrition values stale. RaceFoodRefresh does what vanilla's own branch does, in one place instead of three. The Trenta prefix now reports __result, or a working refresh would have renewed the slot without consuming the seed. Aswid devour was gated by one timestamp shared by every corpse, so a pack killed at once fed the player once; it is now per corpse, floored at a second, and a refused meal says $msg_nomore. MonsterAI.UpdateTarget discards any target IsEnemy refuses, so a truced mob could not retaliate at all - it stood still or fled. RaceGrudge records the hit on the AI owner's client and both truce postfixes stand down for that pair. The Aswid drain and the Skadi frost aura now skip kin, as the Skeleton's fire aura already did, or an always-on aura would hold every truce permanently broken. Faction sets matched exact prefab names with families half-listed: added Skeleton_NoArcher and Draugr_Ranged to the Swamp, Greyling to the Black Forest. Co-Authored-By: Claude Opus 5 --- JotunnModStub/Aswid/AswidConfig.cs | 2 +- JotunnModStub/Aswid/AswidPatches.cs | 16 +-- JotunnModStub/Aswid/AswidRace.cs | 87 ++++++++++-- JotunnModStub/Draugh/DraughFoodPatches.cs | 16 +-- .../Factions/FactionHostilityPatch.cs | 29 +++- JotunnModStub/Factions/FactionsConfig.cs | 16 ++- JotunnModStub/Fenrir/FenrirBehaviors.cs | 62 +++++++++ JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RaceEyeHeight.cs | 93 +++++++++++++ JotunnModStub/RaceFoodRefresh.cs | 63 +++++++++ JotunnModStub/RaceGrudge.cs | 127 ++++++++++++++++++ JotunnModStub/RaceHostilityManager.cs | 11 +- JotunnModStub/RacesOfValheim.cs | 2 +- JotunnModStub/Skadi/SkadiRace.cs | 5 + JotunnModStub/Trenta/TrentaFoodPatches.cs | 29 ++-- JotunnModStub/ZdoVisualSync.cs | 7 + README.md | 10 ++ manifest.json | 2 +- 18 files changed, 524 insertions(+), 55 deletions(-) create mode 100644 JotunnModStub/RaceEyeHeight.cs create mode 100644 JotunnModStub/RaceFoodRefresh.cs create mode 100644 JotunnModStub/RaceGrudge.cs diff --git a/JotunnModStub/Aswid/AswidConfig.cs b/JotunnModStub/Aswid/AswidConfig.cs index 498f63e..da24f9d 100644 --- a/JotunnModStub/Aswid/AswidConfig.cs +++ b/JotunnModStub/Aswid/AswidConfig.cs @@ -172,7 +172,7 @@ namespace RacesOfValheim const string devour = "Aswid - Devour"; DevourCooldown = config.Bind(devour, "Consume Cooldown", 5f, - new ConfigDescription("Minimum seconds between devouring a corpse, outside of an execute (which bypasses this).", new AcceptableValueRange(0f, 60f))); + new ConfigDescription("How long one body stays drunk-dry, in seconds. A single death is reported to the devour more than once - by two damage patches, by the aura's execute, by a thrall's kill - and this is the window that keeps those from feeding you twice off the same corpse. It is per body, not per player: killing a whole pack at once devours every one of them. One second is used as the floor, so no corpse feeds you twice even at 0.", new AcceptableValueRange(0f, 60f))); const string domination = "Aswid - Domination"; EnslaveCooldown = config.Bind(domination, "Enslave Cooldown", 900f, diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index 5375aad..400e4a4 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -383,17 +383,11 @@ namespace RacesOfValheim Player.Food f = foodObj as Player.Food; if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain()) { - f.m_time = 0f; - f.m_item = item; - - var consumeEffects = HarmonyLib.Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue(); - if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1); - - var zanim = HarmonyLib.Traverse.Create(__instance).Field("m_zanim").GetValue(); - if (zanim != null) zanim.SetTrigger("eat"); - - if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true); - + // Was `f.m_time = 0f`, which expired the meal instead of renewing + // it - see RaceFoodRefresh for the whole story. The fourth slot + // above genuinely does count up from zero; this list does not. + RaceFoodRefresh.Refresh(__instance, f, item); + refreshed = true; break; } diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index 4fe1d7e..3078f06 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -949,6 +949,20 @@ namespace RacesOfValheim continue; } + // The truce holds here too, or it holds nowhere. This aura is always on + // and asks nothing of the player, so before RaceGrudge it quietly drained + // and executed the race's own kin while they stood there and took it; + // after RaceGrudge that same drain would have kept every leech, draugr and + // blob in the swamp permanently angry at an Aswid who never raised a hand. + // Asking BaseAI.IsEnemy is what the Skeleton's fire aura already does, and + // it is the one question both truce patches answer, so the aura now agrees + // with everything else by construction. The execute is untouched: it still + // fires, on anything the Aswid is actually at war with. + if (!c.IsPlayer() && !BaseAI.IsEnemy(Player.m_localPlayer, c)) + { + continue; + } + float maxHp = c.GetMaxHealth(); float currentHp = c.GetHealth(); @@ -960,7 +974,7 @@ namespace RacesOfValheim if (currentHp > 0 && currentHp <= maxHp * AswidConfig.AuraExecuteThreshold.Value && !c.IsBoss()) { totalDamage = currentHp * 2f; // Lethal damage for execute - TryConsumeMob(c, maxHp, true); // Automatically devour when executed, bypassing cooldown + TryConsumeMob(c, maxHp); // Automatically devour when executed } HitData hd = new HitData(); @@ -987,17 +1001,40 @@ namespace RacesOfValheim public static bool DevourEnabled = true; public static bool AuraEnabled = true; - private static float lastConsumeTime = 0f; - public static void TryConsumeMob(Character c, float maxHp, bool bypassCooldown = false) + /// + /// When each corpse was last drunk from, so one body is never devoured twice. + /// + /// This used to be a single timestamp shared by every corpse in the world, which is what + /// testers hit as "killing with the claws or the aura sometimes adds nothing at all": + /// clear a pack with one blast and the first body ate the cooldown for all of them, the + /// rest dying unnoticed inside the window. The guard was never about pacing kills - it is + /// there because a single death reaches TryConsumeMob from more than one place (two + /// Character.Damage postfixes, the aura's own execute, a thrall's kill), and without it + /// one corpse could feed the player twice. Keyed per corpse it does that job exactly and + /// stops taxing the kills that follow. + /// + private static readonly Dictionary lastConsumedCorpse = new Dictionary(); + private static float lastCorpseSweep = 0f; + + public static void TryConsumeMob(Character c, float maxHp) { if (!DevourEnabled) return; + if (c == null) return; - if (!bypassCooldown && Time.time - lastConsumeTime < AswidConfig.DevourCooldown.Value) + // The window is the config's own "Consume Cooldown", scoped to the body it is about. + // Floored at a second even when that is set to zero: the paths that report one death + // all arrive within the same frame or two, and letting a corpse feed the player twice + // is a bug rather than a setting. + float window = Mathf.Max(AswidConfig.DevourCooldown != null ? AswidConfig.DevourCooldown.Value : 5f, 1f); + ZDOID corpse = c.GetZDOID(); + if (lastConsumedCorpse.TryGetValue(corpse, out float drunkAt) && Time.time - drunkAt < window) { - return; // Cooldown active + return; // This body has already been drunk from. } + SweepConsumedCorpses(window); + string cleanName = c.name.Replace("(Clone)", "").Trim(); string customFoodName = "AswidFood_" + cleanName; @@ -1012,6 +1049,11 @@ namespace RacesOfValheim // Fallback to RawMeat if no specific custom item was generated (e.g. mob not in trophy map) if (foodPrefab == null) { + // Logged rather than shown: a creature with no blood food of its own is a whole + // category, not an event, and a message on every such kill would be noise. It is + // here at all because from the player's chair this looks exactly like a devour + // that failed, and the log is the only way to tell the two apart. + Jotunn.Logger.LogDebug($"[Aswid] '{cleanName}' has no '{customFoodName}' to drink - not edible."); return; // Mob is not edible } @@ -1030,7 +1072,7 @@ namespace RacesOfValheim if (addedItem != null) { - lastConsumeTime = Time.time; + lastConsumedCorpse[corpse] = Time.time; // UseItem natively plays animation and consumes it. // If stomach is full, EatFood fails, UseItem does not consume the item, and virtualInv is destroyed (disintegrated) @@ -1047,8 +1089,15 @@ namespace RacesOfValheim // Vae Victis XP logic - similar to Dead Raiser Player.m_localPlayer.RaiseSkill(Skills.SkillType.BloodMagic, 1f); } - // If it was not eaten the stomach was full: the item disintegrates with - // the virtual inventory, so there is nothing to clean up. + else + { + // The stomach was full and had nothing worth refreshing, so the food + // disintegrates with the virtual inventory - there is nothing to clean + // up, but there used to be nothing to see either. Silence is what made + // a refused meal indistinguishable from a devour that never fired: + // vanilla's own "can't eat more" line, localized for free. + Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_nomore"); + } } else { @@ -1058,6 +1107,28 @@ namespace RacesOfValheim } } + /// + /// Drops corpses the window has passed, so a long session does not carry a growing list of + /// bodies nobody will ever drink from again. Once every window at most - this runs off + /// kills, and a pack dying together should not walk the list once per body. + /// + private static void SweepConsumedCorpses(float window) + { + if (Time.time - lastCorpseSweep < window) return; + lastCorpseSweep = Time.time; + if (lastConsumedCorpse.Count == 0) return; + + List stale = null; + foreach (var entry in lastConsumedCorpse) + { + if (Time.time - entry.Value < window) continue; + if (stale == null) stale = new List(); + stale.Add(entry.Key); + } + if (stale == null) return; + foreach (ZDOID id in stale) lastConsumedCorpse.Remove(id); + } + private static void SpawnBloodVFX(Character target) { try diff --git a/JotunnModStub/Draugh/DraughFoodPatches.cs b/JotunnModStub/Draugh/DraughFoodPatches.cs index 7e2e1af..847a615 100644 --- a/JotunnModStub/Draugh/DraughFoodPatches.cs +++ b/JotunnModStub/Draugh/DraughFoodPatches.cs @@ -134,17 +134,11 @@ namespace RacesOfValheim Player.Food f = foodObj as Player.Food; if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain()) { - f.m_time = 0f; - f.m_item = item.Clone(); - - var consumeEffects = Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue(); - if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1); - - var zanim = Traverse.Create(__instance).Field("m_zanim").GetValue(); - if (zanim != null) zanim.SetTrigger("eat"); - - if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true); - + // Was `f.m_time = 0f`, which expired the flesh instead of renewing + // it. This is the original of the copy the Aswid and the Trenta + // both inherited - see RaceFoodRefresh. + RaceFoodRefresh.Refresh(__instance, f, item); + refreshed = true; break; } diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs index a9743c4..2ba265b 100644 --- a/JotunnModStub/Factions/FactionHostilityPatch.cs +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -24,8 +24,15 @@ namespace RacesOfValheim // is the same as no truce at all - the unexempted Fulings open fire, the player defends // themselves, and every Berserker in earshot joins in through damage retaliation, which // IsEnemy has no say over. Verified against the asset manifest, not the wiki's display names. + // Matching is by exact prefab name, so every variant of a creature has to be named here in + // its own right - a family left half-listed is what made the truce look random by biome + // (see PaludeMobs below for the report that turned this up). "Greyling" is the Meadows + // greydwarf and was missing outright: a Trol or a Furling was at peace with the whole + // Black Forest and still fought the smallest thing in it. The Trenta never noticed, + // because its own list in RaceHostilityManager matches on substrings instead. private static readonly HashSet NeraForestaMobs = new HashSet { + "Greyling", "Greydwarf", "Greydwarf_Elite", "Greydwarf_Shaman", "Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman", "Troll", @@ -38,10 +45,19 @@ namespace RacesOfValheim "Dverger", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands", }; + // Skeleton_NoArcher and Draugr_Ranged are the two that were missing, and they are why an + // Aswid reported skeletons that were peaceful in one biome and hostile in another: it was + // never the biome, it was which variant that particular spawner places. Skeleton_NoArcher + // is vanilla's guaranteed-melee skeleton (the same one SkeletonBonePile borrows), so a + // spawner using it produced hostile skeletons standing next to peaceful ones. Draugr_Ranged + // is the bow draugr, left out while the melee and elite ones were exempt. + // + // Skeleton_Hildir stays out deliberately, on the same rule that keeps GoblinKing and the + // Hildir brothers out of the Black Forest set: a quest boss is not somebody's kin. private static readonly HashSet PaludeMobs = new HashSet { - "Ghost", "Skeleton", "Skeleton_Poison", // Skeleton, Rancid remains - "Draugr", "Draugr_Elite", + "Ghost", "Skeleton", "Skeleton_NoArcher", "Skeleton_Poison", // Skeleton, Rancid remains + "Draugr", "Draugr_Elite", "Draugr_Ranged", "Wraith", "Leech", "Abomination", "Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth }; @@ -107,6 +123,10 @@ namespace RacesOfValheim Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null); if (!(playerCharacter is Player p) || monster == null) return; + // Same stand-down as the per-race truces get: hit your own faction and it hits back + // until the grudge runs out. See RaceGrudge. + if (RaceGrudge.Holds(monster, p)) return; + if (IsSameFaction(p, monster)) { __result = false; @@ -170,8 +190,9 @@ namespace RacesOfValheim // Filtering the RESULT rather than restating the rule keeps one source of truth: the public // instance IsEnemy(Character) calls the static overload both postfixes above hook, so this // honours whatever the faction sets and RaceHostilityManager's per-race lists already agree - // on. Retaliation is untouched - a mob the player hits is targeted through - // BaseAI.OnDamaged/SetTarget, which never goes near FindEnemy. + // on. Retaliation does not come through here either way - a mob the player hits is targeted + // through BaseAI.OnDamaged/SetTarget, which never goes near FindEnemy. That target only + // SURVIVES because of RaceGrudge, though: UpdateTarget drops anything IsEnemy refuses. [HarmonyPatch(typeof(BaseAI), "FindEnemy")] public static class FactionHuntPlayerPatch { diff --git a/JotunnModStub/Factions/FactionsConfig.cs b/JotunnModStub/Factions/FactionsConfig.cs index 2898c7a..91edfe6 100644 --- a/JotunnModStub/Factions/FactionsConfig.cs +++ b/JotunnModStub/Factions/FactionsConfig.cs @@ -20,12 +20,14 @@ namespace RacesOfValheim { public static ConfigEntry HostilityEnabled; public static ConfigEntry MerchantsEnabled; + public static ConfigEntry GrudgeDuration; // Null-safe, defaulting to ON, for the same reason WarVultureConfig guards its own reads: // a patch that somehow runs before Bind() should behave like the shipped default rather // than throw. Awake() binds before harmony.PatchAll(), so this should never fire. public static bool Hostility => HostilityEnabled?.Value ?? true; public static bool Merchants => MerchantsEnabled?.Value ?? true; + public static float GrudgeSeconds => GrudgeDuration?.Value ?? 60f; public static void Bind(ConfigFile config) { @@ -44,8 +46,18 @@ namespace RacesOfValheim "per-race passives in RaceHostilityManager - Fenrir's wolves, Aswid's " + "progression list, the Draugh's undead, the Trenta's Black Forest, the Sverm's " + "invertebrates. Switching this off gives those five races up along with the " + - "faction truce. Hitting a mob still starts a fight either way: retaliation runs " + - "through BaseAI.OnDamaged, which no truce has a say over.")); + "faction truce. Hitting a mob still starts a fight: see Faction grudge below, " + + "which is what makes that true.")); + + GrudgeDuration = config.Bind(factions, "Faction grudge", 60f, + new ConfigDescription("Seconds a creature stays angry at a player of its own faction who hit it. " + + "Without this the truce is absolute in both directions: MonsterAI.UpdateTarget " + + "throws away any target BaseAI.IsEnemy calls a non-enemy, so a truced mob could " + + "not fight back even after being struck - it stood still, or fled because it " + + "was hurt and had no enemy it was allowed to have. The grudge is per attacker " + + "and per creature, on whichever machine runs that creature's AI. 0 restores the " + + "old absolute truce.", + new AcceptableValueRange(0f, 600f))); MerchantsEnabled = config.Bind(factions, "Faction merchants", true, new ConfigDescription("Certain mobs of your own faction can be traded with - 'E - Talk' opens a shop " + diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 20c7157..19e880a 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -39,6 +39,68 @@ namespace RacesOfValheim } } + /// + /// The animation half of somebody else's form. + /// + /// The four behaviours below drive their model's Animator from the player's own, and every + /// one of them runs on the transformed player's client only: FenrirRace.ExecuteTransformation + /// is what adds them, and they read Player.m_localPlayer throughout. RacesVisualController + /// spawns the same model on every other client from the ZDO, and used to spawn nothing else - + /// no parameter was ever written to that copy's Animator, so it sat in its controller's + /// default state and slid across the terrain. The wolf's owner saw a wolf running; everyone + /// else saw a statue on rails. + /// + /// This is the piece that was missing, and it is the arrangement Skadi already uses for its + /// remote dragons (RemoteSkadiAnimator). The parameters come from the remote player's own + /// Visual Animator, which ZSyncAnimation keeps fed over the network for every character a + /// client can see - hiding the body hides renderers, not the animation - so the form walks, + /// runs, jumps and creeps exactly when the real player does. + /// + /// Kept next to the four local behaviours on purpose: this mirrors the movement half of their + /// Update, and the two have to be changed together. + /// + /// Attacks are not mirrored. Those are triggers fired from input on the owner's client and + /// nothing replicates them, so a remote form still bites in silence - that needs a counter of + /// its own on the ZDO and is a separate job. + /// + public class RemoteFenrirAnimator : MonoBehaviour + { + private Player player; + private Animator playerAnim; + private Animator formAnim; + + private void Update() + { + // Resolved here rather than in Start: the model is instantiated under a player who may + // still be assembling their own rig on the frame it arrives. + if (player == null) player = GetComponentInParent(); + if (player == null) return; + + if (formAnim == null) formAnim = GetComponent() ?? GetComponentInChildren(); + if (playerAnim == null) + { + Transform visual = player.transform.Find("Visual"); + if (visual != null) playerAnim = visual.GetComponent(); + } + if (formAnim == null || playerAnim == null) return; + + bool grounded = playerAnim.GetBool("onGround"); + + // All four borrowed creatures answer to these, and they are still written through + // try/catch the way the local behaviours do it: a controller missing one of them would + // otherwise throw once per frame, for every onlooker. + try { formAnim.SetBool("onGround", grounded); } catch {} + try { formAnim.SetBool("inWater", playerAnim.GetBool("inWater")); } catch {} + + // The same three cases the local behaviours use, so both views of the same wolf agree: + // airborne and crouching each read as standing still. Player.IsCrouching answers off + // the animator's current state, which is replicated, so it is true here too. + bool still = !grounded || player.IsCrouching(); + try { formAnim.SetFloat("forward_speed", still ? 0f : playerAnim.GetFloat("forward_speed")); } catch {} + try { formAnim.SetFloat("sideway_speed", still ? 0f : playerAnim.GetFloat("sideway_speed")); } catch {} + } + } + public class FenrirFormBehavior : MonoBehaviour { private Animator playerAnim; diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index fe12525..e88f106 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.18", + "version_number": "1.4.19", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RaceEyeHeight.cs b/JotunnModStub/RaceEyeHeight.cs new file mode 100644 index 0000000..7195861 --- /dev/null +++ b/JotunnModStub/RaceEyeHeight.cs @@ -0,0 +1,93 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Puts the camera at the height of the body the player is actually wearing. + /// + /// Every race that resizes a player does it on the "Visual" child and never on the root: the + /// root carries the collider and the camera pivot, and scaling that drops the player through + /// the ground they are standing on. The cost of that - which is what testers reported - is + /// that Character.m_eye hangs off the same unscaled root. GameCamera.GetCameraBaseOffset takes + /// the camera from m_eye.position minus the root's, and aim raycasts start there too, so a + /// Trol grew a head taller for everyone else while still seeing the world from human eye + /// level, and a Dvergar shrank without ever having to look up at anything. The height was + /// real, and only the other players could see it. + /// + /// The eye is moved by whatever factor the Visual is wearing at that instant, rather than by a + /// per-race number: that way it follows the Trol's transformation lerp for free, costs nothing + /// for a race that is not sizing anybody (the factor is 1), and returns to the measured + /// original the moment a player stops being of that race. + /// + /// Races that scale the player root instead - the Skeleton is the one - are already carrying + /// their eye with them, and read as a factor of 1 here, so they are left alone by + /// construction. So is a player inside a borrowed form (wolf, drake, bat): those hide the + /// body's renderers and leave its scale at 1, and the form's own camera handling is its + /// business. + /// + /// Applied to every player, not just the one at the keyboard. m_eye is also what a mob aims + /// at, so a Dvergar's head being where the Dvergar's head is matters on every client. + /// + public static class RaceEyeHeight + { + // Below this the body is not small, it is being hidden - an old scale-to-zero trick, or a + // transformation caught mid-lerp. Dividing the player's viewpoint down with it would put + // the camera inside the ground, so the eye is left where it last was. + private const float MinScale = 0.05f; + + /// + /// Remembers where the eye sat before any race touched it, on the eye itself, so it dies + /// with the player object and can never be read back as an already-scaled value. + /// + private class EyeRest : MonoBehaviour + { + public Vector3 LocalPosition; + } + + public static void Apply(Player player) + { + if (player == null) return; + + Transform eye = Traverse.Create(player).Field("m_eye").GetValue(); + if (eye == null) return; + + GameObject visual = Traverse.Create(player).Field("m_visual").GetValue(); + if (visual == null) return; + + // If this build ever parents the eye inside the rig, the body scale already carries + // it and doing the same thing here would apply it twice. + if (eye.IsChildOf(visual.transform)) return; + + EyeRest rest = eye.GetComponent(); + if (rest == null) + { + rest = eye.gameObject.AddComponent(); + rest.LocalPosition = eye.localPosition; + } + + float scale = visual.transform.localScale.y; + if (scale < MinScale) return; + + Vector3 wanted = rest.LocalPosition * scale; + if ((eye.localPosition - wanted).sqrMagnitude > 0.000001f) + { + eye.localPosition = wanted; + } + } + + /// + /// Driven from Player.Update, the same place the scales themselves are applied from. The + /// order the postfixes run in does not matter: this reads whatever scale is on the Visual + /// now, so the worst a late scale can cost is one frame. + /// + [HarmonyPatch(typeof(Player), "Update")] + public static class Player_Update_EyeHeight_Patch + { + public static void Postfix(Player __instance) + { + Apply(__instance); + } + } + } +} diff --git a/JotunnModStub/RaceFoodRefresh.cs b/JotunnModStub/RaceFoodRefresh.cs new file mode 100644 index 0000000..daa2a66 --- /dev/null +++ b/JotunnModStub/RaceFoodRefresh.cs @@ -0,0 +1,63 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Eating something you are already digesting, for the three races that hand their own food + /// straight to Player.EatFood instead of going through the native right-click path. + /// + /// WHAT WAS WRONG. All three wrote `food.m_time = 0f` to mean "this meal is fresh again". + /// Player.Food.m_time is the opposite: it is the time LEFT. Read out of assembly_valheim - + /// Player.EatFood refreshes a repeat meal with + /// + /// food.m_time = item.m_shared.m_foodBurnTime; + /// + /// and Player.UpdateFood counts it down with `m_time -= dt` and drops the entry the moment it + /// reaches zero. So the line meant to restart the timer was expiring the food on the spot, and + /// the stomach slot vanished instead. + /// + /// The inversion came in honestly: the Aswid's fourth slot and the Trol's fifth are run by + /// this mod rather than by Valheim, and those DO count up from zero (see + /// Aswid_PlayerUpdateFood_Patch). Two opposite conventions, one field name, three copies of + /// the same code - which is why this now lives in one place instead of three. + /// + /// Only a food that answers Player.Food.CanEatAgain() may be refreshed, which is vanilla's own + /// rule (`m_time < m_foodBurnTime / 2`): you cannot top up a meal you have barely started. + /// The callers check it; this does the refreshing. + /// + public static class RaceFoodRefresh + { + /// + /// Puts a slot back to a full meal and plays the eating feedback, exactly as vanilla's own + /// repeat-meal branch does - the three nutrition values included. Leaving those stale was + /// the second half of the bug: a refreshed meal kept whatever health, stamina and eitr the + /// old one had decayed to, so even a correct timer handed back a worn-out slot. + /// + /// Whoever is eating; the one being fed the effects and the heal. + /// The slot already holding this meal. + /// What is being eaten now. Cloned, so the caller's copy - which for the + /// Aswid is a virtual inventory that is thrown away on the next line - can go. + public static void Refresh(Player player, Player.Food food, ItemDrop.ItemData item) + { + if (player == null || food == null || item == null || item.m_shared == null) return; + + food.m_item = item.Clone(); + food.m_time = item.m_shared.m_foodBurnTime; + food.m_health = item.m_shared.m_food; + food.m_stamina = item.m_shared.m_foodStamina; + food.m_eitr = item.m_shared.m_foodEitr; + + EffectList consumeEffects = Traverse.Create(player).Field("m_consumeItemEffects").GetValue(); + if (consumeEffects != null) + { + consumeEffects.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1); + } + + ZSyncAnimation zanim = Traverse.Create(player).Field("m_zanim").GetValue(); + if (zanim != null) zanim.SetTrigger("eat"); + + if (item.m_shared.m_food > 0f) player.Heal(item.m_shared.m_food, true); + } + } +} diff --git a/JotunnModStub/RaceGrudge.cs b/JotunnModStub/RaceGrudge.cs new file mode 100644 index 0000000..927f4b5 --- /dev/null +++ b/JotunnModStub/RaceGrudge.cs @@ -0,0 +1,127 @@ +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Hit something that is at peace with you and it hits back. + /// + /// WHY THIS HAS TO EXIST. Both truce patches answer BaseAI.IsEnemy with false, and the comment + /// they each carried - that retaliation runs through BaseAI.OnDamaged and no truce has a say + /// over it - is wrong. Read out of assembly_valheim: + /// + /// MonsterAI.OnDamaged calls SetTarget(attacker), so the mob does take the hit + /// personally, exactly as those comments said, and then + /// MonsterAI.UpdateTarget on its very next tick does + /// if (!IsEnemy(m_targetCreature)) m_targetCreature = null; + /// + /// so the target is thrown away a frame later. A truced mob could not fight back at all: it + /// stood there being hit, or - hurt, with no enemy it was allowed to have - fell into + /// UpdateAI's flee branches and ran away. That is what testers saw and reported. + /// + /// WHAT THIS DOES. It remembers who hit whom, for a while, and both truce postfixes stand down + /// for that one pair while the memory lasts. The mob is an enemy again by vanilla's own rules, + /// which means everything downstream - acquiring, chasing, retaliating, giving up - is vanilla + /// behaviour rather than anything reimplemented here. + /// + /// WHERE IT RUNS. On the client that owns the mob's AI, which is the only one whose UpdateTarget + /// matters and the only one that runs Character.ApplyDamage for it. BaseAI.OnDamaged is reached + /// through the character's damage callback on exactly that machine, so the record is made where + /// it will be read. Nothing is replicated and nothing needs to be: another client's copy of the + /// same mob is not the one deciding who it chases. + /// + /// Vanilla has its own version of this idea in BaseAI.SetAggravated, and it is not usable here: + /// it does nothing unless the prefab sets m_aggravatable, which only the dvergr and the seekers + /// do. + /// + public static class RaceGrudge + { + private struct Grudge + { + public ZDOID Attacker; + public float Until; + } + + // One grudge per mob, against the last thing that hit it. A creature can only chase one + // target anyway, and if two players of the same race are both poking it, the one it wants + // is whoever hit it last. + private static readonly Dictionary grudges = new Dictionary(); + private static float lastSweep = 0f; + + private static float Duration => FactionsConfig.GrudgeSeconds; + + /// + /// True while is owed a hit by . Both + /// truce postfixes ask this first and leave IsEnemy alone when it answers yes. + /// + public static bool Holds(Character monster, Character player) + { + if (monster == null || player == null) return false; + if (Duration <= 0f) return false; + + if (!grudges.TryGetValue(monster.GetZDOID(), out Grudge grudge)) return false; + if (Time.time >= grudge.Until) return false; + + return grudge.Attacker == player.GetZDOID(); + } + + public static void Remember(Character monster, Character attacker) + { + if (monster == null || attacker == null) return; + if (Duration <= 0f) return; + + grudges[monster.GetZDOID()] = new Grudge + { + Attacker = attacker.GetZDOID(), + Until = Time.time + Duration + }; + + Sweep(); + } + + /// + /// Drops grudges nobody is owed any more. At most once per duration: a fight is a burst of + /// damage events and the list should not be walked on each one. + /// + private static void Sweep() + { + if (Time.time - lastSweep < Duration) return; + lastSweep = Time.time; + + List expired = null; + foreach (var entry in grudges) + { + if (Time.time < entry.Value.Until) continue; + if (expired == null) expired = new List(); + expired.Add(entry.Key); + } + if (expired == null) return; + foreach (ZDOID id in expired) grudges.Remove(id); + } + + /// + /// The one place a grudge is born. BaseAI.OnDamaged is the base every AI's own override + /// calls first, so patching it here covers MonsterAI and AnimalAI both, and it lands before + /// MonsterAI.OnDamaged's SetTarget on the same hit - the grudge is on the books by the time + /// UpdateTarget next asks whether that target is allowed. + /// + /// Only a player's hit counts. A greydwarf caught in another greydwarf's swing has vanilla's + /// own rules for that and no truce of ours in the way. + /// + [HarmonyPatch(typeof(BaseAI), "OnDamaged")] + public static class BaseAI_OnDamaged_Grudge_Patch + { + public static void Postfix(BaseAI __instance, Character attacker) + { + if (!FactionsConfig.Hostility) return; + if (attacker == null || !attacker.IsPlayer()) return; + + Character monster = Traverse.Create(__instance).Field("m_character").Value; + if (monster == null || monster.IsPlayer()) return; + + Remember(monster, attacker); + } + } + } +} diff --git a/JotunnModStub/RaceHostilityManager.cs b/JotunnModStub/RaceHostilityManager.cs index ae99bc0..e182951 100644 --- a/JotunnModStub/RaceHostilityManager.cs +++ b/JotunnModStub/RaceHostilityManager.cs @@ -25,6 +25,11 @@ namespace RacesOfValheim Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null); Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null); + // A truce the player has just broken is not a truce. Without this the mob cannot + // retaliate at all - not because it does not try, but because MonsterAI.UpdateTarget + // throws away any target this method calls a non-enemy. See RaceGrudge. + if (RaceGrudge.Holds(monster, playerCharacter)) return; + if (playerCharacter != null && monster != null) { Player p = playerCharacter as Player; @@ -80,8 +85,10 @@ namespace RacesOfValheim // only in flavour text - Greyling/Greydwarf/Leech/Deathsquito "don't see" a // Trenta as prey (root-kin, or simply nothing with blood to sense), while // Fuling/Troll "choose" not to fight one - but there is no third state to code - // for: vanilla's own damage-response AI already makes any of them retaliate if - // the Trenta strikes first, same as it does for Fenrir's wolves above. + // for. Striking first is handled, though not by the AI on its own as this + // comment used to claim: MonsterAI.UpdateTarget discards any target IsEnemy + // calls a non-enemy, so retaliation needed RaceGrudge, checked at the top of + // this method. if (playerRace == TrentaConfig.RaceId) { string prefabName = monster.gameObject.name.ToLower(); diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 2cf0c9f..78db93b 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.4.18"; + public const string PluginVersion = "1.4.19"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index aa141fa..fe7a3ef 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -522,6 +522,11 @@ namespace RacesOfValheim if (c == Player.m_localPlayer) continue; if (c.IsTamed() || c.IsPlayer()) continue; + // Same guard as the Skeleton's fire aura and the Aswid's drain: an always-on aura + // that burns the race's own kin would, with RaceGrudge in place, keep every wolf, + // drake and dverger permanently angry at a Skadi who never attacked anything. + if (!BaseAI.IsEnemy(Player.m_localPlayer, c)) continue; + if (Vector3.Distance(center, c.transform.position) <= SkadiConfig.AuraRadius.Value) { HitData hit = new HitData(); diff --git a/JotunnModStub/Trenta/TrentaFoodPatches.cs b/JotunnModStub/Trenta/TrentaFoodPatches.cs index c20b87f..f083369 100644 --- a/JotunnModStub/Trenta/TrentaFoodPatches.cs +++ b/JotunnModStub/Trenta/TrentaFoodPatches.cs @@ -137,7 +137,14 @@ namespace RacesOfValheim [HarmonyPatch(typeof(Player), "EatFood")] public static class Trenta_Player_EatFood_DuplicateGuard_Patch { - public static bool Prefix(Player __instance, ItemDrop.ItemData item) + // __result matters here, unlike in a prefix that only ever falls through to vanilla: + // the caller above is TrentaFoodPatches' own UseItem prefix, and it removes the seed + // from the bag only when EatFood answers true. Without this the refresh below would + // renew the slot and leave the seed in the inventory to be eaten again, forever. It + // went unnoticed while the refresh was broken: the old code destroyed the slot instead + // of renewing it, so the free seed had nothing to show for it. The Aswid and the + // Draugh versions of this patch already took __result. + public static bool Prefix(Player __instance, ItemDrop.ItemData item, ref bool __result) { hiddenFoods.Clear(); @@ -155,22 +162,18 @@ namespace RacesOfValheim Player.Food f = foodObj as Player.Food; if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain()) { - f.m_time = 0f; - f.m_item = item.Clone(); + // Was `f.m_time = 0f`, which expired the seed instead of renewing it - + // this is the "eating a second seed deletes the first" report. See + // RaceFoodRefresh. + RaceFoodRefresh.Refresh(__instance, f, item); - var consumeEffects = Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue(); - if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1); - - var zanim = Traverse.Create(__instance).Field("m_zanim").GetValue(); - if (zanim != null) zanim.SetTrigger("eat"); - - if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true); - - return false; // Refreshed ourselves - skip native EatFood + __result = true; // Eaten: the caller consumes the seed. + return false; // Refreshed ourselves - skip native EatFood } } - return false; // Full, and nothing to refresh + __result = false; // Full, and nothing in it worth topping up: the seed stays. + return false; } // Temporarily hide any existing slot with the same name to force native EatFood diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index c7d2f2f..ecff680 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -217,6 +217,13 @@ namespace RacesOfValheim { Destroy(col); } + + // Without this the model arrives with nobody writing to its + // Animator and stands in its default pose, sliding wherever the + // player walks. The local form has four behaviours doing this job; + // none of them can run here, because all of them are built around + // Player.m_localPlayer. + m_currentFormInstance.AddComponent(); } } } diff --git a/README.md b/README.md index 11e2bba..1db8120 100644 --- a/README.md +++ b/README.md @@ -404,12 +404,22 @@ Aswid, Draugh, Skeleton / at peace with Ghost, Skeleton, Draugr, Wraith, Leech, The **Sverm** belongs to no faction. Its Hive Pheromones make every invertebrate in the game ignore it instead — leeches, ticks, deathsquitos, seekers and bees — with no boss gate and no trading. +A truce is not a shield: hit one of your own and it hits back, for **Faction grudge** seconds (60 by default), then forgets about it. Your always-on auras — the Aswid's drain, the Skadi's frost — leave your own kin alone, so they never start that fight for you. + Both halves have an off switch under `Factions` in Configuration Manager: **Faction truce** for whether your faction's mobs leave you alone, **Faction merchants** for whether they will trade. Both are on by default and both take effect without a restart. Be aware that turning the truce off also gives up every race's own peace — Fenrir's wolves, the Aswid's list, the Draugh's undead, the Trenta's Black Forest, the Sverm's invertebrates, the Furling's Plains roster and the Skeleton's undead — because they are all the same question asked of the same vanilla method. --- ## Changelog +### v1.4.19 +- **Fix - You could not see your own height:** the Trol stood a head taller and the Dvergar came up short for everyone except themselves — the body was resized, but the camera stayed at human eye level, so from your own chair nothing had changed. Your eyes now sit where your head is, and your shots start from there too. Every race that resizes its body is covered, at whatever size it happens to be wearing: the Trol's True Form lifts the view as it grows and lowers it again on the way back. Thanks to the testers who noticed it only worked on other people. +- **Fix - Other players saw a Fenrir's wolf standing still and sliding:** the form's animations were only ever driven on the transformed player's own screen. Everyone else got the model in its default pose, gliding across the ground. Wolf, Ulv, Fenring and Cultist now walk, run, jump and creep for every player who can see them. Their attacks are still silent to onlookers — that needs its own fix and is not in this build. +- **Fix - Eating the same creature or seed again destroyed that food instead of refreshing it:** the timer was being set to "expired" rather than "full", so a repeat meal deleted the slot it was meant to renew — and it only happened once the food was under half, which is exactly when it starts flashing. Above half, nothing happened at all. The Aswid's devoured creatures, the Trenta's awakened seeds and the Draugh's raw flesh all had it; all three now renew the slot the way any vanilla food does, nourishment included. Thanks to the tester who worked out that it was the flashing ones. +- **Fix - Devouring only ever caught the first kill:** the Aswid's devour was on a five-second timer shared by every corpse in the world, so clearing a group with the claws or the aura fed you once and let the rest die unnoticed. It is now per body: kill a pack and you drink from all of them. A refused meal also says so instead of failing silently. +- **Fix - Mobs of your own faction would not fight back:** attacking one of your own kin did nothing — it stood there, or ran away — because the truce was absolute in both directions and the game threw away any target it was not allowed to have. Now hitting one starts a real fight for **Faction grudge** seconds (60 by default, configurable, 0 for the old behaviour), per creature and per attacker. The Aswid's drain and the Skadi's frost aura no longer touch their own kin, so an always-on aura can no longer pick that fight on your behalf. Thanks to the tester who reported the Trenta and the Aswid. +- **Fix - Friendly skeletons in one biome, hostile ones in the next:** the faction truce matched creatures by exact name and several families were only half-listed, so an Aswid was at peace with one kind of skeleton and at war with another standing next to it. Added the melee-only skeleton and the bow draugr to the Swamp, and the greyling to the Black Forest — a Trol or a Furling was at peace with the whole forest and still fought the smallest thing in it. Thanks to the tester who mapped it out biome by biome. + ### v1.4.18 - **Fix - Drake flight stopped working after the latest Valheim hotfix:** the hotfix changed how the game reads the gamepad's left stick, and the drake's flight still asked for it the old way. Every frame in the air threw a `MissingMethodException` into the log and the drake could not fly. Flight now works on both the new and the old version of the game. - **Fix - Faction merchants would not open their shop:** Valheim 1.0 added a name, tooltip, buy effects and unlock keys to every shop item, and the shop window reads some of them without checking they are there. The merchants' goods were missing them, so pressing E threw a `NullReferenceException` and nothing opened. Buying is covered too — it would have hit the same wall on the buy effects. Thanks to the tester who tracked this down. diff --git a/manifest.json b/manifest.json index fe12525..e88f106 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.18", + "version_number": "1.4.19", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 64d8869f987007845d62cb209a339d72d9cd238b Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Mon, 21 Sep 2026 09:05:56 +0200 Subject: [PATCH 050/290] bugfix 21/09/26 --- JotunnModStub/PieceDensityLimit.cs | 42 +++++++++++++++++++++++++++++ JotunnModStub/Skadi/SkadiPatches.cs | 5 +++- JotunnModStub/Skadi/SkadiRace.cs | 26 ++++++++++++++++-- 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/PieceDensityLimit.cs b/JotunnModStub/PieceDensityLimit.cs index e39f9b4..1546e21 100644 --- a/JotunnModStub/PieceDensityLimit.cs +++ b/JotunnModStub/PieceDensityLimit.cs @@ -199,4 +199,46 @@ namespace RacesOfValheim return PieceDensityLimit.Allow(__instance, Utils.GetPrefabName(__0.gameObject), __1); } } + + /// + /// What makes "a prefix returning false spends nothing" TRUE, which on its own it is not. + /// + /// Read off the 1.0 IL: nothing is paid inside PlacePiece. TryPlacePiece calls it and then does an + /// unconditional `ldc.i4.1; ret`, and it is UpdatePlacement that, on that true, runs + /// ConsumeResources and UseStamina. So every race lock in the mod - this class's gates, the Trol + /// totem, the Dvergar bank and barrel, the Trenta Root - stopped the building and still took the + /// wood: "Only the Sverm can raise a hive", and 40 wood and 20 resin gone. + /// + /// Fixed here once rather than in each lock: a last-priority prefix on the same PlacePiece + /// overload sees __runOriginal after every other prefix has had its say, and if any of them said + /// no, TryPlacePiece reports false - the path vanilla already takes for a blocked placement, which + /// charges nothing. Any lock added later is covered without knowing this exists. + /// + [HarmonyPatch(typeof(Player), "PlacePiece", + new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool), typeof(bool) })] + public static class PlacementRefusalWatch + { + internal static bool Refused; + + [HarmonyPriority(Priority.Last)] + public static void Prefix(bool __runOriginal) + { + if (!__runOriginal) Refused = true; + } + } + + [HarmonyPatch(typeof(Player), "TryPlacePiece")] + public static class PlacementRefusalCharge + { + public static void Prefix() + { + PlacementRefusalWatch.Refused = false; + } + + public static void Postfix(ref bool __result) + { + if (PlacementRefusalWatch.Refused) __result = false; + PlacementRefusalWatch.Refused = false; + } + } } diff --git a/JotunnModStub/Skadi/SkadiPatches.cs b/JotunnModStub/Skadi/SkadiPatches.cs index 6db166c..1a793db 100644 --- a/JotunnModStub/Skadi/SkadiPatches.cs +++ b/JotunnModStub/Skadi/SkadiPatches.cs @@ -549,7 +549,10 @@ namespace RacesOfValheim // the live button state (via the configured shortcut, so a rebind stays in sync) // rather than a flag set during our Update, so it does not depend on whether // PlayerController's FixedUpdate happens to run first. - if (secondaryAttack && SkadiConfig.ColdSpellKey.Value.IsPressedIgnoringHeldKeys() && + // The pad's secondary attack casts only bare-handed (SkadiRace.PadCastsColdSpell), so it + // swallows the kick only then; with a weapon in hand the weapon's secondary goes through. + bool padCast = RaceInput.PadAttackHeld(2) && SkadiRace.PadCastsColdSpell(Player.m_localPlayer); + if (secondaryAttack && (SkadiConfig.ColdSpellKey.Value.IsPressedIgnoringHeldKeys() || padCast) && SkadiRace.Instance != null && SkadiRace.Instance.IsSkadi()) { var rules = SkadiProgression.GetRules(BossProgressionManager.GetCurrentProgressionState()); diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index fe7a3ef..34886e8 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -339,9 +339,18 @@ namespace RacesOfValheim if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return; if (isTransformed) return; // Do not cast human spell while in dragon form + // Hammer, hoe or cultivator in hand: every build button is vanilla's. Middle mouse is + // Remove on the keyboard, and on the pad JoySecondaryAttack shares its physical button + // with JoyRemove (Classic) or JoyPlace (Alt2) - read off ZInput.AddGamepad*Buttons - so + // each piece built or removed also cast the spell and drained the stamina for it. + if (Player.m_localPlayer.InPlaceMode()) return; + // Middle Mouse Button to cast, by default - rebindable via SkadiConfig.ColdSpellKey. - // On a gamepad, the secondary attack button (the pad's own middle-mouse equivalent). - if (SkadiConfig.ColdSpellKey.Value.IsDownIgnoringHeldKeys() || RaceInput.PadAttackDown(2)) + // On a gamepad, the secondary attack button (the pad's own middle-mouse equivalent) - + // but only bare-handed: the pad has no separate spell key, so with a weapon or a tool + // that button belongs to the item's own secondary attack, as it does in vanilla. + if (SkadiConfig.ColdSpellKey.Value.IsDownIgnoringHeldKeys() || + (RaceInput.PadAttackDown(2) && PadCastsColdSpell(Player.m_localPlayer))) { // The improved cast is a burst rather than a rapid-fire, so it waits longer. float cooldown = rules.ImprovedColdSpell ? IMPROVED_SPELL_COOLDOWN : SPELL_COOLDOWN; @@ -373,6 +382,19 @@ namespace RacesOfValheim } } + /// + /// Whether the pad's secondary attack button casts the Cold Spell right now: out of build + /// mode and with nothing in either hand. Shared with SkadiAttackPatch, which swallows the + /// unarmed kick under exactly the same condition. + /// + public static bool PadCastsColdSpell(Player player) + { + if (player == null || player.InPlaceMode()) return false; + var hands = HarmonyLib.Traverse.Create(player); + return hands.Field("m_rightItem").Value == null && + hands.Field("m_leftItem").Value == null; + } + private IEnumerator ColdSpellKickCoroutine(SkadiProgression.FormRules rules) { // Wait for the cast animation to reach the release point From 6499eb71df89df8ffdf2768c2eb88c8803c6e013 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Mon, 21 Sep 2026 17:38:53 +0200 Subject: [PATCH 051/290] chore(release): v1.4.20 - refused buildings cost nothing, Skadi pad cold spell Co-Authored-By: Claude Opus 5 --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 5 +++++ manifest.json | 2 +- 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index e88f106..4c8d434 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.19", + "version_number": "1.4.20", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 78db93b..b050b4b 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.4.19"; + public const string PluginVersion = "1.4.20"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index 1db8120..68ac96b 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,11 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.4.20 +- **Fix - A refused race building still took your materials:** building something your race is not allowed to build, or before its boss has fallen, showed the refusal and then charged the full cost anyway — a non-Sverm trying the Brood Mound got "Only the Sverm can raise a hive." and lost 40 wood and 20 resin. The refusal stopped the building, but Valheim takes the cost in a separate step that never heard about it. Now a refused building costs nothing, no stamina included. This covered every locked building in the mod: the Sverm hive and market (and the one-hive-per-area limit), the Skadi golem, the Dvergar contract bank and barrel, the Trenta Elder Root and the Trol totem. Thanks to the tester who noticed the wood going missing. +- **Fix - On a gamepad the Skadi cast the Cold Spell every time she built:** the spell sits on the pad's secondary attack button, which Valheim also uses to remove pieces (Classic layout) or place them (Alt 2). Every piece built or removed also cast the spell and drained stamina, which made building nearly impossible. The spell no longer casts while you hold the hammer, hoe or cultivator — on the keyboard as well, where middle mouse is Remove. +- **Changed - On a gamepad the Cold Spell now casts bare-handed only:** the pad has no separate key for the spell, so with a weapon, shield, torch or tool in hand the button goes back to that item's own secondary attack, as it does in vanilla. Previously both fired together. Bare-handed, the spell casts without the unarmed kick. Keyboard players are unaffected: the Cold Spell key works as before. Thanks to the tester who reported it from a controller. + ### v1.4.19 - **Fix - You could not see your own height:** the Trol stood a head taller and the Dvergar came up short for everyone except themselves — the body was resized, but the camera stayed at human eye level, so from your own chair nothing had changed. Your eyes now sit where your head is, and your shots start from there too. Every race that resizes its body is covered, at whatever size it happens to be wearing: the Trol's True Form lifts the view as it grows and lowers it again on the way back. Thanks to the testers who noticed it only worked on other people. - **Fix - Other players saw a Fenrir's wolf standing still and sliding:** the form's animations were only ever driven on the transformed player's own screen. Everyone else got the model in its default pose, gliding across the ground. Wolf, Ulv, Fenring and Cultist now walk, run, jump and creep for every player who can see them. Their attacks are still silent to onlookers — that needs its own fix and is not in this build. diff --git a/manifest.json b/manifest.json index e88f106..4c8d434 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.19", + "version_number": "1.4.20", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From e7325e4d256e27791bbd4f9ec11b3ba8505ffe9f Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Wed, 23 Sep 2026 11:56:09 +0200 Subject: [PATCH 052/290] chore(release): v1.4.21 - dragon form multiplayer sync, Sverm Ravager networking, dorsal spine fix Co-Authored-By: Claude Sonnet 5 --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- JotunnModStub/Skadi/DrakeFormBehavior.cs | 15 +++ JotunnModStub/Skadi/SkadiPatches.cs | 47 ++++++- JotunnModStub/Skadi/SkadiRace.cs | 12 ++ JotunnModStub/Sverm/SvermConfig.cs | 9 +- JotunnModStub/Sverm/SvermConfigManagement.cs | 14 ++ JotunnModStub/Sverm/SvermPatches.cs | 135 +++++++++++++++++++ JotunnModStub/Sverm/SvermRavagerForm.cs | 54 ++++++++ JotunnModStub/Sverm/SvermVisuals.cs | 14 +- README.md | 7 + manifest.json | 2 +- 12 files changed, 303 insertions(+), 10 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 4c8d434..3baa445 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.20", + "version_number": "1.4.21", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index b050b4b..009df99 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.4.20"; + public const string PluginVersion = "1.4.21"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/JotunnModStub/Skadi/DrakeFormBehavior.cs b/JotunnModStub/Skadi/DrakeFormBehavior.cs index 7258cb8..ffd3b74 100644 --- a/JotunnModStub/Skadi/DrakeFormBehavior.cs +++ b/JotunnModStub/Skadi/DrakeFormBehavior.cs @@ -105,6 +105,14 @@ namespace RacesOfValheim } } + // Read by RemoteSkadiAnimator (SkadiPatches.cs) so other clients' copy of the form actually + // plays the bite/claw/breath clip instead of just locomotion. The suffix is a running count, + // not just the trigger name, because the same attack (e.g. two bites in a row) has to look + // like a NEW event to a remote client diffing the ZDO string - an unchanged value never + // re-triggers a Unity Animator trigger parameter. + public const string AttackTriggerKey = "RacesOfValheim_SkadiAttackTrigger"; + private static int attackTriggerSeq = 0; + /// /// Animator.SetTrigger on a name the controller does not have is silently ignored by Unity, /// so a wrong trigger looks exactly like "the animation did not play" with nothing in the @@ -120,6 +128,13 @@ namespace RacesOfValheim if (p.type == AnimatorControllerParameterType.Trigger && p.name == trigger) { anim.SetTrigger(trigger); + + ZNetView nview = Player.m_localPlayer?.GetComponent(); + if (nview != null && nview.IsValid()) + { + attackTriggerSeq++; + nview.GetZDO().Set(AttackTriggerKey, trigger + "#" + attackTriggerSeq); + } return; } } diff --git a/JotunnModStub/Skadi/SkadiPatches.cs b/JotunnModStub/Skadi/SkadiPatches.cs index 1a793db..2979b84 100644 --- a/JotunnModStub/Skadi/SkadiPatches.cs +++ b/JotunnModStub/Skadi/SkadiPatches.cs @@ -78,7 +78,11 @@ namespace RacesOfValheim formInstance.name = wanted; formInstance.transform.localPosition = formName == "Hatchling" ? new Vector3(0f, -1.0f, 0f) : Vector3.zero; formInstance.transform.localRotation = Quaternion.identity; - + // Same config-driven size the transforming player's own client applies (see + // SkadiRace.GetFormScale) - without it every remote observer saw the prefab's + // raw 1x Visual scale, Moder's ModerScale shrink included. + formInstance.transform.localScale = SkadiRace.GetFormScaleForPrefab(formName); + if (formInstance.GetComponent() == null) { formInstance.AddComponent(); @@ -94,27 +98,62 @@ namespace RacesOfValheim { private Animator anim; private Player player; + private ZNetView nview; + + // Seeded from whatever the ZDO already holds in Start, not "", so a value left over from an + // earlier transformation on this same player does not read as a brand-new attack the moment + // this component is built and replay a stale trigger on entry. + private string lastAttackTrigger; private void Start() { anim = GetComponent(); if (anim == null) anim = GetComponentInChildren(); player = GetComponentInParent(); + nview = player != null ? player.GetComponent() : null; + + if (nview != null && nview.IsValid()) + { + lastAttackTrigger = nview.GetZDO().GetString(DrakeFormBehavior.AttackTriggerKey, ""); + } } private void Update() { if (anim == null || player == null) return; - + bool flying = HarmonyLib.Traverse.Create(player).Field("m_flying").Value; bool grounded = !flying && player.IsOnGround(); - + anim.SetBool("onGround", grounded); anim.SetBool("flying", flying); - + Vector3 vel = player.GetVelocity(); vel.y = 0f; anim.SetFloat("forward_speed", vel.magnitude); + + // The bite/claw/breath trigger DrakeFormBehavior fires on the transforming player's own + // client - without this, remote observers only ever saw locomotion, never an attack play. + if (nview != null && nview.IsValid()) + { + string current = nview.GetZDO().GetString(DrakeFormBehavior.AttackTriggerKey, ""); + if (!string.IsNullOrEmpty(current) && current != lastAttackTrigger) + { + 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; + } + } + } + } } } diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index 34886e8..af64056 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -600,6 +600,18 @@ namespace RacesOfValheim return Vector3.one * SkadiConfig.DrakeScale.Value; // Drake } + // Same lookup, keyed by the prefab name the ZDO actually carries ("RacesOfValheim_SkadiForm"), + // so Skadi_MultiplayerVisuals_Patch can size a remote observer's copy of the form the same way + // the transforming player's own client does. Without this the remote instance was left at the + // prefab's raw Visual scale (1x) no matter which form or config value was in play - Moder's + // ModerScale nerf, in particular, only ever applied on the transformed player's own screen. + public static Vector3 GetFormScaleForPrefab(string prefabName) + { + if (prefabName == "Dragon") return Vector3.one * SkadiConfig.ModerScale.Value; + if (prefabName == "Fader") return Vector3.one * SkadiConfig.FaderScale.Value; + return Vector3.one * SkadiConfig.DrakeScale.Value; // Hatchling + } + private IEnumerator TransformRoutine(SkadiProgression.FormRules rules) { isTransformingSequence = true; diff --git a/JotunnModStub/Sverm/SvermConfig.cs b/JotunnModStub/Sverm/SvermConfig.cs index 0a74c95..f5f0c93 100644 --- a/JotunnModStub/Sverm/SvermConfig.cs +++ b/JotunnModStub/Sverm/SvermConfig.cs @@ -192,8 +192,8 @@ namespace RacesOfValheim // it is a real prefab that resolves by name, and it reads as xenomorph spines rather than // as a bird. public const string SpinesPrefab = "UndeadBjornRibcage"; - public static readonly float SpineSizeSmall = 0.45f; // metres, state 5-6 - public static readonly float SpineSizeFull = 0.80f; // metres, state 7+ + public static readonly float SpineSizeSmall = 0.315f; // metres, state 5-6 (0.45 * 0.7) + public static readonly float SpineSizeFull = 0.56f; // metres, state 7+ (0.80 * 0.7) /// /// Which bone they ride. Spine2 and ONLY Spine2 - no fallback chain. /// @@ -214,6 +214,11 @@ namespace RacesOfValheim public static readonly float SpineRotationY = -90f; public static readonly float SpineRotationZ = 90f; + // No extra nudge by default - ApplySpines already centres the crest on the bone (half its + // own height each way) before this is added, which is what keeps the Full-Crest size from + // reaching up over the head the way basing the whole thing at the bone once did. + public static readonly float SpineOffsetY = 0f; + /// /// What holds a falling Sverm up: the Mistlands' own fireflies, swarming under the body. /// diff --git a/JotunnModStub/Sverm/SvermConfigManagement.cs b/JotunnModStub/Sverm/SvermConfigManagement.cs index 4cd7290..30ebfce 100644 --- a/JotunnModStub/Sverm/SvermConfigManagement.cs +++ b/JotunnModStub/Sverm/SvermConfigManagement.cs @@ -32,6 +32,7 @@ namespace RacesOfValheim public static ConfigEntry SpineRotationX; public static ConfigEntry SpineRotationY; public static ConfigEntry SpineRotationZ; + public static ConfigEntry SpineOffsetY; // ─── Emberform ─────────────────────────────────────────────────────── public static ConfigEntry EmberGlowStrength; @@ -255,6 +256,17 @@ namespace RacesOfValheim SpineRotationX = config.Bind(spines, "Rotation X", SvermConfig.SpineRotationX, "Pitch of the spines, in degrees."); SpineRotationY = config.Bind(spines, "Rotation Y", SvermConfig.SpineRotationY, "Yaw of the spines, in degrees."); SpineRotationZ = config.Bind(spines, "Rotation Z", SvermConfig.SpineRotationZ, "Roll of the spines, in degrees."); + + // FOUND IN PLAY: at Size Full (0.8 m) the crest reached up past the shoulders and onto + // the head - ModelBorrow.Attach grounds a borrowed model's BOTTOM at the mount point and + // grows it from there, and Spine2's own local up axis runs toward the head, not out and + // away from the back. ApplySpines now centres the crest on the bone by default (half its + // height below the mount point, half above) instead of basing the whole thing there, which + // is a size-aware correction rather than a guess; this is purely an extra nudge on top of + // that, in metres along the same axis, for whatever an eye still wants adjusted. + SpineOffsetY = config.Bind(spines, "Offset Y", SvermConfig.SpineOffsetY, + "Extra nudge along the mount bone's own up axis, in metres, on top of the automatic " + + "centring. Positive moves the crest toward the head, negative toward the tail."); } // ─── Live reads ────────────────────────────────────────────────────── @@ -269,6 +281,8 @@ namespace RacesOfValheim SpineRotationZ?.Value ?? SvermConfig.SpineRotationZ); } + public static float SpineOffset => SpineOffsetY?.Value ?? SvermConfig.SpineOffsetY; + public static float EmberStrength => EmberGlowStrength?.Value ?? SvermConfig.EmberGlowStrength; public static int Brood => CapBrood?.Value ?? SvermConfig.CapBrood; diff --git a/JotunnModStub/Sverm/SvermPatches.cs b/JotunnModStub/Sverm/SvermPatches.cs index 4a21dc6..5d909f1 100644 --- a/JotunnModStub/Sverm/SvermPatches.cs +++ b/JotunnModStub/Sverm/SvermPatches.cs @@ -310,6 +310,141 @@ namespace RacesOfValheim } } + // ─── Ravager Strain (remote observers) ────────────────────────────── + + /// + /// 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. + /// + [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(); + if (player == null || player.IsOwner()) return; // Local player: SvermRavagerForm handles itself. + + if (!SvermVisuals.IsSvermPlayer(player)) return; + + ZNetView nview = player.GetComponent(); + 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(); + } + } + + PlayerVisualHider.Hide(playerVisual, "sverm-ravager-remote"); + } + } + + /// + /// 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. + /// + 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(); + player = GetComponentInParent(); + nview = player != null ? player.GetComponent() : 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 ─────────────────────────────────────────────────────────── /// diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index 9ef37a1..a8b9b88 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -28,6 +28,18 @@ namespace RacesOfValheim { public static bool IsActive { get; private set; } + // Read by Sverm_RavagerRemoteVisuals_Patch (SvermPatches.cs) so every other client can + // tell the form is up at all - without this the whole thing was local-only, exactly like + // DrakeFormBehavior's flight flag and Fenrir's own form key, and other players saw nothing + // but a Sverm standing still for the whole two minutes. + public const string ActiveKey = "RacesOfValheim_SvermRavagerForm"; + + // Same running-count trick as DrakeFormBehavior.AttackTriggerKey: the trigger name alone + // cannot tell a remote client "a new bite just happened" when the same trigger fires twice + // in a row, since an unchanged ZDO string never re-fires a Unity Animator trigger. + public const string AttackTriggerKey = "RacesOfValheim_SvermRavagerAttack"; + private static int attackTriggerSeq = 0; + private static GameObject model; private static float expiresAt; private static float nextAllowedAt; @@ -214,6 +226,9 @@ namespace RacesOfValheim IsActive = true; expiresAt = Time.time + SvermConfig.RavagerDurationSeconds; + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(ActiveKey, true); + player.GetSEMan().AddStatusEffect(SvermConfig.RavagerSE.GetStableHashCode(), true); Transform visual = player.transform.Find("Visual"); @@ -289,6 +304,9 @@ namespace RacesOfValheim { IsActive = false; + ZNetView exitNview = player.GetComponent(); + if (exitNview != null && exitNview.IsValid()) exitNview.GetZDO().Set(ActiveKey, false); + PlayEffect(SvermConfig.RavagerMorphOutEffects, player.transform.position); // Nothing was ever equipped for this form - see the class doc for why - so there is @@ -382,6 +400,40 @@ namespace RacesOfValheim if (target != null) target.transform.localScale = to; } + // ─── Remote observers ─────────────────────────────────────────────── + + /// + /// Builds the same costume Enter() does, minus the grow-in tween (a remote observer just + /// needs the steady-state model, not the entrance) and minus RavagerFormBehavior, which is + /// built around Player.m_localPlayer and would do nothing useful on a copy driven by + /// someone else's client. Sverm_RavagerRemoteVisuals_Patch adds RemoteRavagerAnimator + /// instead, the same way Skadi_MultiplayerVisuals_Patch adds RemoteSkadiAnimator. + /// + public static GameObject SpawnRemoteModel(Transform playerTransform) + { + if (template == null) return null; + + GameObject model = Object.Instantiate(template, playerTransform.position, playerTransform.rotation, playerTransform); + model.transform.localPosition = Vector3.zero; + model.transform.localScale = template.transform.localScale * SvermConfigManagement.RavagerScale; + model.transform.localRotation = Quaternion.Euler(0f, SvermConfigManagement.RavagerYaw, 0f); + return model; + } + + /// + /// Called by RavagerFormBehavior right after it fires a trigger on the local player's own + /// copy of the Animator, so RemoteRavagerAnimator can replay the same clip on every other + /// client. See AttackTriggerKey for why a sequence number rides along with the name. + /// + public static void PublishAttackTrigger(Player player, string trigger) + { + ZNetView nview = player != null ? player.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + attackTriggerSeq++; + nview.GetZDO().Set(AttackTriggerKey, trigger + "#" + attackTriggerSeq); + } + // ─── The three attacks ─────────────────────────────────────────────── /// @@ -584,6 +636,7 @@ namespace RacesOfValheim if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger)) { anim.SetTrigger(profile.Trigger); + SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger); } yield return new WaitForSeconds(hitDelay); @@ -614,6 +667,7 @@ namespace RacesOfValheim if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger)) { anim.SetTrigger(profile.Trigger); + SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger); } PlaySound(SvermConfig.RavagerTauntSoundEffects); diff --git a/JotunnModStub/Sverm/SvermVisuals.cs b/JotunnModStub/Sverm/SvermVisuals.cs index f8017c0..5dd352c 100644 --- a/JotunnModStub/Sverm/SvermVisuals.cs +++ b/JotunnModStub/Sverm/SvermVisuals.cs @@ -454,9 +454,19 @@ namespace RacesOfValheim // metres and degrees - what was ASKED for - not bone-local numbers. Quaternion wantedRotation = SvermConfigManagement.SpineRotation(); + // Basing the whole crest AT the bone and growing it upward (ModelBorrow.Attach grounds + // a borrowed model's bottom at the mount point) reached up past the shoulders and onto + // the head once the crest got tall - Spine2's own local up axis runs toward the head, + // not out and away from the back. Centring it on the bone instead - half its height + // below the mount point, half above - keeps the same rotation an eye already approved + // while stopping the Full Crest size from overshooting. SpineOffsetY is an additional + // nudge along the same axis, for whatever still needs adjusting by eye. + float wantedOffsetY = -wanted / 2f + SvermConfigManagement.SpineOffset; + SvermSpineTag tag = existing != null ? existing.GetComponent() : null; if (existing != null && (tag == null || !Mathf.Approximately(tag.Size, wanted) + || !Mathf.Approximately(tag.OffsetY, wantedOffsetY) || Quaternion.Angle(tag.Rotation, wantedRotation) > 0.5f)) { existing.name = SpinesName + "_Removed"; @@ -474,7 +484,7 @@ namespace RacesOfValheim bone, SpinesName, SvermConfig.SpinesPrefab, - Vector3.zero, + new Vector3(0f, wantedOffsetY / lossy, 0f), wantedRotation, wanted / lossy, "Sverm"); @@ -484,6 +494,7 @@ namespace RacesOfValheim SvermSpineTag built = holder.AddComponent(); built.Size = wanted; built.Rotation = wantedRotation; + built.OffsetY = wantedOffsetY; existing = holder.transform; } @@ -532,6 +543,7 @@ namespace RacesOfValheim { public float Size; public Quaternion Rotation = Quaternion.identity; + public float OffsetY; } // ─── Glide motes ───────────────────────────────────────────────────── diff --git a/README.md b/README.md index 68ac96b..c0e1878 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,13 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.4.21 +- **Fix - Other players saw Moder, the Drake and Fader at full size no matter what:** the dragon forms' own size (Moder's shrink included) was only ever applied on the transformed player's own screen — every other client built the remote copy at the prefab's raw scale. Two Skadi players who both turned into Moder each saw themselves correctly and the other one full-sized. Thanks to the tester who caught it from a second Skadi. +- **Fix - Drake and Moder's bite, claw and breath attacks played no animation for onlookers:** the attack trigger was only ever set on the transforming player's own Animator, so everyone else saw the form fly, walk and idle but never actually swing or breathe. The trigger now reaches every other client too. +- **Fix - Sverm Ravager Strain was invisible to everyone but the player using it:** the whole form — the model, the hidden human body, the attacks — was built entirely around the local player and never told the ZDO it was active. Other players saw a Sverm standing still for the whole two minutes with no Brute in sight. It is now networked the same way the Skadi and Fenrir forms already are. +- **Fix - The Sverm's dorsal spines were mounted up over the shoulders, onto the face:** the crest was based at its mount bone and grown upward from there, which reached past the head once the Full Crest size (Queen tier on) came in. It is now centred on the bone instead, with a live "Offset Y" knob under `[Sverm - Dorsal Spines]` in Configuration Manager for any further nudging. Thanks to the tester who sent the screenshot. +- **Changed - The Sverm's dorsal spines are 30% smaller:** 0.45 m down to 0.315 m from Moder to the Queen, 0.8 m down to 0.56 m from the Queen on. + ### v1.4.20 - **Fix - A refused race building still took your materials:** building something your race is not allowed to build, or before its boss has fallen, showed the refusal and then charged the full cost anyway — a non-Sverm trying the Brood Mound got "Only the Sverm can raise a hive." and lost 40 wood and 20 resin. The refusal stopped the building, but Valheim takes the cost in a separate step that never heard about it. Now a refused building costs nothing, no stamina included. This covered every locked building in the mod: the Sverm hive and market (and the one-hive-per-area limit), the Skadi golem, the Dvergar contract bank and barrel, the Trenta Elder Root and the Trol totem. Thanks to the tester who noticed the wood going missing. - **Fix - On a gamepad the Skadi cast the Cold Spell every time she built:** the spell sits on the pad's secondary attack button, which Valheim also uses to remove pieces (Classic layout) or place them (Alt 2). Every piece built or removed also cast the spell and drained stamina, which made building nearly impossible. The spell no longer casts while you hold the hammer, hoe or cultivator — on the keyboard as well, where middle mouse is Remove. diff --git a/manifest.json b/manifest.json index 4c8d434..3baa445 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.20", + "version_number": "1.4.21", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 9bebcf340b1e7ab812adf047045a6cbc5c7ea684 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Thu, 24 Sep 2026 10:30:39 +0200 Subject: [PATCH 053/290] bugfix 24/09/26 --- JotunnModStub/Aswid/AswidBloodRefinery.cs | 11 +- JotunnModStub/Fenrir/FenrirBehaviors.cs | 198 +++++++++++++++++++--- JotunnModStub/Fenrir/FenrirRace.cs | 16 +- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 5 + manifest.json | 2 +- 7 files changed, 205 insertions(+), 31 deletions(-) diff --git a/JotunnModStub/Aswid/AswidBloodRefinery.cs b/JotunnModStub/Aswid/AswidBloodRefinery.cs index 1990b1e..c89a2fd 100644 --- a/JotunnModStub/Aswid/AswidBloodRefinery.cs +++ b/JotunnModStub/Aswid/AswidBloodRefinery.cs @@ -234,8 +234,11 @@ namespace RacesOfValheim refinery.m_haveMeatObject = smelter.m_haveOreObject; refinery.m_noMeatObject = smelter.m_noOreObject; refinery.m_animators = smelter.m_animators; - refinery.m_meatAddedEffects = smelter.m_oreAddedEffects; - refinery.m_boneAddedEffects = smelter.m_fuelAddedEffects; + // Crossed on purpose: the sounds sit the other way round from the slots. The ore + // effect is the dry clatter and the fuel effect the wet slap, so flesh takes the + // fuel one and bone the ore one. + refinery.m_meatAddedEffects = smelter.m_fuelAddedEffects; + refinery.m_boneAddedEffects = smelter.m_oreAddedEffects; refinery.m_produceEffects = smelter.m_produceEffects; refinery.m_smokeSpawner = smelter.m_smokeSpawner; @@ -243,8 +246,8 @@ namespace RacesOfValheim // Two Radiators under _enabled are what shot the tester: see IsOffensive. StripOffensive(prefab, PieceName); - SanitiseEffects(refinery.m_meatAddedEffects, PieceName + ".oreAdded"); - SanitiseEffects(refinery.m_boneAddedEffects, PieceName + ".fuelAdded"); + SanitiseEffects(refinery.m_meatAddedEffects, PieceName + ".fuelAdded"); + SanitiseEffects(refinery.m_boneAddedEffects, PieceName + ".oreAdded"); SanitiseEffects(refinery.m_produceEffects, PieceName + ".produce"); prefab.transform.localScale = Vector3.one * ModelScale; diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 19e880a..2d1180c 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -39,6 +39,73 @@ namespace RacesOfValheim } } + /// + /// The attack half of somebody else's form: the owner's client publishes each trigger it fires + /// on its own copy of the Animator, RemoteFenrirAnimator replays it on the copy every other + /// client sees. The running count rides along because an unchanged ZDO string would never + /// re-fire a Unity Animator trigger when the same bite lands twice in a row - the same trick as + /// DrakeFormBehavior.AttackTriggerKey and SvermRavagerForm.AttackTriggerKey. + /// + public static class FenrirAttackSync + { + public const string Key = "RacesOfValheim_FenrirAttack"; + private static int seq = 0; + + // The cultist's flame is a held bool on the Animator, not a one-shot trigger, so it gets a + // key of its own: a sequence number would say "it started" but never "it stopped". + public const string FireKey = "RacesOfValheim_FenrirFire"; + + /// + /// The flame the cultist breathes, parented to the given player so it follows them. One + /// place for it because the owner's own copy and every onlooker's copy have to look alike. + /// + public static GameObject SpawnFlames(Player player) + { + if (player == null || ZNetScene.instance == null) return null; + + // Un effetto che dura nel tempo, trovato dai log! + GameObject fireVfx = ZNetScene.instance.GetPrefab("fx_fenring_flames"); + if (fireVfx == null) return null; + + GameObject instance = Object.Instantiate(fireVfx, player.transform.position + Vector3.up * 1.5f + player.transform.forward, player.transform.rotation, player.transform); + + // Aumentiamo la durata delle particelle del 20% + foreach (ParticleSystem ps in instance.GetComponentsInChildren()) + { + var main = ps.main; + main.startLifetimeMultiplier *= 1.2f; + } + return instance; + } + + public static void PublishFire(bool on) + { + Player player = Player.m_localPlayer; + ZNetView nview = player != null ? player.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + nview.GetZDO().Set(FireKey, on); + } + + /// + /// Publishes a trigger, and with it the swing's sound: the candidate prefab names in the + /// order the owner's own PlaySFX would try them, or "@Creature" for a howl borrowed from + /// that creature's alert effect. Only the opening cue rides along; the impact sounds are + /// decided by what the swing hits, which an onlooker's client never works out. + /// + public static void Publish(string trigger, params string[] sfx) + { + Player player = Player.m_localPlayer; + ZNetView nview = player != null ? player.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + seq++; + string payload = trigger + "#" + seq; + if (sfx != null && sfx.Length > 0) payload += "#" + string.Join("|", sfx); + nview.GetZDO().Set(Key, payload); + } + } + /// /// The animation half of somebody else's form. /// @@ -59,15 +126,23 @@ namespace RacesOfValheim /// Kept next to the four local behaviours on purpose: this mirrors the movement half of their /// Update, and the two have to be changed together. /// - /// Attacks are not mirrored. Those are triggers fired from input on the owner's client and - /// nothing replicates them, so a remote form still bites in silence - that needs a counter of - /// its own on the ZDO and is a separate job. + /// Attacks are triggers fired from input on the owner's client; FenrirAttackSync publishes + /// each one on the ZDO and this component replays it below. /// public class RemoteFenrirAnimator : MonoBehaviour { private Player player; private Animator playerAnim; private Animator formAnim; + private ZNetView nview; + private string lastAttack; + private GameObject flames; + + // The flames hang off the player, not this model, so they outlive it unless taken down. + private void OnDestroy() + { + if (flames != null) Destroy(flames); + } private void Update() { @@ -84,6 +159,9 @@ namespace RacesOfValheim } if (formAnim == null || playerAnim == null) return; + ReplayAttack(); + ReplayFire(); + bool grounded = playerAnim.GetBool("onGround"); // All four borrowed creatures answer to these, and they are still written through @@ -99,6 +177,84 @@ namespace RacesOfValheim try { formAnim.SetFloat("forward_speed", still ? 0f : playerAnim.GetFloat("forward_speed")); } catch {} try { formAnim.SetFloat("sideway_speed", still ? 0f : playerAnim.GetFloat("sideway_speed")); } catch {} } + + // Written every frame while the flag is set, and only when the controller has the bool: a + // wolf or a Ulv has no "attack_fire", and the ZDO key is only ever true for the cultist. + private void ReplayFire() + { + if (nview == null || !nview.IsValid()) return; + + bool fire = nview.GetZDO().GetBool(FenrirAttackSync.FireKey, false); + + // The breath itself: up while the flag is, gone when it drops. Only the cultist ever + // sets the flag, so no other form can grow flames here. + if (fire && flames == null) + { + flames = FenrirAttackSync.SpawnFlames(player); + + // The roar that opens the breath, once per start, the same cue the owner hears. + GameObject sfx = PrefabManager.Cache.GetPrefab("sfx_cultist_attack_fire_start"); + if (sfx != null) Instantiate(sfx, player.transform.position, Quaternion.identity); + } + else if (!fire && flames != null) { Destroy(flames); flames = null; } + + foreach (AnimatorControllerParameter p in formAnim.parameters) + { + if (p.type == AnimatorControllerParameterType.Bool && p.name == "attack_fire") + { + formAnim.SetBool("attack_fire", fire); + break; + } + } + } + + private void PlayAttackSound(string[] names) + { + foreach (string name in names) + { + if (name.StartsWith("@")) + { + FenrirCreatureSound.PlayHowl(name.Substring(1), player.transform.position); + return; + } + + GameObject sfx = PrefabManager.Cache.GetPrefab(name); + if (sfx != null) + { + Instantiate(sfx, player.transform.position, Quaternion.identity); + return; + } + } + } + + private void ReplayAttack() + { + if (nview == null) nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) return; + + string current = nview.GetZDO().GetString(FenrirAttackSync.Key, ""); + + // First look at the ZDO only records what is already there, so a trigger left over from + // an earlier form does not replay the instant this model is built. + if (lastAttack == null) { lastAttack = current; return; } + if (string.IsNullOrEmpty(current) || current == lastAttack) return; + lastAttack = current; + + string[] parts = current.Split('#'); + string trigger = parts[0]; + if (parts.Length > 2) PlayAttackSound(parts[2].Split('|')); + + // Only the triggers this particular borrowed controller actually has: the four forms + // share none of the attack names but the taunt. + foreach (AnimatorControllerParameter p in formAnim.parameters) + { + if (p.type == AnimatorControllerParameterType.Trigger && p.name == trigger) + { + formAnim.SetTrigger(trigger); + break; + } + } + } } public class FenrirFormBehavior : MonoBehaviour @@ -192,6 +348,7 @@ namespace RacesOfValheim fenrirAnim.SetFloat("sideway_speed", 0f); fenrirAnim.SetTrigger("attack_taunt"); + FenrirAttackSync.Publish("attack_taunt", "@Fenring"); FenrirCreatureSound.PlayHowl("Fenring", Player.m_localPlayer.transform.position); @@ -208,6 +365,7 @@ namespace RacesOfValheim fenrirAnim.SetFloat("sideway_speed", 0f); fenrirAnim.SetTrigger(triggerName); + FenrirAttackSync.Publish(triggerName, "sfx_fenring_attack", "sfx_fenring_attack_claw", "sfx_wolf_attack"); PlaySFX("sfx_fenring_attack", "sfx_fenring_attack_claw", "sfx_wolf_attack"); yield return new WaitForSeconds(dmgDelay); @@ -241,6 +399,7 @@ namespace RacesOfValheim fenrirAnim.SetFloat("sideway_speed", 0f); fenrirAnim.SetTrigger("attack_jump"); + FenrirAttackSync.Publish("attack_jump"); // Aspettiamo che l'animazione si carichi (0.75s) yield return new WaitForSeconds(0.75f); @@ -477,6 +636,7 @@ namespace RacesOfValheim // Cultist ha una vera e propria animazione di "taunt" cultistAnim.SetTrigger("attack_taunt"); + FenrirAttackSync.Publish("attack_taunt", "@Fenring_Cultist"); FenrirCreatureSound.PlayHowl("Fenring_Cultist", Player.m_localPlayer.transform.position); @@ -496,27 +656,13 @@ namespace RacesOfValheim cultistAnim.SetFloat("forward_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetBool("attack_fire", true); + FenrirAttackSync.PublishFire(true); PlaySFX("sfx_cultist_attack_fire_start"); cultistAnim.SetTrigger("attack_flames"); + FenrirAttackSync.Publish("attack_flames"); - if (ZNetScene.instance != null && fireEffectInstance == null) - { - // Un effetto che dura nel tempo, trovato dai log! - GameObject fireVfx = ZNetScene.instance.GetPrefab("fx_fenring_flames"); - if (fireVfx != null) - { - fireEffectInstance = Instantiate(fireVfx, Player.m_localPlayer.transform.position + Vector3.up * 1.5f + Player.m_localPlayer.transform.forward, Player.m_localPlayer.transform.rotation, Player.m_localPlayer.transform); - - // Aumentiamo la durata delle particelle del 20% - ParticleSystem[] pss = fireEffectInstance.GetComponentsInChildren(); - foreach (ParticleSystem ps in pss) - { - var main = ps.main; - main.startLifetimeMultiplier *= 1.2f; - } - } - } + if (fireEffectInstance == null) fireEffectInstance = FenrirAttackSync.SpawnFlames(Player.m_localPlayer); } private void UpdateFire() @@ -533,10 +679,17 @@ namespace RacesOfValheim } } + // Leaving the form mid-flame must not leave the flag up for onlookers. + private void OnDestroy() + { + if (isShootingFire) FenrirAttackSync.PublishFire(false); + } + private void StopFire() { isShootingFire = false; cultistAnim.ResetTrigger("attack_flames"); + FenrirAttackSync.PublishFire(false); if (fireEffectInstance != null) { @@ -617,6 +770,7 @@ namespace RacesOfValheim // Per il Cultista usiamo esplicitamente il trigger dell'artigliata cultistAnim.SetTrigger("attack_claw"); + FenrirAttackSync.Publish("attack_claw", "sfx_cultist_attack", "sfx_fenring_attack", "sfx_wolf_attack"); yield return new WaitForSeconds(0.4f); @@ -642,6 +796,7 @@ namespace RacesOfValheim cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetTrigger("attack_claw_double"); + FenrirAttackSync.Publish("attack_claw_double", "sfx_cultist_attack_double", "sfx_cultist_attack", "sfx_fenring_attack"); // L'animazione double claw è più lunga, facciamo il danno un po' dopo yield return new WaitForSeconds(0.6f); @@ -805,6 +960,7 @@ namespace RacesOfValheim try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} wolfAnim.SetTrigger(triggerName); + FenrirAttackSync.Publish(triggerName, "sfx_wolf_attack"); yield return new WaitForSeconds(dmgDelay); @@ -979,6 +1135,7 @@ namespace RacesOfValheim try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} try { ulvAnim.SetTrigger(triggerName); } catch {} + FenrirAttackSync.Publish(triggerName, "sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack"); // Scegli il suono appropriato per l'attacco if (triggerName == "attack_bite") @@ -1084,6 +1241,7 @@ namespace RacesOfValheim try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} try { ulvAnim.SetTrigger("attack_slash"); } catch {} + FenrirAttackSync.Publish("attack_slash", "sfx_ulv_attack", "sfx_wolf_attack"); PlaySFX("sfx_ulv_attack", "sfx_wolf_attack"); yield return new WaitForSeconds(0.3f); // Wait 0.3s before leaping diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index 51617c8..784cffd 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -135,9 +135,15 @@ namespace RacesOfValheim { } else if (!isNight && wasNight) { - // Sunrise: force revert and block transforming again for a while - sunSicknessTimer = FenrirConfig.SunSicknessDuration.Value; - ForceRevert(); + // Sunrise: a form that was granted for the night only is taken back, and the + // beast is tired for a while. A form the progression lets through by day (Queen's + // Fenrir, Fader's Cultist, Bonemass's Wolf) is not the sun's to take: activeRules is + // what the transform was actually granted under. + if (activeRules == null || activeRules.NeedsNight) + { + sunSicknessTimer = FenrirConfig.SunSicknessDuration.Value; + ForceRevert(); + } } wasNight = isNight; @@ -166,7 +172,9 @@ namespace RacesOfValheim { { if (rules == null || rules.Form == FenrirProgression.FormType.None) return; - if (sunSicknessTimer > 0f) + // The tiredness is the sun's doing, so it only stands in the way of a night form; the + // forms allowed by day would otherwise be locked out right after every sunrise. + if (rules.NeedsNight && sunSicknessTimer > 0f) { Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The beast is tired"); return; diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 3baa445..14ffb1a 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.21", + "version_number": "1.4.22", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 009df99..e5b9d0a 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.4.21"; + public const string PluginVersion = "1.4.22"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index c0e1878..d7f1b85 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,11 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.4.22 +- **Fix - Other players saw Fenrir forms standing silent:** every form's attacks - the Fenring's claws, the Cultist's claws and flames, the Wolf's and the Ulv's bites - were only ever triggered on the transformed player's own Animator, so onlookers saw the form run but never swing. The attacks now reach every other client, along with the opening sound of each swing and the howls. The Cultist's flame breath, its roar and the fire itself are shown to onlookers too. The sounds of the impact itself and the Fenring's jump are still heard only by the player who makes them. +- **Fix - Fenrir players turned back to human at every sunrise, even with a form the day allows:** after the Queen the Fenring form (and the Wolf after Bonemass, the Cultist after Fader) is meant to work day and night, but sunrise took it away regardless. Only forms granted for the night alone are taken back now, and "The beast is tired" no longer blocks the daytime forms either. Thanks to the tester who noticed it. +- **Fix - The Aswid's Blood Refinery had the insertion sounds the wrong way round:** flesh and bone played each other's sound. They are swapped. + ### v1.4.21 - **Fix - Other players saw Moder, the Drake and Fader at full size no matter what:** the dragon forms' own size (Moder's shrink included) was only ever applied on the transformed player's own screen — every other client built the remote copy at the prefab's raw scale. Two Skadi players who both turned into Moder each saw themselves correctly and the other one full-sized. Thanks to the tester who caught it from a second Skadi. - **Fix - Drake and Moder's bite, claw and breath attacks played no animation for onlookers:** the attack trigger was only ever set on the transforming player's own Animator, so everyone else saw the form fly, walk and idle but never actually swing or breathe. The trigger now reaches every other client too. diff --git a/manifest.json b/manifest.json index 3baa445..14ffb1a 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.21", + "version_number": "1.4.22", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From f64fe83d9d9385b97f80412faa5c9fc4faa4b1c2 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Fri, 25 Sep 2026 12:26:51 +0200 Subject: [PATCH 054/290] bugfix 25/09/26 --- JotunnModStub/ConfigSync.cs | 96 ++++++++++++++++++++++++ JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 4 +- JotunnModStub/Trol/TrolFarmingPatches.cs | 11 +-- README.md | 4 + manifest.json | 2 +- 6 files changed, 111 insertions(+), 8 deletions(-) create mode 100644 JotunnModStub/ConfigSync.cs diff --git a/JotunnModStub/ConfigSync.cs b/JotunnModStub/ConfigSync.cs new file mode 100644 index 0000000..fb38b9c --- /dev/null +++ b/JotunnModStub/ConfigSync.cs @@ -0,0 +1,96 @@ +using System; +using System.Linq; +using System.Reflection; +using BepInEx.Configuration; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Marks every gameplay config entry as admin-only so Jotunn syncs it from the server to the + /// clients (and locks it for non-admins in Configuration Manager). + /// + /// Jotunn only recognises ITS OWN ConfigurationManagerAttributes (global namespace, in + /// Jotunn.dll) as a tag - it does an `is` check, not the field-name duck typing Configuration + /// Manager does - so our internal look-alike tag is not enough. This runs once after every + /// Bind() and adds Jotunn's tag beside whatever tags the entry already has, rather than + /// touching each of the ~350 Bind() calls. + /// + /// Left local, because they are per-player preferences and syncing them would only take the + /// choice away from the player: keybinds, and the purely cosmetic entries (eye/claw colours, + /// glow, tint, rotation and offset of models, the VFX toggle, the stamina-bar toggle, debug + /// logging). Anything that changes a number the game computes with stays synced. + /// + internal static class ConfigSync + { + // Whole sections that are cosmetic or per-player. + private static readonly string[] LocalSections = + { + "Aswid - Claws", + "Aswid - Eyes", + "Skeleton - Visuals", + "Sverm - Dorsal Spines", + "Sverm - Emberform", + "War Vulture - Model", + "War Vulture - Interface", + }; + + // Cosmetic entries scattered through otherwise gameplay sections. + private static readonly string[] LocalKeyParts = + { + "marker light", "tint", "colour", "color", "glow", "swarm scale", "log rounds", "debug", + }; + + public static void Apply(ConfigFile config) + { + FieldInfo descField = typeof(ConfigEntryBase) + .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) + .FirstOrDefault(f => f.FieldType == typeof(ConfigDescription)); + if (descField == null) + { + Debug.LogWarning("[RacesOfValheim] Config sync skipped: ConfigEntryBase has no ConfigDescription field."); + return; + } + + int synced = 0, local = 0; + foreach (ConfigDefinition def in config.Keys.ToList()) + { + ConfigEntryBase entry = config[def]; + if (!ShouldSync(entry)) { local++; continue; } + + ConfigDescription old = entry.Description; + object[] tags = (old.Tags ?? new object[0]).Concat(new object[] + { + new global::ConfigurationManagerAttributes { IsAdminOnly = true } + }).ToArray(); + descField.SetValue(entry, new ConfigDescription(old.Description, old.AcceptableValues, tags)); + synced++; + } + Debug.Log($"[RacesOfValheim] Config sync: {synced} entries admin-synced, {local} left local."); + } + + private static bool ShouldSync(ConfigEntryBase entry) + { + Type type = entry.SettingType; + if (type == typeof(KeyboardShortcut) || type == typeof(KeyCode)) return false; + + string section = entry.Definition.Section ?? ""; + string key = (entry.Definition.Key ?? "").ToLowerInvariant(); + + if (section.EndsWith("Keybinds", StringComparison.OrdinalIgnoreCase)) return false; + if (LocalSections.Contains(section, StringComparer.OrdinalIgnoreCase)) return false; + if (LocalKeyParts.Any(key.Contains)) return false; + + // Model pose nudges (rotation/offset/yaw) are cosmetic, but "Attack Reach Offset" is a + // real hit-detection distance and must stay in step with the server. + if ((key.Contains("rotation") || key.Contains("offset") || key.Contains("yaw")) + && !key.Contains("reach")) return false; + + // Decorative note lines (CustomDrawer/ReadOnly) carry no value worth sending. + ConfigurationManagerAttributes ours = (entry.Description?.Tags ?? new object[0]).OfType().FirstOrDefault(); + if (ours != null && (ours.CustomDrawer != null || ours.ReadOnly == true)) return false; + + return true; + } + } +} diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 14ffb1a..fc74963 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.22", + "version_number": "1.4.23", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index e5b9d0a..7061303 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.4.22"; + public const string PluginVersion = "1.4.23"; private readonly Harmony harmony = new Harmony(PluginGUID); @@ -52,6 +52,8 @@ namespace RacesOfValheim // Not a race either: the faction truce and the faction merchants, which cut across // every race at once, so they bind last rather than inside the alphabetical run above. FactionsConfig.Bind(Config); + // After every Bind above: tags the gameplay entries for Jotunn's server-to-client sync. + ConfigSync.Apply(Config); harmony.PatchAll(); gameObject.AddComponent(); gameObject.AddComponent(); diff --git a/JotunnModStub/Trol/TrolFarmingPatches.cs b/JotunnModStub/Trol/TrolFarmingPatches.cs index 1e43a40..00be181 100644 --- a/JotunnModStub/Trol/TrolFarmingPatches.cs +++ b/JotunnModStub/Trol/TrolFarmingPatches.cs @@ -51,7 +51,8 @@ namespace RacesOfValheim } } - [HarmonyPatch(typeof(TreeBase), "RPC_Damage")] + // Patched on Damage (attacker side), not RPC_Damage: the RPC runs on the object owner (host), where the attacker is not the local player. + [HarmonyPatch(typeof(TreeBase), "Damage")] public static class Trol_TreeBase_RPC_Damage_Patch { public static void Prefix(HitData hit) @@ -60,7 +61,7 @@ namespace RacesOfValheim } } - [HarmonyPatch(typeof(TreeLog), "RPC_Damage")] + [HarmonyPatch(typeof(TreeLog), "Damage")] public static class Trol_TreeLog_RPC_Damage_Patch { public static void Prefix(HitData hit) @@ -69,7 +70,7 @@ namespace RacesOfValheim } } - [HarmonyPatch(typeof(Destructible), "RPC_Damage")] + [HarmonyPatch(typeof(Destructible), "Damage")] public static class Trol_Destructible_RPC_Damage_Patch { public static void Prefix(HitData hit, Destructible __instance) @@ -81,7 +82,7 @@ namespace RacesOfValheim } } - [HarmonyPatch(typeof(MineRock), "RPC_Hit")] + [HarmonyPatch(typeof(MineRock), "Damage")] public static class Trol_MineRock_RPC_Hit_Patch { public static void Prefix(HitData hit) @@ -90,7 +91,7 @@ namespace RacesOfValheim } } - [HarmonyPatch(typeof(MineRock5), "DamageArea")] + [HarmonyPatch(typeof(MineRock5), "Damage")] public static class Trol_MineRock5_DamageArea_Patch { public static void Prefix(HitData hit) diff --git a/README.md b/README.md index d7f1b85..010b03d 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,10 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.4.23 +- **Fix - Trol clients could not chop trees or mine rocks with their fists:** the fist bonus (chop and pickaxe damage, and the tool tier that grows with the bosses) was applied on whichever machine owned the tree or rock - usually the host - where the hit did not belong to the local player, so it only ever worked for the host. It is now applied on the attacking player's own machine before the hit is sent. Thanks to the players who reported it. +- **New - Configuration is synced from the server:** every gameplay setting now follows the server's value in multiplayer, and is locked in Configuration Manager for players who are not admins. Keybinds and the purely cosmetic settings (eye and claw colours, glow, model rotation and offsets, the Head Fire VFX and stamina-bar toggles, debug logging) stay local, so each player keeps their own. + ### v1.4.22 - **Fix - Other players saw Fenrir forms standing silent:** every form's attacks - the Fenring's claws, the Cultist's claws and flames, the Wolf's and the Ulv's bites - were only ever triggered on the transformed player's own Animator, so onlookers saw the form run but never swing. The attacks now reach every other client, along with the opening sound of each swing and the howls. The Cultist's flame breath, its roar and the fire itself are shown to onlookers too. The sounds of the impact itself and the Fenring's jump are still heard only by the player who makes them. - **Fix - Fenrir players turned back to human at every sunrise, even with a form the day allows:** after the Queen the Fenring form (and the Wolf after Bonemass, the Cultist after Fader) is meant to work day and night, but sunrise took it away regardless. Only forms granted for the night alone are taken back now, and "The beast is tired" no longer blocks the daytime forms either. Thanks to the tester who noticed it. diff --git a/manifest.json b/manifest.json index 14ffb1a..fc74963 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.22", + "version_number": "1.4.23", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 00d4fd6e4688cd39fff34ff02a14acf1cbd893e3 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 25 Sep 2026 15:54:21 +0200 Subject: [PATCH 055/290] fix(skeleton): stop the fire aura borrowing another mod's VFX by name The tier-5 fire aura looked for "vfx_smoke", then "vfx_surtling_death". Neither name exists in Valheim, checked against the game's own asset manifests, so both lookups came back null and the aura has never been visible in a plain install. The dead branch was not harmless. PrefabManager.Cache resolves by asset name across everything in memory, other mods' asset bundles included, and its tie-break for a duplicate name ends in "newest wins". A name vanilla does not use has no vanilla candidate to beat, so it is a free slot. Magic_Supremacy fills it. The lookup resolved to 'EncounterCreatureRikoMountain_DO/vfx_smoke', a child node of one of its creatures carrying 'club_trail_riko_DO' on 'Dreanegade/ParticleAlphaEmission' - a weapon trail, on an emissive shader, sprayed through a 4.5m sphere on the player. That is the purple smoke around the burning skull users reported, on every client that could see the skeleton. The aura now draws nothing on purpose, which costs it nothing it had. Its damage, radius and tick are untouched. The two identical EnsureFireAuraVFX copies in SkeletonRace and ZdoVisualSync are replaced by one SkeletonVisuals.EnsureFireAura, shaped like DraughVisuals.EnsureAura; the call sites stay, so reinstating the visual needs no change in either file. The comment on it records the whole chain and the way to build it properly, through BorrowEffect, the way HeadFlame already does. Also keeps a resolution log on the model lookup: every magic mod in the report ships an object called "Skeleton", which is this race's own tier-0 model name. The vanilla creature won during the repro; root=False in that log is what says it stopped winning. Co-Authored-By: Claude Opus 5 --- JotunnModStub/Skeleton/SkeletonPatches.cs | 8 +++ JotunnModStub/Skeleton/SkeletonRace.cs | 79 +------------------- JotunnModStub/Skeleton/SkeletonVisuals.cs | 87 +++++++++++++++++++++++ JotunnModStub/ZdoVisualSync.cs | 72 ++----------------- 4 files changed, 102 insertions(+), 144 deletions(-) diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index 78b1cf2..10fdf7d 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -283,6 +283,14 @@ namespace RacesOfValheim if (skeletonBodyTransform == null) { GameObject skelPrefab = PrefabManager.Cache.GetPrefab(rules.ModelPrefab); + + // The cache answers by name alone, and every magic mod named in the + // purple-smoke report carries an object of its own called "Skeleton" - + // which is this race's own tier-0 model name. So far the vanilla + // creature has always won; the log is here to say so, or to say which + // mod's object took its place. See SkeletonVisuals.EnsureFireAura. + SkeletonVisuals.LogResolvedPrefabOnce("model " + rules.ModelPrefab, skelPrefab); + if (skelPrefab == null) { // The human body was switched off two lines up, so an unresolved diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index 90311d6..3f0a3cb 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -279,7 +279,7 @@ namespace RacesOfValheim // only path taken once they stop being one. A Fader-tier Skeleton who reset to // Human kept a burning skull and a collapsed jaw, since neither the flame nor the // jaw was ever switched back from outside the Skeleton branch below. - EnsureFireAuraVFX(false); + SkeletonVisuals.EnsureFireAura(Player.m_localPlayer, false, ref fireAuraVFX); headFlame.Apply(Player.m_localPlayer, false); RestoreJawBone(); @@ -446,7 +446,7 @@ namespace RacesOfValheim if (rules.FireAura) { - EnsureFireAuraVFX(true); + SkeletonVisuals.EnsureFireAura(Player.m_localPlayer, true, ref fireAuraVFX); if (Time.time - lastAuraTime >= SkeletonConfig.FireAuraTickInterval.Value) { ApplyFireAura(); @@ -455,7 +455,7 @@ namespace RacesOfValheim } else { - EnsureFireAuraVFX(false); + SkeletonVisuals.EnsureFireAura(Player.m_localPlayer, false, ref fireAuraVFX); } } @@ -478,79 +478,6 @@ namespace RacesOfValheim } } - private void EnsureFireAuraVFX(bool enable) - { - if (enable && Player.m_localPlayer != null) - { - if (fireAuraVFX == null) - { - // Look for a smoke or fog effect to tint as fire fog - GameObject sourceVFX = PrefabManager.Cache.GetPrefab("vfx_smoke") ?? - PrefabManager.Cache.GetPrefab("vfx_surtling_death"); - - fireAuraVFX = new GameObject("SkeletonFireAuraVFX"); - fireAuraVFX.transform.SetParent(Player.m_localPlayer.transform, false); - fireAuraVFX.transform.localPosition = new Vector3(0, 1f, 0); - - if (sourceVFX != null) - { - ParticleSystem[] pss = sourceVFX.GetComponentsInChildren(); - if (pss.Length > 0) - { - ParticleSystem ps = fireAuraVFX.AddComponent(); - var main = ps.main; - main.loop = true; - main.duration = 1f; - main.startLifetime = 1.5f; - main.startSize = new ParticleSystem.MinMaxCurve(1.5f, 3f); - main.startSpeed = 0f; - main.simulationSpace = ParticleSystemSimulationSpace.World; - - var renderer = fireAuraVFX.GetComponent(); - renderer.material = pss[0].GetComponent().material; - - var shape = ps.shape; - shape.shapeType = ParticleSystemShapeType.Sphere; - shape.radius = 4.5f; // Similar to the damage radius - - var emission = ps.emission; - emission.rateOverTime = 40f; - - // Add a fire-like color gradient - var colorOverLifetime = ps.colorOverLifetime; - colorOverLifetime.enabled = true; - Gradient grad = new Gradient(); - grad.SetKeys( - new GradientColorKey[] { - new GradientColorKey(new Color(1f, 0.8f, 0.2f), 0.0f), // Yellow - new GradientColorKey(new Color(1f, 0.3f, 0.0f), 0.5f), // Orange/Red - new GradientColorKey(new Color(0.2f, 0.0f, 0.0f), 1.0f) // Dark red/smoke - }, - new GradientAlphaKey[] { - new GradientAlphaKey(0.0f, 0.0f), - new GradientAlphaKey(0.6f, 0.2f), - new GradientAlphaKey(0.6f, 0.8f), - new GradientAlphaKey(0.0f, 1.0f) - } - ); - colorOverLifetime.color = grad; - } - } - } - if (!fireAuraVFX.activeSelf) - { - fireAuraVFX.SetActive(true); - } - } - else - { - if (fireAuraVFX != null && fireAuraVFX.activeSelf) - { - fireAuraVFX.SetActive(false); - } - } - } - private void ApplyFireAura() { if (Player.m_localPlayer == null) return; diff --git a/JotunnModStub/Skeleton/SkeletonVisuals.cs b/JotunnModStub/Skeleton/SkeletonVisuals.cs index 825b64a..5f82dbc 100644 --- a/JotunnModStub/Skeleton/SkeletonVisuals.cs +++ b/JotunnModStub/Skeleton/SkeletonVisuals.cs @@ -169,6 +169,49 @@ namespace RacesOfValheim (passengers.Count == 0 ? "." : ", stripped " + string.Join(", ", passengers.ToArray()) + ".")); } + /// + /// Says what a borrowed-by-name prefab actually resolved to: which object, where it sits in + /// ITS OWN hierarchy, and the material and shader the first particle on it carries. Once per + /// name per session, so it costs a handful of lines and answers the question that took a + /// bundle extractor to answer the first time. + /// + /// READ THE root FLAG FIRST. A root-level object is a real prefab and almost certainly the + /// vanilla one. A parented one is a child node that Jotunn's cache picked up because nothing + /// better in memory answered to that name - which is what happens when the name does not + /// exist in vanilla at all, and is exactly how another mod's weapon trail ended up worn as + /// this race's fire aura. See EnsureFireAura. + /// + private static readonly HashSet loggedResolutions = new HashSet(); + + public static void LogResolvedPrefabOnce(string wanted, GameObject resolved) + { + if (!loggedResolutions.Add(wanted)) return; + + if (resolved == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] Prefab lookup '{wanted}' resolved to NOTHING."); + return; + } + + string path = resolved.name; + for (Transform t = resolved.transform.parent; t != null; t = t.parent) + { + path = t.name + "/" + path; + } + + ParticleSystem first = resolved.GetComponentInChildren(true); + ParticleSystemRenderer psr = first != null ? first.GetComponent() : null; + Material material = psr != null ? psr.sharedMaterial : null; + + Jotunn.Logger.LogInfo( + $"[Skeleton] Prefab lookup '{wanted}' resolved to '{path}' " + + $"(root={resolved.transform.parent == null}) " + + $"particle='{(first != null ? first.name : "none")}' " + + $"material='{(material != null ? material.name : "none")}' " + + $"shader='{(material != null && material.shader != null ? material.shader.name : "none")}' " + + $"startColor={(first != null ? first.main.startColor.color.ToString() : "-")}"); + } + private static GameObject cachedFlameSource; private static bool flameSourceResolved; @@ -306,6 +349,50 @@ namespace RacesOfValheim return copy; } + /// + /// The fire aura's visual, and the reason it now has none. + /// + /// The aura itself (SkeletonRace.ApplyFireAura) burns everything inside FireAuraRadius from + /// Moder on and is untouched. What is gone is the way it used to try to show itself: + /// + /// PrefabManager.Cache.GetPrefab<GameObject>("vfx_smoke") + /// ?? PrefabManager.Cache.GetPrefab<GameObject>("vfx_surtling_death") + /// + /// NEITHER NAME EXISTS IN VALHEIM. Checked against the game's own asset manifest: there is no + /// vfx_smoke, and no surtling death effect under any spelling. In a plain install both + /// lookups came back null, no particle system was ever added, and this aura has never been + /// visible to anybody since the day it was written. + /// + /// A dead branch would be harmless if the lookup were harmless. It is not. PrefabManager.Cache + /// is, in Jotunn's own words, a "global cache of Unity Objects by asset name" built with + /// Resources.FindObjectsOfTypeAll, so it answers with anything in memory - including the + /// contents of every other mod's asset bundle - and its tie-break for a duplicate name ends + /// in "the newly discovered object replaces the cached one". A name vanilla does not use has + /// no vanilla candidate to beat, which leaves it a free slot for whoever ships one. + /// + /// Somebody shipped one. With Magic_Supremacy installed the lookup resolved to + /// 'EncounterCreatureRikoMountain_DO/vfx_smoke' - a CHILD node of one of that mod's + /// creatures, carrying the material 'club_trail_riko_DO' on the shader + /// 'Dreanegade/ParticleAlphaEmission'. A weapon trail, on an emissive shader, sprayed through + /// a 4.5m sphere centred on the player: the purple smoke around the burning skull this race + /// was reported for, on every client that could see the skeleton. + /// + /// So the aura is invisible deliberately now, which costs it nothing it ever had. To give it + /// a look, build it the way HeadFlame does: resolve a prefab under a name vanilla really uses + /// (ResolveFlameSource already holds one that works) and clone it through BorrowEffect, + /// instead of hand-rolling a particle system around a material taken by name. + /// + public static void EnsureFireAura(Player player, bool enable, ref GameObject aura) + { + // Nothing is built, so there is nothing to switch on either way - but a leftover is + // destroyed rather than left riding the player, which is what a session that swapped + // this assembly in mid-flight would otherwise be stuck with. + if (aura == null) return; + + Object.Destroy(aura); + aura = null; + } + /// /// One player's burning skull. Cosmetic only - it deals nothing and blocks nothing. /// diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index ecff680..686a831 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -173,8 +173,9 @@ namespace RacesOfValheim m_player.transform.localScale = targetScale; } - // Fire Aura VFX - EnsureFireAuraVFX(rules.FireAura); + // Deliberately draws nothing - see SkeletonVisuals.EnsureFireAura for why. Called + // anyway so reinstating the visual needs no change here. + SkeletonVisuals.EnsureFireAura(m_player, rules.FireAura, ref m_fireAuraVFX); } private void UpdateFenrirVisuals() @@ -263,7 +264,7 @@ namespace RacesOfValheim PlayerVisualHider.Show(playerVisual, "zdosync-revert"); if (m_currentFormInstance != null) Destroy(m_currentFormInstance); - EnsureFireAuraVFX(false); + SkeletonVisuals.EnsureFireAura(m_player, false, ref m_fireAuraVFX); DraughVisuals.EnsureAura(m_player, false, ref m_draughAuraVFX); m_skeletonHeadFlame.Apply(m_player, false); // Takes the crown off a Trenta who has died or changed race; a no-op for everyone else. @@ -283,70 +284,5 @@ namespace RacesOfValheim m_lastFenrirForm = ""; m_lastSkadiForm = ""; } - - private void EnsureFireAuraVFX(bool enable) - { - if (enable) - { - if (m_fireAuraVFX == null) - { - GameObject sourceVFX = Jotunn.Managers.PrefabManager.Cache.GetPrefab("vfx_smoke") ?? - Jotunn.Managers.PrefabManager.Cache.GetPrefab("vfx_surtling_death"); - - m_fireAuraVFX = new GameObject("SkeletonFireAuraVFX"); - m_fireAuraVFX.transform.SetParent(m_player.transform, false); - m_fireAuraVFX.transform.localPosition = new Vector3(0, 1f, 0); - - if (sourceVFX != null) - { - ParticleSystem[] pss = sourceVFX.GetComponentsInChildren(); - if (pss.Length > 0) - { - ParticleSystem ps = m_fireAuraVFX.AddComponent(); - var main = ps.main; - main.loop = true; - main.duration = 1f; - main.startLifetime = 1.5f; - main.startSize = new ParticleSystem.MinMaxCurve(1.5f, 3f); - main.startSpeed = 0f; - main.simulationSpace = ParticleSystemSimulationSpace.World; - - var renderer = m_fireAuraVFX.GetComponent(); - renderer.material = pss[0].GetComponent().material; - - var shape = ps.shape; - shape.shapeType = ParticleSystemShapeType.Sphere; - shape.radius = 4.5f; - - var emission = ps.emission; - emission.rateOverTime = 40f; - - var colorOverLifetime = ps.colorOverLifetime; - colorOverLifetime.enabled = true; - Gradient grad = new Gradient(); - grad.SetKeys( - new GradientColorKey[] { - new GradientColorKey(new Color(1f, 0.8f, 0.2f), 0.0f), - new GradientColorKey(new Color(1f, 0.3f, 0.0f), 0.5f), - new GradientColorKey(new Color(0.2f, 0.0f, 0.0f), 1.0f) - }, - new GradientAlphaKey[] { - new GradientAlphaKey(0.0f, 0.0f), - new GradientAlphaKey(0.6f, 0.2f), - new GradientAlphaKey(0.6f, 0.8f), - new GradientAlphaKey(0.0f, 1.0f) - } - ); - colorOverLifetime.color = grad; - } - } - } - if (!m_fireAuraVFX.activeSelf) m_fireAuraVFX.SetActive(true); - } - else - { - if (m_fireAuraVFX != null && m_fireAuraVFX.activeSelf) m_fireAuraVFX.SetActive(false); - } - } } } From e75c7072c4241f9f4b24051fa66deeebb8659f60 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 00:20:02 +0200 Subject: [PATCH 056/290] fix(prefabs): replace every lookup name that does not exist in vanilla An audit of all 59 prefab names the mod resolves, against the game's own asset manifests, found nine that are not in Valheim at all. A name vanilla does not use has no vanilla candidate to beat in Jotunn's name cache, so it is a free slot for whoever ships one - which is how another mod's weapon trail became the Skeleton's fire aura in 00d4fd6. Eight of the nine failed in silence, which is why none of them was ever reported: vfx_corpse_destruction -> _medium, _large for the Muspell. The puff that covers a transformation. Fenrir and Skadi at least had their sparks; the Muspell swapped bodies in plain view with nothing at all. vfx_surtling_death -> vfx_wraith_death for the Aswid's Mist Form, which reads as mist by construction and is the same creature the form already borrows its Visual from; vfx_corpse_destruction_medium for the thrall, where nothing is misty. Vanilla has no surtling death effect under any spelling. TrophyTroll -> TrophyForestTroll. TrophyBat -> TrophyDeathsquito. Vanilla ships no bat trophy, so the Aswid's two status effects and its radial entry had no icon. vfx_smoke -> gone. It was the Trenta's fallback for Purple Rain's particle material behind Greydwarf_Shaman, and the day the Shaman failed to resolve it would have worn whatever a mod supplies. Purple Rain is purple by design, so nobody would ever have reported it. The ninth did not fail in silence. vfx_OozeHit was passed to Instantiate unguarded, so every successful Draugh parry threw ArgumentException and took the North Wind nova below it down as well. It is vfx_blob_hit. Co-Authored-By: Claude Opus 5 --- JotunnModStub/Aswid/AswidRace.cs | 16 ++++++++++++++-- JotunnModStub/Aswid/AswidStatusEffects.cs | 4 ++-- JotunnModStub/Aswid/AswidThrall.cs | 5 ++++- .../Draugh/DraughProgressionPatches.cs | 12 ++++++++++-- JotunnModStub/Fenrir/FenrirRace.cs | 5 ++++- JotunnModStub/RaceRadial.cs | 2 +- JotunnModStub/RacesOfValheim.cs | 5 ++++- JotunnModStub/Skadi/SkadiRace.cs | 5 ++++- JotunnModStub/Trenta/TrentaAbilities.cs | 18 ++++++++++++++++-- JotunnModStub/Trenta/TrentaMuspell.cs | 7 ++++++- 10 files changed, 65 insertions(+), 14 deletions(-) diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index 3078f06..b1f1cd2 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -708,7 +708,17 @@ namespace RacesOfValheim { isTransformingSequence = true; - GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("vfx_surtling_death"); + // WAS "vfx_surtling_death", WHICH IS NOT A PREFAB IN THIS GAME. The surtling has no + // death effect under any spelling, so this resolved to nothing and the Mist Form has + // always appeared and disappeared with no puff at all - both here and in + // RevertMistFormRoutine. Kept as a note rather than a fallback: a name vanilla does not + // use is a free slot for any mod that ships one, which is how another mod's weapon trail + // became the Skeleton's fire aura (see SkeletonVisuals.EnsureFireAura). + // + // The Wraith's own death effect reads as mist by construction, which is what this wanted, + // and it is already the right creature: the form borrows the Wraith's Visual a few lines + // below. If the look wants changing, that effect is the thing to alter. + GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("vfx_wraith_death"); if (poofPrefab != null) Instantiate(poofPrefab, Player.m_localPlayer.transform.position, Quaternion.identity); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_MistForm".GetStableHashCode(), true); @@ -763,7 +773,9 @@ namespace RacesOfValheim { isTransformingSequence = true; - GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("vfx_surtling_death"); + // The same puff as going in - see TransformIntoMistRoutine for why the old name never + // resolved to anything. + GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("vfx_wraith_death"); if (poofPrefab != null) Instantiate(poofPrefab, Player.m_localPlayer.transform.position, Quaternion.identity); Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); diff --git a/JotunnModStub/Aswid/AswidStatusEffects.cs b/JotunnModStub/Aswid/AswidStatusEffects.cs index f87e9bb..ac3ab3f 100644 --- a/JotunnModStub/Aswid/AswidStatusEffects.cs +++ b/JotunnModStub/Aswid/AswidStatusEffects.cs @@ -114,13 +114,13 @@ namespace RacesOfValheim { var aswidStats = ScriptableObject.CreateInstance(); aswidStats.name = "SE_AswidStats"; - aswidStats.m_icon = PrefabManager.Cache.GetPrefab("TrophyBat")?.m_itemData.m_shared.m_icons[0]; + aswidStats.m_icon = PrefabManager.Cache.GetPrefab("TrophyDeathsquito")?.m_itemData.m_shared.m_icons[0]; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(aswidStats, fixReference: false)); var batForm = ScriptableObject.CreateInstance(); batForm.name = "SE_BatForm"; - batForm.m_icon = PrefabManager.Cache.GetPrefab("TrophyBat")?.m_itemData.m_shared.m_icons[0]; + batForm.m_icon = PrefabManager.Cache.GetPrefab("TrophyDeathsquito")?.m_itemData.m_shared.m_icons[0]; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(batForm, fixReference: false)); diff --git a/JotunnModStub/Aswid/AswidThrall.cs b/JotunnModStub/Aswid/AswidThrall.cs index 816517e..35d1562 100644 --- a/JotunnModStub/Aswid/AswidThrall.cs +++ b/JotunnModStub/Aswid/AswidThrall.cs @@ -117,7 +117,10 @@ namespace RacesOfValheim m_ai.SetFollowTarget(user.gameObject); } - GameObject vfx = ZNetScene.instance.GetPrefab("vfx_surtling_death"); + // "vfx_surtling_death" was asked for here and is not a prefab in this game, so dominating + // a creature happened with no effect at all. The generic body-sized puff, rather than the + // Wraith's mist the Mist Form wears: nothing about domination is misty. + GameObject vfx = ZNetScene.instance.GetPrefab("vfx_corpse_destruction_medium"); if (vfx) Instantiate(vfx, m_character.transform.position, Quaternion.identity); user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} dominated!"); diff --git a/JotunnModStub/Draugh/DraughProgressionPatches.cs b/JotunnModStub/Draugh/DraughProgressionPatches.cs index 8162551..f56ce0f 100644 --- a/JotunnModStub/Draugh/DraughProgressionPatches.cs +++ b/JotunnModStub/Draugh/DraughProgressionPatches.cs @@ -98,8 +98,16 @@ namespace RacesOfValheim attacker.ApplyDamage(poisonSplash, true, false); - // Visual effect for splash - UnityEngine.Object.Instantiate(ZNetScene.instance.GetPrefab("vfx_OozeHit"), attacker.GetCenterPoint(), Quaternion.identity); + // Visual effect for splash. "vfx_OozeHit" is not a prefab in this game - + // the blob's hit effect is vfx_blob_hit - and this was the one dead name + // in the mod that was passed to Instantiate unguarded, so every + // successful parry threw ArgumentException here and took the North Wind + // nova below down with it. + GameObject splashVfx = ZNetScene.instance.GetPrefab("vfx_blob_hit"); + if (splashVfx != null) + { + UnityEngine.Object.Instantiate(splashVfx, attacker.GetCenterPoint(), Quaternion.identity); + } // Stage 5: North Wind (AoE Frost) if (state >= 5) diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index 784cffd..a98f6d3 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -316,7 +316,10 @@ namespace RacesOfValheim { if (Player.m_localPlayer == null) return; Vector3 pos = Player.m_localPlayer.transform.position + Vector3.up; - GameObject smoke = PrefabManager.Cache.GetPrefab("vfx_corpse_destruction"); + // Vanilla's puff carries a size suffix and has no bare "vfx_corpse_destruction" - so + // this used to resolve to nothing and the body swap happened in plain view, with only + // the sparks below to soften it. _medium is the one built for a body this size. + GameObject smoke = PrefabManager.Cache.GetPrefab("vfx_corpse_destruction_medium"); if (smoke != null) Instantiate(smoke, pos, Quaternion.identity); GameObject sparks = PrefabManager.Cache.GetPrefab("vfx_HitSparks"); diff --git a/JotunnModStub/RaceRadial.cs b/JotunnModStub/RaceRadial.cs index f381421..3e4e0da 100644 --- a/JotunnModStub/RaceRadial.cs +++ b/JotunnModStub/RaceRadial.cs @@ -49,7 +49,7 @@ namespace RacesOfValheim new Entry { Race = "Fenrir", Label = "Cultist Form", Key = () => FenrirConfig.CultistFormKey, Icon = "TrophyCultist" }, new Entry { Race = "Fenrir", Label = "Howl", Key = () => FenrirConfig.HowlKey, Icon = "TrophyUlv" }, - new Entry { Race = "Aswid", Label = "Bat Form", Key = () => AswidConfig.BatFormKey, Icon = "TrophyBat" }, + new Entry { Race = "Aswid", Label = "Bat Form", Key = () => AswidConfig.BatFormKey, Icon = "TrophyDeathsquito" }, new Entry { Race = "Aswid", Label = "Mist Form", Key = () => AswidConfig.MistFormKey, Icon = "TrophyWraith" }, new Entry { Race = "Aswid", Label = "Eclipse", Key = () => AswidConfig.EclipseKey, Icon = "TrophyFader" }, new Entry { Race = "Aswid", Label = "Tame", Key = () => AswidConfig.TameKey, Icon = "TrophyWolf" }, diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 7061303..0235ed9 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -695,7 +695,10 @@ namespace RacesOfValheim private Sprite GetTrolIcon() { GameObject trophyPrefab = PrefabManager.Cache.GetPrefab("TrophyFrostTroll")?.gameObject; - if (trophyPrefab == null) trophyPrefab = PrefabManager.Cache.GetPrefab("TrophyTroll")?.gameObject; + // TrophyForestTroll, not "TrophyTroll": the latter is not a prefab in this game, so the + // fallback could never fire and the name sat here as a free slot for any mod that + // happens to ship one. See SkeletonVisuals.EnsureFireAura for what that costs. + if (trophyPrefab == null) trophyPrefab = PrefabManager.Cache.GetPrefab("TrophyForestTroll")?.gameObject; if (trophyPrefab != null) { ItemDrop trophyDrop = trophyPrefab.GetComponent(); diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index af64056..cfe78d4 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -690,7 +690,10 @@ namespace RacesOfValheim if (Player.m_localPlayer == null) return; Vector3 pos = Player.m_localPlayer.transform.position + Vector3.up; - GameObject smoke = PrefabManager.Cache.GetPrefab("vfx_corpse_destruction"); + // _medium, not a bare "vfx_corpse_destruction": that name is not in the game, so this + // resolved to nothing and the swap into a drake happened in plain view. See + // FenrirRace.SpawnPoofEffect for the same fix. + GameObject smoke = PrefabManager.Cache.GetPrefab("vfx_corpse_destruction_medium"); if (smoke != null) Instantiate(smoke, pos, Quaternion.identity); GameObject sparks = PrefabManager.Cache.GetPrefab("vfx_HitSparks"); diff --git a/JotunnModStub/Trenta/TrentaAbilities.cs b/JotunnModStub/Trenta/TrentaAbilities.cs index 8e8e3c9..4380e28 100644 --- a/JotunnModStub/Trenta/TrentaAbilities.cs +++ b/JotunnModStub/Trenta/TrentaAbilities.cs @@ -233,13 +233,27 @@ namespace RacesOfValheim if (!vfxMaterialResolved) { vfxMaterialResolved = true; - GameObject source = PrefabManager.Cache.GetPrefab(TrentaConfig.PurpleRainVfxSourcePrefab) - ?? PrefabManager.Cache.GetPrefab("vfx_smoke"); + // The "vfx_smoke" fallback that used to sit here is gone. That name is not a prefab + // in this game, so it could only ever resolve to another mod's object - and with + // Magic_Supremacy installed it resolved to a weapon trail, which is what put purple + // smoke on the Skeleton (see SkeletonVisuals.EnsureFireAura). Purple Rain is purple + // by design, so the same theft here would never have looked wrong enough to report. + // + // Losing the fallback means a miss is now a miss. Said out loud, because the resolve + // is cached for the session either way and a silent one would be invisible: 1.0 + // loads creature assets lazily, so the Shaman is not guaranteed to be in memory. + GameObject source = PrefabManager.Cache.GetPrefab(TrentaConfig.PurpleRainVfxSourcePrefab); if (source != null) { ParticleSystemRenderer sourceRenderer = source.GetComponentInChildren(true); if (sourceRenderer != null) cachedVfxMaterial = sourceRenderer.material; } + else + { + Jotunn.Logger.LogWarning( + $"[Trenta] Purple Rain: '{TrentaConfig.PurpleRainVfxSourcePrefab}' not in the prefab " + + "cache; falling back to Unity's default particle material for this session."); + } } GameObject vfx = new GameObject("TrentaPurpleRainVFX"); diff --git a/JotunnModStub/Trenta/TrentaMuspell.cs b/JotunnModStub/Trenta/TrentaMuspell.cs index 01157a9..6f7fbf6 100644 --- a/JotunnModStub/Trenta/TrentaMuspell.cs +++ b/JotunnModStub/Trenta/TrentaMuspell.cs @@ -141,7 +141,12 @@ namespace RacesOfValheim if (player == null) return; Vector3 pos = player.transform.position + Vector3.up; - GameObject smoke = PrefabManager.Cache.GetPrefab("vfx_corpse_destruction"); + // _large rather than the _medium the other two forms use: the Muspell is the biggest + // thing this mod turns a player into, and a body-sized puff does not cover it. A bare + // "vfx_corpse_destruction" is not a prefab in this game, so until now the Muspell was + // the one transformation with no covering effect of any kind - Fenrir and Skadi at least + // had their sparks. + GameObject smoke = PrefabManager.Cache.GetPrefab("vfx_corpse_destruction_large"); if (smoke != null) Object.Instantiate(smoke, pos, Quaternion.identity); } From 276ff9383401fd5733e7dda01d94c81a967c355b Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 00:20:16 +0200 Subject: [PATCH 057/290] feat(draugh): add the Human Meat item the Bonemass perk has always promised Two places in the mod used an item called "HumanMeat" and nothing registered it: the drop in Draugh_DeathAura_Patch and the "fatal to the living" block in DraughFoodPatches. Both check for null, so the perk has been a no-op since it was written - a README line with no item behind it. The two consumers are unchanged; what was missing was the producer. Built from two vanilla items, one for the look and one for the numbers. RawMeat gives the model and icon, because that is what a piece of somebody looks like and because raw flesh is the Draugh's whole food identity. BloodPudding gives the nourishment, copied field by field at start-up rather than written down here, so the item stays balanced against the game's own progression and follows any change made to it. Blood Pudding's stamina goes onto health and stamina is left at zero. A Draugh does not use stamina, so nourishment spent there is thrown away: the food slot would read full while giving the race half of what it cost. RawMeat is a Material in vanilla - raw meat is not edible - so m_itemType is forced to Consumable. That is the one assumption worth knowing about, and the registration logs what it produced so a silent failure cannot hide. The meat is tinted on copies of the materials, never the shared ones, or every piece of raw meat in the world would darken with it. The README said humanoids drop it. The patch is on Player.OnDeath and always was, so the line now says what the code does: a player who dies inside the death aura, the Draugh included. Co-Authored-By: Claude Opus 5 --- JotunnModStub/Draugh/DraughConfig.cs | 5 + JotunnModStub/Draugh/DraughHumanMeat.cs | 140 ++++++++++++++++++++++++ JotunnModStub/Draugh/DraughRace.cs | 4 + README.md | 2 +- 4 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 JotunnModStub/Draugh/DraughHumanMeat.cs diff --git a/JotunnModStub/Draugh/DraughConfig.cs b/JotunnModStub/Draugh/DraughConfig.cs index 8f3c8fe..8aa0a88 100644 --- a/JotunnModStub/Draugh/DraughConfig.cs +++ b/JotunnModStub/Draugh/DraughConfig.cs @@ -33,6 +33,7 @@ namespace RacesOfValheim // ─── Undead Fortitude (tier 4+: crit on staggered, death aura) ────────── public static ConfigEntry StaggerCritMultiplier; public static ConfigEntry DeathAuraRadius; + public static ConfigEntry HumanMeatNourishmentMultiplier; // ─── North Wind (tier 5+: AoE frost on parry, on the same cooldown) ────── public static ConfigEntry NorthWindCooldown; @@ -79,6 +80,10 @@ namespace RacesOfValheim new ConfigDescription("Multiplies physical damage dealt to staggered enemies, tier 4+.", new AcceptableValueRange(1f, 3f))); DeathAuraRadius = config.Bind(fortitude, "Death Aura Radius", 100f, new ConfigDescription("Meters within which an ally's death drops Human Meat for you, tier 4+.", new AcceptableValueRange(10f, 300f))); + // A multiplier rather than absolute numbers: Human Meat is built from Blood Pudding's own + // nourishment at start-up, and those are the game's values, not ours to hardcode. + HumanMeatNourishmentMultiplier = config.Bind(fortitude, "Human Meat Nourishment Multiplier", 1f, + new ConfigDescription("Scales Human Meat's health, stamina and eitr against the Blood Pudding it is built from. Read once at start-up.", new AcceptableValueRange(0.1f, 3f))); const string northWind = "Draugh - North Wind"; NorthWindCooldown = config.Bind(northWind, "Cooldown", 20f, diff --git a/JotunnModStub/Draugh/DraughHumanMeat.cs b/JotunnModStub/Draugh/DraughHumanMeat.cs new file mode 100644 index 0000000..6ba3293 --- /dev/null +++ b/JotunnModStub/Draugh/DraughHumanMeat.cs @@ -0,0 +1,140 @@ +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Human Meat, the Bonemass-tier reward: an ally who dies near a Draugh leaves a piece of + /// themselves behind, and only a Draugh can stomach it. + /// + /// THIS ITEM DID NOT EXIST. Two places in the mod already used it - the drop in + /// DraughProgressionPatches.Draugh_DeathAura_Patch and the "fatal to the living" block in + /// DraughFoodPatches - and both looked it up by the name "HumanMeat", which nothing registered. + /// So the drop never happened and the block never fired: a perk the README has promised since + /// 1.4 with no item behind it. The two consumers are unchanged; what was missing was the + /// producer. + /// + /// BUILT FROM TWO VANILLA ITEMS, one for the look and one for the numbers: + /// + /// RawMeat gives the clone its model and icon, because that is what a piece of somebody looks + /// like, and because the Draugh's whole food identity is raw flesh. + /// + /// BloodPudding gives the nourishment, copied field by field at start-up rather than written + /// down here. Blood Pudding is a real cooked food in the game's own progression, so its + /// numbers are balanced against the rest of it, and reading them means this item follows any + /// change the game makes to them. DraughConfig.HumanMeatNourishmentMultiplier scales them. + /// Its stamina is folded into health rather than copied across - see the note further down. + /// + /// RawMeat is a Material in vanilla - raw meat is not edible - so m_itemType is forced to + /// Consumable. That is the one assumption in here worth knowing about: the alternative, which + /// DraughRace.CreateModAssets uses for its EdibleUncooked_ items, is to clone the COOKED item and + /// dress it as the raw one, which gets consumability for free but keeps the cooked model. If the + /// game ever refuses to eat this, that is the fallback, and the log line below prints exactly + /// what was produced so it can be told apart from a missing prefab. + /// + internal static class DraughHumanMeat + { + /// The name the two consumers look it up by. Changing it breaks both. + public const string PrefabName = "HumanMeat"; + + private const string LookSource = "RawMeat"; + private const string NourishmentSource = "BloodPudding"; + + /// + /// Darkens the meat and pulls it towards blood, so a stack of Human Meat is not mistaken for + /// the deer meat it is built from. Multiplied into the material's own colour, so it darkens + /// whatever the texture already is rather than replacing it. + /// + private static readonly Color Tint = new Color(0.62f, 0.34f, 0.38f, 1f); + + /// + /// Called from DraughRace.CreateModAssets, which is to say while vanilla prefabs are + /// available and before anything can ask for this item. + /// + public static void Register() + { + ItemDrop look = FindItem(LookSource); + ItemDrop nourishment = FindItem(NourishmentSource); + + if (look == null || nourishment == null) + { + // Nothing is registered rather than a half-built item: the two consumers both check + // for null, so no meat is a quiet no-op, while a nameless inedible one is not. + Jotunn.Logger.LogWarning( + $"[Draugh] Human Meat not registered: '{LookSource}' " + + $"{(look == null ? "missing" : "ok")}, '{NourishmentSource}' " + + $"{(nourishment == null ? "missing" : "ok")}."); + return; + } + + CustomItem item = new CustomItem(PrefabName, LookSource); + ItemDrop.ItemData.SharedData shared = item.ItemDrop.m_itemData.m_shared; + ItemDrop.ItemData.SharedData source = nourishment.m_itemData.m_shared; + + shared.m_name = "Human Meat"; + shared.m_description = "A piece of somebody. The living gag on it; you do not."; + + // Raw meat is a Material in vanilla, so none of the food fields below would be read + // without this. + shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable; + + // BLOOD PUDDING'S STAMINA GOES ONTO HEALTH, AND STAMINA IS LEFT AT ZERO. A Draugh does + // not use stamina, so nourishment spent there is nourishment thrown away - the food + // slot would look full while giving the race half of what it cost. Adding the two + // together keeps the item worth the same as the pudding it is balanced against, which + // is the point of reading the pudding at all. + float scale = DraughConfig.HumanMeatNourishmentMultiplier.Value; + shared.m_food = (source.m_food + source.m_foodStamina) * scale; + shared.m_foodStamina = 0f; + shared.m_foodEitr = source.m_foodEitr * scale; + shared.m_foodRegen = source.m_foodRegen; + shared.m_foodBurnTime = source.m_foodBurnTime; + shared.m_maxStackSize = source.m_maxStackSize; + shared.m_consumeStatusEffect = source.m_consumeStatusEffect; + + Recolour(item.ItemDrop.gameObject); + + ItemManager.Instance.AddItem(item); + + Jotunn.Logger.LogInfo( + $"[Draugh] Human Meat registered from '{LookSource}' + '{NourishmentSource}': " + + $"type={shared.m_itemType} food={shared.m_food:F0} stamina={shared.m_foodStamina:F0} " + + $"eitr={shared.m_foodEitr:F0} regen={shared.m_foodRegen:F0} " + + $"burn={shared.m_foodBurnTime:F0}s stack={shared.m_maxStackSize}."); + } + + private static ItemDrop FindItem(string prefabName) + { + GameObject prefab = PrefabManager.Cache.GetPrefab(prefabName); + return prefab != null ? prefab.GetComponent() : null; + } + + /// + /// Tints the clone's own materials, on copies. + /// + /// The clone's renderers still point at the vanilla RawMeat materials, which are shared with + /// every piece of raw meat in the world - writing a colour into one of those would tint the + /// lot. Each renderer gets its own copy instead, which this prefab then owns. + /// + private static void Recolour(GameObject root) + { + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + Material[] materials = renderer.sharedMaterials; + if (materials == null) continue; + + for (int i = 0; i < materials.Length; i++) + { + if (materials[i] == null) continue; + + Material copy = new Material(materials[i]); + if (copy.HasProperty("_Color")) copy.color = copy.color * Tint; + materials[i] = copy; + } + + renderer.sharedMaterials = materials; + } + } + } +} diff --git a/JotunnModStub/Draugh/DraughRace.cs b/JotunnModStub/Draugh/DraughRace.cs index a9f130f..9362f5c 100644 --- a/JotunnModStub/Draugh/DraughRace.cs +++ b/JotunnModStub/Draugh/DraughRace.cs @@ -23,6 +23,10 @@ namespace RacesOfValheim // Draugr is ever set up as a bench. DraughSpawner.Register(); + // The Bonemass-tier drop. Registered here for the same reason as the pile: two places in + // the mod already look it up by name, and until now nothing created it. + DraughHumanMeat.Register(); + // Generate EdibleUncooked prefabs for Draugh raw food logic foreach (var mapping in DraughFoodPatches.rawToCookedMapping) { diff --git a/README.md b/README.md index 010b03d..d3141fa 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ Three races grow a pair of their own, refused by the holster key and never dragg - **Base:** Born Dead, Buried Alive. -20% Slash/Pierce/Blunt; +50% Fire/Spirit taken. Poison resistant. Eats only raw flesh, eyes, entrails, blood. Swamp undead ignore you. - **Eikthyr:** Immune to Wet, swim faster, regen when wet/swimming. - **Elder:** Toxic Trace – attacks poison over time. -- **Bonemass:** Flesh and the Power It Holds – humanoids drop Human Meat food. Corpse Run permanently active. +- **Bonemass:** Flesh and the Power It Holds – a player who dies inside your death aura leaves Human Meat behind, yourself included. Only a Draugh can eat it. Corpse Run permanently active. - **Moder:** Parrying unleashes freezing nova (20s CD). - **Yagluth:** Zombie Ritual – fatal damage = ghost state, immune to damage, Eitr drains, die if Eitr hits 0. Raw food gives Eitr. - **Queen:** Swarm of Terror – being hit summons 2 Seeker Broods to fight for you. From 9907cae29237bb296d86600ea39902fe2ee9225b Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 00:20:31 +0200 Subject: [PATCH 058/290] fix(fenrir): give the forms a voice, and stop the sounds writing to the save Every sound the Fenrir forms played was looked up by a name, and most of those names are not prefabs in this game. The chains hid it: PlaySFX walks its arguments and stops at the first that resolves, so a claw that asked for "sfx_fenring_attack", "sfx_fenring_attack_claw", "sfx_wolf_attack" had a Fenring swinging with a wolf's voice through a fallback nobody noticed. The cultist's double claw asked for three dead names in a row and was silent from the day it was written. The creatures do have their own sounds. The forms now use them: sfx_fenring_claw_start for the swing, sfx_fenring_claw_hit for the landing, sfx_fenring_fireclaw to open the fire breath. The Ulv keeps the wolf's, since vanilla ships it nothing but sfx_ulv_death. THE HOWL WAS NEVER A PREFAB TO LOOK UP. It is an AnimationEvent inside the wolf's 'C_Hawl' clip, firing at 0.39s with the sound handed over as an object reference - and a player in wolf form idles through that clip and howls out loud already, with the game's own AnimationEffect doing the work. Three spellings of one word are why this took so long to find: the clip is 'C_Hawl', the sound is 'sfx_wolf_haul', and the mod was looking for 'sfx_wolf_howl', the only correct spelling of the three and the only one that does not exist. The Fenring has no howl of its own at all, so it borrows the wolf's over its Taunt. The jump attack's impact moved to where the jump lands, next to the damage, instead of firing before the dash while the form is still standing. FenrirCreatureSound.Spawn is the other half. Some vanilla sound prefabs carry a ZNetView - sfx_fenring_alerted does - and one that wakes with no init ZDO writes a persistent record into the world, once per swing. Spawning now runs inside ZNetView.StartGhostInit, the game's own answer, so no ZDO is made. All nine sound spawns in these forms go through it. sfx_fenring_howl resolves to an ordinary sound prefab and hard-exits the process when spawned on its own. It is named in a Suspect set, described in the log and never instantiated, because a name nobody records is a name somebody adds back. Co-Authored-By: Claude Opus 5 --- JotunnModStub/Fenrir/FenrirBehaviors.cs | 286 ++++++++++++++++----- JotunnModStub/Fenrir/FenrirRace.cs | 62 ++++- JotunnModStub/Fenrir/FormAnimEventSound.cs | 89 +++++++ 3 files changed, 363 insertions(+), 74 deletions(-) create mode 100644 JotunnModStub/Fenrir/FormAnimEventSound.cs diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 2d1180c..380f47c 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -1,4 +1,5 @@ using System.Collections; +using System.Collections.Generic; using BepInEx; using HarmonyLib; using Jotunn.Configs; @@ -10,32 +11,202 @@ using UnityEngine.UI; // Added for UI namespace RacesOfValheim { /// - /// Howl vocalisation, borrowed from the real creature instead of guessed at. Wolves and their - /// kin do not carry a standalone "sfx_wolf_howl"-style prefab that PlaySFX's - /// PrefabManager.Cache lookup could ever find - dumpdverger's own hierarchy dump for - /// Fenring_Cultist shows no ZSFX anywhere on it. + /// The voice of the creature a Fenrir is wearing. /// - /// BaseAI.m_idleSound was the first guess and was wrong in a quieter way: it is real, but it - /// is the creature's passive ambient noise (DoIdleSound, on a timer while it is doing nothing - /// in particular) - a small grunt, not a howl, and it played back sounding like whatever - /// generic "the form did something" cue the transformation itself already uses. What a - /// creature actually vocalises WHEN IT SPOTS SOMETHING is BaseAI.m_alertedEffects, fired from - /// SetAlerted(true) - reading that off the real "Fenring"/"Fenring_Cultist" prefab and calling - /// Create() plays the same aggressive bark the creature itself makes going on alert. + /// THE HISTORY MATTERS HERE, because two reasonable-sounding answers were tried and both were + /// silent, and the note that used to sit in this place asserted the second one worked. + /// + /// "sfx_wolf_howl" was the first guess. There is no such prefab in the game. + /// + /// BaseAI.m_idleSound was the second. Real, but it is the creature's ambient grunt on a timer + /// (DoIdleSound) - the wrong sound even when it plays. + /// + /// BaseAI.m_alertedEffects was the third, on the reasoning that a creature's alert bark is the + /// nearest thing it has to a howl and that these creatures carry no standalone ZSFX at all. + /// That last part is simply not true - see the table below - and calling Create() on a PREFAB's + /// EffectList produced nothing audible in testing while instantiating a sound prefab directly, + /// two lines away in the same file, worked. So the alert-list route is now the last resort + /// rather than the plan. + /// + /// What actually plays is a real prefab, instantiated the same way the claw and the landing thud + /// are. Every name below was checked against the game's own asset manifest. Note "sfx_wolf_haul", + /// which is the wolf's howl under the game's own misspelling - that single typo is most of why + /// nobody found it by searching for "howl". /// internal static class FenrirCreatureSound { + /// + /// Per creature, best first, and every name checked against the game's own asset manifest. + /// The Ulv has no vocalisation of its own in vanilla beyond sfx_ulv_death, so it borrows the + /// wolf's. "sfx_wolf_haul" is the wolf's howl under the game's own misspelling, which is most + /// of why nobody found it by searching for "howl". + /// + /// THE FENRING BORROWS THE WOLF'S HOWL. It has none of its own: its 19 clips carry no howl, + /// and its taunt fires no sound event at all. Its own "sfx_fenring_howl" is in Suspect below + /// and must not be spawned. Its alert bark stays as the second entry - that is its real voice, + /// just not an ululation. + /// + private static readonly Dictionary Howls = new Dictionary + { + { "Wolf", new[] { "sfx_wolf_haul", "sfx_wolf_alerted" } }, + { "Ulv", new[] { "sfx_wolf_haul", "sfx_wolf_alerted" } }, + { "Fenring", new[] { "sfx_wolf_haul", "sfx_fenring_alerted" } }, + { "Fenring_Cultist", new[] { "sfx_wolf_haul", "sfx_fenring_alerted" } }, + }; + + /// The cue that opens the cultist's fire breath: its own fire-claw snarl. + private static readonly string[] FireRoar = { "sfx_fenring_fireclaw" }; + + /// + /// PREFABS THAT RESOLVE AND MUST NOT BE INSTANTIATED. + /// + /// "sfx_fenring_howl" exists, resolves through the cache to a real GameObject, and takes the + /// process down with it - not an exception BepInEx can catch, a hard exit. It killed the game + /// the first time a Fenrir transformation reached it, and the only reason we know which prefab + /// did it is that its log line had been flushed a moment before. + /// + /// Best guess is that it is not a standalone sound at all but a node belonging to the + /// creature's own rig, fired by that creature's animator and meaningless off it. Described + /// here rather than deleted, because the description is what will settle that - and because a + /// name nobody records is a name somebody adds back. + /// + private static readonly HashSet Suspect = new HashSet { "sfx_fenring_howl" }; + + // Said once per name, because "the howl is silent" cost two rounds of testing to notice and + // the log said nothing either time. + private static readonly HashSet logged = new HashSet(); + public static void PlayHowl(string sourcePrefabName, Vector3 position) + { + string[] names; + if (Howls.TryGetValue(sourcePrefabName, out names) && Play(names, position, sourcePrefabName)) + { + return; + } + + // A form not in the table, or one whose whole list was refused, still gets a voice. + PlayAlertedEffects(sourcePrefabName, position); + } + + public static void PlayFireRoar(Vector3 position) + { + if (!Play(FireRoar, position, "fire roar")) PlayAlertedEffects("Fenring_Cultist", position); + } + + /// Instantiates the first name that resolves and is safe. True if anything played. + private static bool Play(string[] prefabNames, Vector3 position, string label) + { + foreach (string name in prefabNames) + { + GameObject prefab = PrefabManager.Cache.GetPrefab(name); + if (prefab == null) continue; + + // BEFORE the Instantiate, not after. Anything that goes the way sfx_fenring_howl went + // now names itself, and says what it is, while the log can still be written. + if (logged.Add(name)) Describe(label, name, prefab); + + if (Suspect.Contains(name)) continue; + + // A parented object is not a prefab, it is a node inside somebody else's hierarchy. + // Spawning one on its own is the thing this route is suspected of getting wrong. + if (prefab.transform.parent != null) continue; + + Spawn(prefab, position); + return true; + } + + return false; + } + + /// + /// Spawns a sound prefab without letting it write itself into the save. + /// + /// SOME VANILLA SOUND PREFABS CARRY A ZNetView. "sfx_fenring_alerted" is one - the Describe + /// line below printed it, which is how this was noticed. A ZNetView that wakes with no init + /// ZDO calls ZDOMan.CreateNewZDO at its position, marks itself persistent, stamps itself with + /// the prefab hash and registers with the scene. On a sound played every time somebody howls + /// or swings a claw, that is one persistent "there is a noise here" record per swing, saved + /// with the world. It is the same bug that left burnt-in torches in people's worlds; the long + /// version is on SkeletonVisuals.BorrowEffect. + /// + /// ZNetView.StartGhostInit is the game's own answer, not ours: between the two calls a + /// ZNetView comes up with no ZDO at all. Cheaper and far less invasive than stripping the + /// component off a copy, and free on the prefabs that carry no ZNetView. + /// + /// The finally matters. Leaving ghost init switched on because an Instantiate threw would + /// break every ZNetView created afterwards, for the rest of the session. + /// + public static void Spawn(GameObject prefab, Vector3 position) + { + if (prefab == null) return; + + ZNetView.StartGhostInit(); + try + { + Object.Instantiate(prefab, position, Quaternion.identity); + } + finally + { + ZNetView.FinishGhostInit(); + } + + // NOT FOLLOWED BY A Play() CALL, and that took a while to establish. ZSFX is ticked by + // CustomUpdate rather than Unity's Update, so it starts on a later frame: reading + // AudioSource.isPlaying straight after this says false for every sound there is, and + // nudging Play() in on top of a prefab whose own m_playOnAwake is already set is as + // likely to interrupt it as to help. Every sound this mod spawns self-starts. If one ever + // turns up that does not - m_playOnAwake false, checked with "dumpanim " - that is + // the moment to call ZSFX.Play() here, and not before. + } + + /// + /// What a resolved sound actually is: where it sits in its own hierarchy, and what it carries. + /// The root flag is the one to read first - see Play. + /// + private static void Describe(string label, string name, GameObject prefab) + { + string path = prefab.name; + for (Transform t = prefab.transform.parent; t != null; t = t.parent) path = t.name + "/" + path; + + List parts = new List(); + foreach (Component comp in prefab.GetComponentsInChildren(true)) + { + if (comp != null && !(comp is Transform)) parts.Add(comp.GetType().Name); + } + + Jotunn.Logger.LogInfo( + $"[FenrirForm] {label}: '{name}' -> '{path}' root={prefab.transform.parent == null} " + + $"suspect={Suspect.Contains(name)} carries=[{string.Join(", ", parts.ToArray())}]"); + } + + /// + /// The creature's alert EffectList, kept as a fallback. Not trusted as the primary any more: + /// it is what left every howl in the mod silent. + /// + private static void PlayAlertedEffects(string sourcePrefabName, Vector3 position) { GameObject source = PrefabManager.Cache.GetPrefab(sourcePrefabName); BaseAI ai = source != null ? source.GetComponent() : null; - if (ai == null || ai.m_alertedEffects == null) + if (ai == null || ai.m_alertedEffects == null || ai.m_alertedEffects.m_effectPrefabs == null || + ai.m_alertedEffects.m_effectPrefabs.Length == 0) { - Jotunn.Logger.LogWarning($"[FenrirForm] No BaseAI.m_alertedEffects found on '{sourcePrefabName}'."); + if (logged.Add(sourcePrefabName + "-alerted")) + { + Jotunn.Logger.LogWarning( + $"[FenrirForm] No sound for '{sourcePrefabName}': nothing from its table was " + + "playable and its BaseAI.m_alertedEffects is empty."); + } return; } ai.m_alertedEffects.Create(position, Quaternion.identity); + if (logged.Add(sourcePrefabName + "-alerted")) + { + Jotunn.Logger.LogWarning( + $"[FenrirForm] '{sourcePrefabName}': fell through to BaseAI.m_alertedEffects " + + $"({ai.m_alertedEffects.m_effectPrefabs.Length} effect(s)). This route has been " + + "silent before - if you hear nothing, that is why."); + } } } @@ -193,8 +364,9 @@ namespace RacesOfValheim flames = FenrirAttackSync.SpawnFlames(player); // The roar that opens the breath, once per start, the same cue the owner hears. - GameObject sfx = PrefabManager.Cache.GetPrefab("sfx_cultist_attack_fire_start"); - if (sfx != null) Instantiate(sfx, player.transform.position, Quaternion.identity); + // "sfx_cultist_attack_fire_start" was asked for here and there is no sfx_cultist_* + // prefab in the game at all; the fenring's own fire-claw snarl is the real one. + FenrirCreatureSound.PlayFireRoar(player.transform.position); } else if (!fire && flames != null) { Destroy(flames); flames = null; } @@ -221,7 +393,7 @@ namespace RacesOfValheim GameObject sfx = PrefabManager.Cache.GetPrefab(name); if (sfx != null) { - Instantiate(sfx, player.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(sfx, player.transform.position); return; } } @@ -333,7 +505,7 @@ namespace RacesOfValheim GameObject sfx = PrefabManager.Cache.GetPrefab(name); if (sfx != null) { - Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position); return; } } @@ -365,19 +537,19 @@ namespace RacesOfValheim fenrirAnim.SetFloat("sideway_speed", 0f); fenrirAnim.SetTrigger(triggerName); - FenrirAttackSync.Publish(triggerName, "sfx_fenring_attack", "sfx_fenring_attack_claw", "sfx_wolf_attack"); - PlaySFX("sfx_fenring_attack", "sfx_fenring_attack_claw", "sfx_wolf_attack"); + // The swing. The chain here used to be "sfx_fenring_attack", "sfx_fenring_attack_claw", + // "sfx_wolf_attack", and only the last of those is a prefab in this game - so a Fenring + // has been swinging with a wolf's voice, through a fallback, while the creature's own + // sound sat there unused under a different name. + FenrirAttackSync.Publish(triggerName, "sfx_fenring_claw_start"); + PlaySFX("sfx_fenring_claw_start"); yield return new WaitForSeconds(dmgDelay); - if (ZNetScene.instance != null) - { - GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_fenring_attack"); - if (attackSfx != null) - { - Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); - } - } + // The hit, as opposed to the swing PlaySFX covers above. This asked for + // "sfx_fenring_attack" on its own, which is not a prefab in this game, so the claw landed + // in silence - same dead name as the jump attack's, same replacement. + PlaySFX("sfx_fenring_claw_hit"); ExecuteClawDamage(baseDamage); @@ -404,16 +576,12 @@ namespace RacesOfValheim // Aspettiamo che l'animazione si carichi (0.75s) yield return new WaitForSeconds(0.75f); - if (ZNetScene.instance != null) - { - GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_fenring_attack"); - if (attackSfx != null) - { - Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); - } - } + // The impact sound used to be played HERE, which is mid-air: the jump has not started + // yet, let alone landed. It now fires at the end of the dash, next to the damage. It also + // asked for "sfx_fenring_attack", which is not a prefab in this game, so it was silent + // either way. - // Invece di una singola spinta di velocità (che viene subito annullata da Valheim), + // Invece di una singola spinta di velocità (che viene subito annullata da Valheim), // muoviamo esplicitamente il personaggio fotogramma per fotogramma per 0.2 secondi float dashDuration = 0.2f; float elapsedDash = 0f; @@ -438,7 +606,9 @@ namespace RacesOfValheim yield return new WaitForFixedUpdate(); } - // Infliggiamo il danno al termine dello scatto + // Infliggiamo il danno al termine dello scatto, che è anche il momento dell'atterraggio: + // il suono d'impatto va qui, non prima dello scatto. + PlaySFX("sfx_fenring_claw_hit"); ExecuteClawDamage(FenrirConfig.FenringJumpAttackDamage.Value); // Tempo per riprendersi dall'atterraggio prima di potersi muovere di nuovo @@ -620,7 +790,7 @@ namespace RacesOfValheim GameObject sfx = PrefabManager.Cache.GetPrefab(name); if (sfx != null) { - Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position); return; } } @@ -658,7 +828,8 @@ namespace RacesOfValheim cultistAnim.SetBool("attack_fire", true); FenrirAttackSync.PublishFire(true); - PlaySFX("sfx_cultist_attack_fire_start"); + // Same cue the remote mirror plays - see the fire branch in the sync behaviour above. + FenrirCreatureSound.PlayFireRoar(Player.m_localPlayer.transform.position); cultistAnim.SetTrigger("attack_flames"); FenrirAttackSync.Publish("attack_flames"); @@ -770,11 +941,11 @@ namespace RacesOfValheim // Per il Cultista usiamo esplicitamente il trigger dell'artigliata cultistAnim.SetTrigger("attack_claw"); - FenrirAttackSync.Publish("attack_claw", "sfx_cultist_attack", "sfx_fenring_attack", "sfx_wolf_attack"); + FenrirAttackSync.Publish("attack_claw", "sfx_fenring_claw_start"); yield return new WaitForSeconds(0.4f); - PlaySFX("sfx_cultist_attack", "sfx_fenring_attack", "sfx_wolf_attack"); + PlaySFX("sfx_fenring_claw_start"); ExecuteClawDamage(FenrirConfig.CultistClawDamage.Value); @@ -796,12 +967,12 @@ namespace RacesOfValheim cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetTrigger("attack_claw_double"); - FenrirAttackSync.Publish("attack_claw_double", "sfx_cultist_attack_double", "sfx_cultist_attack", "sfx_fenring_attack"); + FenrirAttackSync.Publish("attack_claw_double", "sfx_fenring_claw_start"); // L'animazione double claw è più lunga, facciamo il danno un po' dopo yield return new WaitForSeconds(0.6f); - PlaySFX("sfx_cultist_attack_double", "sfx_cultist_attack", "sfx_fenring_attack"); + PlaySFX("sfx_fenring_claw_start"); ExecuteClawDamage(FenrirConfig.CultistDoubleClawDamage.Value); @@ -946,7 +1117,7 @@ namespace RacesOfValheim GameObject sfx = PrefabManager.Cache.GetPrefab(name); if (sfx != null) { - Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position); return; } } @@ -969,7 +1140,7 @@ namespace RacesOfValheim GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wolf_attack"); if (attackSfx != null) { - Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position); } } @@ -1121,7 +1292,7 @@ namespace RacesOfValheim GameObject sfx = PrefabManager.Cache.GetPrefab(name); if (sfx != null) { - Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position); return; } } @@ -1135,17 +1306,12 @@ namespace RacesOfValheim try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} try { ulvAnim.SetTrigger(triggerName); } catch {} - FenrirAttackSync.Publish(triggerName, "sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack"); + FenrirAttackSync.Publish(triggerName, "sfx_wolf_attack"); - // Scegli il suono appropriato per l'attacco - if (triggerName == "attack_bite") - { - PlaySFX("sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack"); - } - else - { - PlaySFX("sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack"); - } + // Un solo suono per entrambi i trigger. I due rami esistevano per scegliere fra + // "sfx_ulv_attack" e il ripiego sul lupo, ma l'Ulv non ha un prefab d'attacco in vanilla + // - c'e solo sfx_ulv_death - quindi entrambi suonavano il lupo comunque. + PlaySFX("sfx_wolf_attack"); yield return new WaitForSeconds(dmgDelay); @@ -1154,7 +1320,7 @@ namespace RacesOfValheim GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wood_hit"); if (attackSfx != null) { - Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position); } } @@ -1241,8 +1407,8 @@ namespace RacesOfValheim try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} try { ulvAnim.SetTrigger("attack_slash"); } catch {} - FenrirAttackSync.Publish("attack_slash", "sfx_ulv_attack", "sfx_wolf_attack"); - PlaySFX("sfx_ulv_attack", "sfx_wolf_attack"); + FenrirAttackSync.Publish("attack_slash", "sfx_wolf_attack"); + PlaySFX("sfx_wolf_attack"); yield return new WaitForSeconds(0.3f); // Wait 0.3s before leaping @@ -1267,7 +1433,7 @@ namespace RacesOfValheim GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wood_hit"); if (attackSfx != null) { - Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position); } } diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index a98f6d3..4e55a80 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -236,11 +236,16 @@ namespace RacesOfValheim { SpawnPoofEffect(); - if (ZNetScene.instance != null) - { - GameObject howlPrefab = ZNetScene.instance.GetPrefab("sfx_wolf_howl") ?? ZNetScene.instance.GetPrefab("sfx_fenring_idle"); - if (howlPrefab != null) Instantiate(howlPrefab, Player.m_localPlayer.transform.position, Quaternion.identity); - } + // The howl of the creature being turned into, read off that creature. This used to look + // for "sfx_wolf_howl" and fall back to "sfx_fenring_idle": the first is not a prefab in + // this game, and the second is real but is the creature's ambient grunt, so every + // transformation announced itself with a small idle noise. FenrirCreatureSound exists for + // exactly this - see the note at the top of FenrirBehaviors for how it reads a creature's + // own voice off BaseAI.m_alertedEffects, which is the only route the Wolf and the Ulv + // have. The two Fenring forms could do better: vanilla does ship "sfx_fenring_howl", a + // real howl rather than an alert bark, and preferring it when it exists would cost four + // lines here. + FenrirCreatureSound.PlayHowl(CreaturePrefabFor(rules.Form), Player.m_localPlayer.transform.position); yield return new WaitForSeconds(0.1f); @@ -326,18 +331,26 @@ namespace RacesOfValheim { if (sparks != null) Instantiate(sparks, pos, Quaternion.identity); } + /// + /// The vanilla creature a form is built from. One place rather than two, because the howl + /// that announces a transformation has to be read off the same creature the body comes from. + /// + private static string CreaturePrefabFor(FenrirProgression.FormType form) + { + switch (form) + { + case FenrirProgression.FormType.Wolf: return "Wolf"; + case FenrirProgression.FormType.Ulv: return "Ulv"; + case FenrirProgression.FormType.Fenring: return "Fenring"; + case FenrirProgression.FormType.Cultist: return "Fenring_Cultist"; + } + return ""; + } + private void ExecuteTransformation(FenrirProgression.FormRules rules) { Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); - string prefabName = ""; - - switch (rules.Form) - { - case FenrirProgression.FormType.Wolf: prefabName = "Wolf"; break; - case FenrirProgression.FormType.Ulv: prefabName = "Ulv"; break; - case FenrirProgression.FormType.Fenring: prefabName = "Fenring"; break; - case FenrirProgression.FormType.Cultist: prefabName = "Fenring_Cultist"; break; - } + string prefabName = CreaturePrefabFor(rules.Form); GameObject prefab = PrefabManager.Cache.GetPrefab(prefabName); @@ -363,9 +376,30 @@ namespace RacesOfValheim { currentTransformation = Instantiate(visual.gameObject, Player.m_localPlayer.transform); currentTransformation.transform.localPosition = Vector3.zero; currentTransformation.transform.localRotation = Quaternion.identity; + // DEAD LINE, kept until somebody decides what it was for. The game has no type + // called "AnimEvent" - the animation-event dispatcher is CharacterAnimEvent - and + // GetComponent(string) matches a type name in full, so this has never found + // anything and the Destroy has never run. Component animEvent = currentTransformation.GetComponent("AnimEvent"); if (animEvent != null) Destroy(animEvent); + // The creature's own animations carry their sounds as events; this is what hears + // them. On the object that owns the Animator, because that is where Unity delivers + // an animation event - for the wolf that is WolfSmooth, two levels down, not the + // Visual this method has in hand. + Animator formAnimator = currentTransformation.GetComponentInChildren(true); + if (formAnimator != null) + { + formAnimator.gameObject.AddComponent(); + Jotunn.Logger.LogInfo( + $"[FenrirForm] animation-event listener on '{formAnimator.gameObject.name}'."); + } + else + { + Jotunn.Logger.LogWarning( + "[FenrirForm] no Animator under the form; animation sounds will not play."); + } + float ttl = rules.DurationMinutes > 0 ? (rules.DurationMinutes * 60f) : 0f; if (prefabName == "Ulv") diff --git a/JotunnModStub/Fenrir/FormAnimEventSound.cs b/JotunnModStub/Fenrir/FormAnimEventSound.cs new file mode 100644 index 0000000..4fdea87 --- /dev/null +++ b/JotunnModStub/Fenrir/FormAnimEventSound.cs @@ -0,0 +1,89 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Plays the sounds Valheim wires into a creature's own animation clips, for a player wearing + /// that creature. + /// + /// THE HOWL WAS NEVER A PREFAB TO LOOK UP. It is an AnimationEvent. The wolf's animator carries a + /// clip called 'C_Hawl' whose single event, at 0.39s, calls a method named Effect and hands it the + /// sound as an object reference: + /// + /// 'C_Hawl' 3.13s loop=True events=1 + /// @0.39s Effect() ref='sfx_wolf_haul' (GameObject) + /// + /// Two things follow from that, and both are better than what the mod was doing. First, the clip + /// already plays on its own: a player in wolf form idles through 'C_Hawl' like any other idle, so + /// the howl animation costs nothing to get. Second, the sound belongs at 0.39s into that clip and + /// nowhere else, which is something no amount of instantiating a prefab on a keypress can match. + /// + /// Three names, three spellings, and that is the whole reason this took so long to find: the clip + /// is 'C_Hawl', the sound is 'sfx_wolf_haul', and the mod was looking for 'sfx_wolf_howl' - the + /// only correct spelling of the three, and the only one that does not exist. + /// + /// Unity calls Effect BY NAME on the components of the GameObject that owns the Animator, so this + /// has to sit there and the method must keep that name. + /// + internal class FormAnimEventSound : MonoBehaviour + { + private static readonly HashSet logged = new HashSet(); + + /// + /// Off whenever the game's own receiver is on this object, which in practice is always. + /// + /// A player in wolf form idles through 'C_Hawl' and howls, out loud, with no help from this + /// class - confirmed in game. AnimationEffect, which sits beside the Animator on the form + /// along with CharacterAnimEvent, is doing that already. Two receivers for one event means two + /// howls, so this stands down and stays only as cover for a form that turns out not to carry + /// one. The log says which of the two happened, once per form, so nobody has to wonder. + /// + private bool standDown; + + private void Awake() + { + standDown = GetComponent("AnimationEffect") != null; + + if (logged.Add("attach/" + name)) + { + Jotunn.Logger.LogInfo( + standDown + ? $"[FenrirForm] '{name}' already carries AnimationEffect; leaving animation sounds to it." + : $"[FenrirForm] '{name}' has no AnimationEffect; handling animation sounds here."); + } + } + + /// + /// CALLED BY UNITY from an AnimationEvent. Do not rename, and do not make it private. + /// + /// Only object references are taken, and only when they carry audio. The clips also fire + /// Effect with a string and no reference - 'Jump' does, with string='jump' - and that form + /// means "look something up", which is a different job and somebody else's. The audio test is + /// there because an animation can reference anything at all, and a form is not the place to + /// find out what spawning an arbitrary vanilla object does. + /// + public void Effect(AnimationEvent e) + { + if (standDown) return; + + GameObject prefab = e.objectReferenceParameter as GameObject; + if (prefab == null) return; + + bool audible = prefab.GetComponentInChildren(true) != null; + + if (logged.Add(prefab.name)) + { + Jotunn.Logger.LogInfo( + $"[FenrirForm] animation event Effect on '{name}' -> '{prefab.name}' " + + $"audio={audible}{(audible ? "" : ", skipped")}."); + } + + if (!audible) return; + + // Through the same ghost-init spawn as everything else here: some vanilla sound prefabs + // carry a ZNetView, and this one fires every time the animation comes round. + FenrirCreatureSound.Spawn(prefab, transform.position); + } + } +} From 22170087aeaef5373597affbc4ecf8d662e25edf Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 00:20:42 +0200 Subject: [PATCH 059/290] feat(debug): dumpanim, for reading an animator instead of guessing at it Guessing at animation has cost this mod real time: a howl looked for under three wrong names, a taunt animation nobody knew played, and a sound prefab that kills the process when spawned on its own. dumpanim lists a creature's parameters, layers, every clip in its controller with name and length, and every AnimationEvent on every clip - the instant, the method called, and the asset an event hands over. That last column is where a sound wired into an animation lives, and it is what finally found the wolf's howl. It also prints the components beside the Animator, because an animation event is delivered to those and nowhere else. On a prefab with no animator at all it falls back to dumping the hierarchy, the components and the audio setup, which is how a sound prefab gets looked at without being spawned - and some of them must not be spawned. dumpanim live watches every animator under the player and reports each clip change as it happens. Standing still in wolf form and reading the log is what showed 'C_Hawl' coming round in the idle rotation on its own. What Unity will not give up, and it is worth knowing before starting: the state machine. States and transitions are editor-only and GetCurrentAnimatorStateInfo returns hashes with no names, so a state can only be guessed and then confirmed. Co-Authored-By: Claude Opus 5 --- JotunnModStub/AnimatorDump.cs | 303 ++++++++++++++++++++++++++++++++ JotunnModStub/RacesOfValheim.cs | 1 + 2 files changed, 304 insertions(+) create mode 100644 JotunnModStub/AnimatorDump.cs diff --git a/JotunnModStub/AnimatorDump.cs b/JotunnModStub/AnimatorDump.cs new file mode 100644 index 0000000..edb5e40 --- /dev/null +++ b/JotunnModStub/AnimatorDump.cs @@ -0,0 +1,303 @@ +using System.Collections.Generic; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Reads out a creature's animator, because guessing at animation has cost this mod real time: + /// a howl that was looked for under three wrong names, a taunt animation nobody knew played, and + /// a sound prefab that killed the process when spawned on its own. + /// + /// WHAT UNITY LETS US SEE AT RUNTIME, and what it does not, because the line matters: + /// + /// Readable. Every parameter with its type. Every layer. Every CLIP in the controller with its + /// name and length, through RuntimeAnimatorController.animationClips - so a creature's whole + /// vocabulary can be listed without ever wearing it. And every AnimationEvent on every clip: + /// the instant, the method name it calls, and its parameters. That last one is where a sound + /// fired by an animation lives, which is the thing this was written to find. + /// + /// Not readable. The state machine. States and transitions live in AnimatorController, which is + /// an editor-only type, and GetCurrentAnimatorStateInfo hands back hashes with no names. States + /// can only be guessed and then confirmed: AnimatorStateInfo.IsName("Layer.Name") answers yes or + /// no, and Animator.Play takes a state name we can try and then verify by reading back which + /// clip actually started. + /// + /// So "catch the howl and trigger just that stretch" is possible, in this order: list the clips + /// here, find the one that looks like a howl, look at its events to see whether the sound is + /// wired into the animation, then Play the state and CrossFade back to idle at the point wanted. + /// Worth knowing before starting: if the sound is an animation event, playing the clip alone will + /// not make it, because events are dispatched to a component on the animated object and Valheim's + /// dispatcher is CharacterAnimEvent. The animation is the prize; the audio we already play + /// ourselves. + /// + public class DumpAnimCommand : ConsoleCommand + { + public override string Name => "dumpanim"; + + public override string Help => + "[DEBUG] dumpanim - lists a creature's animator parameters, layers, clips and " + + "every animation event on them. dumpanim live - logs which clip each animator under you " + + "starts playing, as it happens; run it again to stop."; + + public override void Run(string[] args) + { + if (args.Length == 0) + { + Console.instance.Print("dumpanim | dumpanim live"); + return; + } + + if (args[0].ToLower() == "live") + { + ToggleWatcher(); + return; + } + + DumpPrefab(args[0]); + } + + /// + /// Everything the controller of can play. Reads a prefab in + /// memory, so it needs no transformation and cannot disturb a live one. + /// + private static void DumpPrefab(string prefabName) + { + GameObject prefab = PrefabManager.Cache.GetPrefab(prefabName); + if (prefab == null) + { + Report($"[Anim] '{prefabName}' is not in the prefab cache."); + return; + } + + Animator[] animators = prefab.GetComponentsInChildren(true); + if (animators.Length == 0) + { + // Not a creature. Say what it is anyway: this is also how a sound prefab gets looked + // at without being spawned, which matters for the ones that cannot safely be spawned. + Report($"[Anim] '{prefabName}' has no Animator. Contents:"); + foreach (Transform t in prefab.GetComponentsInChildren(true)) + { + Jotunn.Logger.LogInfo($"[Anim] '{PathOf(t)}' [{ComponentsOf(t.gameObject)}]"); + DescribeAudio(t.gameObject); + } + return; + } + + Report($"[Anim] '{prefabName}': {animators.Length} animator(s)."); + + foreach (Animator animator in animators) + { + RuntimeAnimatorController controller = animator.runtimeAnimatorController; + Report($"[Anim] on '{PathOf(animator.transform)}' controller " + + $"'{(controller != null ? controller.name : "none")}'"); + + // What else lives on that object, because an animation event is delivered to THESE + // components and nowhere else. CharacterAnimEvent showing up here is the game's own + // receiver; a form that carries it is a form where vanilla is already handling - or + // already failing to handle - every event the clips fire. + Jotunn.Logger.LogInfo($"[Anim] receivers: [{ComponentsOf(animator.gameObject)}]"); + + if (controller == null) continue; + + foreach (AnimatorControllerParameter p in animator.parameters) + { + Jotunn.Logger.LogInfo($"[Anim] param {p.name} ({p.type})"); + } + + for (int i = 0; i < animator.layerCount; i++) + { + Jotunn.Logger.LogInfo($"[Anim] layer {i} '{animator.GetLayerName(i)}'"); + } + + AnimationClip[] clips = controller.animationClips; + Report($"[Anim] {clips.Length} clip(s):"); + + foreach (AnimationClip clip in clips) + { + if (clip == null) continue; + + AnimationEvent[] events = clip.events; + Jotunn.Logger.LogInfo( + $"[Anim] '{clip.name}' {clip.length:F2}s loop={clip.isLooping} " + + $"events={events.Length}"); + + foreach (AnimationEvent e in events) + { + // The object reference is the interesting one: a sound wired into an + // animation arrives here as the asset itself, name included. + string reference = e.objectReferenceParameter != null + ? $" ref='{e.objectReferenceParameter.name}' ({e.objectReferenceParameter.GetType().Name})" + : ""; + Jotunn.Logger.LogInfo( + $"[Anim] @{e.time:F2}s {e.functionName}(" + + $"string='{e.stringParameter}' float={e.floatParameter:F2} " + + $"int={e.intParameter}){reference}"); + } + } + } + } + + private static void ToggleWatcher() + { + if (Player.m_localPlayer == null) + { + Console.instance.Print("dumpanim live needs you to be in the world."); + return; + } + + AnimatorWatcher existing = Player.m_localPlayer.GetComponent(); + if (existing != null) + { + Object.Destroy(existing); + Report("[Anim] live watch off."); + return; + } + + Player.m_localPlayer.gameObject.AddComponent(); + Report("[Anim] live watch on: every clip change under you, as it happens."); + } + + /// + /// Why a sound prefab is or is not audible when it is simply instantiated. + /// + /// The AudioSource settings say whether anything starts by itself, and ZSFX's own fields say + /// what it would play if asked - it keeps a LIST of clips and chooses at play time, so a + /// prefab whose AudioSource has no clip is normal rather than broken. Read through reflection + /// because these are the game's private serialized fields. + /// + private static void DescribeAudio(GameObject go) + { + AudioSource audio = go.GetComponent(); + if (audio != null) + { + Jotunn.Logger.LogInfo( + $"[Anim] AudioSource playOnAwake={audio.playOnAwake} " + + $"clip='{(audio.clip != null ? audio.clip.name : "none")}' " + + $"volume={audio.volume:F2} spatialBlend={audio.spatialBlend:F2} " + + $"range={audio.minDistance:F1}-{audio.maxDistance:F1} loop={audio.loop} " + + $"mixer='{(audio.outputAudioMixerGroup != null ? audio.outputAudioMixerGroup.name : "none")}'"); + } + + foreach (Component comp in go.GetComponents()) + { + if (comp == null || comp.GetType().Name != "ZSFX") continue; + + List fields = new List(); + foreach (System.Reflection.FieldInfo f in comp.GetType().GetFields( + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.NonPublic)) + { + object value = f.GetValue(comp); + System.Array array = value as System.Array; + if (array == null) + { + fields.Add($"{f.Name}={value}"); + continue; + } + + // The elements, not just the count. m_audioClips is where a sound's actual clips + // live, and whether they are AudioClips or unloaded soft references is the whole + // question when a sound spawns and stays silent. + List elements = new List(); + for (int e = 0; e < array.Length && e < 4; e++) + { + object item = array.GetValue(e); + Object asObject = item as Object; + elements.Add(item == null + ? "null" + : $"{item.GetType().Name}:'{(asObject != null ? asObject.name : item.ToString())}'"); + } + fields.Add($"{f.Name}[{array.Length}]={{{string.Join(", ", elements.ToArray())}}}"); + } + + Jotunn.Logger.LogInfo($"[Anim] ZSFX {string.Join(" ", fields.ToArray())}"); + Jotunn.Logger.LogInfo( + $"[Anim] ZSFX methods: {string.Join(", ", MethodNamesOf(comp))}"); + } + } + + private static string[] MethodNamesOf(Component comp) + { + List names = new List(); + foreach (System.Reflection.MethodInfo m in comp.GetType().GetMethods( + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.DeclaredOnly)) + { + names.Add(m.Name + "(" + m.GetParameters().Length + ")"); + } + return names.ToArray(); + } + + /// The component type names on one object, Transform left out as noise. + private static string ComponentsOf(GameObject go) + { + List names = new List(); + foreach (Component comp in go.GetComponents()) + { + if (comp != null && !(comp is Transform)) names.Add(comp.GetType().Name); + } + return string.Join(", ", names.ToArray()); + } + + private static string PathOf(Transform t) + { + string path = t.name; + for (Transform p = t.parent; p != null; p = p.parent) path = p.name + "/" + path; + return path; + } + + /// To the log and to the console both, since one of the two is always the wrong one. + private static void Report(string line) + { + Jotunn.Logger.LogInfo(line); + if (Console.instance != null) Console.instance.Print(line); + } + + /// + /// Watches every animator under the player and says when one starts a different clip. + /// + /// Only the change is logged, not the state: an animator asked every frame would fill the log + /// with the idle it is already playing. The heaviest clip is the one reported, because during + /// a transition two are live at once and the heavier one is the one being watched on screen. + /// + private class AnimatorWatcher : MonoBehaviour + { + private readonly Dictionary last = new Dictionary(); + + private void Update() + { + foreach (Animator animator in GetComponentsInChildren(true)) + { + if (animator == null || animator.runtimeAnimatorController == null) continue; + + AnimatorClipInfo[] playing = animator.GetCurrentAnimatorClipInfo(0); + if (playing.Length == 0) continue; + + AnimationClip heaviest = null; + float weight = -1f; + foreach (AnimatorClipInfo info in playing) + { + if (info.clip != null && info.weight > weight) + { + heaviest = info.clip; + weight = info.weight; + } + } + if (heaviest == null) continue; + + string previous; + if (last.TryGetValue(animator, out previous) && previous == heaviest.name) continue; + + last[animator] = heaviest.name; + Jotunn.Logger.LogInfo( + $"[Anim] live: '{PathOf(animator.transform)}' -> '{heaviest.name}' " + + $"{heaviest.length:F2}s weight={weight:F2} events={heaviest.events.Length}"); + } + } + } + } +} diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 0235ed9..c703e24 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -79,6 +79,7 @@ namespace RacesOfValheim CommandManager.Instance.AddConsoleCommand(new FenrirPackSpawnCommand()); CommandManager.Instance.AddConsoleCommand(new DumpPotionsCommand()); CommandManager.Instance.AddConsoleCommand(new ListPrefabsCommand()); + CommandManager.Instance.AddConsoleCommand(new DumpAnimCommand()); } /// From da896179fd6c4d4f407900d13a0d98a12cf8bb87 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 01:41:00 +0200 Subject: [PATCH 060/290] feat(fenrir): howl on demand, in every form The howl key was only ever read by the two Fenring forms. As a wolf or an Ulv it did nothing at all - not a misconfiguration, the classes simply never looked at it. All four forms read it now. The wolf and the Ulv perform the creature's own howl animation and NO SOUND IS SPAWNED, because their clip already carries one: 'C_Hawl' fires an animation event at 0.39s holding sfx_wolf_haul, and the game's own AnimationEffect plays it. The audio comes out of the animation, at the instant the animation means it to, which no prefab fired on a keypress can match. Spawning one as well would be a second howl over the first. A trigger is looked for before a state, and that is about multiplayer rather than tidiness: FenrirAttackSync replicates trigger names, so a howl fired through a trigger is one the other clients see and hear, while Animator.Play is local and nobody else knows. Which route was taken is logged once per creature, and if neither exists the log prints the animator's whole parameter list rather than leaving another keypress that quietly does nothing. The Fenring and the Cultist have no howl clip in vanilla - 19 and 18 clips, none of them a howl, and their taunt fires no sound event - so they keep the Taunt animation and take the wolf's howl as their voice. Co-Authored-By: Claude Opus 5 --- JotunnModStub/Fenrir/FenrirBehaviors.cs | 141 +++++++++++++++++++++++- 1 file changed, 139 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 380f47c..70137f4 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -93,6 +93,71 @@ namespace RacesOfValheim if (!Play(FireRoar, position, "fire roar")) PlayAlertedEffects("Fenring_Cultist", position); } + /// + /// State names to try when a creature has no howl trigger. 'C_Hawl' first, and that spelling + /// is not a typo here - it is the game's, on the wolf's own clip. + /// + private static readonly string[] HowlStates = { "C_Hawl", "C_Howl", "Hawl", "Howl", "Taunt" }; + + /// + /// Makes the worn creature perform its own howl, and says whether it could. + /// + /// WORTH KNOWING BEFORE READING THE CODE: on the wolf this brings the sound with it. Its howl + /// clip carries the sound as an animation event - 'C_Hawl' fires Effect at 0.39s holding + /// sfx_wolf_haul - and the game's own AnimationEffect, which sits beside the Animator on the + /// form, plays it. So for the wolf and the Ulv there is no sound to spawn at all: play the + /// animation and the howl comes out of it, at the instant the animation means it to. + /// + /// A TRIGGER IS TRIED BEFORE A STATE, and the reason is multiplayer rather than tidiness. + /// FenrirAttackSync replicates trigger names, so a howl fired through a trigger is a howl the + /// other clients see and hear. Animator.Play is local: it works, and nobody else knows. + /// comes back non-null exactly when the caller has something + /// worth publishing. + /// + public static bool TryHowlAnimation(Animator animator, string creature, out string triggerName) + { + triggerName = null; + if (animator == null || animator.runtimeAnimatorController == null) return false; + + foreach (AnimatorControllerParameter p in animator.parameters) + { + if (p.type != AnimatorControllerParameterType.Trigger) continue; + + string lower = p.name.ToLower(); + if (!lower.Contains("hawl") && !lower.Contains("howl") && !lower.Contains("taunt")) continue; + + animator.SetTrigger(p.name); + triggerName = p.name; + LogHowlRouteOnce(creature, $"trigger '{p.name}'"); + return true; + } + + foreach (string state in HowlStates) + { + int hash = Animator.StringToHash(state); + if (!animator.HasState(0, hash)) continue; + + animator.Play(hash, 0); + LogHowlRouteOnce(creature, $"state '{state}', played directly - local only, " + + "no trigger exists to replicate it"); + return true; + } + + // Nothing matched, so say what there was to match against. A keypress that does nothing is + // the thing this whole exercise started from. + List parameters = new List(); + foreach (AnimatorControllerParameter p in animator.parameters) parameters.Add($"{p.name}({p.type})"); + LogHowlRouteOnce(creature, + "no howl trigger and no howl state. Parameters: " + string.Join(", ", parameters.ToArray()) + + ". Run 'dumpanim " + creature + "' for its clip list"); + return false; + } + + private static void LogHowlRouteOnce(string creature, string route) + { + if (logged.Add("howl/" + creature)) Jotunn.Logger.LogInfo($"[FenrirForm] howl for '{creature}': {route}."); + } + /// Instantiates the first name that resolves and is safe. True if anything played. private static bool Play(string[] prefabNames, Vector3 position, string label) { @@ -1094,7 +1159,13 @@ namespace RacesOfValheim if (isGrounded && RaceInput.Allowed) { - if (RaceInput.AttackDown(0)) // Left Click + // The howl, on the same key as every other form. It used to be read only by the + // two Fenring forms, so pressing it as a wolf did nothing at all. + if (!isAttacking && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys()) + { + StartCoroutine(WolfHowlRoutine()); + } + else if (RaceInput.AttackDown(0)) // Left Click { StartCoroutine(WolfAttackRoutine("attack1", FenrirConfig.WolfAttack1Damage.Value, 0.6f, 0.2f)); } @@ -1123,6 +1194,36 @@ namespace RacesOfValheim } } + + /// + /// The howl on demand, which for this creature is the animation and nothing else: its clip + /// carries the sound as an event, so spawning one on top would be a second howl over the + /// first. The prefab is only reached if the animator turns out to have no howl at all. + /// + private IEnumerator WolfHowlRoutine() + { + isAttacking = true; + + try { wolfAnim.SetFloat("forward_speed", 0f); } catch {} + try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} + + string trigger; + if (FenrirCreatureSound.TryHowlAnimation(wolfAnim, "Wolf", out trigger)) + { + if (trigger != null) FenrirAttackSync.Publish(trigger); + } + else + { + FenrirCreatureSound.PlayHowl("Wolf", Player.m_localPlayer.transform.position); + } + + // The wolf's howl clip runs 3.13s. Held a little past it so the form does not snap back + // into a bite the instant the sound ends. + yield return new WaitForSeconds(3.3f); + + isAttacking = false; + } + private IEnumerator WolfAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay) { isAttacking = true; @@ -1268,7 +1369,13 @@ namespace RacesOfValheim if (isGrounded && RaceInput.Allowed) { - if (RaceInput.AttackDown(0)) // Left Click + // The howl, on the same key as every other form. It used to be read only by the + // two Fenring forms, so pressing it as a wolf did nothing at all. + if (!isAttacking && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys()) + { + StartCoroutine(UlvHowlRoutine()); + } + else if (RaceInput.AttackDown(0)) // Left Click { StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvBiteDamage.Value, 0.6f, 0.2f)); } @@ -1298,6 +1405,36 @@ namespace RacesOfValheim } } + + /// + /// The howl on demand, which for this creature is the animation and nothing else: its clip + /// carries the sound as an event, so spawning one on top would be a second howl over the + /// first. The prefab is only reached if the animator turns out to have no howl at all. + /// + private IEnumerator UlvHowlRoutine() + { + isAttacking = true; + + try { ulvAnim.SetFloat("forward_speed", 0f); } catch {} + try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} + + string trigger; + if (FenrirCreatureSound.TryHowlAnimation(ulvAnim, "Ulv", out trigger)) + { + if (trigger != null) FenrirAttackSync.Publish(trigger); + } + else + { + FenrirCreatureSound.PlayHowl("Ulv", Player.m_localPlayer.transform.position); + } + + // The wolf's howl clip runs 3.13s. Held a little past it so the form does not snap back + // into a bite the instant the sound ends. + yield return new WaitForSeconds(3.3f); + + isAttacking = false; + } + private IEnumerator UlvAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay) { isAttacking = true; From 421bc72eb73c1481aa1975e6c239b122dc18cf99 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 01:45:08 +0200 Subject: [PATCH 061/290] chore(release): v1.4.24 Version bumped in both places that carry it - manifest.json is what Thunderstore ships, PluginVersion is what the game logs - since those two have drifted apart before. The Nexus description is generated now rather than rewritten by hand. It had fallen thirteen versions behind the README, which is how a hand-maintained copy of a 72KB document goes. scripts/nexus-readme.py converts README.md to the BBCode the page wants, following what the 1.4.11 page did by hand so the two are comparable, and writes dist/NEXUS_README_.bbcode.txt. The wiki link was on the Nexus page and had never been in the README, so every other channel shipped without it. It is in the README now, which means it reaches Nexus, Thunderstore and the repository from one place. Co-Authored-By: Claude Opus 5 --- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 10 +++ manifest.json | 2 +- scripts/nexus-readme.py | 105 ++++++++++++++++++++++++++++++++ 4 files changed, 117 insertions(+), 2 deletions(-) create mode 100644 scripts/nexus-readme.py diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index c703e24..9b7a5c3 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.4.23"; + public const string PluginVersion = "1.4.24"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index d3141fa..48a2fbd 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ A comprehensive Valheim mod allowing you to play as unique races, each providing ## Development & Feedback This is a stable release, but more races and refinements are planned! +Wiki: [https://wiki.aledanidev.ovh/](https://wiki.aledanidev.ovh/) Bug reports, feedback, ideas: [https://discord.gg/jJzuKBZNC](https://discord.gg/jJzuKBZNC) Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorTheModder) @@ -412,6 +413,15 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.4.24 +- **Fix - Purple smoke around the Skeleton's burning skull with some magic mods installed:** the fire aura the Skeleton wears from Moder on looked for its particles under two names that are not in Valheim at all. A name the game does not use is a free slot for whichever mod ships one, and with Magic Supremacy installed the aura picked up that mod's weapon trail on an emissive shader and sprayed it through a five-metre sphere. The aura had never actually been visible in a plain install, so it now draws nothing on purpose; its damage, radius and tick are untouched. Thanks to the players who reported it and named the mods they were running. +- **Fix - Effects and sounds that were quietly missing across five races:** an audit of every prefab the mod asks for by name found nine that do not exist in the game, each one failing in silence. The puff that covers a transformation never played for the Fenrir, the Skadi or the Trenta's Muspell; the Aswid's Mist Form appeared and vanished with no effect at all, and so did dominating a creature with a thrall; the Aswid's two status effects and its Bat Form entry in the radial had no icon. All of them now use names the game really has. +- **Fix - A Draugh's successful parry threw an error and cancelled its own frost nova:** the poison splash asked for an effect that does not exist and passed it straight to the game without checking, so every parry inside the window failed at that line - taking the North Wind nova that runs immediately after it down as well. Both work now. +- **New - Human Meat is a real item at last:** the Bonemass tier has promised it since 1.4 and nothing ever created it, so the drop never happened and the "fatal to the living" warning never fired. A player who dies inside your death aura now leaves a piece behind, yourself included, and only a Draugh can stomach it. It is built from Blood Pudding's own nourishment, with its stamina folded into health since a Draugh has no use for stamina, and is tunable under `Draugh - Undead Fortitude`. +- **Fix - Fenrir forms fought in a borrowed voice, or in silence:** every form's sounds were looked up by name and most of those names are not in the game. The chains hid it - a Fenring swung with a wolf's voice through a fallback - and the Cultist's double claw asked for three dead names in a row and had never made a sound at all. Each form now uses the creature's own sounds, and the jump attack's impact lands with the jump instead of firing while the form is still standing. +- **New - Howl on demand in every Fenrir form:** the howl key was only ever read by the Fenring and the Cultist. As a wolf or an Ulv it did nothing. All four howl now, and the wolf and the Ulv use the creature's real howl animation - the sound is carried inside that animation, so it lands at the moment the animation means it to. +- **Fix - Fenrir form sounds no longer write into your world save:** some of the game's sound prefabs carry a networked component, and spawning one the ordinary way leaves a persistent record behind - one per claw swing. They are now spawned the way the game itself does it, and leave nothing. + ### v1.4.23 - **Fix - Trol clients could not chop trees or mine rocks with their fists:** the fist bonus (chop and pickaxe damage, and the tool tier that grows with the bosses) was applied on whichever machine owned the tree or rock - usually the host - where the hit did not belong to the local player, so it only ever worked for the host. It is now applied on the attacking player's own machine before the hit is sent. Thanks to the players who reported it. - **New - Configuration is synced from the server:** every gameplay setting now follows the server's value in multiplayer, and is locked in Configuration Manager for players who are not admins. Keybinds and the purely cosmetic settings (eye and claw colours, glow, model rotation and offsets, the Head Fire VFX and stamina-bar toggles, debug logging) stay local, so each player keeps their own. diff --git a/manifest.json b/manifest.json index fc74963..23d6c7d 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.23", + "version_number": "1.4.24", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/scripts/nexus-readme.py b/scripts/nexus-readme.py new file mode 100644 index 0000000..d83142d --- /dev/null +++ b/scripts/nexus-readme.py @@ -0,0 +1,105 @@ +"""Turns the mod's README.md into the BBCode Nexus wants. + +The Nexus page had been rewritten by hand each release and had fallen thirteen +versions behind the README, so it is generated now. Run it after the changelog +entry is in and the version is bumped: + + python scripts/nexus-readme.py + +It reads manifest.json for the version and writes +dist/NEXUS_README_.bbcode.txt. + +The conversion follows what the 1.4.11 page did by hand, so the two are +comparable: headings become sized bold, a horizontal rule goes above every +top-level section, images are gathered onto one line per group, backticks +become quotes because Nexus has no code style, and the
wrappers +around the progressions are dropped while their summaries survive as headings. +""" +import json +import pathlib +import re + +ROOT = pathlib.Path(__file__).resolve().parent.parent +RULE = "[s]---------------------------------------------------[/s]" + + +def inline(text): + """Markdown's inline marks, in an order where they cannot eat each other.""" + text = re.sub(r"\*\*(.+?)\*\*", r"[b]\1[/b]", text) + text = re.sub(r"`([^`]+)`", r'"\1"', text) + # An in-page anchor means nothing on a Nexus description, so the link text stays and the + # link goes: "Full details under Sverm" reads the same, and a dead #10-sverm does not. + text = re.sub(r"\[([^\]]+)\]\(#[^)]*\)", r"\1", text) + text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"[url=\2]\1[/url]", text) + return text + + +def image(url): + # The march gif is a strip rather than a portrait, and was shown smaller by hand. + return f"[img height={200 if 'small' in url else 350}]{url}[/img]" + + +def table_row(line): + cells = [inline(c.strip()) for c in line.strip().strip("|").split("|")] + if not cells: + return None + return "- [b]" + cells[0] + "[/b]" + ("" if len(cells) == 1 else " — " + " — ".join(cells[1:])) + + +def convert(markdown): + out = [] + pending_images = [] + + def flush_images(): + if pending_images: + out.append("".join(pending_images)) + pending_images.clear() + + for line in markdown.splitlines(): + stripped = line.strip() + + # Images stack up so a group of them lands on one line, the way Nexus shows them. + match = re.fullmatch(r"!\[[^\]]*\]\(([^)]+)\)", stripped) + if match: + pending_images.append(image(match.group(1))) + continue + flush_images() + + if not stripped or stripped in ("
", "
", "---"): + continue + + match = re.fullmatch(r"(.+?)", stripped) + if match: + out.append(f"[size=4][b]{inline(match.group(1))}[/b][/size]") + continue + + match = re.fullmatch(r"(#{1,3})\s+(.*)", stripped) + if match: + level, title = len(match.group(1)), inline(match.group(2)) + if level == 2: + out.append(RULE) + out.append(f"[size={7 - level}][b]{title}[/b][/size]") + continue + + if stripped.startswith("|"): + if re.fullmatch(r"\|[\s\-:|]+\|", stripped): # the --- separator row + continue + row = table_row(stripped) + if row: + out.append(row) + continue + + out.append(inline(stripped)) + + flush_images() + return "\n".join(out) + "\n" + + +def main(): + version = json.loads((ROOT / "manifest.json").read_text(encoding="utf-8-sig"))["version_number"] + target = ROOT / "dist" / f"NEXUS_README_{version}.bbcode.txt" + target.write_text(convert((ROOT / "README.md").read_text(encoding="utf-8-sig")), encoding="utf-8") + print(f"{target.relative_to(ROOT)} ({len(target.read_text(encoding='utf-8').splitlines())} lines)") + + +main() From 1c8fa7357fbbb7555c170f8bb81d37e3b356d7fd Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 01:50:21 +0200 Subject: [PATCH 062/290] chore(release): sync the packaging manifest to 1.4.24 JotunnModStub/Package/manifest.json is a second copy of the root manifest, kept by hand and differing from it only in the version - a third place for the version to drift, on top of the two MAINTAINING.md already warns about. It was still on 1.4.23. Synced rather than fixed: the packaging step should copy the root manifest instead of there being two, which is a change to make when the artifacts are built rather than in a version bump. Co-Authored-By: Claude Opus 5 --- JotunnModStub/Package/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index fc74963..23d6c7d 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.23", + "version_number": "1.4.24", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 6b43d3544e3a2b92b1d7cb04c2fa046a3423eb1a Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 14:00:21 +0200 Subject: [PATCH 063/290] feat(fenrir): say why the fire breath did not come, and log a Draugh's parry Holding right mouse as a Cultist with no eitr did nothing whatsoever - no flames, no sound, no reason given. The form arrives at Yagluth and eitr is a Mistlands thing, so a Cultist meets that silence before it ever meets the fire. It now says "Only breath comes out. The fire wants eitr." on a three-second timer, since the button is read every frame and the message would otherwise be a wall. The parry that fires the Draugh's poison splash is logged, with the block timer against the window and whether the splash effect resolved. A parry has to land inside a quarter-second window while blocking, so "nothing looks different after tier 3" is as likely to mean the window was missed as it is to mean the splash did not draw, and there was no way to tell those apart. Co-Authored-By: Claude Opus 5 --- .../Draugh/DraughProgressionPatches.cs | 9 +++++++ JotunnModStub/Fenrir/FenrirBehaviors.cs | 24 +++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/Draugh/DraughProgressionPatches.cs b/JotunnModStub/Draugh/DraughProgressionPatches.cs index f56ce0f..105eb1b 100644 --- a/JotunnModStub/Draugh/DraughProgressionPatches.cs +++ b/JotunnModStub/Draugh/DraughProgressionPatches.cs @@ -109,6 +109,15 @@ namespace RacesOfValheim UnityEngine.Object.Instantiate(splashVfx, attacker.GetCenterPoint(), Quaternion.identity); } + // Said on every parry, which are rare enough not to be noise. A parry has + // to land inside a quarter-second window while blocking, so "nothing looks + // different" is as likely to mean the window was missed as it is to mean + // the splash did not draw - and there was no way to tell the two apart. + Jotunn.Logger.LogInfo( + $"[Draugh] Parry on '{attacker.name}': {DraughConfig.PoisonSplashDamage.Value:F0} poison, " + + $"blockTimer={blockTimer:F3} of {parryTime:F2}, " + + $"splash vfx={(splashVfx != null ? "vfx_blob_hit" : "NOT RESOLVED")}."); + // Stage 5: North Wind (AoE Frost) if (state >= 5) { diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 70137f4..ef2d09c 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -815,9 +815,14 @@ namespace RacesOfValheim UpdateFire(); } } - else if (isShootingFire) + else { - StopFire(); + // Held with an empty pool. Until now this did nothing whatsoever: no + // flames, no sound, no reason given - and the form's own tier is Yagluth + // while eitr is a Mistlands thing, so a Cultist meets this before it ever + // meets the fire. + SayNoEitr(); + if (isShootingFire) StopFire(); } } else if (isShootingFire) @@ -883,6 +888,21 @@ namespace RacesOfValheim private GameObject fireEffectInstance; + private float lastNoEitrMessage = -100f; + + /// + /// Says why the fire did not come. Held down rather than tapped, so it is on a timer: the + /// button is read every frame and the message would otherwise be a wall. + /// + private void SayNoEitr() + { + if (Player.m_localPlayer == null || Time.time - lastNoEitrMessage < 3f) return; + + lastNoEitrMessage = Time.time; + Player.m_localPlayer.Message(MessageHud.MessageType.Center, + "Only breath comes out. The fire wants eitr."); + } + private void StartFire() { if (Player.m_localPlayer == null || isShootingFire) return; From cd1072259475800f123481b2c4d7142b01e6331a Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 16:27:42 +0200 Subject: [PATCH 064/290] docs: say that the Cultist's fire breath runs on eitr The feature list said "Transform into a Cultist to use fire abilities" and never mentioned a cost. The flames take 12.5 eitr per second, and eitr comes from the Mistlands while the form unlocks at Yagluth - so the form can be had with its signature attack still out of reach. Both the feature bullet and the changelog say so now. Co-Authored-By: Claude Opus 5 --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 48a2fbd..3f7f542 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Full details under [Sverm](#10-sverm) and [Sverm Progression](#race-progressions ![Fenrir1](https://wiki.aledanidev.ovh/assets/images/fenrir1.gif) ![Fenrir3](https://wiki.aledanidev.ovh/assets/images/fenrir3.gif) - **Beast Form:** Transform into a wolf-like beast. -- **Cultist Form:** Transform into a Cultist to use fire abilities. +- **Cultist Form:** Transform into a Cultist. Its claws cost nothing, but the **fire breath (hold Right Mouse) runs on eitr** — 12.5 per second — and eitr comes from the Mistlands, so the form unlocks at Yagluth with its flames still out of reach. Holding the button with an empty pool now says so. - **Cursed Claws:** The wolf's hands, kept on in the man's shape — see [Claws](#claws). - **A Pack of Your Own:** The Pack Trough keeps a standing pack of wolves, ulvs and, late, fenrir — see [Race Stations](#race-stations--companions). - **Progression:** Forms grow as you defeat bosses, unlocking new powers and reducing cooldowns. Immune to fall damage. @@ -419,6 +419,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact - **Fix - A Draugh's successful parry threw an error and cancelled its own frost nova:** the poison splash asked for an effect that does not exist and passed it straight to the game without checking, so every parry inside the window failed at that line - taking the North Wind nova that runs immediately after it down as well. Both work now. - **New - Human Meat is a real item at last:** the Bonemass tier has promised it since 1.4 and nothing ever created it, so the drop never happened and the "fatal to the living" warning never fired. A player who dies inside your death aura now leaves a piece behind, yourself included, and only a Draugh can stomach it. It is built from Blood Pudding's own nourishment, with its stamina folded into health since a Draugh has no use for stamina, and is tunable under `Draugh - Undead Fortitude`. - **Fix - Fenrir forms fought in a borrowed voice, or in silence:** every form's sounds were looked up by name and most of those names are not in the game. The chains hid it - a Fenring swung with a wolf's voice through a fallback - and the Cultist's double claw asked for three dead names in a row and had never made a sound at all. Each form now uses the creature's own sounds, and the jump attack's impact lands with the jump instead of firing while the form is still standing. +- **New - The Cultist says why its fire will not come:** holding Right Mouse with no eitr did nothing whatsoever - no flames, no sound, no reason given. The form arrives at Yagluth and eitr is a Mistlands thing, so a Cultist meets that silence before it ever meets the fire. It now tells you the flames want eitr. - **New - Howl on demand in every Fenrir form:** the howl key was only ever read by the Fenring and the Cultist. As a wolf or an Ulv it did nothing. All four howl now, and the wolf and the Ulv use the creature's real howl animation - the sound is carried inside that animation, so it lands at the moment the animation means it to. - **Fix - Fenrir form sounds no longer write into your world save:** some of the game's sound prefabs carry a networked component, and spawning one the ordinary way leaves a persistent record behind - one per claw swing. They are now spawned the way the game itself does it, and leave nothing. From 7ad1d6920ea8100582909e6a5a9f9dc74eade928 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 16:55:19 +0200 Subject: [PATCH 065/290] fix(fenrir): the Ulv was mouthing a silent howl The howl code took a playing animation as proof the sound was coming, because the wolf's does bring it: 'C_Hawl' fires an Effect event at 0.39s holding sfx_wolf_haul. The Ulv is the same family on the same rig and its 'Idle Howl' carries no event at all - events=0, read straight off dumpanim - so pressing the key as an Ulv played the animation and nothing else. The muzzle went up in silence. Which creatures bring their own sound is now written down rather than assumed, and it is only the wolf. FenrirCreatureSound.Howl does the whole thing - animation, trigger published for the other clients, and a sound unless the animation is already carrying one - so the four forms call one line and the distinction lives in one place. The Ulv's hold also went from 3.3s to 3.8s: it was the wolf's clip length, copied, and 'Idle Howl' runs 3.67s. Co-Authored-By: Claude Opus 5 --- JotunnModStub/Fenrir/FenrirBehaviors.cs | 69 +++++++++++++++---------- 1 file changed, 42 insertions(+), 27 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index ef2d09c..86d25fc 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -99,6 +99,36 @@ namespace RacesOfValheim ///
private static readonly string[] HowlStates = { "C_Hawl", "C_Howl", "Hawl", "Howl", "Taunt" }; + /// + /// The creatures whose howl ANIMATION already carries the sound, so playing a prefab as well + /// would be a second howl over the first. + /// + /// ONLY THE WOLF. Its 'C_Hawl' fires an Effect event at 0.39s holding sfx_wolf_haul. The Ulv + /// is the same family on the same rig and its 'Idle Howl' carries no event at all - checked + /// with "dumpanim Ulv", which reads events=0 on that clip. Assuming the two behaved alike is + /// what made the Ulv mouth a silent howl: the animation played, the code took that as proof + /// the sound was coming, and nothing was ever spawned. + /// + private static readonly HashSet HowlAnimationHasSound = new HashSet { "Wolf" }; + + /// + /// One howl: the creature's own animation where it has one, and a sound unless that animation + /// is already bringing it. The four forms call this and nothing else. + /// + public static void Howl(Animator animator, string creature, Vector3 position) + { + string trigger; + bool animated = TryHowlAnimation(animator, creature, out trigger); + + // A trigger replicates to the other clients; a state played directly does not. + if (animated && trigger != null) FenrirAttackSync.Publish(trigger); + + if (!animated || !HowlAnimationHasSound.Contains(creature)) + { + PlayHowl(creature, position); + } + } + /// /// Makes the worn creature perform its own howl, and says whether it could. /// @@ -1216,9 +1246,9 @@ namespace RacesOfValheim /// - /// The howl on demand, which for this creature is the animation and nothing else: its clip - /// carries the sound as an event, so spawning one on top would be a second howl over the - /// first. The prefab is only reached if the animator turns out to have no howl at all. + /// The howl on demand. For the wolf it is the animation and nothing else: 'C_Hawl' carries + /// the sound as an event, so spawning a prefab on top would be a second howl over the first. + /// FenrirCreatureSound.Howl knows which creatures those are. /// private IEnumerator WolfHowlRoutine() { @@ -1227,15 +1257,7 @@ namespace RacesOfValheim try { wolfAnim.SetFloat("forward_speed", 0f); } catch {} try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} - string trigger; - if (FenrirCreatureSound.TryHowlAnimation(wolfAnim, "Wolf", out trigger)) - { - if (trigger != null) FenrirAttackSync.Publish(trigger); - } - else - { - FenrirCreatureSound.PlayHowl("Wolf", Player.m_localPlayer.transform.position); - } + FenrirCreatureSound.Howl(wolfAnim, "Wolf", Player.m_localPlayer.transform.position); // The wolf's howl clip runs 3.13s. Held a little past it so the form does not snap back // into a bite the instant the sound ends. @@ -1427,9 +1449,10 @@ namespace RacesOfValheim /// - /// The howl on demand, which for this creature is the animation and nothing else: its clip - /// carries the sound as an event, so spawning one on top would be a second howl over the - /// first. The prefab is only reached if the animator turns out to have no howl at all. + /// The howl on demand. The Ulv animates one and carries NO sound with it - 'Idle Howl' has no + /// events at all - so unlike the wolf it needs a prefab played over the animation. Assuming + /// the two behaved alike is what left this howl silent; FenrirCreatureSound.Howl holds the + /// distinction now. /// private IEnumerator UlvHowlRoutine() { @@ -1438,19 +1461,11 @@ namespace RacesOfValheim try { ulvAnim.SetFloat("forward_speed", 0f); } catch {} try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} - string trigger; - if (FenrirCreatureSound.TryHowlAnimation(ulvAnim, "Ulv", out trigger)) - { - if (trigger != null) FenrirAttackSync.Publish(trigger); - } - else - { - FenrirCreatureSound.PlayHowl("Ulv", Player.m_localPlayer.transform.position); - } + FenrirCreatureSound.Howl(ulvAnim, "Ulv", Player.m_localPlayer.transform.position); - // The wolf's howl clip runs 3.13s. Held a little past it so the form does not snap back - // into a bite the instant the sound ends. - yield return new WaitForSeconds(3.3f); + // The Ulv's 'Idle Howl' runs 3.67s. Held a little past it so the form does not snap + // back into a bite the instant it ends. + yield return new WaitForSeconds(3.8f); isAttacking = false; } From 2b900d91e782dfa0f30f2364591f7fe6ed76206b Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 17:15:21 +0200 Subject: [PATCH 066/290] fix(input): the radial menu no longer swings the form it is opening a menu on Clicking an entry in the race wheel also fired the transformed form's attack. The click picks the entry AND is read here as a raw mouse button, because the forms read the device directly rather than going through Humanoid.StartAttack. Vanilla attacks never had this: they go through ZInput, which the radial already blocks, so only input read straight off the device got through - which is all of ours. Hud.InRadial() answers it, the same shape of call as the Hud.IsPieceSelectionVisible() already here for the hammer's build panel. That is now the second GUI Player.TakeInput knows nothing about. CHECKED IN AttackDown AND NOT IN Allowed, deliberately. The radial fires an ability by queueing its keybind through Press(), and the ability's own reader picks that up inside an Allowed gate - so blocking Allowed while the wheel is open would risk the wheel swallowing the abilities it exists to trigger. The second half is the same bug one layer down: an ability bound to a mouse BUTTON does not go through AttackDown at all. Skadi's cold spell sits on middle mouse, so middle-clicking an entry in the wheel cast it. IsDownIgnoringHeldKeys now takes the queued press first and without any gate - that one is the radial itself - and ignores a raw mouse button while the wheel is up. Keys at the keyboard are untouched: nothing about an open wheel makes pressing K ambiguous. Co-Authored-By: Claude Opus 5 --- JotunnModStub/RaceInput.cs | 55 +++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/RaceInput.cs b/JotunnModStub/RaceInput.cs index 4ec970b..2622a5d 100644 --- a/JotunnModStub/RaceInput.cs +++ b/JotunnModStub/RaceInput.cs @@ -15,13 +15,16 @@ namespace RacesOfValheim /// (InventoryGui covers the backpack and chests alike), so mirror that instead of maintaining /// a parallel list of GUI checks that would drift as the game changes. /// - /// ONE GUI THAT TakeInput DOES NOT COVER: the hammer's piece selection panel. Read off the IL, + /// TWO GUIS THAT TakeInput DOES NOT COVER. The first is the hammer's piece selection panel. Read off the IL, /// TakeInput tests Chat, Console, TextInput, StoreGui, InventoryGui, Menu, TextViewer, the map, /// free-fly and the barber - and nothing else. Vanilla does not need it there because build /// input is handled separately in UpdatePlacement, but a mod ability reading the device /// directly does: Skadi's cold spell is bound to middle mouse and kept casting while the build /// menu was open. Hud.IsPieceSelectionVisible is static, public and null-safe on its own /// instance, so it costs one call and no reflection. + /// + /// The second is the radial menu, and it is handled in AttackDown rather than here - see + /// RadialOpen for why the difference matters. /// public static class RaceInput { @@ -77,8 +80,18 @@ namespace RacesOfValheim ///
public static bool IsDownIgnoringHeldKeys(this KeyboardShortcut shortcut) { + // The queued press is taken FIRST and without any gate, because that is the radial menu + // firing this very ability - see Press(). Everything below is the device being read raw. if (ConsumePress(shortcut)) return true; if (shortcut.MainKey == KeyCode.None) return false; + + // A keybind that sits on a mouse button is the radial's own click as far as the device is + // concerned, so the wheel closes this door too. AttackDown covers the forms' attacks; + // this covers abilities bound to a button instead - Skadi's cold spell is on middle + // mouse, and middle-clicking an entry in the wheel used to cast it. Keys at the keyboard + // are left alone: nothing about the wheel makes pressing K ambiguous. + if (RadialOpen && IsMouseButton(shortcut.MainKey)) return false; + if (!Input.GetKeyDown(shortcut.MainKey)) return false; foreach (KeyCode modifier in shortcut.Modifiers) @@ -143,15 +156,55 @@ namespace RacesOfValheim ///
public static bool AttackDown(int mouseButton) { + if (RadialOpen) return false; return Input.GetMouseButtonDown(mouseButton) || PadAttackDown(mouseButton); } /// Held-down counterpart of . public static bool AttackHeld(int mouseButton) { + if (RadialOpen) return false; return Input.GetMouseButton(mouseButton) || PadAttackHeld(mouseButton); } + /// + /// Whether the radial menu is up, which is a third GUI TakeInput knows nothing about. + /// + /// Clicking an entry in the wheel was also swinging the transformed form's attack: the click + /// picks the entry AND is read here as a raw mouse button. Vanilla attacks are untouched by + /// this because they go through ZInput, which the radial already blocks - only input read + /// straight off the device gets through, which is all of ours. + /// + /// CHECKED HERE AND NOT IN , deliberately. The radial fires an ability by + /// queueing its keybind through Press(), and the ability's own reader picks that up inside an + /// Allowed gate - so blocking Allowed while the wheel is open would risk the wheel swallowing + /// the very abilities it exists to trigger. The queued press does survive, since it holds for + /// PressWindow rather than a single frame, but there is no reason to lean on that when only + /// the mouse reads are the problem. Keybinds pressed at the keyboard while the wheel is open + /// are left alone for the same reason. + /// + private static bool IsMouseButton(KeyCode key) + { + return key >= KeyCode.Mouse0 && key <= KeyCode.Mouse6; + } + + private static bool RadialOpen + { + get + { + try + { + return Hud.InRadial(); + } + catch + { + // Fail open, like the TakeInput path above: a game update that moves this must + // cost the fix, not every attack in every form. + return false; + } + } + } + /// The gamepad half of alone, for attacks whose mouse /// side is a rebindable KeyboardShortcut rather than a fixed button. public static bool PadAttackDown(int mouseButton) From e973e2100307757da11087cce92a89e1071e173b Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 17:30:35 +0200 Subject: [PATCH 067/290] chore(input): quieten the radial proof to one line per state The transition log did its job - it showed Hud.InRadial() reporting False at spawn with no wheel on screen, which is what the gate depends on and what the method's name alone could not promise. Left in, because that proof is worth one line in every player's log, but said once per state instead of twice per use of the wheel. Co-Authored-By: Claude Opus 5 --- JotunnModStub/RaceInput.cs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/RaceInput.cs b/JotunnModStub/RaceInput.cs index 2622a5d..283b34e 100644 --- a/JotunnModStub/RaceInput.cs +++ b/JotunnModStub/RaceInput.cs @@ -188,13 +188,33 @@ namespace RacesOfValheim return key >= KeyCode.Mouse0 && key <= KeyCode.Mouse6; } + // Said once for each answer it ever gives, and then never again. The whole gate rests on what + // Hud.InRadial() means, and that was read off the method's name rather than its body - so it + // is worth one line of proof in every player's log that it reports False with no wheel on + // screen. If it ever logs only True, the gate is eating input it has no business eating. + private static bool loggedOpen; + private static bool loggedClosed; + private static bool RadialOpen { get { try { - return Hud.InRadial(); + bool open = Hud.InRadial(); + + if (open && !loggedOpen) + { + loggedOpen = true; + Jotunn.Logger.LogInfo("[RaceInput] Radial menu open: form attacks and mouse-bound abilities are held."); + } + else if (!open && !loggedClosed) + { + loggedClosed = true; + Jotunn.Logger.LogInfo("[RaceInput] Radial menu closed: form attacks and mouse-bound abilities are live."); + } + + return open; } catch { From 97d02855e5fda8df211ed7aa938d35dd46b61d77 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 18:12:34 +0200 Subject: [PATCH 068/290] feat(skadi): say why a Cold Spell press did not cast, and log each step of the cast Every gate on the spell was silent, so "it does nothing" looked the same as "it was never pressed". Each refusal now logs its reason once per session, and the cast logs each step before taking it, because the crash it chases kills the process without a stack trace. The prefab descriptions run after the Instantiate, so reading them can't be what makes the spawn safe. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Skadi/SkadiRace.cs | 140 +++++++++++++++++++++++++++++-- 1 file changed, 133 insertions(+), 7 deletions(-) diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index cfe78d4..4746139 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -232,6 +232,12 @@ namespace RacesOfValheim { HandleColdSpell(rules); } + else if (ColdSpellKeyPressed()) + { + ColdSpellBail(!rules.ColdSpell + ? $"the tier does not grant it - state {BossProgressionManager.GetCurrentProgressionState()}, needs 2" + : "RaceInput.Allowed is false - a GUI has the input"); + } if (isTransformingSequence) return; @@ -334,16 +340,84 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo($"=== END {prefabName.ToUpper()} DEBUG INFO ==="); } + /// + /// Whether the Cold Spell's own key went down this frame, read raw and with no gate at all. + /// Only for the diagnostics below: five different conditions can swallow this spell and every + /// one of them is silent, so "it does nothing" was impossible to tell apart from "it was + /// never pressed". + /// + private static bool ColdSpellKeyPressed() + { + KeyCode key = SkadiConfig.ColdSpellKey.Value.MainKey; + return key != KeyCode.None && Input.GetKeyDown(key); + } + + private static readonly System.Collections.Generic.HashSet coldSpellBails = + new System.Collections.Generic.HashSet(); + + /// One step of the cast, said before it is taken. Once per distinct step. + private static void ColdSpellStep(string step) + { + if (coldSpellBails.Add("step:" + step)) + { + Jotunn.Logger.LogInfo($"[Skadi] Cold Spell: {step}."); + } + } + + /// + /// What a borrowed prefab actually is. The root flag matters for the same reason it did on + /// the Skeleton's fire aura: a parented object is a node inside somebody else's hierarchy, + /// not a prefab, and spawning one on its own is how this mod has crashed before. + /// + private static string Describe(GameObject prefab) + { + if (prefab == null) return "null"; + + string path = prefab.name; + for (Transform t = prefab.transform.parent; t != null; t = t.parent) path = t.name + "/" + path; + + var parts = new System.Collections.Generic.List(); + foreach (Component comp in prefab.GetComponents()) + { + if (comp != null && !(comp is Transform)) parts.Add(comp.GetType().Name); + } + + return $"{path}' root={prefab.transform.parent == null} carries=[{string.Join(", ", parts.ToArray())}]"; + } + + /// Says why a press did not become a cast, once per reason per session. + private static void ColdSpellBail(string reason) + { + if (coldSpellBails.Add(reason)) + { + Jotunn.Logger.LogInfo($"[Skadi] Cold Spell key pressed but not cast: {reason}."); + } + } + private void HandleColdSpell(SkadiProgression.FormRules rules) { - if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return; - if (isTransformed) return; // Do not cast human spell while in dragon form + bool pressed = ColdSpellKeyPressed(); + + if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) + { + if (pressed) ColdSpellBail("the player is dead"); + return; + } + if (isTransformed) + { + if (pressed) ColdSpellBail("you are in a dragon form"); + return; + } // Hammer, hoe or cultivator in hand: every build button is vanilla's. Middle mouse is // Remove on the keyboard, and on the pad JoySecondaryAttack shares its physical button // with JoyRemove (Classic) or JoyPlace (Alt2) - read off ZInput.AddGamepad*Buttons - so // each piece built or removed also cast the spell and drained the stamina for it. - if (Player.m_localPlayer.InPlaceMode()) return; + if (Player.m_localPlayer.InPlaceMode()) + { + if (pressed) ColdSpellBail("a hammer, hoe or cultivator is in hand"); + return; + } // Middle Mouse Button to cast, by default - rebindable via SkadiConfig.ColdSpellKey. // On a gamepad, the secondary attack button (the pad's own middle-mouse equivalent) - @@ -354,7 +428,11 @@ namespace RacesOfValheim { // The improved cast is a burst rather than a rapid-fire, so it waits longer. float cooldown = rules.ImprovedColdSpell ? IMPROVED_SPELL_COOLDOWN : SPELL_COOLDOWN; - if (Time.time - lastSpellTime < cooldown) return; + if (Time.time - lastSpellTime < cooldown) + { + ColdSpellBail($"it is on cooldown - {cooldown - (Time.time - lastSpellTime):F1}s left of {cooldown:F0}s"); + return; + } // Stamina, never eitr: the spell unlocks at Eikthyr but eitr food only exists from // the Mistlands onward, so the old HaveEitr gate left it unusable for five tiers. @@ -378,8 +456,17 @@ namespace RacesOfValheim zanim.SetTrigger("gpower"); } + if (coldSpellBails.Add("cast")) Jotunn.Logger.LogInfo("[Skadi] Cold Spell cast."); + StartCoroutine(ColdSpellKickCoroutine(rules)); } + else if (pressed) + { + // The key physically went down and the wrapper still said no. That is the last place + // left for this to fail, and the only one with no condition of its own above it. + ColdSpellBail($"'{SkadiConfig.ColdSpellKey.Value.MainKey}' went down but " + + "IsDownIgnoringHeldKeys refused it"); + } } /// @@ -402,10 +489,31 @@ namespace RacesOfValheim if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) yield break; + // EVERY STEP BELOW IS SAID BEFORE IT IS TAKEN, once per session. Casting this spell exits + // the process outright - no exception, no stack, the log simply stops - which is the same + // signature as sfx_fenring_howl, the sound that cannot be spawned either. The only reason + // we know where either one dies is that the line before it had already been flushed. + ColdSpellStep("resolving 'StaffIceShards'"); + GameObject staffPrefab = PrefabManager.Cache.GetPrefab("StaffIceShards"); - if (staffPrefab == null) yield break; + if (staffPrefab == null) + { + ColdSpellStep("'StaffIceShards' did not resolve - no shards fired"); + yield break; + } ItemDrop staffDrop = staffPrefab.GetComponent(); - if (staffDrop == null) yield break; + if (staffDrop == null) + { + ColdSpellStep("'StaffIceShards' has no ItemDrop - no shards fired"); + yield break; + } + // NOT described here, deliberately, and this is an experiment rather than a style choice. + // Describe() reads the prefab's components, and reading them may be what forces a + // soft-referenced asset to finish loading - which would mean the diagnostic was quietly + // fixing the crash it was added to measure. Both descriptions now run AFTER the shards + // are spawned, so nothing touches either prefab before the Instantiate that was dying. + // If the crash comes back, the touch was the fix and becomes a real one. If it does not, + // the crash was never about loading. string projName = rules.ImprovedColdSpell ? "hatchling_cold_projectile" : null; GameObject projPrefab = null; @@ -418,7 +526,13 @@ namespace RacesOfValheim { projPrefab = staffDrop.m_itemData.m_shared.m_attack.m_attackProjectile; // Default Staff of Frost projectile } - if (projPrefab == null) yield break; + if (projPrefab == null) + { + ColdSpellStep("no projectile prefab at all - no shards fired"); + yield break; + } + ColdSpellStep("projectile chosen from " + + (projName != null ? $"'{projName}' or the staff" : "the staff")); int count = rules.ImprovedColdSpell ? IMPROVED_SPELL_SHARDS : 1; @@ -446,7 +560,19 @@ namespace RacesOfValheim Vector3 spawnPos = Player.m_localPlayer.transform.position + Vector3.up * 1.4f + lookDir * 0.6f; + ColdSpellStep($"instantiating shard {i + 1} of {count}"); + GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(lookDir)); + + ColdSpellStep("shard instantiated"); + + // Described only now that a shard has survived being spawned, so the reading itself + // cannot be what made the spawning safe. See the note above the staff lookup. + if (i == 0) + { + ColdSpellStep($"staff was '{Describe(staffPrefab)}"); + ColdSpellStep($"projectile was '{Describe(projPrefab)}"); + } Projectile proj = projInstance.GetComponent(); if (proj != null) From 5bdd7200a58ba805f2e3860f7bc75acae9f37786 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 18:17:37 +0200 Subject: [PATCH 069/290] fix(fenrir): the Ulv no longer asks the player for feet called LeftHand The form's CharacterAnimEvent finds its FootStep on the nearest Character up the hierarchy, which for a form parented under the player is the player. The Ulv's Run clip names its front paws LeftHand and RightHand, a human rig has neither, and vanilla logged "FAiled to find foot" twice per stride. The form's receivers are now cut from the player's FootStep, on the local form and on the copy other players see. The footsteps stay: the hidden human animator keeps running and FootStep steps off its curve. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Fenrir/FenrirRace.cs | 2 ++ JotunnModStub/Fenrir/FormFootsteps.cs | 47 +++++++++++++++++++++++++++ JotunnModStub/ZdoVisualSync.cs | 4 ++- 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 JotunnModStub/Fenrir/FormFootsteps.cs diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index 4e55a80..5c00200 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -383,6 +383,8 @@ namespace RacesOfValheim { Component animEvent = currentTransformation.GetComponent("AnimEvent"); if (animEvent != null) Destroy(animEvent); + FormFootsteps.Detach(currentTransformation, prefabName); + // The creature's own animations carry their sounds as events; this is what hears // them. On the object that owns the Animator, because that is where Unity delivers // an animation event - for the wolf that is WolfSmooth, two levels down, not the diff --git a/JotunnModStub/Fenrir/FormFootsteps.cs b/JotunnModStub/Fenrir/FormFootsteps.cs new file mode 100644 index 0000000..d106301 --- /dev/null +++ b/JotunnModStub/Fenrir/FormFootsteps.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Stops a Fenrir form's own animations from stepping on the player's FootStep. + /// + /// The form's CharacterAnimEvent resolves its FootStep in Awake, from + /// GetComponentInParent<Character>() - and a form parented under the player finds the + /// PLAYER. So when the Ulv's 'Run' clip fires FootStep('LeftHand') and FootStep('RightHand') + /// for its front paws, vanilla looks for feet with those names on a human rig, finds none, and + /// logs "FAiled to find foot:LeftHand" twice per stride. That is the warning a user reported. + /// + /// Nothing is lost by cutting the link. The player's hidden Visual keeps animating (the hider + /// only switches renderers off), and FootStep drives its steps from that animator's footstep + /// curve, so the form already has footsteps. A form event naming a foot the player does have + /// would only play a second step on top of that one. + /// + /// CharacterAnimEvent.FootStep checks m_footStep before calling it, so nulling the field is + /// all it takes. It has to happen after Instantiate, which is when that Awake has run. + /// + internal static class FormFootsteps + { + private static readonly HashSet logged = new HashSet(); + + public static void Detach(GameObject form, string formName) + { + if (form == null) return; + + int detached = 0; + foreach (CharacterAnimEvent cae in form.GetComponentsInChildren(true)) + { + var field = HarmonyLib.Traverse.Create(cae).Field("m_footStep"); + if (field.GetValue() == null) continue; + field.SetValue(null); + detached++; + } + + if (logged.Add(formName)) + { + Jotunn.Logger.LogInfo( + $"[FenrirForm] '{formName}': {detached} animation-event receiver(s) cut from the player's FootStep."); + } + } + } +} diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index 686a831..93422ed 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -212,7 +212,9 @@ namespace RacesOfValheim m_currentFormInstance.transform.localRotation = Quaternion.identity; Component animEvent = m_currentFormInstance.GetComponent("AnimEvent"); if (animEvent != null) Destroy(animEvent); - + + FormFootsteps.Detach(m_currentFormInstance, currentForm); + // Clean up colliders on remote visuals foreach (var col in m_currentFormInstance.GetComponentsInChildren()) { From 8f477dd3be5c1c47f890be04334404b6dad2ee17 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 18:29:34 +0200 Subject: [PATCH 070/290] fix(aswid): Eclipse brings the night instead of dying on its first line The coroutine set EnvMan's two debug-time fields the wrong way round and asked for 0.5, which is noon. Handing a bool to the float field threw, so the cast stopped right after the announcement and IsEclipseActive stayed true, and every later press returned without a word. The fields are now set directly, to midnight, and a finally frees the ability if anything in there throws again. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Aswid/AswidRace.cs | 35 +++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index b1f1cd2..b3612bc 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -887,23 +887,34 @@ namespace RacesOfValheim yield return null; } - // Force night client-side - if (EnvMan.instance != null) + // Force night client-side. EnvMan's switch is the bool m_debugTimeOfDay and the time it + // pins is the float m_debugTime, a day fraction where 0 is midnight and 0.5 is noon. + // These two used to be written the other way round: handing a bool to the float threw, + // the coroutine died right after "An Eclipse descends...", and IsEclipseActive stayed + // true for the rest of the session, so every later press returned without a word. + // Public fields both, so no Traverse to get the names wrong through. + try { - HarmonyLib.Traverse.Create(EnvMan.instance).Field("m_debugTime").SetValue(true); - HarmonyLib.Traverse.Create(EnvMan.instance).Field("m_debugTimeOfDay").SetValue(0.5f); // Midnight + if (EnvMan.instance != null) + { + EnvMan.instance.m_debugTime = 0f; + EnvMan.instance.m_debugTimeOfDay = true; + } + + yield return new WaitForSeconds(AswidConfig.EclipseDuration.Value); + } + finally + { + // In a finally so that a throw in here can never again leave the ability locked. + // Unity does not dispose a coroutine it stops, so this does not cover that case. + if (EnvMan.instance != null) EnvMan.instance.m_debugTimeOfDay = false; + IsEclipseActive = false; } - yield return new WaitForSeconds(AswidConfig.EclipseDuration.Value); - - // Revert to server time - if (EnvMan.instance != null) + if (Player.m_localPlayer != null) { - HarmonyLib.Traverse.Create(EnvMan.instance).Field("m_debugTime").SetValue(false); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The Eclipse has ended."); } - - IsEclipseActive = false; - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The Eclipse has ended."); } private float damageTickTimer = 0f; From 0674329592adbe36e54af39863217563558bcbea Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 18:50:51 +0200 Subject: [PATCH 071/290] fix(fenrir): spawn sounds the way vanilla spawns effects, without ghost init Ghost init was meant to keep a sound's ZNetView from writing a ZDO. It does not: ZNetView.Awake still creates the ZDO and only skips registering the instance, so ZNetScene sees an unbuilt ZDO and builds a second copy. Vanilla's EffectList.Create uses a plain Instantiate, and TimedDestruction deletes the ZDO through ZNetScene.Destroy when the sound ends. The spawn now does the same. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Fenrir/FenrirBehaviors.cs | 36 ++++++++-------------- JotunnModStub/Fenrir/FormAnimEventSound.cs | 3 +- 2 files changed, 14 insertions(+), 25 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 86d25fc..9b13a35 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -214,36 +214,26 @@ namespace RacesOfValheim } /// - /// Spawns a sound prefab without letting it write itself into the save. + /// Spawns a sound prefab the way the game's own EffectList.Create does: a plain Instantiate. /// - /// SOME VANILLA SOUND PREFABS CARRY A ZNetView. "sfx_fenring_alerted" is one - the Describe - /// line below printed it, which is how this was noticed. A ZNetView that wakes with no init - /// ZDO calls ZDOMan.CreateNewZDO at its position, marks itself persistent, stamps itself with - /// the prefab hash and registers with the scene. On a sound played every time somebody howls - /// or swings a claw, that is one persistent "there is a noise here" record per swing, saved - /// with the world. It is the same bug that left burnt-in torches in people's worlds; the long - /// version is on SkeletonVisuals.BorrowEffect. + /// THIS USED TO WRAP THE INSTANTIATE IN ZNetView GHOST INIT, and that was wrong. Some vanilla + /// sound and effect prefabs carry a ZNetView ("sfx_fenring_alerted" does), and the fear was + /// one persistent ZDO per play left in the save. The ones logged so far also carry + /// TimedDestruction, which ends in ZNetScene.Destroy, and that deletes the ZDO. They are + /// network effects by design, which is how other players hear them. /// - /// ZNetView.StartGhostInit is the game's own answer, not ours: between the two calls a - /// ZNetView comes up with no ZDO at all. Cheaper and far less invasive than stripping the - /// component off a copy, and free on the prefabs that carry no ZNetView. - /// - /// The finally matters. Leaving ghost init switched on because an Instantiate threw would - /// break every ZNetView created afterwards, for the rest of the session. + /// Ghost init does not prevent the ZDO either. Read off ZNetView.Awake: it still calls + /// CreateNewZDO and only skips ZNetScene.AddInstance. That leaves the ZDO with Created=false, + /// and ZNetScene.CreateObjectsSorted builds a second copy of the object from it. Vanilla + /// uses ghost init for zone generation, where the ZDOs are the point and the objects are not. + /// The switch that really yields no ZDO is m_forceDisableInit, which is for item icons and + /// inventory copies, not for anything meant to be seen or heard by others. /// public static void Spawn(GameObject prefab, Vector3 position) { if (prefab == null) return; - ZNetView.StartGhostInit(); - try - { - Object.Instantiate(prefab, position, Quaternion.identity); - } - finally - { - ZNetView.FinishGhostInit(); - } + Object.Instantiate(prefab, position, Quaternion.identity); // NOT FOLLOWED BY A Play() CALL, and that took a while to establish. ZSFX is ticked by // CustomUpdate rather than Unity's Update, so it starts on a later frame: reading diff --git a/JotunnModStub/Fenrir/FormAnimEventSound.cs b/JotunnModStub/Fenrir/FormAnimEventSound.cs index 4fdea87..3a2ee51 100644 --- a/JotunnModStub/Fenrir/FormAnimEventSound.cs +++ b/JotunnModStub/Fenrir/FormAnimEventSound.cs @@ -81,8 +81,7 @@ namespace RacesOfValheim if (!audible) return; - // Through the same ghost-init spawn as everything else here: some vanilla sound prefabs - // carry a ZNetView, and this one fires every time the animation comes round. + // Through the same spawn as every other Fenrir sound, so a change there reaches this too. FenrirCreatureSound.Spawn(prefab, transform.position); } } From 055635d1b43c6b7c061c8a243c947491f4f30346 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 19:16:08 +0200 Subject: [PATCH 072/290] feat(aswid): Eclipse runs the sky through dusk instead of cutting to night While EnvMan's debug time is on it copies the value straight onto the sky, so setting midnight in one go made night fall in a single frame. The clock now eases forward from the current hour to midnight over 3.5 seconds. The dawn already eased back on its own, because EnvMan smooths towards the real time once the switch is off. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Aswid/AswidRace.cs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index b3612bc..7a7543f 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -863,6 +863,9 @@ namespace RacesOfValheim StartCoroutine(EclipseRoutine()); } + /// How long the sky takes to run from the cast to midnight. + private const float EclipseDuskSeconds = 3.5f; + private System.Collections.IEnumerator EclipseRoutine() { IsEclipseActive = true; @@ -897,8 +900,22 @@ namespace RacesOfValheim { if (EnvMan.instance != null) { - EnvMan.instance.m_debugTime = 0f; + // Run the clock forward through dusk to midnight rather than cutting to it. + // While m_debugTimeOfDay is on, EnvMan copies m_debugTime straight onto the sky + // with no smoothing of its own, so the easing has to happen here. Forward means + // up to 1, which is midnight again; the Aswid's night buffs start at 0.75, + // partway through. The way back needs nothing: once the switch is off, EnvMan + // eases towards the real time by itself. + float from = EnvMan.instance.GetDayFraction(); + EnvMan.instance.m_debugTime = from; EnvMan.instance.m_debugTimeOfDay = true; + + for (float t = 0f; t < EclipseDuskSeconds && EnvMan.instance != null; t += Time.deltaTime) + { + EnvMan.instance.m_debugTime = Mathf.Lerp(from, 1f, Mathf.SmoothStep(0f, 1f, t / EclipseDuskSeconds)); + yield return null; + } + if (EnvMan.instance != null) EnvMan.instance.m_debugTime = 1f; } yield return new WaitForSeconds(AswidConfig.EclipseDuration.Value); From 52c26d9b52383b31c56e6945e10bf27729007650 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 19:24:23 +0200 Subject: [PATCH 073/290] feat(aswid): the Eclipse's dusk spends its time on the sunset An even sweep from the afternoon to midnight looked still for three seconds and then fell dark in half of one, because the sky hardly changes between 0.25 and 0.75 and does its darkening around sunset. The dusk now walks keyframes: half a second to late afternoon, three through the sunset band, half a second to midnight. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Aswid/AswidRace.cs | 44 +++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index 7a7543f..c864a7f 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -863,8 +863,37 @@ namespace RacesOfValheim StartCoroutine(EclipseRoutine()); } - /// How long the sky takes to run from the cast to midnight. - private const float EclipseDuskSeconds = 3.5f; + /// + /// The Eclipse's dusk as (seconds, day fraction) keys, walked linearly between them. + /// + /// Not one even sweep, because the sky does not change evenly. EnvMan keeps it looking like + /// day from 0.25 to 0.75 and does all its darkening around sunset, so an even run from + /// the afternoon to midnight looked still for three seconds and then fell dark in half of + /// one. Here the afternoon goes by in half a second and the sunset band gets three. + /// The first key's fraction is replaced by the time of the cast, and any key earlier in + /// the day than that is lifted to it, so a cast near dusk does not run the clock backwards. + /// + private static readonly Vector2[] EclipseDuskKeys = + { + new Vector2(0f, 0f), // the time of the cast + new Vector2(0.5f, 0.70f), // late afternoon, just before the sky starts to change + new Vector2(3.5f, 0.95f), // through the sunset band, slowly + new Vector2(4f, 1f), // midnight + }; + + private static float EclipseDuskFraction(float from, float seconds) + { + float prevT = 0f, prevF = from; + for (int i = 1; i < EclipseDuskKeys.Length; i++) + { + float keyT = EclipseDuskKeys[i].x; + float keyF = Mathf.Max(EclipseDuskKeys[i].y, from); + if (seconds <= keyT) return Mathf.Lerp(prevF, keyF, Mathf.InverseLerp(prevT, keyT, seconds)); + prevT = keyT; + prevF = keyF; + } + return 1f; + } private System.Collections.IEnumerator EclipseRoutine() { @@ -902,17 +931,18 @@ namespace RacesOfValheim { // Run the clock forward through dusk to midnight rather than cutting to it. // While m_debugTimeOfDay is on, EnvMan copies m_debugTime straight onto the sky - // with no smoothing of its own, so the easing has to happen here. Forward means - // up to 1, which is midnight again; the Aswid's night buffs start at 0.75, - // partway through. The way back needs nothing: once the switch is off, EnvMan + // with no smoothing of its own, so the pacing has to happen here - see + // EclipseDuskKeys. Forward means up to 1, which is midnight again; the Aswid's + // night buffs start at 0.75, partway through. The way back needs nothing: once the switch is off, EnvMan // eases towards the real time by itself. float from = EnvMan.instance.GetDayFraction(); EnvMan.instance.m_debugTime = from; EnvMan.instance.m_debugTimeOfDay = true; - for (float t = 0f; t < EclipseDuskSeconds && EnvMan.instance != null; t += Time.deltaTime) + float duskSeconds = EclipseDuskKeys[EclipseDuskKeys.Length - 1].x; + for (float t = 0f; t < duskSeconds && EnvMan.instance != null; t += Time.deltaTime) { - EnvMan.instance.m_debugTime = Mathf.Lerp(from, 1f, Mathf.SmoothStep(0f, 1f, t / EclipseDuskSeconds)); + EnvMan.instance.m_debugTime = EclipseDuskFraction(from, t); yield return null; } if (EnvMan.instance != null) EnvMan.instance.m_debugTime = 1f; From 19c934777235603075b60785a33af151b80c2b2f Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 19:30:56 +0200 Subject: [PATCH 074/290] fix(skadi): the Cold Spell key's description says tier 2+, where it unlocks Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Skadi/SkadiConfig.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Skadi/SkadiConfig.cs b/JotunnModStub/Skadi/SkadiConfig.cs index 22db0ab..133d7c1 100644 --- a/JotunnModStub/Skadi/SkadiConfig.cs +++ b/JotunnModStub/Skadi/SkadiConfig.cs @@ -90,7 +90,7 @@ namespace RacesOfValheim PrimaryAttackKey = config.Bind(keybinds, "Dragon Primary Attack", new KeyboardShortcut(KeyCode.Mouse0), KeyDesc("Bite/claw attack in any dragon form.", keyOrder--)); ColdSpellKey = config.Bind(keybinds, "Cold Spell Cast", new KeyboardShortcut(KeyCode.Mouse2), - KeyDesc("Casts the Cold Spell in human form, tier 1+.", keyOrder--)); + KeyDesc("Casts the Cold Spell in human form, tier 2+ (Eikthyr).", keyOrder--)); BreathAttackKey = config.Bind(keybinds, "Dragon Breath Attack", new KeyboardShortcut(KeyCode.Mouse2), KeyDesc("Ranged breath/barrage attack in Moder and Skeleton Dragon form.", keyOrder--)); SpinAttackKey = config.Bind(keybinds, "Fader Spin Attack", new KeyboardShortcut(KeyCode.Mouse1), From 73b67cd6ce547057e070a666d6f261018584ee62 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 19:43:48 +0200 Subject: [PATCH 075/290] feat(text): the race menu reads its texts from translation files First step of moving every piece of text out of the code so modders can translate the mod. The texts live in Translations//*.json, one file per kind of text, which Jotunn finds on its own and falls back to English for. ModText reads them; values take Valheim's $1, $2 placeholders. This step covers the race selection menu: title, buttons, every race's name and description, in English and Italian. The race ID and the name on screen are now separate strings. The ID is what the save and the ZDO hold, so it must never be translated. The files are deployed to plugins\RacesOfValheim\Translations and packed into both release zips. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/ModText.cs | 50 +++++++++++++++++++ JotunnModStub/RacesOfValheim.cs | 48 ++++++++++-------- JotunnModStub/RacesOfValheim.csproj | 17 ++++++- JotunnModStub/Translations/English/races.json | 38 ++++++++++++++ JotunnModStub/Translations/Italian/races.json | 38 ++++++++++++++ 5 files changed, 169 insertions(+), 22 deletions(-) create mode 100644 JotunnModStub/ModText.cs create mode 100644 JotunnModStub/Translations/English/races.json create mode 100644 JotunnModStub/Translations/Italian/races.json diff --git a/JotunnModStub/ModText.cs b/JotunnModStub/ModText.cs new file mode 100644 index 0000000..4e43258 --- /dev/null +++ b/JotunnModStub/ModText.cs @@ -0,0 +1,50 @@ +using System.Linq; + +namespace RacesOfValheim +{ + /// + /// Every piece of text the mod shows, read from the translation files instead of the code. + /// + /// The files are JSON under Translations/<Language>/, one per kind of text, next to the DLL. + /// Jotunn finds them on its own: it searches the whole plugins folder for any .json whose + /// grandparent folder is called "Translations", takes the language from the folder name + /// (Valheim's own names: English, Italian, German...), and falls back to English for any key a + /// language leaves out. A key missing from English too shows up on screen as [key]. + /// + /// Keys go in the files without the leading $ and are read here the same way. Values take + /// Valheim's own placeholders, $1, $2..., filled from the arguments in order, so a translator + /// can move a number to wherever their grammar wants it. + /// + internal static class ModText + { + public static string Get(string key, params object[] args) + { + if (Localization.instance == null) return "[" + key + "]"; + + string[] words = args.Select(a => a?.ToString() ?? "").ToArray(); + return Localization.instance.Localize("$" + key, words); + } + + /// + /// A race's name as the player reads it. Only ever for display. + /// + /// The race ID ("Skadi", "Trol"...) is a different thing and never goes through here: it is + /// written into the character save and the ZDO, and compared all over the code. Translate + /// that and a character saved under one language stops being recognised under another. + /// + public static string RaceName(string raceId) + { + return Get(RaceKey(raceId) + "_name"); + } + + public static string RaceDescription(string raceId, params object[] args) + { + return Get(RaceKey(raceId) + "_desc", args); + } + + private static string RaceKey(string raceId) + { + return "rov_race_" + raceId.ToLowerInvariant(); + } + } +} diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 9b7a5c3..7778632 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -303,7 +303,7 @@ namespace RacesOfValheim titleObj.transform.SetParent(selectionPanel.transform, false); Text titleText = titleObj.AddComponent(); titleText.font = GUIManager.Instance.AveriaSerifBold; - titleText.text = "Choose your Race"; + titleText.text = ModText.Get("rov_menu_choose_race"); titleText.fontSize = 50; titleText.alignment = TextAnchor.MiddleCenter; titleText.color = Color.white; @@ -346,7 +346,7 @@ namespace RacesOfValheim btnOkTxtObj.transform.SetParent(btnOkObj.transform, false); Text btnOkTxt = btnOkTxtObj.AddComponent(); btnOkTxt.font = GUIManager.Instance.AveriaSerifBold; - btnOkTxt.text = "OK"; + btnOkTxt.text = ModText.Get("rov_menu_ok"); btnOkTxt.fontSize = 24; btnOkTxt.alignment = TextAnchor.MiddleCenter; btnOkTxt.color = Color.white; @@ -371,7 +371,7 @@ namespace RacesOfValheim btnBackTxtObj.transform.SetParent(btnBackObj.transform, false); Text btnBackTxt = btnBackTxtObj.AddComponent(); btnBackTxt.font = GUIManager.Instance.AveriaSerifBold; - btnBackTxt.text = "Back"; + btnBackTxt.text = ModText.Get("rov_menu_back"); btnBackTxt.fontSize = 24; btnBackTxt.alignment = TextAnchor.MiddleCenter; btnBackTxt.color = Color.white; @@ -379,34 +379,40 @@ namespace RacesOfValheim btnBackTxtRect.anchorMin = Vector2.zero; btnBackTxtRect.anchorMax = Vector2.one; btnBackTxtRect.offsetMin = Vector2.zero; btnBackTxtRect.offsetMax = Vector2.zero; - void CreateRaceButtonWithConfirm(string label, Vector2 position, Sprite iconSprite, string description, UnityEngine.Events.UnityAction onConfirm) + // The race ID picks the texts and is what gets saved; the button, the title and the + // description only ever show the translated name. See ModText.RaceName for why the two + // must never be the same string. + void CreateRaceButtonWithConfirm(string raceId, Vector2 position, Sprite iconSprite, UnityEngine.Events.UnityAction onConfirm, params object[] descArgs) { - CreateRaceButton(label, position, iconSprite, selectionPanel.transform, () => { + string name = ModText.RaceName(raceId); + CreateRaceButton(raceId, name, position, iconSprite, selectionPanel.transform, () => { selectionPanel.SetActive(false); confirmationPanel.SetActive(true); - confTitleText.text = label; - confDescText.text = description; + confTitleText.text = name; + confDescText.text = ModText.RaceDescription(raceId, descArgs); btnOk.onClick.RemoveAllListeners(); btnOk.onClick.AddListener(onConfirm); }); } // Row 1 (y = 100) - CreateRaceButtonWithConfirm("Human", new Vector2(-450, 100), GetHumanIcon(), "The versatile founders of Midgard. Balanced stats with no specific weaknesses.", SelectHuman); - CreateRaceButtonWithConfirm("Fenrir", new Vector2(-150, 100), GetFenrirIcon(), "Cursed by the blood of the wolf. Fast and deadly, but vulnerable to silver.", SelectFenrir); - CreateRaceButtonWithConfirm("Skadi", new Vector2(150, 100), GetSkadiIcon(), "Children of the mountains. Resistant to frost, at home in the freezing cold.", SelectSkadi); - CreateRaceButtonWithConfirm("Skeleton", new Vector2(450, 100), GetSkeletonIcon(), "Undead warriors. Immune to poison, but brittle against blunt trauma.", SelectSkeleton); - + CreateRaceButtonWithConfirm("Human", new Vector2(-450, 100), GetHumanIcon(), SelectHuman); + CreateRaceButtonWithConfirm("Fenrir", new Vector2(-150, 100), GetFenrirIcon(), SelectFenrir); + CreateRaceButtonWithConfirm("Skadi", new Vector2(150, 100), GetSkadiIcon(), SelectSkadi); + CreateRaceButtonWithConfirm(SkeletonVisuals.RaceId, new Vector2(450, 100), GetSkeletonIcon(), SelectSkeleton); + // Row 2 (y = -20) - CreateRaceButtonWithConfirm("Aswid", new Vector2(-450, -20), GetAswidIcon(), "Fierce night stalker. Strong and resilient, transforms into a bat.", SelectAswid); - CreateRaceButtonWithConfirm("Furling", new Vector2(-150, -20), GetFurlingIcon(), "Cunning goblin-like creatures. Agile and resourceful.", SelectFurling); - CreateRaceButtonWithConfirm("Trol", new Vector2(150, -20), GetTrolIcon(), $"Massive brute strength. Towering over others, at peace with the Black Forest - but fire burns a Trol {(TrolConfig.FireWeaknessMultiplier.Value - 1f) * 100f:0}% harder than anyone else.", SelectTrol); - CreateRaceButtonWithConfirm("Draugh", new Vector2(450, -20), GetDraughIcon(), "A decaying undead warrior fueled by dark magic and extreme metal.", SelectDraugh); + CreateRaceButtonWithConfirm("Aswid", new Vector2(-450, -20), GetAswidIcon(), SelectAswid); + CreateRaceButtonWithConfirm("Furling", new Vector2(-150, -20), GetFurlingIcon(), SelectFurling); + // $1 in the Trol's description is how much harder fire burns it, read from the config. + CreateRaceButtonWithConfirm("Trol", new Vector2(150, -20), GetTrolIcon(), SelectTrol, + ((TrolConfig.FireWeaknessMultiplier.Value - 1f) * 100f).ToString("0")); + CreateRaceButtonWithConfirm(DraughVisuals.RaceId, new Vector2(450, -20), GetDraughIcon(), SelectDraugh); // Row 3 (y = -140) - CreateRaceButtonWithConfirm("Dvergar", new Vector2(-450, -140), GetDvergarIcon(), "Small, stubborn smiths of the deep. Frail of frame, but masters of metal, mine and market.", SelectDvergar); - CreateRaceButtonWithConfirm("Trenta", new Vector2(-150, -140), GetTrentaIcon(), "Tree-born folk, kin to root and leaf. Patient and hard to fell.", SelectTrenta); - CreateRaceButtonWithConfirm("Sverm", new Vector2(150, -140), GetSvermIcon(), "Chitin-born swarm kin. Armoured from birth and never slowed, venomous, at peace with every crawling thing - but blunt trauma and fire find the seams.", SelectSverm); + CreateRaceButtonWithConfirm(DvergarConfig.RaceId, new Vector2(-450, -140), GetDvergarIcon(), SelectDvergar); + CreateRaceButtonWithConfirm(TrentaConfig.RaceId, new Vector2(-150, -140), GetTrentaIcon(), SelectTrenta); + CreateRaceButtonWithConfirm(SvermConfig.RaceId, new Vector2(150, -140), GetSvermIcon(), SelectSverm); GUIManager.BlockInput(true); } @@ -481,9 +487,9 @@ namespace RacesOfValheim return null; } - private void CreateRaceButton(string label, Vector2 position, Sprite iconSprite, Transform parentTransform, UnityEngine.Events.UnityAction onClick) + private void CreateRaceButton(string raceId, string label, Vector2 position, Sprite iconSprite, Transform parentTransform, UnityEngine.Events.UnityAction onClick) { - GameObject btnObj = new GameObject(label + "Button"); + GameObject btnObj = new GameObject(raceId + "Button"); btnObj.transform.SetParent(parentTransform, false); RectTransform btnRect = btnObj.AddComponent(); btnRect.sizeDelta = new Vector2(250, 80); diff --git a/JotunnModStub/RacesOfValheim.csproj b/JotunnModStub/RacesOfValheim.csproj index 58ed010..188493c 100644 --- a/JotunnModStub/RacesOfValheim.csproj +++ b/JotunnModStub/RacesOfValheim.csproj @@ -138,18 +138,33 @@ + + + + + + $(REPO_ROOT)dist\ + + + $(IntermediateOutputPath)nexus\ + + + - + diff --git a/JotunnModStub/Translations/English/races.json b/JotunnModStub/Translations/English/races.json new file mode 100644 index 0000000..8d930c3 --- /dev/null +++ b/JotunnModStub/Translations/English/races.json @@ -0,0 +1,38 @@ +{ + "rov_menu_choose_race": "Choose your Race", + "rov_menu_ok": "OK", + "rov_menu_back": "Back", + + "rov_race_human_name": "Human", + "rov_race_human_desc": "The versatile founders of Midgard. Balanced stats with no specific weaknesses.", + + "rov_race_fenrir_name": "Fenrir", + "rov_race_fenrir_desc": "Cursed by the blood of the wolf. Fast and deadly, but vulnerable to silver.", + + "rov_race_skadi_name": "Skadi", + "rov_race_skadi_desc": "Children of the mountains. Resistant to frost, at home in the freezing cold.", + + "rov_race_skeleton_name": "Skeleton", + "rov_race_skeleton_desc": "Undead warriors. Immune to poison, but brittle against blunt trauma.", + + "rov_race_aswid_name": "Aswid", + "rov_race_aswid_desc": "Fierce night stalker. Strong and resilient, transforms into a bat.", + + "rov_race_furling_name": "Furling", + "rov_race_furling_desc": "Cunning goblin-like creatures. Agile and resourceful.", + + "rov_race_trol_name": "Trol", + "rov_race_trol_desc": "Massive brute strength. Towering over others, at peace with the Black Forest - but fire burns a Trol $1% harder than anyone else.", + + "rov_race_draugh_name": "Draugh", + "rov_race_draugh_desc": "A decaying undead warrior fueled by dark magic and extreme metal.", + + "rov_race_dvergar_name": "Dvergar", + "rov_race_dvergar_desc": "Small, stubborn smiths of the deep. Frail of frame, but masters of metal, mine and market.", + + "rov_race_trenta_name": "Trenta", + "rov_race_trenta_desc": "Tree-born folk, kin to root and leaf. Patient and hard to fell.", + + "rov_race_sverm_name": "Sverm", + "rov_race_sverm_desc": "Chitin-born swarm kin. Armoured from birth and never slowed, venomous, at peace with every crawling thing - but blunt trauma and fire find the seams." +} diff --git a/JotunnModStub/Translations/Italian/races.json b/JotunnModStub/Translations/Italian/races.json new file mode 100644 index 0000000..2e29263 --- /dev/null +++ b/JotunnModStub/Translations/Italian/races.json @@ -0,0 +1,38 @@ +{ + "rov_menu_choose_race": "Scegli la tua razza", + "rov_menu_ok": "OK", + "rov_menu_back": "Indietro", + + "rov_race_human_name": "Umano", + "rov_race_human_desc": "I versatili fondatori di Midgard. Statistiche equilibrate, senza debolezze particolari.", + + "rov_race_fenrir_name": "Fenrir", + "rov_race_fenrir_desc": "Maledetti dal sangue del lupo. Veloci e letali, ma vulnerabili all'argento.", + + "rov_race_skadi_name": "Skadi", + "rov_race_skadi_desc": "Figli delle montagne. Resistenti al gelo, a casa loro nel freddo più rigido.", + + "rov_race_skeleton_name": "Scheletro", + "rov_race_skeleton_desc": "Guerrieri non morti. Immuni al veleno, ma fragili contro i colpi contundenti.", + + "rov_race_aswid_name": "Aswid", + "rov_race_aswid_desc": "Feroce cacciatore notturno. Forte e resistente, si trasforma in pipistrello.", + + "rov_race_furling_name": "Furling", + "rov_race_furling_desc": "Astute creature simili a goblin. Agili e piene di risorse.", + + "rov_race_trol_name": "Trol", + "rov_race_trol_desc": "Forza bruta smisurata. Sovrasta tutti gli altri ed è in pace con la Foresta Nera, ma il fuoco brucia un Trol il $1% in più di chiunque altro.", + + "rov_race_draugh_name": "Draugh", + "rov_race_draugh_desc": "Un guerriero non morto in decomposizione, alimentato da magia oscura e metallo estremo.", + + "rov_race_dvergar_name": "Dvergar", + "rov_race_dvergar_desc": "Piccoli e testardi fabbri del profondo. Fragili nel fisico, ma maestri di metallo, miniera e mercato.", + + "rov_race_trenta_name": "Trenta", + "rov_race_trenta_desc": "Popolo nato dagli alberi, parente di radici e foglie. Paziente e difficile da abbattere.", + + "rov_race_sverm_name": "Sverm", + "rov_race_sverm_desc": "Stirpe dello sciame nata dalla chitina. Corazzata dalla nascita e mai rallentata, velenosa, in pace con ogni cosa che striscia, ma i colpi contundenti e il fuoco trovano le giunture." +} From 9bf144aedc255833bcbfa1e15ee7c4ba394d921b Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 19:51:10 +0200 Subject: [PATCH 076/290] feat(text): status effect names and tooltips come from translation files Every status effect the mod registers now carries a $rov_se_ token instead of English, and status_effects.json holds the texts in English and Italian. Valheim localizes both fields itself when it shows them. The blood potion's tooltip has numbers in it, so SE_BloodPotion fills its $1 and $2 in GetTooltipString, at display time. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Aswid/AswidBloodPotions.cs | 15 ++++- JotunnModStub/Aswid/AswidPatches.cs | 4 +- JotunnModStub/Aswid/AswidStatusEffects.cs | 20 +++--- .../Draugh/DraughProgressionPatches.cs | 2 +- JotunnModStub/Dvergar/DvergarStatusEffects.cs | 18 +++--- JotunnModStub/Fenrir/FenrirRace.cs | 14 ++--- JotunnModStub/RaceClaws.cs | 2 +- JotunnModStub/Skadi/SkadiRace.cs | 16 ++--- JotunnModStub/Skadi/SkadiStatusEffects.cs | 4 +- JotunnModStub/Skeleton/SkeletonRace.cs | 2 +- .../Skeleton/SkeletonStatusEffects.cs | 4 +- JotunnModStub/Sverm/SvermStatusEffects.cs | 18 +++--- .../Translations/English/status_effects.json | 62 +++++++++++++++++++ .../Translations/Italian/status_effects.json | 62 +++++++++++++++++++ JotunnModStub/Trenta/TrentaStatusEffects.cs | 14 ++--- JotunnModStub/Trol/TrolStatusEffects.cs | 12 ++-- 16 files changed, 203 insertions(+), 66 deletions(-) create mode 100644 JotunnModStub/Translations/English/status_effects.json create mode 100644 JotunnModStub/Translations/Italian/status_effects.json diff --git a/JotunnModStub/Aswid/AswidBloodPotions.cs b/JotunnModStub/Aswid/AswidBloodPotions.cs index 83ebf3c..a9a17f1 100644 --- a/JotunnModStub/Aswid/AswidBloodPotions.cs +++ b/JotunnModStub/Aswid/AswidBloodPotions.cs @@ -176,7 +176,7 @@ namespace RacesOfValheim SE_BloodPotion effect = ScriptableObject.CreateInstance(); effect.name = name; effect.m_name = displayName; - effect.m_tooltip = $"Stomachs filled with blood. Healing {Mathf.RoundToInt(fraction * 100f)}% over {HealDuration:0} seconds."; + effect.m_tooltip = "$rov_se_aswid_bloodpotion_tooltip"; // numbers go in at display, see GetTooltipString effect.m_ttl = HealDuration; effect.m_healFraction = fraction; effect.m_essencePrefab = essencePrefab; @@ -287,6 +287,19 @@ namespace RacesOfValheim public float m_healFraction = 0.05f; public string m_essencePrefab = ""; + /// + /// The tooltip's $1 and $2 are the heal share and the duration. Filled in here, at display + /// time, because a translation can only be looked up once the language is loaded, and the + /// game localizes this string after us in a single pass that would leave $1 as it is. + /// + public override string GetTooltipString() + { + string text = base.GetTooltipString(); + if (Localization.instance == null) return text; + return Localization.instance.Localize(text, + Mathf.RoundToInt(m_healFraction * 100f).ToString(), m_ttl.ToString("0")); + } + public override void Setup(Character character) { // SEMan clones the effect before setting it up, so writing the resolved amount here diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index 400e4a4..0bc1753 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -502,9 +502,9 @@ namespace RacesOfValheim __instance.m_icon = null; } - __instance.m_name = "Night Aura"; + __instance.m_name = "$rov_se_aswid_nightaura_name"; __instance.m_startMessage = ""; // "The darkness empowers you."; - __instance.m_tooltip = "The cold strengthens your beastly senses."; + __instance.m_tooltip = "$rov_se_aswid_nightaura_tooltip"; if (__instance is SE_Stats stats) { diff --git a/JotunnModStub/Aswid/AswidStatusEffects.cs b/JotunnModStub/Aswid/AswidStatusEffects.cs index ac3ab3f..0a91feb 100644 --- a/JotunnModStub/Aswid/AswidStatusEffects.cs +++ b/JotunnModStub/Aswid/AswidStatusEffects.cs @@ -11,8 +11,8 @@ namespace RacesOfValheim { base.Setup(character); name = "SE_AswidStats"; - m_name = "Benedictus et Afflictus"; - m_tooltip = "Vampiric senses and life drain."; + m_name = "$rov_se_aswid_stats_name"; + m_tooltip = "$rov_se_aswid_stats_tooltip"; } public void UpdateStats(int state) @@ -59,8 +59,8 @@ namespace RacesOfValheim { base.Setup(character); name = "SE_BatForm"; - m_name = "Like a Bat out of Hell"; - m_tooltip = "You have taken the form of a Bat. You can fly, but cannot attack."; + m_name = "$rov_se_aswid_batform_name"; + m_tooltip = "$rov_se_aswid_batform_tooltip"; m_fallDamageModifier = -1f; // Immune to fall damage just in case } } @@ -71,8 +71,8 @@ namespace RacesOfValheim { base.Setup(character); name = "SE_MistForm"; - m_name = "Weight of Shadows"; - m_tooltip = "You are mist. Immune to physical damage and poison. Cannot attack or run."; + m_name = "$rov_se_aswid_mistform_name"; + m_tooltip = "$rov_se_aswid_mistform_tooltip"; m_fallDamageModifier = -1f; m_mods = new System.Collections.Generic.List { @@ -90,7 +90,7 @@ namespace RacesOfValheim { base.Setup(character); name = "SE_AswidSensesMark"; - m_name = "Sensed"; + m_name = "$rov_se_aswid_sensed_name"; m_tooltip = ""; m_ttl = 2f; m_icon = null; // No icon needed for mobs @@ -103,8 +103,8 @@ namespace RacesOfValheim { base.Setup(character); name = "SE_SuperhumanSenses"; - m_name = "Auspex"; - m_tooltip = "Sensing life force of nearby creatures."; + m_name = "$rov_se_aswid_auspex_name"; + m_tooltip = "$rov_se_aswid_auspex_tooltip"; } } @@ -132,7 +132,7 @@ namespace RacesOfValheim var sensesMark = ScriptableObject.CreateInstance(); sensesMark.name = "SE_AswidSensesMark"; - sensesMark.m_name = "Sensed"; + sensesMark.m_name = "$rov_se_aswid_sensed_name"; sensesMark.m_ttl = 2f; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(sensesMark, fixReference: false)); diff --git a/JotunnModStub/Draugh/DraughProgressionPatches.cs b/JotunnModStub/Draugh/DraughProgressionPatches.cs index 105eb1b..eaa8357 100644 --- a/JotunnModStub/Draugh/DraughProgressionPatches.cs +++ b/JotunnModStub/Draugh/DraughProgressionPatches.cs @@ -22,7 +22,7 @@ namespace RacesOfValheim // Invert the Wet debuff to actually heal the Draugh __instance.m_healthRegenMultiplier = DraughConfig.WetHealthRegenMultiplier.Value; __instance.m_staminaRegenMultiplier = 1f; // No stamina penalty - __instance.m_tooltip = "The water restores your rotten flesh. Health regeneration increased."; + __instance.m_tooltip = "$rov_se_draugh_wet_tooltip"; } } } diff --git a/JotunnModStub/Dvergar/DvergarStatusEffects.cs b/JotunnModStub/Dvergar/DvergarStatusEffects.cs index 10f83d1..23055b9 100644 --- a/JotunnModStub/Dvergar/DvergarStatusEffects.cs +++ b/JotunnModStub/Dvergar/DvergarStatusEffects.cs @@ -16,8 +16,8 @@ namespace RacesOfValheim { base.Setup(character); name = DvergarConfig.StatsSE; - m_name = "Stone and Forge"; - m_tooltip = "Small, sturdy, and born to the anvil."; + m_name = "$rov_se_dvergar_stats_name"; + m_tooltip = "$rov_se_dvergar_stats_tooltip"; } public override void ModifyAttackStaminaUsage(float baseStaminaUse, ref float staminaUse) @@ -80,7 +80,7 @@ namespace RacesOfValheim var stats = ScriptableObject.CreateInstance(); stats.name = DvergarConfig.StatsSE; - stats.m_name = "Stone and Forge"; + stats.m_name = "$rov_se_dvergar_stats_name"; stats.m_icon = icon; CustomStatusEffect customStats = new CustomStatusEffect(stats, fixReference: false); ItemManager.Instance.AddStatusEffect(customStats); @@ -88,22 +88,22 @@ namespace RacesOfValheim var overcharge = ScriptableObject.CreateInstance(); overcharge.name = DvergarConfig.OverchargeSE; - overcharge.m_name = "Runic Overcharge"; - overcharge.m_tooltip = "Your next blow with a favoured weapon carries the whole of the charge."; + overcharge.m_name = "$rov_se_dvergar_overcharge_name"; + overcharge.m_tooltip = "$rov_se_dvergar_overcharge_tooltip"; overcharge.m_icon = GetItemIcon("Eitr") ?? icon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(overcharge, fixReference: false)); var pingCd = ScriptableObject.CreateInstance(); pingCd.name = DvergarConfig.RunicPingCdSE; - pingCd.m_name = "Runic Ping"; - pingCd.m_tooltip = "The runes must settle before you may call on them again."; + pingCd.m_name = "$rov_se_dvergar_pingcd_name"; + pingCd.m_tooltip = "$rov_se_dvergar_pingcd_tooltip"; pingCd.m_icon = GetItemIcon("DvergrKeyFragment") ?? icon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(pingCd, fixReference: false)); var overchargeCd = ScriptableObject.CreateInstance(); overchargeCd.name = DvergarConfig.OverchargeCdSE; - overchargeCd.m_name = "Overcharge Cooldown"; - overchargeCd.m_tooltip = "The runes are spent."; + overchargeCd.m_name = "$rov_se_dvergar_overchargecd_name"; + overchargeCd.m_tooltip = "$rov_se_dvergar_overchargecd_tooltip"; overchargeCd.m_icon = GetItemIcon("Eitr") ?? icon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(overchargeCd, fixReference: false)); } diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index 5c00200..22c1ee6 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -42,8 +42,8 @@ namespace RacesOfValheim { curseSE = ScriptableObject.CreateInstance(); curseSE.name = "SE_FenrirCurse"; - curseSE.m_name = "Fenrir's Blood"; - curseSE.m_tooltip = "You are of the Fenrir race."; + curseSE.m_name = "$rov_se_fenrir_curse_name"; + curseSE.m_tooltip = "$rov_se_fenrir_curse_tooltip"; curseSE.m_mods = new System.Collections.Generic.List() { new HitData.DamageModPair() { m_type = HitData.DamageType.Spirit, m_modifier = HitData.DamageModifier.Weak } @@ -64,19 +64,19 @@ namespace RacesOfValheim { fenrirCdSE = ScriptableObject.CreateInstance(); fenrirCdSE.name = "SE_FenrirCooldown"; - fenrirCdSE.m_name = "Fenrir Form Cooldown"; + fenrirCdSE.m_name = "$rov_se_fenrir_formcd_name"; fenrirCdSE.m_icon = fenringTrophyIcon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(fenrirCdSE, fixReference: false)); cultistCdSE = ScriptableObject.CreateInstance(); cultistCdSE.name = "SE_CultistCooldown"; - cultistCdSE.m_name = "Cultist Form Cooldown"; + cultistCdSE.m_name = "$rov_se_fenrir_cultistcd_name"; cultistCdSE.m_icon = fenringTrophyIcon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistCdSE, fixReference: false)); formBuffSE = ScriptableObject.CreateInstance(); formBuffSE.name = "SE_FenrirForm"; - formBuffSE.m_name = "Bestial Fury"; + formBuffSE.m_name = "$rov_se_fenrir_form_name"; formBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value; formBuffSE.m_jumpModifier = new Vector3(0, FenrirConfig.FullFormJumpBonus.Value, 0); formBuffSE.m_fallDamageModifier = -FenrirConfig.FullFormFallDamageReduction.Value; @@ -87,7 +87,7 @@ namespace RacesOfValheim { cultistFormBuffSE = ScriptableObject.CreateInstance(); cultistFormBuffSE.name = "SE_CultistForm"; - cultistFormBuffSE.m_name = "Cultist Fury"; + cultistFormBuffSE.m_name = "$rov_se_fenrir_cultistform_name"; cultistFormBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value; cultistFormBuffSE.m_jumpModifier = new Vector3(0, FenrirConfig.FullFormJumpBonus.Value, 0); cultistFormBuffSE.m_fallDamageModifier = -FenrirConfig.FullFormFallDamageReduction.Value; @@ -98,7 +98,7 @@ namespace RacesOfValheim { wolfFormBuffSE = ScriptableObject.CreateInstance(); wolfFormBuffSE.name = "SE_WolfForm"; - wolfFormBuffSE.m_name = "Wolf Senses"; + wolfFormBuffSE.m_name = "$rov_se_fenrir_wolfform_name"; wolfFormBuffSE.m_speedModifier = FenrirConfig.WolfFormSpeedBonus.Value; wolfFormBuffSE.m_fallDamageModifier = -FenrirConfig.WolfFormFallDamageReduction.Value; wolfFormBuffSE.m_staminaRegenMultiplier = FenrirConfig.FormStaminaRegenMultiplier.Value; diff --git a/JotunnModStub/RaceClaws.cs b/JotunnModStub/RaceClaws.cs index 660fabc..3fc2bbb 100644 --- a/JotunnModStub/RaceClaws.cs +++ b/JotunnModStub/RaceClaws.cs @@ -302,7 +302,7 @@ namespace RacesOfValheim StatusEffect se = ScriptableObject.CreateInstance(); se.name = ActiveSeName; se.m_name = DisplayName; - se.m_tooltip = "Your claws are out. They retract when this runs out."; + se.m_tooltip = "$rov_se_claws_tooltip"; se.m_icon = icon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(se, fixReference: false)); diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index 4746139..fbdffb6 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -58,7 +58,7 @@ namespace RacesOfValheim var se = ScriptableObject.CreateInstance(); se.name = "SE_SkadiStats"; - se.m_name = "Skadi's Blessing"; + se.m_name = "$rov_se_skadi_stats_name"; // Icon GameObject drakeTrophy = PrefabManager.Cache.GetPrefab("TrophyHatchling")?.gameObject; @@ -81,14 +81,14 @@ namespace RacesOfValheim skadiCdSE = ScriptableObject.CreateInstance(); skadiCdSE.name = "SE_SkadiCooldown"; - skadiCdSE.m_name = "Dragon Form Cooldown"; + skadiCdSE.m_name = "$rov_se_skadi_formcd_name"; skadiCdSE.m_icon = dragonIcon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(skadiCdSE, fixReference: false)); skadiFormSE = ScriptableObject.CreateInstance(); skadiFormSE.name = "SE_SkadiForm"; - skadiFormSE.m_name = "Dragon Form"; - skadiFormSE.m_tooltip = "Your dragon shape holds for a while longer."; + skadiFormSE.m_name = "$rov_se_skadi_form_name"; + skadiFormSE.m_tooltip = "$rov_se_skadi_form_tooltip"; skadiFormSE.m_icon = dragonIcon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(skadiFormSE, fixReference: false)); @@ -96,15 +96,15 @@ namespace RacesOfValheim // differently from a dragon attack on cooldown at a glance. var spellCd = ScriptableObject.CreateInstance(); spellCd.name = SPELL_COOLDOWN_SE; - spellCd.m_name = "Cold Spell"; - spellCd.m_tooltip = "The frost must gather again before you may cast."; + spellCd.m_name = "$rov_se_skadi_coldspellcd_name"; + spellCd.m_tooltip = "$rov_se_skadi_coldspellcd_tooltip"; spellCd.m_icon = GetItemIcon("StaffIceShards") ?? dragonIcon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(spellCd, fixReference: false)); var attackCd = ScriptableObject.CreateInstance(); attackCd.name = ATTACK_COOLDOWN_SE; - attackCd.m_name = "Dragon Attack"; - attackCd.m_tooltip = "Your dragon shape must ready itself to strike again."; + attackCd.m_name = "$rov_se_skadi_dragonattackcd_name"; + attackCd.m_tooltip = "$rov_se_skadi_dragonattackcd_tooltip"; attackCd.m_icon = GetItemIcon("TrophyHatchling") ?? dragonIcon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(attackCd, fixReference: false)); } diff --git a/JotunnModStub/Skadi/SkadiStatusEffects.cs b/JotunnModStub/Skadi/SkadiStatusEffects.cs index 00a7e56..6f47454 100644 --- a/JotunnModStub/Skadi/SkadiStatusEffects.cs +++ b/JotunnModStub/Skadi/SkadiStatusEffects.cs @@ -23,8 +23,8 @@ namespace RacesOfValheim { base.Setup(character); name = "SE_SkadiStats"; - m_name = "Skadi's Aura"; - m_tooltip = "Empowered by the frost."; + m_name = "$rov_se_skadi_aura_name"; + m_tooltip = "$rov_se_skadi_aura_tooltip"; } // What the last UpdateStats call actually wrote. SEMan.AddStatusEffect stores a Clone() of diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index 3f0a3cb..22bc3ec 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -24,7 +24,7 @@ namespace RacesOfValheim var se = ScriptableObject.CreateInstance(); se.name = "SE_SkeletonStats"; - se.m_name = "Undead Fortitude"; + se.m_name = "$rov_se_skeleton_stats_name"; // Icon GameObject skelTrophy = PrefabManager.Cache.GetPrefab("TrophySkeleton")?.gameObject; diff --git a/JotunnModStub/Skeleton/SkeletonStatusEffects.cs b/JotunnModStub/Skeleton/SkeletonStatusEffects.cs index 502dd04..6bc69ac 100644 --- a/JotunnModStub/Skeleton/SkeletonStatusEffects.cs +++ b/JotunnModStub/Skeleton/SkeletonStatusEffects.cs @@ -60,8 +60,8 @@ namespace RacesOfValheim public override void Setup(Character character) { base.Setup(character); - m_name = "Resurrection Cooldown"; - m_tooltip = "Your skeletal body is too weak to resurrect again right now."; + m_name = "$rov_se_skeleton_resurrectcd_name"; + m_tooltip = "$rov_se_skeleton_resurrectcd_tooltip"; m_icon = Jotunn.Managers.PrefabManager.Cache.GetPrefab("TrophySkeletonPoison")?.GetComponent()?.m_itemData.GetIcon() ?? Jotunn.Managers.PrefabManager.Cache.GetPrefab("TrophySkeleton")?.GetComponent()?.m_itemData.GetIcon(); m_ttl = SkeletonConfig.ResurrectionCooldown.Value; diff --git a/JotunnModStub/Sverm/SvermStatusEffects.cs b/JotunnModStub/Sverm/SvermStatusEffects.cs index 7d05d34..3566dcc 100644 --- a/JotunnModStub/Sverm/SvermStatusEffects.cs +++ b/JotunnModStub/Sverm/SvermStatusEffects.cs @@ -30,8 +30,8 @@ namespace RacesOfValheim { base.Setup(character); name = SvermConfig.StatsSE; - m_name = "Chitin Plating"; - m_tooltip = "Armoured, venomous, and never alone."; + m_name = "$rov_se_sverm_stats_name"; + m_tooltip = "$rov_se_sverm_stats_tooltip"; RebuildForState(); } @@ -101,8 +101,8 @@ namespace RacesOfValheim public override void Setup(Character character) { base.Setup(character); - m_name = "Ravager Strain Cooldown"; - m_tooltip = "The strain is spent. It will take again soon."; + m_name = "$rov_se_sverm_ravagercd_name"; + m_tooltip = "$rov_se_sverm_ravagercd_tooltip"; m_ttl = SvermConfig.RavagerCooldownSeconds; } } @@ -120,8 +120,8 @@ namespace RacesOfValheim public override void Setup(Character character) { base.Setup(character); - m_name = "Ravager Strain"; - m_tooltip = "The shell doubles, and nothing that hits it lands the same again."; + m_name = "$rov_se_sverm_ravager_name"; + m_tooltip = "$rov_se_sverm_ravager_tooltip"; m_ttl = SvermConfig.RavagerDurationSeconds; } } @@ -138,7 +138,7 @@ namespace RacesOfValheim var stats = ScriptableObject.CreateInstance(); stats.name = SvermConfig.StatsSE; - stats.m_name = "Chitin Plating"; + stats.m_name = "$rov_se_sverm_stats_name"; stats.m_icon = icon; CustomStatusEffect customStats = new CustomStatusEffect(stats, fixReference: false); ItemManager.Instance.AddStatusEffect(customStats); @@ -146,13 +146,13 @@ namespace RacesOfValheim var form = ScriptableObject.CreateInstance(); form.name = SvermConfig.RavagerSE; - form.m_name = "Ravager Strain"; + form.m_name = "$rov_se_sverm_ravager_name"; form.m_icon = icon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(form, fixReference: false)); var cooldown = ScriptableObject.CreateInstance(); cooldown.name = SvermConfig.RavagerCdSE; - cooldown.m_name = "Ravager Strain Cooldown"; + cooldown.m_name = "$rov_se_sverm_ravagercd_name"; cooldown.m_icon = icon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cooldown, fixReference: false)); } diff --git a/JotunnModStub/Translations/English/status_effects.json b/JotunnModStub/Translations/English/status_effects.json new file mode 100644 index 0000000..ba0b959 --- /dev/null +++ b/JotunnModStub/Translations/English/status_effects.json @@ -0,0 +1,62 @@ +{ + "rov_se_aswid_auspex_name": "Auspex", + "rov_se_aswid_auspex_tooltip": "Sensing life force of nearby creatures.", + "rov_se_aswid_batform_name": "Like a Bat out of Hell", + "rov_se_aswid_batform_tooltip": "You have taken the form of a Bat. You can fly, but cannot attack.", + "rov_se_aswid_bloodpotion_tooltip": "Stomachs filled with blood. Healing $1% over $2 seconds.", + "rov_se_aswid_mistform_name": "Weight of Shadows", + "rov_se_aswid_mistform_tooltip": "You are mist. Immune to physical damage and poison. Cannot attack or run.", + "rov_se_aswid_nightaura_name": "Night Aura", + "rov_se_aswid_nightaura_tooltip": "The cold strengthens your beastly senses.", + "rov_se_aswid_sensed_name": "Sensed", + "rov_se_aswid_stats_name": "Benedictus et Afflictus", + "rov_se_aswid_stats_tooltip": "Vampiric senses and life drain.", + "rov_se_claws_tooltip": "Your claws are out. They retract when this runs out.", + "rov_se_draugh_wet_tooltip": "The water restores your rotten flesh. Health regeneration increased.", + "rov_se_dvergar_overcharge_name": "Runic Overcharge", + "rov_se_dvergar_overcharge_tooltip": "Your next blow with a favoured weapon carries the whole of the charge.", + "rov_se_dvergar_overchargecd_name": "Overcharge Cooldown", + "rov_se_dvergar_overchargecd_tooltip": "The runes are spent.", + "rov_se_dvergar_pingcd_name": "Runic Ping", + "rov_se_dvergar_pingcd_tooltip": "The runes must settle before you may call on them again.", + "rov_se_dvergar_stats_name": "Stone and Forge", + "rov_se_dvergar_stats_tooltip": "Small, sturdy, and born to the anvil.", + "rov_se_fenrir_cultistcd_name": "Cultist Form Cooldown", + "rov_se_fenrir_cultistform_name": "Cultist Fury", + "rov_se_fenrir_curse_name": "Fenrir's Blood", + "rov_se_fenrir_curse_tooltip": "You are of the Fenrir race.", + "rov_se_fenrir_form_name": "Bestial Fury", + "rov_se_fenrir_formcd_name": "Fenrir Form Cooldown", + "rov_se_fenrir_wolfform_name": "Wolf Senses", + "rov_se_skadi_aura_name": "Skadi's Aura", + "rov_se_skadi_aura_tooltip": "Empowered by the frost.", + "rov_se_skadi_coldspellcd_name": "Cold Spell", + "rov_se_skadi_coldspellcd_tooltip": "The frost must gather again before you may cast.", + "rov_se_skadi_dragonattackcd_name": "Dragon Attack", + "rov_se_skadi_dragonattackcd_tooltip": "Your dragon shape must ready itself to strike again.", + "rov_se_skadi_form_name": "Dragon Form", + "rov_se_skadi_form_tooltip": "Your dragon shape holds for a while longer.", + "rov_se_skadi_formcd_name": "Dragon Form Cooldown", + "rov_se_skadi_stats_name": "Skadi's Blessing", + "rov_se_skeleton_resurrectcd_name": "Resurrection Cooldown", + "rov_se_skeleton_resurrectcd_tooltip": "Your skeletal body is too weak to resurrect again right now.", + "rov_se_skeleton_stats_name": "Undead Fortitude", + "rov_se_sverm_ravager_name": "Ravager Strain", + "rov_se_sverm_ravager_tooltip": "The shell doubles, and nothing that hits it lands the same again.", + "rov_se_sverm_ravagercd_name": "Ravager Strain Cooldown", + "rov_se_sverm_ravagercd_tooltip": "The strain is spent. It will take again soon.", + "rov_se_sverm_stats_name": "Chitin Plating", + "rov_se_sverm_stats_tooltip": "Armoured, venomous, and never alone.", + "rov_se_trenta_portalcd_name": "Homecoming Portal", + "rov_se_trenta_portalcd_tooltip": "The way home has not yet settled enough to open again.", + "rov_se_trenta_purpleraincd_name": "Purple Rain", + "rov_se_trenta_purpleraincd_tooltip": "The pollen must settle before you may call the rain again.", + "rov_se_trenta_stats_name": "Heartwood", + "rov_se_trenta_stats_tooltip": "Rooted, patient, and hard to fell.", + "rov_se_trol_throwcd_name": "Throw Rock Cooldown", + "rov_se_trol_throwcd_tooltip": "You must wait before throwing another rock.", + "rov_se_trol_trueform_name": "True Form", + "rov_se_trol_trueform_tooltip": "You have unleashed your inner troll!", + "rov_se_trol_trueformcd_name": "True Form Cooldown", + "rov_se_trol_trueformcd_tooltip": "You are exhausted from your True Form." +} diff --git a/JotunnModStub/Translations/Italian/status_effects.json b/JotunnModStub/Translations/Italian/status_effects.json new file mode 100644 index 0000000..4e8c742 --- /dev/null +++ b/JotunnModStub/Translations/Italian/status_effects.json @@ -0,0 +1,62 @@ +{ + "rov_se_aswid_auspex_name": "Auspex", + "rov_se_aswid_auspex_tooltip": "Percepisci la forza vitale delle creature vicine.", + "rov_se_aswid_batform_name": "Come un pipistrello dall'inferno", + "rov_se_aswid_batform_tooltip": "Hai preso la forma di un pipistrello. Puoi volare, ma non puoi attaccare.", + "rov_se_aswid_bloodpotion_tooltip": "Stomaci pieni di sangue. Cura il $1% in $2 secondi.", + "rov_se_aswid_mistform_name": "Peso delle ombre", + "rov_se_aswid_mistform_tooltip": "Sei nebbia. Immune ai danni fisici e al veleno. Non puoi attaccare né correre.", + "rov_se_aswid_nightaura_name": "Aura notturna", + "rov_se_aswid_nightaura_tooltip": "Il freddo acuisce i tuoi sensi bestiali.", + "rov_se_aswid_sensed_name": "Percepito", + "rov_se_aswid_stats_name": "Benedictus et Afflictus", + "rov_se_aswid_stats_tooltip": "Sensi vampirici e risucchio vitale.", + "rov_se_claws_tooltip": "Hai gli artigli fuori. Si ritraggono quando questo effetto finisce.", + "rov_se_draugh_wet_tooltip": "L'acqua ristora la tua carne putrefatta. Rigenerazione della salute aumentata.", + "rov_se_dvergar_overcharge_name": "Sovraccarico runico", + "rov_se_dvergar_overcharge_tooltip": "Il tuo prossimo colpo con un'arma prediletta scarica tutta la carica.", + "rov_se_dvergar_overchargecd_name": "Ricarica del sovraccarico", + "rov_se_dvergar_overchargecd_tooltip": "Le rune sono esaurite.", + "rov_se_dvergar_pingcd_name": "Richiamo runico", + "rov_se_dvergar_pingcd_tooltip": "Le rune devono assestarsi prima che tu possa invocarle di nuovo.", + "rov_se_dvergar_stats_name": "Pietra e forgia", + "rov_se_dvergar_stats_tooltip": "Piccolo, robusto e nato per l'incudine.", + "rov_se_fenrir_cultistcd_name": "Ricarica forma Cultista", + "rov_se_fenrir_cultistform_name": "Furia del Cultista", + "rov_se_fenrir_curse_name": "Sangue di Fenrir", + "rov_se_fenrir_curse_tooltip": "Sei della razza Fenrir.", + "rov_se_fenrir_form_name": "Furia bestiale", + "rov_se_fenrir_formcd_name": "Ricarica forma Fenrir", + "rov_se_fenrir_wolfform_name": "Sensi del lupo", + "rov_se_skadi_aura_name": "Aura di Skadi", + "rov_se_skadi_aura_tooltip": "Potenziato dal gelo.", + "rov_se_skadi_coldspellcd_name": "Incantesimo del freddo", + "rov_se_skadi_coldspellcd_tooltip": "Il gelo deve raccogliersi di nuovo prima che tu possa lanciare.", + "rov_se_skadi_dragonattackcd_name": "Attacco del drago", + "rov_se_skadi_dragonattackcd_tooltip": "La tua forma di drago deve prepararsi prima di colpire ancora.", + "rov_se_skadi_form_name": "Forma di drago", + "rov_se_skadi_form_tooltip": "La tua forma di drago resiste ancora per un po'.", + "rov_se_skadi_formcd_name": "Ricarica forma di drago", + "rov_se_skadi_stats_name": "Benedizione di Skadi", + "rov_se_skeleton_resurrectcd_name": "Ricarica resurrezione", + "rov_se_skeleton_resurrectcd_tooltip": "Il tuo corpo scheletrico è troppo debole per risorgere di nuovo adesso.", + "rov_se_skeleton_stats_name": "Tempra non morta", + "rov_se_sverm_ravager_name": "Ceppo Devastatore", + "rov_se_sverm_ravager_tooltip": "Il guscio raddoppia, e niente di ciò che lo colpisce va a segno come prima.", + "rov_se_sverm_ravagercd_name": "Ricarica Ceppo Devastatore", + "rov_se_sverm_ravagercd_tooltip": "Il ceppo è esaurito. Attecchirà di nuovo presto.", + "rov_se_sverm_stats_name": "Corazza di chitina", + "rov_se_sverm_stats_tooltip": "Corazzato, velenoso e mai solo.", + "rov_se_trenta_portalcd_name": "Portale del ritorno", + "rov_se_trenta_portalcd_tooltip": "La via di casa non si è ancora assestata abbastanza per riaprirsi.", + "rov_se_trenta_purpleraincd_name": "Pioggia viola", + "rov_se_trenta_purpleraincd_tooltip": "Il polline deve posarsi prima che tu possa richiamare la pioggia.", + "rov_se_trenta_stats_name": "Durame", + "rov_se_trenta_stats_tooltip": "Radicato, paziente e difficile da abbattere.", + "rov_se_trol_throwcd_name": "Ricarica lancio di massi", + "rov_se_trol_throwcd_tooltip": "Devi aspettare prima di lanciare un altro masso.", + "rov_se_trol_trueform_name": "Vera forma", + "rov_se_trol_trueform_tooltip": "Hai scatenato il troll che è in te!", + "rov_se_trol_trueformcd_name": "Ricarica vera forma", + "rov_se_trol_trueformcd_tooltip": "Sei esausto dopo la tua vera forma." +} diff --git a/JotunnModStub/Trenta/TrentaStatusEffects.cs b/JotunnModStub/Trenta/TrentaStatusEffects.cs index 7afb670..ae0351d 100644 --- a/JotunnModStub/Trenta/TrentaStatusEffects.cs +++ b/JotunnModStub/Trenta/TrentaStatusEffects.cs @@ -16,8 +16,8 @@ namespace RacesOfValheim { base.Setup(character); name = TrentaConfig.StatsSE; - m_name = "Heartwood"; - m_tooltip = "Rooted, patient, and hard to fell."; + m_name = "$rov_se_trenta_stats_name"; + m_tooltip = "$rov_se_trenta_stats_tooltip"; // Resistant/Weak are exactly ±50% damage taken (0.5x / 1.5x) - verified against // HitData.ApplyModifier's own IL rather than assumed, since the enum names alone @@ -83,7 +83,7 @@ namespace RacesOfValheim { var stats = ScriptableObject.CreateInstance(); stats.name = TrentaConfig.StatsSE; - stats.m_name = "Heartwood"; + stats.m_name = "$rov_se_trenta_stats_name"; stats.m_icon = GetItemIcon("Wood"); // TODO: pick the icon the race should carry CustomStatusEffect customStats = new CustomStatusEffect(stats, fixReference: false); @@ -92,15 +92,15 @@ namespace RacesOfValheim var purpleRainCd = ScriptableObject.CreateInstance(); purpleRainCd.name = TrentaConfig.PurpleRainCdSE; - purpleRainCd.m_name = "Purple Rain"; - purpleRainCd.m_tooltip = "The pollen must settle before you may call the rain again."; + purpleRainCd.m_name = "$rov_se_trenta_purpleraincd_name"; + purpleRainCd.m_tooltip = "$rov_se_trenta_purpleraincd_tooltip"; purpleRainCd.m_icon = GetItemIcon("TrophyGreydwarfShaman") ?? GetItemIcon("Wood"); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(purpleRainCd, fixReference: false)); var portalCd = ScriptableObject.CreateInstance(); portalCd.name = TrentaConfig.PortalCdSE; - portalCd.m_name = "Homecoming Portal"; - portalCd.m_tooltip = "The way home has not yet settled enough to open again."; + portalCd.m_name = "$rov_se_trenta_portalcd_name"; + portalCd.m_tooltip = "$rov_se_trenta_portalcd_tooltip"; portalCd.m_icon = GetItemIcon("Wood"); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(portalCd, fixReference: false)); } diff --git a/JotunnModStub/Trol/TrolStatusEffects.cs b/JotunnModStub/Trol/TrolStatusEffects.cs index 9c0c4dc..7873ce7 100644 --- a/JotunnModStub/Trol/TrolStatusEffects.cs +++ b/JotunnModStub/Trol/TrolStatusEffects.cs @@ -10,8 +10,8 @@ namespace RacesOfValheim { base.Setup(character); name = "SE_TrolThrowRockCooldown"; - m_name = "Throw Rock Cooldown"; - m_tooltip = "You must wait before throwing another rock."; + m_name = "$rov_se_trol_throwcd_name"; + m_tooltip = "$rov_se_trol_throwcd_tooltip"; m_ttl = 60f; // 1 minute cooldown // Try to find a rock-like icon, e.g. Stone @@ -33,8 +33,8 @@ namespace RacesOfValheim { base.Setup(character); name = "SE_TrolTrueForm"; - m_name = "True Form"; - m_tooltip = "You have unleashed your inner troll!"; + m_name = "$rov_se_trol_trueform_name"; + m_tooltip = "$rov_se_trol_trueform_tooltip"; // Past Fader the form no longer runs out: m_ttl 0 is vanilla's "never expires", and // the True Form key becomes the only way back (see TrolRace.TryTrueForm). m_ttl = BossProgressionManager.GetCurrentProgressionState() >= 8 ? 0f : TrolConfig.TrueFormDuration.Value; @@ -57,8 +57,8 @@ namespace RacesOfValheim { base.Setup(character); name = "SE_TrolTrueFormCooldown"; - m_name = "True Form Cooldown"; - m_tooltip = "You are exhausted from your True Form."; + m_name = "$rov_se_trol_trueformcd_name"; + m_tooltip = "$rov_se_trol_trueformcd_tooltip"; m_ttl = TrolConfig.TrueFormCooldown.Value; GameObject itemPrefab = PrefabManager.Cache.GetPrefab("Stone"); From b177c89c71619e19248890dc681d7482739c8a88 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 19:58:53 +0200 Subject: [PATCH 077/290] feat(text): item, piece and creature names come from translation files The mod's own items, build pieces and summoned creatures now carry $rov_item_, $rov_piece_ and $rov_creature_ tokens for their names and descriptions, and items.json holds the texts in English and Italian. Valheim localizes these fields wherever it shows them: tooltips, hover texts, messages, the build menu. Where a name doubles as an identifier, both sides use the same constant, so the comparisons still hold. The Aswid foods keep their prefix as a constant for the refinery's check and now name the creature with its vanilla token, so "Boar" translates too. The Furling crops get one whole description per crop instead of an English sentence with the metal dropped in. The Race Menu Ward's panel title is a mod UI Text, so it reads the translation directly. Saves are unaffected: items and eaten foods are stored by prefab name. The Sverm hive's goods stay for the merchant step. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Aswid/AswidBloodPotions.cs | 17 ++- JotunnModStub/Aswid/AswidBloodRefinery.cs | 20 ++- JotunnModStub/Aswid/AswidClaws.cs | 4 +- JotunnModStub/Aswid/AswidRace.cs | 11 +- JotunnModStub/Aswid/AswidSpectralClaw.cs | 4 +- JotunnModStub/Butler/BoneServant.cs | 12 +- JotunnModStub/Draugh/DraughHumanMeat.cs | 4 +- JotunnModStub/Draugh/DraughSpawner.cs | 16 +-- JotunnModStub/Dvergar/DvergarBanco.cs | 4 +- JotunnModStub/Dvergar/DvergarBotte.cs | 5 +- JotunnModStub/Fenrir/FenrirClaws.cs | 4 +- JotunnModStub/Fenrir/FenrirMangiatoia.cs | 26 ++-- JotunnModStub/Furling/FurlingCrops.cs | 49 ++++--- JotunnModStub/RaceMenuWard.cs | 8 +- JotunnModStub/Skadi/SkadiFrostHeart.cs | 4 +- JotunnModStub/Skadi/SkadiGolem.cs | 5 +- JotunnModStub/Skeleton/SkeletonBonePile.cs | 23 ++- JotunnModStub/Skeleton/SkeletonSentry.cs | 4 +- JotunnModStub/Sverm/SvermBlisterTick.cs | 2 +- JotunnModStub/Sverm/SvermClawSlot.cs | 4 +- JotunnModStub/Sverm/SvermConfig.cs | 2 +- JotunnModStub/Sverm/SvermHive.cs | 2 +- JotunnModStub/Sverm/SvermHiveStore.cs | 4 +- JotunnModStub/Sverm/SvermRace.cs | 2 +- JotunnModStub/Translations/English/items.json | 131 ++++++++++++++++++ JotunnModStub/Translations/Italian/items.json | 131 ++++++++++++++++++ JotunnModStub/Trenta/TrentaComposter.cs | 8 +- JotunnModStub/Trenta/TrentaConfig.cs | 14 +- JotunnModStub/Trenta/TrentaElderRoot.cs | 3 +- JotunnModStub/Trenta/TrentaHeartwoodGrove.cs | 4 +- JotunnModStub/Trol/TrolRace.cs | 4 +- JotunnModStub/Trol/TrolTotem.cs | 4 +- JotunnModStub/TrolsHammer/TrolsHammerItem.cs | 6 +- JotunnModStub/WarVulture/WarVultureItem.cs | 6 +- 34 files changed, 405 insertions(+), 142 deletions(-) create mode 100644 JotunnModStub/Translations/English/items.json create mode 100644 JotunnModStub/Translations/Italian/items.json diff --git a/JotunnModStub/Aswid/AswidBloodPotions.cs b/JotunnModStub/Aswid/AswidBloodPotions.cs index a9a17f1..cf592e4 100644 --- a/JotunnModStub/Aswid/AswidBloodPotions.cs +++ b/JotunnModStub/Aswid/AswidBloodPotions.cs @@ -27,8 +27,8 @@ namespace RacesOfValheim public const string SuperiorBaseName = "MeadBaseSuperiorBloodPotion"; public const string SuperiorPotionName = "MeadSuperiorBloodPotion"; - private const string PotionDisplayName = "Blood Potion"; - private const string SuperiorPotionDisplayName = "Superior Blood Potion"; + private const string PotionDisplayName = "$rov_item_aswid_bloodpotion_name"; + private const string SuperiorPotionDisplayName = "$rov_item_aswid_superiorbloodpotion_name"; private const float HealDuration = 8f; private const float HealFraction = 0.05f; @@ -54,15 +54,14 @@ namespace RacesOfValheim SE_BloodPotion superiorDrink = CreateEffect("SE_SuperiorBloodPotion", SuperiorPotionDisplayName, SuperiorHealFraction, AswidBloodRefinery.SuperiorEssenceName, "MoltenCore"); - GameObject meadBase = CloneItem(BaseName, "MeadBaseHealthMinor", "Blood Potion Mead Base", - "Blood, berries and crypt light, waiting on a barrel."); + GameObject meadBase = CloneItem(BaseName, "MeadBaseHealthMinor", "$rov_item_aswid_bloodpotionbase_name", + "$rov_item_aswid_bloodpotionbase_desc"); GameObject potion = CloneItem(PotionName, "MeadHealthMinor", PotionDisplayName, - "Drink and the hunger stops mattering for a while. Fills every stomach with blood essence, " + - "full or not, and knits the flesh back together."); - GameObject superiorBase = CloneItem(SuperiorBaseName, "MeadBaseHealthMedium", "Superior Blood Potion Mead Base", - "The twice-rendered draught, still raw."); + "$rov_item_aswid_bloodpotion_desc"); + GameObject superiorBase = CloneItem(SuperiorBaseName, "MeadBaseHealthMedium", "$rov_item_aswid_superiorbloodpotionbase_name", + "$rov_item_aswid_superiorbloodpotionbase_desc"); GameObject superiorPotion = CloneItem(SuperiorPotionName, "MeadHealthMedium", SuperiorPotionDisplayName, - "The same mercy, twice as deep."); + "$rov_item_aswid_superiorbloodpotion_desc"); AttachEffect(potion, drink); AttachEffect(superiorPotion, superiorDrink); diff --git a/JotunnModStub/Aswid/AswidBloodRefinery.cs b/JotunnModStub/Aswid/AswidBloodRefinery.cs index c89a2fd..0e8d711 100644 --- a/JotunnModStub/Aswid/AswidBloodRefinery.cs +++ b/JotunnModStub/Aswid/AswidBloodRefinery.cs @@ -30,10 +30,10 @@ namespace RacesOfValheim // The Aswid food patches recognise a meal by its display name, so these strings are part // of the contract with AswidPatches - see IsAswidMeal. - public const string EssenceDisplayName = "Blood Essence"; - public const string SuperiorEssenceDisplayName = "Superior Blood Essence"; - public const string CoreDisplayName = "Blood Core"; - public const string PieceDisplayName = "Blood Refinery"; + public const string EssenceDisplayName = "$rov_item_aswid_bloodessence_name"; + public const string SuperiorEssenceDisplayName = "$rov_item_aswid_superiorbloodessence_name"; + public const string CoreDisplayName = "$rov_item_aswid_bloodcore_name"; + public const string PieceDisplayName = "$rov_piece_aswid_bloodrefinery_name"; // Regeneration is tied to the health value rather than set per tier, so 60 hp gives 5 and // 80 hp gives 6.67 without a second number to keep in sync. @@ -94,7 +94,7 @@ namespace RacesOfValheim public static bool IsAswidMeal(ItemDrop.ItemData item) { if (item == null || item.m_shared == null || item.m_shared.m_name == null) return false; - return item.m_shared.m_name.StartsWith("Aswid Food:") + return item.m_shared.m_name.StartsWith(AswidRace.AswidFoodNamePrefix) || item.m_shared.m_name == EssenceDisplayName || IsEssence(item); } @@ -122,8 +122,7 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = CoreDisplayName; - shared.m_description = "A knot of clotted blood kept beating by something that is not a heart. " + - "The dead trade them; only the dead know how they are made."; + shared.m_description = "$rov_item_aswid_bloodcore_desc"; shared.m_itemType = ItemDrop.ItemData.ItemType.Material; shared.m_food = 0f; shared.m_foodStamina = 0f; @@ -142,8 +141,7 @@ namespace RacesOfValheim EssencePrefab = BuildEssence( EssenceName, EssenceDisplayName, - "Blood rendered down to what it actually is. The only real food an Aswid can " + - "still chew, and the base of every draught worth brewing.", + "$rov_item_aswid_bloodessence_desc", food: 60f, tint: EssenceTint, iconSource: "GemstoneRed"); @@ -151,7 +149,7 @@ namespace RacesOfValheim SuperiorEssencePrefab = BuildEssence( SuperiorEssenceName, SuperiorEssenceDisplayName, - "The same blood, rendered twice. Darker, thicker, and worth five of the first pass.", + "$rov_item_aswid_superiorbloodessence_desc", food: 80f, tint: SuperiorEssenceTint, iconSource: "MoltenCore"); @@ -267,7 +265,7 @@ namespace RacesOfValheim PieceConfig config = new PieceConfig { Name = PieceDisplayName, - Description = "Flesh goes in, bone goes in, and what is left of both comes out red.", + Description = "$rov_piece_aswid_bloodrefinery_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Crafting, Requirements = new[] diff --git a/JotunnModStub/Aswid/AswidClaws.cs b/JotunnModStub/Aswid/AswidClaws.cs index cbfe3db..774857d 100644 --- a/JotunnModStub/Aswid/AswidClaws.cs +++ b/JotunnModStub/Aswid/AswidClaws.cs @@ -20,8 +20,8 @@ namespace RacesOfValheim public override string RaceId => "Aswid"; public override string ItemName => "AswidBeastClaws"; - public override string DisplayName => "Claws of the Beast"; - public override string Description => "Grown in the dark, and darker for it. They do not come off."; + public override string DisplayName => "$rov_item_aswid_claws_name"; + public override string Description => "$rov_item_aswid_claws_desc"; // The Bjorn claw first, by name, because that is the one this race is meant to wear. The // rest are the near-identical ids the manifest also carries - see SvermConfig's own diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index c864a7f..2ca35de 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -7,6 +7,9 @@ namespace RacesOfValheim { public class AswidRace : MonoBehaviour { + /// The start of every Aswid food's name, and how those items are told apart. + public const string AswidFoodNamePrefix = "$rov_item_aswid_food_name"; + public static AswidRace Instance { get; private set; } private static Dictionary mobToTrophyMap = new Dictionary @@ -117,8 +120,12 @@ namespace RacesOfValheim string foodName = "AswidFood_" + mobName; Jotunn.Configs.ItemConfig config = new Jotunn.Configs.ItemConfig(); - config.Name = "Aswid Food: " + mobName; - config.Description = "The life force of the conquered."; + // The prefix token and the creature's own vanilla token ("$enemy_boar"), which the + // game translates too. The prefix is also how the refinery recognises these items - + // see AswidBloodRefinery.IsAswidMeal - so the two must stay the same string. + string mobDisplay = Jotunn.Managers.PrefabManager.Cache.GetPrefab(mobName)?.m_name; + config.Name = AswidFoodNamePrefix + " " + (string.IsNullOrEmpty(mobDisplay) ? mobName : mobDisplay); + config.Description = "$rov_item_aswid_food_desc"; Jotunn.Entities.CustomItem customItem = null; diff --git a/JotunnModStub/Aswid/AswidSpectralClaw.cs b/JotunnModStub/Aswid/AswidSpectralClaw.cs index 64f2c87..01e568d 100644 --- a/JotunnModStub/Aswid/AswidSpectralClaw.cs +++ b/JotunnModStub/Aswid/AswidSpectralClaw.cs @@ -156,8 +156,8 @@ namespace RacesOfValheim ItemDrop itemDrop = clone.GetComponent(); if (itemDrop == null) return false; - itemDrop.m_itemData.m_shared.m_name = "Spectral Claw"; - itemDrop.m_itemData.m_shared.m_description = "A claw of pure shadow, bound to your rage rather than your grip."; + itemDrop.m_itemData.m_shared.m_name = "$rov_item_aswid_spectralclaw_name"; + itemDrop.m_itemData.m_shared.m_description = "$rov_item_aswid_spectralclaw_desc"; itemDrop.m_itemData.m_shared.m_weight = 0f; itemDrop.m_itemData.m_shared.m_useDurability = false; itemDrop.m_itemData.m_shared.m_questItem = true; // undroppable, unsellable diff --git a/JotunnModStub/Butler/BoneServant.cs b/JotunnModStub/Butler/BoneServant.cs index bbd9147..8c7a0a3 100644 --- a/JotunnModStub/Butler/BoneServant.cs +++ b/JotunnModStub/Butler/BoneServant.cs @@ -42,13 +42,13 @@ namespace RacesOfValheim // The smith inherits the names the single servant had, so nothing already built is orphaned. public const string SmithName = "BoneServant"; public const string SmithTableName = "ServantTable"; - public const string SmithDisplay = "Bone Smith"; - public const string SmithTableDisplay = "Smith's Table"; + public const string SmithDisplay = "$rov_creature_bonesmith_name"; + public const string SmithTableDisplay = "$rov_piece_smithtable_name"; public const string CookName = "BoneCook"; public const string CookTableName = "CookTable"; - public const string CookDisplay = "Bone Cook"; - public const string CookTableDisplay = "Cook's Table"; + public const string CookDisplay = "$rov_creature_bonecook_name"; + public const string CookTableDisplay = "$rov_piece_cooktable_name"; /// Vanilla's guaranteed-melee skeleton: the plain one rolls its own weapon, and the /// point here is to have none at all. @@ -90,7 +90,7 @@ namespace RacesOfValheim if (RegisterServant(SmithName, SmithDisplay, ButlerFamily.Forge)) { RegisterTable(SmithTableName, SmithTableDisplay, SmithName, ButlerFamily.Forge, - "A slab of bone and slate, dusted with ore. Something patient waits by the fires.", + "$rov_piece_smithtable_desc", "Coal"); PieceDensityLimit.Register(SmithTableName, TableSpacing, 1, @@ -114,7 +114,7 @@ namespace RacesOfValheim if (RegisterServant(CookName, CookDisplay, ButlerFamily.Kitchen)) { RegisterTable(CookTableName, CookTableDisplay, CookName, ButlerFamily.Kitchen, - "A slab of bone and slate, worn smooth. Something patient waits by the hearth.", + "$rov_piece_cooktable_desc", "CookedMeat"); PieceDensityLimit.Register(CookTableName, TableSpacing, 1, diff --git a/JotunnModStub/Draugh/DraughHumanMeat.cs b/JotunnModStub/Draugh/DraughHumanMeat.cs index 6ba3293..8a4977f 100644 --- a/JotunnModStub/Draugh/DraughHumanMeat.cs +++ b/JotunnModStub/Draugh/DraughHumanMeat.cs @@ -72,8 +72,8 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = item.ItemDrop.m_itemData.m_shared; ItemDrop.ItemData.SharedData source = nourishment.m_itemData.m_shared; - shared.m_name = "Human Meat"; - shared.m_description = "A piece of somebody. The living gag on it; you do not."; + shared.m_name = "$rov_item_draugh_humanmeat_name"; + shared.m_description = "$rov_item_draugh_humanmeat_desc"; // Raw meat is a Material in vanilla, so none of the food fields below would be read // without this. diff --git a/JotunnModStub/Draugh/DraughSpawner.cs b/JotunnModStub/Draugh/DraughSpawner.cs index b921be7..9e00fd5 100644 --- a/JotunnModStub/Draugh/DraughSpawner.cs +++ b/JotunnModStub/Draugh/DraughSpawner.cs @@ -25,17 +25,17 @@ namespace RacesOfValheim { // ─── Names ─────────────────────────────────────────────────────────── public const string PieceName = "DraughBodyPile"; - public const string PieceDisplayName = "Cursed Body Pile"; + public const string PieceDisplayName = "$rov_piece_draugh_bodypile_name"; public const string BoneName = "CursedBone"; - public const string BoneDisplayName = "Cursed Bone"; + public const string BoneDisplayName = "$rov_item_draugh_cursedbone_name"; public const string GreaterBoneName = "GreaterCursedBone"; - public const string GreaterBoneDisplayName = "Greater Cursed Bone"; + public const string GreaterBoneDisplayName = "$rov_item_draugh_greatercursedbone_name"; public const string ThrallName = "DraughThrall_Draugr"; public const string ThrallEliteName = "DraughThrall_DraugrElite"; - public const string ThrallDisplayName = "Draugr Thrall"; - public const string ThrallEliteDisplayName = "Draugr Elite Thrall"; + public const string ThrallDisplayName = "$rov_creature_draugh_thrall_name"; + public const string ThrallEliteDisplayName = "$rov_creature_draugh_thrallelite_name"; // RaisedThrall groups by kind for follower caps and for the roster, so these are the strings // that decide "is this one an officer" - no longer a display-name comparison. @@ -118,9 +118,9 @@ namespace RacesOfValheim public static void Register() { RegisterBone(BoneName, BoneDisplayName, BoneTint, - "A bone that will not stay quiet. The dead sell them; the dead do not say why."); + "$rov_item_draugh_cursedbone_desc"); RegisterBone(GreaterBoneName, GreaterBoneDisplayName, GreaterBoneTint, - "The same bone, older, and louder. A pile fed one of these starts keeping officers."); + "$rov_item_draugh_greatercursedbone_desc"); RegisterThrall(ThrallName, "Draugr", ThrallDisplayName, KindNormal, MaxFollowers); RegisterThrall(ThrallEliteName, "Draugr_Elite", ThrallEliteDisplayName, KindElite, MaxEliteFollowers); @@ -263,7 +263,7 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig { Name = PieceDisplayName, - Description = "Feed it and it answers. The dead here are yours, if you are dead enough to ask.", + Description = "$rov_piece_draugh_bodypile_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Crafting, Icon = BorrowIcon(TrophyDraugr), diff --git a/JotunnModStub/Dvergar/DvergarBanco.cs b/JotunnModStub/Dvergar/DvergarBanco.cs index f686d6a..b18e968 100644 --- a/JotunnModStub/Dvergar/DvergarBanco.cs +++ b/JotunnModStub/Dvergar/DvergarBanco.cs @@ -36,7 +36,7 @@ namespace RacesOfValheim public static class DvergarBanco { public const string PieceName = "DvergarContractBank"; - public const string PieceDisplayName = "Contract Bank"; + public const string PieceDisplayName = "$rov_piece_dvergar_contractbank_name"; public const string RaceId = DvergarConfig.RaceId; /// The Queen's drop, mapped to state 7 in BossProgressionManager. Mistlands money for @@ -348,7 +348,7 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig { Name = PieceDisplayName, - Description = "A ledger, a seal and a heap of coin. Sign here and someone else does the dying.", + Description = "$rov_piece_dvergar_contractbank_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Crafting, Icon = BorrowIcon("TrophyDvergr"), diff --git a/JotunnModStub/Dvergar/DvergarBotte.cs b/JotunnModStub/Dvergar/DvergarBotte.cs index b389bc8..05ee712 100644 --- a/JotunnModStub/Dvergar/DvergarBotte.cs +++ b/JotunnModStub/Dvergar/DvergarBotte.cs @@ -33,7 +33,7 @@ namespace RacesOfValheim public static class DvergarBotte { public const string PieceName = "DvergarRuneBarrel"; - public const string PieceDisplayName = "Rune Barrel"; + public const string PieceDisplayName = "$rov_piece_dvergar_runebarrel_name"; public const string RaceId = DvergarConfig.RaceId; /// How many drinks it holds. One dose is one mercenary served, so twenty is four @@ -101,8 +101,7 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig { Name = PieceDisplayName, - Description = "Pour a brew in and the crew drinks. What it does to them is whatever it " + - "would have done to you - if they have the parts for it.", + Description = "$rov_piece_dvergar_runebarrel_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Crafting, Icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr"), diff --git a/JotunnModStub/Fenrir/FenrirClaws.cs b/JotunnModStub/Fenrir/FenrirClaws.cs index ebe749d..a9a8f15 100644 --- a/JotunnModStub/Fenrir/FenrirClaws.cs +++ b/JotunnModStub/Fenrir/FenrirClaws.cs @@ -19,8 +19,8 @@ namespace RacesOfValheim public override string RaceId => "Fenrir"; public override string ItemName => "FenrirCursedClaws"; - public override string DisplayName => "Cursed Claws"; - public override string Description => "The wolf's hands, kept on in the man's shape. They do not come off."; + public override string DisplayName => "$rov_item_fenrir_claws_name"; + public override string Description => "$rov_item_fenrir_claws_desc"; public override string[] ModelPrefabs => new[] { diff --git a/JotunnModStub/Fenrir/FenrirMangiatoia.cs b/JotunnModStub/Fenrir/FenrirMangiatoia.cs index 79a9c38..b098f0a 100644 --- a/JotunnModStub/Fenrir/FenrirMangiatoia.cs +++ b/JotunnModStub/Fenrir/FenrirMangiatoia.cs @@ -35,12 +35,12 @@ namespace RacesOfValheim { // ─── Names ─────────────────────────────────────────────────────────── public const string PieceName = "FenrirPackTrough"; - public const string PieceDisplayName = "Pack Trough"; + public const string PieceDisplayName = "$rov_piece_fenrir_packtrough_name"; public const string UlvsblodName = "Ulvsblod"; - public const string UlvsblodDisplayName = "Ulvsblod"; + public const string UlvsblodDisplayName = "$rov_item_fenrir_ulvsblod_name"; public const string GreaterUlvsblodName = "GreaterUlvsblod"; - public const string GreaterUlvsblodDisplayName = "Greater Ulvsblod"; + public const string GreaterUlvsblodDisplayName = "$rov_item_fenrir_greaterulvsblod_name"; public const int UlvsblodPrice = 500; public const int GreaterUlvsblodPrice = 1500; @@ -49,9 +49,9 @@ namespace RacesOfValheim public const string UlvName = "FenrirPack_Ulv"; public const string FenrirName = "FenrirPack_Fenrir"; - public const string WolfDisplayName = "Pack Wolf"; - public const string UlvDisplayName = "Ulv"; - public const string FenrirDisplayName = "Fenrir"; + public const string WolfDisplayName = "$rov_creature_fenrir_packwolf_name"; + public const string UlvDisplayName = "$rov_creature_fenrir_packulv_name"; + public const string FenrirDisplayName = "$rov_creature_fenrir_packfenrir_name"; public const string KindWolf = "FenrirPackWolf"; public const string KindUlv = "FenrirPackUlv"; @@ -140,18 +140,16 @@ namespace RacesOfValheim public static void Register() { RegisterUlvsblod(UlvsblodName, UlvsblodDisplayName, UlvsblodTint, - "Wolf blood, kept warm by something that should not be able to keep anything warm. " + - "The Fenring sell it and do not explain it."); + "$rov_item_fenrir_ulvsblod_desc"); RegisterUlvsblod(GreaterUlvsblodName, GreaterUlvsblodDisplayName, GreaterUlvsblodTint, - "Older blood, and further down the line. A trough given one of these starts raising " + - "something worse than ulv."); + "$rov_item_fenrir_greaterulvsblod_desc"); RegisterPackAnimal(WolfName, "Wolf", WolfDisplayName, KindWolf, - "It answers to the blood of the wolf, not to you.", 1f); + "$rov_creature_fenrir_pack_desc", 1f); RegisterPackAnimal(UlvName, "Ulv", UlvDisplayName, KindUlv, - "It answers to the blood of the wolf, not to you.", 1f); + "$rov_creature_fenrir_pack_desc", 1f); RegisterPackAnimal(FenrirName, "Fenring", FenrirDisplayName, KindFenrir, - "Only the blood of the wolf commands this one.", FenrirScale); + "$rov_creature_fenrir_packfenrir_desc", FenrirScale); RegisterPiece(); @@ -338,7 +336,7 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig { Name = PieceDisplayName, - Description = "Fill it with meat and the pack comes. One at a time, and it remembers its dead.", + Description = "$rov_piece_fenrir_packtrough_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Crafting, Icon = BorrowIcon("TrophyFenring"), diff --git a/JotunnModStub/Furling/FurlingCrops.cs b/JotunnModStub/Furling/FurlingCrops.cs index 75a7455..79cf5c9 100644 --- a/JotunnModStub/Furling/FurlingCrops.cs +++ b/JotunnModStub/Furling/FurlingCrops.cs @@ -65,27 +65,27 @@ namespace RacesOfValheim { new MetalCrop { - Metal = "Copper", FlaxName = "CopperFlax", FlaxDisplay = "Copper Flax", - DustName = "CopperDust", DustDisplay = "Copper Dust", + Metal = "Copper", FlaxName = "CopperFlax", FlaxDisplay = "$rov_item_furling_copperflax_name", + DustName = "CopperDust", DustDisplay = "$rov_item_furling_copperdust_name", PickableName = "Pickable_CopperFlax", SaplingName = "sapling_copperflax", - SaplingDisplay = "Copper Flax", OrePrefab = "CopperOre", + SaplingDisplay = "$rov_piece_furling_copperflaxsapling_name", OrePrefab = "CopperOre", Tint = new Color(0.72f, 0.45f, 0.20f, 1f), }, new MetalCrop { - Metal = "Tin", FlaxName = "TinFlax", FlaxDisplay = "Tin Flax", - DustName = "TinDust", DustDisplay = "Tin Dust", + Metal = "Tin", FlaxName = "TinFlax", FlaxDisplay = "$rov_item_furling_tinflax_name", + DustName = "TinDust", DustDisplay = "$rov_item_furling_tindust_name", PickableName = "Pickable_TinFlax", SaplingName = "sapling_tinflax", - SaplingDisplay = "Tin Flax", OrePrefab = "TinOre", + SaplingDisplay = "$rov_piece_furling_tinflaxsapling_name", OrePrefab = "TinOre", Tint = new Color(0.80f, 0.82f, 0.85f, 1f), }, new MetalCrop { - Metal = "Iron", FlaxName = "IronFlax", FlaxDisplay = "Iron Flax", - DustName = "IronDust", DustDisplay = "Iron Dust", + Metal = "Iron", FlaxName = "IronFlax", FlaxDisplay = "$rov_item_furling_ironflax_name", + DustName = "IronDust", DustDisplay = "$rov_item_furling_irondust_name", PickableName = "Pickable_IronFlax", SaplingName = "sapling_ironflax", // Iron's raw form is IronScrap, not "IronOre" - there is no IronOre prefab. - SaplingDisplay = "Iron Flax", OrePrefab = "IronScrap", + SaplingDisplay = "$rov_piece_furling_ironflaxsapling_name", OrePrefab = "IronScrap", Tint = new Color(0.35f, 0.36f, 0.38f, 1f), }, }; @@ -104,18 +104,29 @@ namespace RacesOfValheim { new RockBerry { - BerryName = "Stoneberry", BerryDisplay = "Stoneberry", - BushName = "StoneberryBush", BushDisplay = "Stoneberry Bush", + BerryName = "Stoneberry", BerryDisplay = "$rov_item_furling_stoneberry_name", + BushName = "StoneberryBush", BushDisplay = "$rov_piece_furling_stoneberrybush_name", YieldPrefab = "Stone", Tint = new Color(0.55f, 0.55f, 0.55f, 1f), }, new RockBerry { - BerryName = "Flintberry", BerryDisplay = "Flintberry", - BushName = "FlintberryBush", BushDisplay = "Flintberry Bush", + BerryName = "Flintberry", BerryDisplay = "$rov_item_furling_flintberry_name", + BushName = "FlintberryBush", BushDisplay = "$rov_piece_furling_flintberrybush_name", YieldPrefab = "Flint", Tint = new Color(0.30f, 0.32f, 0.35f, 1f), }, }; + /// + /// The description token that goes with a name token: "$rov_item_furling_tinflax_name" gives + /// "$rov_item_furling_tinflax_desc". One whole sentence per crop in the translation files, + /// rather than one sentence with the metal dropped in, so a translator can decline the metal + /// or move it wherever their language wants it. + /// + private static string DescriptionFor(string nameToken) + { + return nameToken.EndsWith("_name") ? nameToken.Substring(0, nameToken.Length - 5) + "_desc" : nameToken; + } + public static void Register() { foreach (MetalCrop crop in Crops) RegisterCrop(crop); @@ -151,8 +162,7 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = crop.FlaxDisplay; - shared.m_description = $"Flax grown in {crop.Metal.ToLowerInvariant()}-poisoned soil, and it took. " + - "Useless as cloth. Grind it and see."; + shared.m_description = DescriptionFor(crop.FlaxDisplay); // Teleportable is inherited from Flax and left alone on purpose: the flax travels, the // dust does not. That asymmetry is the whole point of the chain. @@ -177,8 +187,7 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = crop.DustDisplay; - shared.m_description = $"A sack of {crop.Metal.ToLowerInvariant()} ground fine. " + - "A furnace cannot tell it from ore, and it will not go through a portal either."; + shared.m_description = DescriptionFor(crop.DustDisplay); shared.m_itemType = ItemDrop.ItemData.ItemType.Material; shared.m_food = 0f; shared.m_foodStamina = 0f; @@ -280,7 +289,7 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig { Name = crop.SaplingDisplay, - Description = $"Plant it and it grows more {crop.FlaxDisplay}.", + Description = DescriptionFor(crop.SaplingDisplay), PieceTable = PieceTables.Cultivator, Requirements = new[] { new RequirementConfig(crop.FlaxName, 1, 0, true) }, })); @@ -310,7 +319,7 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = berry.BerryDisplay; - shared.m_description = $"Not a berry, whatever it looks like. Bury one and a {berry.YieldPrefab.ToLowerInvariant()}-bearing bush comes up."; + shared.m_description = DescriptionFor(berry.BerryDisplay); // Inedible, as designed. Material with every food value at zero also keeps it clear of // the Trenta's vegan check and of the Aswid/Skeleton food gates, all three of which only @@ -385,7 +394,7 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig { Name = berry.BushDisplay, - Description = $"Yields {berry.YieldPrefab.ToLowerInvariant()}, and keeps yielding it.", + Description = DescriptionFor(berry.BushDisplay), PieceTable = PieceTables.Cultivator, // The one thing that was actually missing the first time round. Icon = BorrowIcon(berry.YieldPrefab), diff --git a/JotunnModStub/RaceMenuWard.cs b/JotunnModStub/RaceMenuWard.cs index 255b38e..5457560 100644 --- a/JotunnModStub/RaceMenuWard.cs +++ b/JotunnModStub/RaceMenuWard.cs @@ -46,8 +46,8 @@ namespace RacesOfValheim PieceConfig config = new PieceConfig { - Name = "Race Menu Ward", - Description = "Commune with your heritage. Offer a fallen boss's relic to claim its power.", + Name = "$rov_piece_racemenuward_name", + Description = "$rov_piece_racemenuward_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Misc, // Deliberately trivial: this is a utility the player needs early, not a reward. @@ -167,7 +167,7 @@ namespace RacesOfValheim // serialised m_hoverOffset, which is 0 unless the prefab sets one, so 0 is vanilla behaviour. public float GetHoverOffset() => 0f; - public string GetHoverName() => "Race Menu Ward"; + public string GetHoverName() => "$rov_piece_racemenuward_name"; public string GetHoverText() { @@ -266,7 +266,7 @@ namespace RacesOfValheim Image bg = panel.AddComponent(); bg.color = new Color(0f, 0f, 0f, 0.85f); - AddLabel("Title", "Race Menu Ward", 46, new Vector2(0, 230), new Vector2(700, 90)); + AddLabel("Title", ModText.Get("rov_piece_racemenuward_name"), 46, new Vector2(0, 230), new Vector2(700, 90)); AddLabel("Status", BuildStatusText(), 24, new Vector2(0, 110), new Vector2(900, 160)); diff --git a/JotunnModStub/Skadi/SkadiFrostHeart.cs b/JotunnModStub/Skadi/SkadiFrostHeart.cs index 0b53594..d2d50cc 100644 --- a/JotunnModStub/Skadi/SkadiFrostHeart.cs +++ b/JotunnModStub/Skadi/SkadiFrostHeart.cs @@ -18,7 +18,7 @@ namespace RacesOfValheim public static class SkadiFrostHeart { public const string PrefabName = "GreaterFrostHeart"; - public const string DisplayName = "Greater Frost Heart"; + public const string DisplayName = "$rov_item_skadi_greaterfrostheart_name"; public const int Price = 1500; private const string SourcePrefab = "FreezeGland"; @@ -43,7 +43,7 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = DisplayName; - shared.m_description = "Older cold than the mountain's. The cultists sell it and will not say where they dig."; + shared.m_description = "$rov_item_skadi_greaterfrostheart_desc"; shared.m_itemType = ItemDrop.ItemData.ItemType.Material; shared.m_weight = 0.5f; shared.m_maxStackSize = 10; diff --git a/JotunnModStub/Skadi/SkadiGolem.cs b/JotunnModStub/Skadi/SkadiGolem.cs index 07e6aeb..9a1035e 100644 --- a/JotunnModStub/Skadi/SkadiGolem.cs +++ b/JotunnModStub/Skadi/SkadiGolem.cs @@ -39,7 +39,7 @@ namespace RacesOfValheim // ─── Names ─────────────────────────────────────────────────────────── public const string GolemName = "SkadiCrystalGolem"; public const string SeedPieceName = "SkadiCrystalGolemSeed"; - public const string DisplayName = "Crystal Golem"; + public const string DisplayName = "$rov_creature_skadi_crystalgolem_name"; private const string SourceGolem = "StoneGolem"; @@ -271,8 +271,7 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig { Name = DisplayName, - Description = "Cut at the stone and woken with a tear. It will not follow you, and it " + - "will not leave the stonecutter that shaped it.", + Description = "$rov_piece_skadi_crystalgolem_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Crafting, // The stonecutter is the station, so vanilla itself refuses to place one anywhere its diff --git a/JotunnModStub/Skeleton/SkeletonBonePile.cs b/JotunnModStub/Skeleton/SkeletonBonePile.cs index 8824612..35fcdd9 100644 --- a/JotunnModStub/Skeleton/SkeletonBonePile.cs +++ b/JotunnModStub/Skeleton/SkeletonBonePile.cs @@ -33,29 +33,29 @@ namespace RacesOfValheim { // ─── Names ─────────────────────────────────────────────────────────── public const string PieceName = "SkeletonBonePile"; - public const string PieceDisplayName = "Bound Bone Pile"; + public const string PieceDisplayName = "$rov_piece_skeleton_bonepile_name"; // The Soul Stone: a green ruby, sold by the Skeleton bench, and the thing that binds a skull and // ten fragments into a sentry that cannot walk. Cheap on purpose - 50 coins - because the real // cost of a sentry is the skull, which has to be taken off a skeleton rather than bought. public const string SoulStoneName = "SoulStone"; - public const string SoulStoneDisplayName = "Soul Stone"; + public const string SoulStoneDisplayName = "$rov_item_skeleton_soulstone_name"; public const int SoulStonePrice = 50; private static readonly Color SoulStoneTint = new Color(0.15f, 0.85f, 0.35f, 1f); public const string SkullName = "CursedSkull"; - public const string SkullDisplayName = "Cursed Skull"; + public const string SkullDisplayName = "$rov_item_skeleton_cursedskull_name"; public const string GreaterSkullName = "GreaterCursedSkull"; - public const string GreaterSkullDisplayName = "Greater Cursed Skull"; + public const string GreaterSkullDisplayName = "$rov_item_skeleton_greatercursedskull_name"; public const string ThrallMeleeName = "SkeletonThrall_Melee"; public const string ThrallRangedName = "SkeletonThrall_Ranged"; public const string ThrallRancidName = "SkeletonThrall_Rancid"; - public const string ThrallMeleeDisplay = "Bound Skeleton"; - public const string ThrallRangedDisplay = "Bound Archer"; - public const string ThrallRancidDisplay = "Bound Rancid Remains"; + public const string ThrallMeleeDisplay = "$rov_creature_skeleton_thrallmelee_name"; + public const string ThrallRangedDisplay = "$rov_creature_skeleton_thrallranged_name"; + public const string ThrallRancidDisplay = "$rov_creature_skeleton_thrallrancid_name"; public const string KindMelee = "SkeletonMelee"; public const string KindRanged = "SkeletonRanged"; @@ -119,9 +119,9 @@ namespace RacesOfValheim public static void Register() { RegisterSkull(SkullName, SkullDisplayName, SkullTint, - "A skull that keeps counting. Set it down and the ground starts answering."); + "$rov_item_skeleton_cursedskull_desc"); RegisterSkull(GreaterSkullName, GreaterSkullDisplayName, GreaterSkullTint, - "Older, and it counts higher. A pile given one of these raises the rotten too."); + "$rov_item_skeleton_greatercursedskull_desc"); RegisterSoulStone(); @@ -191,8 +191,7 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = SoulStoneDisplayName; - shared.m_description = "Something is still in there, and it is still angry. Bind it to a skull " + - "and it will stand watch as long as the bones hold."; + shared.m_description = "$rov_item_skeleton_soulstone_desc"; shared.m_itemType = ItemDrop.ItemData.ItemType.Material; shared.m_weight = 0.5f; shared.m_maxStackSize = 20; @@ -339,7 +338,7 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig { Name = PieceDisplayName, - Description = "Twenty fragments buy a place in the line. The one who fills it will keep standing up.", + Description = "$rov_piece_skeleton_bonepile_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Crafting, Icon = BorrowIcon("TrophySkeleton"), diff --git a/JotunnModStub/Skeleton/SkeletonSentry.cs b/JotunnModStub/Skeleton/SkeletonSentry.cs index ef37404..dd96949 100644 --- a/JotunnModStub/Skeleton/SkeletonSentry.cs +++ b/JotunnModStub/Skeleton/SkeletonSentry.cs @@ -26,7 +26,7 @@ namespace RacesOfValheim { public const string SentryName = "SkeletonSentry"; public const string SeedPieceName = "SkeletonSentrySeed"; - public const string DisplayName = "Bound Sentry"; + public const string DisplayName = "$rov_creature_skeleton_sentry_name"; /// Seconds without being hit before it starts closing its wounds. public const float RegenDelay = 10f; @@ -157,7 +157,7 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig { Name = DisplayName, - Description = "A skull on a soul stone. It will not walk, and it will not stop watching.", + Description = "$rov_piece_skeleton_sentry_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Crafting, Icon = BorrowIcon("TrophySkeleton"), diff --git a/JotunnModStub/Sverm/SvermBlisterTick.cs b/JotunnModStub/Sverm/SvermBlisterTick.cs index 7363fb1..507b97f 100644 --- a/JotunnModStub/Sverm/SvermBlisterTick.cs +++ b/JotunnModStub/Sverm/SvermBlisterTick.cs @@ -22,7 +22,7 @@ namespace RacesOfValheim public static class SvermBlisterTick { public const string PrefabName = "SvermBlisterTick"; - public const string DisplayName = "Blister Tick"; + public const string DisplayName = "$rov_creature_sverm_blistertick_name"; private const string SourcePrefab = "Tick"; /// How many slots this nest has bought. Permanent, and the respawn reads it. diff --git a/JotunnModStub/Sverm/SvermClawSlot.cs b/JotunnModStub/Sverm/SvermClawSlot.cs index 54201c6..34bf82e 100644 --- a/JotunnModStub/Sverm/SvermClawSlot.cs +++ b/JotunnModStub/Sverm/SvermClawSlot.cs @@ -42,7 +42,7 @@ namespace RacesOfValheim /// longer resolve. The display name below is the only half a player ever reads. /// public const string ItemName = "SvermMaulclaws"; - public const string ItemDisplayName = "Chitin Claws"; + public const string ItemDisplayName = "$rov_item_sverm_claws_name"; /// Row in the reserved column the claws sit on. The other three await the carapace. private const int ClawRow = 0; @@ -80,7 +80,7 @@ namespace RacesOfValheim { ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = ItemDisplayName; - shared.m_description = "Grown, not forged. They do not come off."; + shared.m_description = "$rov_item_sverm_claws_desc"; // Quest item: Valheim refuses to drop, trade or stack these. It is the cheapest // honest way to say "this is part of your body" without a patch per verb. diff --git a/JotunnModStub/Sverm/SvermConfig.cs b/JotunnModStub/Sverm/SvermConfig.cs index f5f0c93..0a341ca 100644 --- a/JotunnModStub/Sverm/SvermConfig.cs +++ b/JotunnModStub/Sverm/SvermConfig.cs @@ -444,7 +444,7 @@ namespace RacesOfValheim public static readonly float MarketSize = 1.6f; // metres, the borrowed model's largest side // ─── Seeker Worker ─────────────────────────────────────────────────── - public const string WorkerDisplayName = "Seeker Worker"; + public const string WorkerDisplayName = "$rov_creature_sverm_worker_name"; public static readonly float WorkerScale = 0.5f; public static readonly float WorkerHealthFraction = 0.5f; public static readonly float WorkerDamageFraction = 0.5f; diff --git a/JotunnModStub/Sverm/SvermHive.cs b/JotunnModStub/Sverm/SvermHive.cs index 6e8f53b..3c2266b 100644 --- a/JotunnModStub/Sverm/SvermHive.cs +++ b/JotunnModStub/Sverm/SvermHive.cs @@ -95,7 +95,7 @@ namespace RacesOfValheim // station ends up unplaceable with no error. Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); piece.m_name = DisplayName; - piece.m_description = "The colony begins here. Everything else grows out of it."; + piece.m_description = "$rov_piece_sverm_broodmound_desc"; piece.m_groundPiece = true; piece.m_groundOnly = true; piece.m_cultivatedGroundOnly = false; diff --git a/JotunnModStub/Sverm/SvermHiveStore.cs b/JotunnModStub/Sverm/SvermHiveStore.cs index 39df58b..f63f642 100644 --- a/JotunnModStub/Sverm/SvermHiveStore.cs +++ b/JotunnModStub/Sverm/SvermHiveStore.cs @@ -258,7 +258,7 @@ namespace RacesOfValheim public static class SvermHiveMarketPiece { public const string PieceName = "SvermHiveMarket"; - public const string DisplayName = "Hive Market"; + public const string DisplayName = "$rov_piece_sverm_hivemarket_name"; /// Scenery only, and checked rather than trusted - see SvermHive.MouthCandidates. private static readonly string[] SourceCandidates = @@ -325,7 +325,7 @@ namespace RacesOfValheim piece.m_craftingStation = null; piece.m_resources = new Piece.Requirement[0]; piece.m_name = DisplayName; - piece.m_description = "Where the colony trades. It spends the tank of the nest it stands in."; + piece.m_description = "$rov_piece_sverm_hivemarket_desc"; piece.m_groundPiece = true; piece.m_groundOnly = true; piece.m_canBeRemoved = true; diff --git a/JotunnModStub/Sverm/SvermRace.cs b/JotunnModStub/Sverm/SvermRace.cs index f3f1450..69a11f9 100644 --- a/JotunnModStub/Sverm/SvermRace.cs +++ b/JotunnModStub/Sverm/SvermRace.cs @@ -101,6 +101,6 @@ namespace RacesOfValheim public static class SvermHiveNames { public const string PieceName = "SvermBroodMound"; - public const string PieceDisplayName = "Brood Mound"; + public const string PieceDisplayName = "$rov_piece_sverm_broodmound_name"; } } diff --git a/JotunnModStub/Translations/English/items.json b/JotunnModStub/Translations/English/items.json new file mode 100644 index 0000000..1d707d6 --- /dev/null +++ b/JotunnModStub/Translations/English/items.json @@ -0,0 +1,131 @@ +{ + "rov_creature_bonecook_name": "Bone Cook", + "rov_creature_bonesmith_name": "Bone Smith", + "rov_creature_draugh_thrall_name": "Draugr Thrall", + "rov_creature_draugh_thrallelite_name": "Draugr Elite Thrall", + "rov_creature_fenrir_pack_desc": "It answers to the blood of the wolf, not to you.", + "rov_creature_fenrir_packfenrir_desc": "Only the blood of the wolf commands this one.", + "rov_creature_fenrir_packfenrir_name": "Fenrir", + "rov_creature_fenrir_packulv_name": "Ulv", + "rov_creature_fenrir_packwolf_name": "Pack Wolf", + "rov_creature_skadi_crystalgolem_name": "Crystal Golem", + "rov_creature_skeleton_sentry_name": "Bound Sentry", + "rov_creature_skeleton_thrallmelee_name": "Bound Skeleton", + "rov_creature_skeleton_thrallrancid_name": "Bound Rancid Remains", + "rov_creature_skeleton_thrallranged_name": "Bound Archer", + "rov_creature_sverm_blistertick_name": "Blister Tick", + "rov_creature_sverm_worker_name": "Seeker Worker", + "rov_item_aswid_bloodcore_desc": "A knot of clotted blood kept beating by something that is not a heart. The dead trade them; only the dead know how they are made.", + "rov_item_aswid_bloodcore_name": "Blood Core", + "rov_item_aswid_bloodessence_desc": "Blood rendered down to what it actually is. The only real food an Aswid can still chew, and the base of every draught worth brewing.", + "rov_item_aswid_bloodessence_name": "Blood Essence", + "rov_item_aswid_bloodpotion_desc": "Drink and the hunger stops mattering for a while. Fills every stomach with blood essence, full or not, and knits the flesh back together.", + "rov_item_aswid_bloodpotion_name": "Blood Potion", + "rov_item_aswid_bloodpotionbase_desc": "Blood, berries and crypt light, waiting on a barrel.", + "rov_item_aswid_bloodpotionbase_name": "Blood Potion Mead Base", + "rov_item_aswid_claws_desc": "Grown in the dark, and darker for it. They do not come off.", + "rov_item_aswid_claws_name": "Claws of the Beast", + "rov_item_aswid_food_desc": "The life force of the conquered.", + "rov_item_aswid_food_name": "Aswid Food:", + "rov_item_aswid_spectralclaw_desc": "A claw of pure shadow, bound to your rage rather than your grip.", + "rov_item_aswid_spectralclaw_name": "Spectral Claw", + "rov_item_aswid_superiorbloodessence_desc": "The same blood, rendered twice. Darker, thicker, and worth five of the first pass.", + "rov_item_aswid_superiorbloodessence_name": "Superior Blood Essence", + "rov_item_aswid_superiorbloodpotion_desc": "The same mercy, twice as deep.", + "rov_item_aswid_superiorbloodpotion_name": "Superior Blood Potion", + "rov_item_aswid_superiorbloodpotionbase_desc": "The twice-rendered draught, still raw.", + "rov_item_aswid_superiorbloodpotionbase_name": "Superior Blood Potion Mead Base", + "rov_item_draugh_cursedbone_desc": "A bone that will not stay quiet. The dead sell them; the dead do not say why.", + "rov_item_draugh_cursedbone_name": "Cursed Bone", + "rov_item_draugh_greatercursedbone_desc": "The same bone, older, and louder. A pile fed one of these starts keeping officers.", + "rov_item_draugh_greatercursedbone_name": "Greater Cursed Bone", + "rov_item_draugh_humanmeat_desc": "A piece of somebody. The living gag on it; you do not.", + "rov_item_draugh_humanmeat_name": "Human Meat", + "rov_item_fenrir_claws_desc": "The wolf's hands, kept on in the man's shape. They do not come off.", + "rov_item_fenrir_claws_name": "Cursed Claws", + "rov_item_fenrir_greaterulvsblod_desc": "Older blood, and further down the line. A trough given one of these starts raising something worse than ulv.", + "rov_item_fenrir_greaterulvsblod_name": "Greater Ulvsblod", + "rov_item_fenrir_ulvsblod_desc": "Wolf blood, kept warm by something that should not be able to keep anything warm. The Fenring sell it and do not explain it.", + "rov_item_fenrir_ulvsblod_name": "Ulvsblod", + "rov_item_furling_copperdust_desc": "A sack of copper ground fine. A furnace cannot tell it from ore, and it will not go through a portal either.", + "rov_item_furling_copperdust_name": "Copper Dust", + "rov_item_furling_copperflax_desc": "Flax grown in copper-poisoned soil, and it took. Useless as cloth. Grind it and see.", + "rov_item_furling_copperflax_name": "Copper Flax", + "rov_item_furling_flintberry_desc": "Not a berry, whatever it looks like. Bury one and a flint-bearing bush comes up.", + "rov_item_furling_flintberry_name": "Flintberry", + "rov_item_furling_irondust_desc": "A sack of iron ground fine. A furnace cannot tell it from ore, and it will not go through a portal either.", + "rov_item_furling_irondust_name": "Iron Dust", + "rov_item_furling_ironflax_desc": "Flax grown in iron-poisoned soil, and it took. Useless as cloth. Grind it and see.", + "rov_item_furling_ironflax_name": "Iron Flax", + "rov_item_furling_stoneberry_desc": "Not a berry, whatever it looks like. Bury one and a stone-bearing bush comes up.", + "rov_item_furling_stoneberry_name": "Stoneberry", + "rov_item_furling_tindust_desc": "A sack of tin ground fine. A furnace cannot tell it from ore, and it will not go through a portal either.", + "rov_item_furling_tindust_name": "Tin Dust", + "rov_item_furling_tinflax_desc": "Flax grown in tin-poisoned soil, and it took. Useless as cloth. Grind it and see.", + "rov_item_furling_tinflax_name": "Tin Flax", + "rov_item_skadi_greaterfrostheart_desc": "Older cold than the mountain's. The cultists sell it and will not say where they dig.", + "rov_item_skadi_greaterfrostheart_name": "Greater Frost Heart", + "rov_item_skeleton_cursedskull_desc": "A skull that keeps counting. Set it down and the ground starts answering.", + "rov_item_skeleton_cursedskull_name": "Cursed Skull", + "rov_item_skeleton_greatercursedskull_desc": "Older, and it counts higher. A pile given one of these raises the rotten too.", + "rov_item_skeleton_greatercursedskull_name": "Greater Cursed Skull", + "rov_item_skeleton_soulstone_desc": "Something is still in there, and it is still angry. Bind it to a skull and it will stand watch as long as the bones hold.", + "rov_item_skeleton_soulstone_name": "Soul Stone", + "rov_item_sverm_claws_desc": "Grown, not forged. They do not come off.", + "rov_item_sverm_claws_name": "Chitin Claws", + "rov_item_trenta_fertilizer_desc": "Everything that was meat, a month later. Press it into the soil and whatever is rooted there stops waiting.", + "rov_item_trenta_fertilizer_name": "Fertilizer", + "rov_item_trenta_heartwoodseed_desc": "A seed fed on a whole barrel of rot. Plant it and go away for a while.", + "rov_item_trenta_heartwoodseed_name": "Heartwood Seed", + "rov_item_trenta_rotseed_desc": "A seed that died before it could sprout, and did not stop. The forest folk sell them; only the forest knows what grows from one.", + "rov_item_trenta_rotseed_name": "Rot Seed", + "rov_item_trol_giantslog_desc": "A massive tree log wielded as a weapon.", + "rov_item_trol_giantslog_name": "Giant's Log", + "rov_item_trolshammer_desc": "A hammer swung by something that never had to duck through a doorway. It builds everything the ordinary one builds, out of the same materials, and simply builds it bigger.", + "rov_item_trolshammer_name": "Trol's Hammer", + "rov_item_warvulture_desc": "A vulture's head, kept. Raise it and the bird comes back under you, and it will carry you as long as you care to stay up - though it only has so much haste in it before it settles into a glide.", + "rov_item_warvulture_name": "War Vulture", + "rov_piece_aswid_bloodrefinery_desc": "Flesh goes in, bone goes in, and what is left of both comes out red.", + "rov_piece_aswid_bloodrefinery_name": "Blood Refinery", + "rov_piece_cooktable_desc": "A slab of bone and slate, worn smooth. Something patient waits by the hearth.", + "rov_piece_cooktable_name": "Cook's Table", + "rov_piece_draugh_bodypile_desc": "Feed it and it answers. The dead here are yours, if you are dead enough to ask.", + "rov_piece_draugh_bodypile_name": "Cursed Body Pile", + "rov_piece_dvergar_contractbank_desc": "A ledger, a seal and a heap of coin. Sign here and someone else does the dying.", + "rov_piece_dvergar_contractbank_name": "Contract Bank", + "rov_piece_dvergar_runebarrel_desc": "Pour a brew in and the crew drinks. What it does to them is whatever it would have done to you - if they have the parts for it.", + "rov_piece_dvergar_runebarrel_name": "Rune Barrel", + "rov_piece_fenrir_packtrough_desc": "Fill it with meat and the pack comes. One at a time, and it remembers its dead.", + "rov_piece_fenrir_packtrough_name": "Pack Trough", + "rov_piece_furling_copperflaxsapling_desc": "Plant it and it grows more Copper Flax.", + "rov_piece_furling_copperflaxsapling_name": "Copper Flax", + "rov_piece_furling_flintberrybush_desc": "Yields flint, and keeps yielding it.", + "rov_piece_furling_flintberrybush_name": "Flintberry Bush", + "rov_piece_furling_ironflaxsapling_desc": "Plant it and it grows more Iron Flax.", + "rov_piece_furling_ironflaxsapling_name": "Iron Flax", + "rov_piece_furling_stoneberrybush_desc": "Yields stone, and keeps yielding it.", + "rov_piece_furling_stoneberrybush_name": "Stoneberry Bush", + "rov_piece_furling_tinflaxsapling_desc": "Plant it and it grows more Tin Flax.", + "rov_piece_furling_tinflaxsapling_name": "Tin Flax", + "rov_piece_racemenuward_desc": "Commune with your heritage. Offer a fallen boss's relic to claim its power.", + "rov_piece_racemenuward_name": "Race Menu Ward", + "rov_piece_skadi_crystalgolem_desc": "Cut at the stone and woken with a tear. It will not follow you, and it will not leave the stonecutter that shaped it.", + "rov_piece_skeleton_bonepile_desc": "Twenty fragments buy a place in the line. The one who fills it will keep standing up.", + "rov_piece_skeleton_bonepile_name": "Bound Bone Pile", + "rov_piece_skeleton_sentry_desc": "A skull on a soul stone. It will not walk, and it will not stop watching.", + "rov_piece_smithtable_desc": "A slab of bone and slate, dusted with ore. Something patient waits by the fires.", + "rov_piece_smithtable_name": "Smith's Table", + "rov_piece_sverm_broodmound_desc": "The colony begins here. Everything else grows out of it.", + "rov_piece_sverm_broodmound_name": "Brood Mound", + "rov_piece_sverm_hivemarket_desc": "Where the colony trades. It spends the tank of the nest it stands in.", + "rov_piece_sverm_hivemarket_name": "Hive Market", + "rov_piece_trenta_composter_desc": "What rots is not lost. It feeds.", + "rov_piece_trenta_composter_name": "Composter", + "rov_piece_trenta_elderroot_desc": "What the Elder left behind, still growing. Mends itself, and everything a player built close enough to it.", + "rov_piece_trenta_elderroot_name": "Root of the Elder", + "rov_piece_trenta_heartwoodgrove_desc": "A crate of rot with something growing out of it. Give it time.", + "rov_piece_trenta_heartwoodgrove_name": "Heartwood Grove", + "rov_piece_trenta_heartwoodsapling_name": "Heartwood Sapling", + "rov_piece_trol_wartotem_desc": "A head that still remembers how to shout. Coin goes in, a warband walks out.", + "rov_piece_trol_wartotem_name": "War Totem" +} diff --git a/JotunnModStub/Translations/Italian/items.json b/JotunnModStub/Translations/Italian/items.json new file mode 100644 index 0000000..40e5ddd --- /dev/null +++ b/JotunnModStub/Translations/Italian/items.json @@ -0,0 +1,131 @@ +{ + "rov_creature_bonecook_name": "Cuoco d'ossa", + "rov_creature_bonesmith_name": "Fabbro d'ossa", + "rov_creature_draugh_thrall_name": "Servo Draugr", + "rov_creature_draugh_thrallelite_name": "Servo Draugr d'élite", + "rov_creature_fenrir_pack_desc": "Risponde al sangue del lupo, non a te.", + "rov_creature_fenrir_packfenrir_desc": "Solo il sangue del lupo comanda questo.", + "rov_creature_fenrir_packfenrir_name": "Fenrir", + "rov_creature_fenrir_packulv_name": "Ulv", + "rov_creature_fenrir_packwolf_name": "Lupo del branco", + "rov_creature_skadi_crystalgolem_name": "Golem di cristallo", + "rov_creature_skeleton_sentry_name": "Sentinella vincolata", + "rov_creature_skeleton_thrallmelee_name": "Scheletro vincolato", + "rov_creature_skeleton_thrallrancid_name": "Resti rancidi vincolati", + "rov_creature_skeleton_thrallranged_name": "Arciere vincolato", + "rov_creature_sverm_blistertick_name": "Zecca vescicante", + "rov_creature_sverm_worker_name": "Operaio cercatore", + "rov_item_aswid_bloodcore_desc": "Un grumo di sangue rappreso che batte ancora, tenuto in vita da qualcosa che non è un cuore. I morti lo commerciano; solo i morti sanno come si fa.", + "rov_item_aswid_bloodcore_name": "Nucleo di sangue", + "rov_item_aswid_bloodessence_desc": "Sangue ridotto a ciò che è davvero. L'unico vero cibo che un Aswid riesce ancora a masticare, e la base di ogni pozione che valga la pena distillare.", + "rov_item_aswid_bloodessence_name": "Essenza di sangue", + "rov_item_aswid_bloodpotion_desc": "Bevi e la fame smette di contare per un po'. Riempie ogni stomaco di essenza di sangue, pieno o no, e ricuce la carne.", + "rov_item_aswid_bloodpotion_name": "Pozione di sangue", + "rov_item_aswid_bloodpotionbase_desc": "Sangue, bacche e luce di cripta, in attesa in un barile.", + "rov_item_aswid_bloodpotionbase_name": "Base per pozione di sangue", + "rov_item_aswid_claws_desc": "Cresciuti nel buio, e più scuri per questo. Non si staccano.", + "rov_item_aswid_claws_name": "Artigli della Bestia", + "rov_item_aswid_food_desc": "La forza vitale dei vinti.", + "rov_item_aswid_food_name": "Cibo Aswid:", + "rov_item_aswid_spectralclaw_desc": "Un artiglio di pura ombra, legato alla tua furia più che alla tua presa.", + "rov_item_aswid_spectralclaw_name": "Artiglio spettrale", + "rov_item_aswid_superiorbloodessence_desc": "Lo stesso sangue, ridotto due volte. Più scuro, più denso, e vale cinque volte il primo passaggio.", + "rov_item_aswid_superiorbloodessence_name": "Essenza di sangue superiore", + "rov_item_aswid_superiorbloodpotion_desc": "La stessa pietà, due volte più profonda.", + "rov_item_aswid_superiorbloodpotion_name": "Pozione di sangue superiore", + "rov_item_aswid_superiorbloodpotionbase_desc": "L'infuso ridotto due volte, ancora crudo.", + "rov_item_aswid_superiorbloodpotionbase_name": "Base per pozione di sangue superiore", + "rov_item_draugh_cursedbone_desc": "Un osso che non vuole stare zitto. I morti lo vendono; i morti non dicono perché.", + "rov_item_draugh_cursedbone_name": "Osso maledetto", + "rov_item_draugh_greatercursedbone_desc": "Lo stesso osso, più vecchio e più rumoroso. Un mucchio nutrito con uno di questi comincia a tenere ufficiali.", + "rov_item_draugh_greatercursedbone_name": "Osso maledetto superiore", + "rov_item_draugh_humanmeat_desc": "Un pezzo di qualcuno. Ai vivi viene il voltastomaco; a te no.", + "rov_item_draugh_humanmeat_name": "Carne umana", + "rov_item_fenrir_claws_desc": "Le mani del lupo, rimaste nella forma dell'uomo. Non si staccano.", + "rov_item_fenrir_claws_name": "Artigli maledetti", + "rov_item_fenrir_greaterulvsblod_desc": "Sangue più antico, più in basso nella discendenza. Una mangiatoia che ne riceve uno comincia a far nascere qualcosa di peggio di un ulv.", + "rov_item_fenrir_greaterulvsblod_name": "Ulvsblod superiore", + "rov_item_fenrir_ulvsblod_desc": "Sangue di lupo, tenuto caldo da qualcosa che non dovrebbe poter scaldare niente. I Fenring lo vendono e non lo spiegano.", + "rov_item_fenrir_ulvsblod_name": "Ulvsblod", + "rov_item_furling_copperdust_desc": "Un sacco di rame macinato fine. Una fornace non lo distingue dal minerale, e non passa nemmeno da un portale.", + "rov_item_furling_copperdust_name": "Polvere di rame", + "rov_item_furling_copperflax_desc": "Lino cresciuto in un terreno avvelenato dal rame, e ha attecchito. Inutile come stoffa. Macinalo e vedrai.", + "rov_item_furling_copperflax_name": "Lino di rame", + "rov_item_furling_flintberry_desc": "Non è una bacca, anche se ci somiglia. Seppelliscine una e spunta un cespuglio che dà selce.", + "rov_item_furling_flintberry_name": "Bacca di selce", + "rov_item_furling_irondust_desc": "Un sacco di ferro macinato fine. Una fornace non lo distingue dal minerale, e non passa nemmeno da un portale.", + "rov_item_furling_irondust_name": "Polvere di ferro", + "rov_item_furling_ironflax_desc": "Lino cresciuto in un terreno avvelenato dal ferro, e ha attecchito. Inutile come stoffa. Macinalo e vedrai.", + "rov_item_furling_ironflax_name": "Lino di ferro", + "rov_item_furling_stoneberry_desc": "Non è una bacca, anche se ci somiglia. Seppelliscine una e spunta un cespuglio che dà pietra.", + "rov_item_furling_stoneberry_name": "Bacca di pietra", + "rov_item_furling_tindust_desc": "Un sacco di stagno macinato fine. Una fornace non lo distingue dal minerale, e non passa nemmeno da un portale.", + "rov_item_furling_tindust_name": "Polvere di stagno", + "rov_item_furling_tinflax_desc": "Lino cresciuto in un terreno avvelenato dallo stagno, e ha attecchito. Inutile come stoffa. Macinalo e vedrai.", + "rov_item_furling_tinflax_name": "Lino di stagno", + "rov_item_skadi_greaterfrostheart_desc": "Un freddo più antico di quello della montagna. I cultisti lo vendono e non dicono dove scavano.", + "rov_item_skadi_greaterfrostheart_name": "Cuore di gelo superiore", + "rov_item_skeleton_cursedskull_desc": "Un teschio che continua a contare. Posalo e il terreno comincia a rispondere.", + "rov_item_skeleton_cursedskull_name": "Teschio maledetto", + "rov_item_skeleton_greatercursedskull_desc": "Più vecchio, e conta più in alto. Un mucchio che ne riceve uno fa risorgere anche i rancidi.", + "rov_item_skeleton_greatercursedskull_name": "Teschio maledetto superiore", + "rov_item_skeleton_soulstone_desc": "Là dentro c'è ancora qualcosa, ed è ancora arrabbiato. Legalo a un teschio e farà la guardia finché le ossa reggono.", + "rov_item_skeleton_soulstone_name": "Pietra dell'anima", + "rov_item_sverm_claws_desc": "Cresciuti, non forgiati. Non si staccano.", + "rov_item_sverm_claws_name": "Artigli di chitina", + "rov_item_trenta_fertilizer_desc": "Tutto ciò che era carne, un mese dopo. Premilo nel terreno e ciò che vi è radicato smette di aspettare.", + "rov_item_trenta_fertilizer_name": "Fertilizzante", + "rov_item_trenta_heartwoodseed_desc": "Un seme nutrito con un intero barile di marciume. Piantalo e vattene per un po'.", + "rov_item_trenta_heartwoodseed_name": "Seme di durame", + "rov_item_trenta_rotseed_desc": "Un seme morto prima di germogliare, che non si è fermato. Il popolo della foresta li vende; solo la foresta sa cosa ne cresce.", + "rov_item_trenta_rotseed_name": "Seme marcio", + "rov_item_trol_giantslog_desc": "Un enorme tronco d'albero brandito come arma.", + "rov_item_trol_giantslog_name": "Tronco del gigante", + "rov_item_trolshammer_desc": "Un martello brandito da qualcosa che non ha mai dovuto chinarsi sotto una porta. Costruisce tutto ciò che costruisce quello normale, con gli stessi materiali, e lo fa semplicemente più grande.", + "rov_item_trolshammer_name": "Martello del Trol", + "rov_item_warvulture_desc": "La testa di un avvoltoio, conservata. Sollevala e l'uccello torna sotto di te, e ti porterà finché vorrai restare in aria, anche se ha solo un po' di slancio prima di mettersi a planare.", + "rov_item_warvulture_name": "Avvoltoio da guerra", + "rov_piece_aswid_bloodrefinery_desc": "Entra carne, entra osso, e quel che resta di entrambi esce rosso.", + "rov_piece_aswid_bloodrefinery_name": "Raffineria di sangue", + "rov_piece_cooktable_desc": "Una lastra di osso e ardesia, consumata dall'uso. Qualcosa di paziente aspetta accanto al focolare.", + "rov_piece_cooktable_name": "Tavolo del cuoco", + "rov_piece_draugh_bodypile_desc": "Nutrilo e risponde. I morti qui sono tuoi, se sei abbastanza morto da chiederlo.", + "rov_piece_draugh_bodypile_name": "Mucchio di corpi maledetto", + "rov_piece_dvergar_contractbank_desc": "Un registro, un sigillo e un mucchio di monete. Firma qui e a morire ci pensa qualcun altro.", + "rov_piece_dvergar_contractbank_name": "Banca dei contratti", + "rov_piece_dvergar_runebarrel_desc": "Versaci una bevanda e la squadra beve. Quello che fa a loro è quello che avrebbe fatto a te, se hanno i pezzi giusti.", + "rov_piece_dvergar_runebarrel_name": "Barile runico", + "rov_piece_fenrir_packtrough_desc": "Riempila di carne e il branco arriva. Uno alla volta, e ricorda i suoi morti.", + "rov_piece_fenrir_packtrough_name": "Mangiatoia del branco", + "rov_piece_furling_copperflaxsapling_desc": "Piantalo e crescerà altro lino di rame.", + "rov_piece_furling_copperflaxsapling_name": "Lino di rame", + "rov_piece_furling_flintberrybush_desc": "Dà selce, e continua a darla.", + "rov_piece_furling_flintberrybush_name": "Cespuglio di bacche di selce", + "rov_piece_furling_ironflaxsapling_desc": "Piantalo e crescerà altro lino di ferro.", + "rov_piece_furling_ironflaxsapling_name": "Lino di ferro", + "rov_piece_furling_stoneberrybush_desc": "Dà pietra, e continua a darla.", + "rov_piece_furling_stoneberrybush_name": "Cespuglio di bacche di pietra", + "rov_piece_furling_tinflaxsapling_desc": "Piantalo e crescerà altro lino di stagno.", + "rov_piece_furling_tinflaxsapling_name": "Lino di stagno", + "rov_piece_racemenuward_desc": "Entra in comunione con la tua stirpe. Offri la reliquia di un boss caduto per reclamarne il potere.", + "rov_piece_racemenuward_name": "Sigillo della razza", + "rov_piece_skadi_crystalgolem_desc": "Tagliato dalla pietra e risvegliato con una lacrima. Non ti seguirà, e non lascerà lo scalpellino che l'ha plasmato.", + "rov_piece_skeleton_bonepile_desc": "Venti frammenti comprano un posto nella fila. Chi lo occupa continuerà a rialzarsi.", + "rov_piece_skeleton_bonepile_name": "Mucchio d'ossa vincolato", + "rov_piece_skeleton_sentry_desc": "Un teschio su una pietra dell'anima. Non camminerà, e non smetterà di guardare.", + "rov_piece_smithtable_desc": "Una lastra di osso e ardesia, spolverata di minerale. Qualcosa di paziente aspetta accanto ai fuochi.", + "rov_piece_smithtable_name": "Tavolo del fabbro", + "rov_piece_sverm_broodmound_desc": "La colonia comincia qui. Tutto il resto cresce da questo.", + "rov_piece_sverm_broodmound_name": "Cumulo della covata", + "rov_piece_sverm_hivemarket_desc": "Dove la colonia commercia. Spende la riserva del nido in cui si trova.", + "rov_piece_sverm_hivemarket_name": "Mercato dell'alveare", + "rov_piece_trenta_composter_desc": "Ciò che marcisce non è perduto. Nutre.", + "rov_piece_trenta_composter_name": "Compostiera", + "rov_piece_trenta_elderroot_desc": "Ciò che l'Antico si è lasciato dietro, ancora in crescita. Si ripara da sé, e ripara tutto ciò che un giocatore ha costruito abbastanza vicino.", + "rov_piece_trenta_elderroot_name": "Radice dell'Antico", + "rov_piece_trenta_heartwoodgrove_desc": "Una cassa di marciume con qualcosa che ci cresce dentro. Dagli tempo.", + "rov_piece_trenta_heartwoodgrove_name": "Boschetto di durame", + "rov_piece_trenta_heartwoodsapling_name": "Germoglio di durame", + "rov_piece_trol_wartotem_desc": "Una testa che ricorda ancora come si urla. Entrano monete, esce una banda da guerra.", + "rov_piece_trol_wartotem_name": "Totem di guerra" +} diff --git a/JotunnModStub/Trenta/TrentaComposter.cs b/JotunnModStub/Trenta/TrentaComposter.cs index 92ddd18..914ec5e 100644 --- a/JotunnModStub/Trenta/TrentaComposter.cs +++ b/JotunnModStub/Trenta/TrentaComposter.cs @@ -100,8 +100,7 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = TrentaConfig.RotSeedDisplayName; - shared.m_description = "A seed that died before it could sprout, and did not stop. " + - "The forest folk sell them; only the forest knows what grows from one."; + shared.m_description = "$rov_item_trenta_rotseed_desc"; shared.m_itemType = ItemDrop.ItemData.ItemType.Material; shared.m_weight = 0.5f; shared.m_maxStackSize = 20; @@ -125,8 +124,7 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = TrentaConfig.FertilizerDisplayName; - shared.m_description = "Everything that was meat, a month later. Press it into the soil and " + - "whatever is rooted there stops waiting."; + shared.m_description = "$rov_item_trenta_fertilizer_desc"; // Consumable, not Material, and this is the only reason: a Material never reaches // Humanoid.UseItem - vanilla refuses it before that - while a Consumable does, which is @@ -223,7 +221,7 @@ namespace RacesOfValheim PieceConfig config = new PieceConfig { Name = TrentaConfig.ComposterDisplayName, - Description = "What rots is not lost. It feeds.", + Description = "$rov_piece_trenta_composter_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Crafting, Requirements = new[] diff --git a/JotunnModStub/Trenta/TrentaConfig.cs b/JotunnModStub/Trenta/TrentaConfig.cs index f395a6e..35fc25d 100644 --- a/JotunnModStub/Trenta/TrentaConfig.cs +++ b/JotunnModStub/Trenta/TrentaConfig.cs @@ -405,13 +405,13 @@ namespace RacesOfValheim // The chain: a Rot Seed bought from the Greydwarf faction bench gates the Composter, the // Composter rots raw flesh into Fertilizer, and Fertilizer grows any plant on the spot. public const string ComposterPieceName = "TrentaComposter"; - public const string ComposterDisplayName = "Composter"; + public const string ComposterDisplayName = "$rov_piece_trenta_composter_name"; public const string FertilizerName = "Fertilizer"; - public const string FertilizerDisplayName = "Fertilizer"; + public const string FertilizerDisplayName = "$rov_item_trenta_fertilizer_name"; public const string RotSeedName = "RotSeed"; - public const string RotSeedDisplayName = "Rot Seed"; + public const string RotSeedDisplayName = "$rov_item_trenta_rotseed_name"; // Same band as the Aswid's Blood Core, which does the same job for the same reason. public const int RotSeedPrice = 500; @@ -452,7 +452,7 @@ namespace RacesOfValheim // point would need if it had one: this is a race identity piece, not a purchase from // someone else's bench (see the War Totem's own note on the same choice). public const string ElderRootPieceName = "TrentaElderRoot"; - public const string ElderRootDisplayName = "Root of the Elder"; + public const string ElderRootDisplayName = "$rov_piece_trenta_elderroot_name"; public const int ElderRootUnlockState = 3; // The Elder dead @@ -507,11 +507,11 @@ namespace RacesOfValheim // Plant a seed, wait, and the tree that comes up fertilises what surrounds it, stings what // approaches it, and fills a chest with honey. Three independent functions on one piece. public const string GroveSeedName = "HeartwoodSeed"; - public const string GroveSeedDisplayName = "Heartwood Seed"; + public const string GroveSeedDisplayName = "$rov_item_trenta_heartwoodseed_name"; public const string GroveSaplingPieceName = "TrentaHeartwoodSapling"; - public const string GroveSaplingDisplayName = "Heartwood Sapling"; + public const string GroveSaplingDisplayName = "$rov_piece_trenta_heartwoodsapling_name"; public const string GrovePieceName = "TrentaHeartwoodGrove"; - public const string GroveDisplayName = "Heartwood Grove"; + public const string GroveDisplayName = "$rov_piece_trenta_heartwoodgrove_name"; // A grove costs exactly one full Composter batch. That is the whole balance argument. public const int GroveSeedFertilizerCost = ComposterYield; diff --git a/JotunnModStub/Trenta/TrentaElderRoot.cs b/JotunnModStub/Trenta/TrentaElderRoot.cs index ccbcc54..d36d67c 100644 --- a/JotunnModStub/Trenta/TrentaElderRoot.cs +++ b/JotunnModStub/Trenta/TrentaElderRoot.cs @@ -93,8 +93,7 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig { Name = TrentaConfig.ElderRootDisplayName, - Description = "What the Elder left behind, still growing. Mends itself, and " + - "everything a player built close enough to it.", + Description = "$rov_piece_trenta_elderroot_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Crafting, Icon = icon, diff --git a/JotunnModStub/Trenta/TrentaHeartwoodGrove.cs b/JotunnModStub/Trenta/TrentaHeartwoodGrove.cs index aeb43c1..a8ca08c 100644 --- a/JotunnModStub/Trenta/TrentaHeartwoodGrove.cs +++ b/JotunnModStub/Trenta/TrentaHeartwoodGrove.cs @@ -58,7 +58,7 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = TrentaConfig.GroveSeedDisplayName; - shared.m_description = "A seed fed on a whole barrel of rot. Plant it and go away for a while."; + shared.m_description = "$rov_item_trenta_heartwoodseed_desc"; shared.m_itemType = ItemDrop.ItemData.ItemType.Material; shared.m_weight = 1f; shared.m_maxStackSize = 10; @@ -129,7 +129,7 @@ namespace RacesOfValheim PieceConfig config = new PieceConfig { Name = TrentaConfig.GroveDisplayName, - Description = "A crate of rot with something growing out of it. Give it time.", + Description = "$rov_piece_trenta_heartwoodgrove_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Misc, Requirements = new[] diff --git a/JotunnModStub/Trol/TrolRace.cs b/JotunnModStub/Trol/TrolRace.cs index 3016bca..591ca5b 100644 --- a/JotunnModStub/Trol/TrolRace.cs +++ b/JotunnModStub/Trol/TrolRace.cs @@ -77,8 +77,8 @@ namespace RacesOfValheim if (logPrefab != null) { Jotunn.Configs.ItemConfig config = new Jotunn.Configs.ItemConfig(); - config.Name = "Giant's Log"; - config.Description = "A massive tree log wielded as a weapon."; + config.Name = "$rov_item_trol_giantslog_name"; + config.Description = "$rov_item_trol_giantslog_desc"; CustomItem customWep = new CustomItem("TrolWeapon_" + logName, "MaceIron", config); if (customWep != null && customWep.ItemPrefab != null) diff --git a/JotunnModStub/Trol/TrolTotem.cs b/JotunnModStub/Trol/TrolTotem.cs index b4beb46..512437b 100644 --- a/JotunnModStub/Trol/TrolTotem.cs +++ b/JotunnModStub/Trol/TrolTotem.cs @@ -26,7 +26,7 @@ namespace RacesOfValheim public static class TrolTotem { public const string PieceName = "TrolWarTotem"; - public const string PieceDisplayName = "War Totem"; + public const string PieceDisplayName = "$rov_piece_trol_wartotem_name"; public const string RaceId = "Trol"; /// Core wood. The item is RoundLog - another display name that does not predict the id. @@ -313,7 +313,7 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig { Name = PieceDisplayName, - Description = "A head that still remembers how to shout. Coin goes in, a warband walks out.", + Description = "$rov_piece_trol_wartotem_desc", PieceTable = PieceTables.Hammer, Category = PieceCategories.Crafting, Icon = BorrowIcon(TrollHead), diff --git a/JotunnModStub/TrolsHammer/TrolsHammerItem.cs b/JotunnModStub/TrolsHammer/TrolsHammerItem.cs index 5fa4076..b008b59 100644 --- a/JotunnModStub/TrolsHammer/TrolsHammerItem.cs +++ b/JotunnModStub/TrolsHammer/TrolsHammerItem.cs @@ -24,7 +24,7 @@ namespace RacesOfValheim public static class TrolsHammerItem { public const string PrefabName = "TrolsHammer"; - public const string DisplayName = "Trol's Hammer"; + public const string DisplayName = "$rov_item_trolshammer_name"; private const string SourcePrefab = "Hammer"; private const string Label = "TrolsHammer"; @@ -51,9 +51,7 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = DisplayName; - shared.m_description = "A hammer swung by something that never had to duck through a " + - "doorway. It builds everything the ordinary one builds, out of the " + - "same materials, and simply builds it bigger."; + shared.m_description = "$rov_item_trolshammer_desc"; if (shared.m_buildPieces == null) { diff --git a/JotunnModStub/WarVulture/WarVultureItem.cs b/JotunnModStub/WarVulture/WarVultureItem.cs index e3443d9..7b735fa 100644 --- a/JotunnModStub/WarVulture/WarVultureItem.cs +++ b/JotunnModStub/WarVulture/WarVultureItem.cs @@ -32,7 +32,7 @@ namespace RacesOfValheim public static class WarVultureItem { public const string PrefabName = "WarVulture"; - public const string DisplayName = "War Vulture"; + public const string DisplayName = "$rov_item_warvulture_name"; private const string SourcePrefab = "StaffSkeleton"; private const string TrophyPrefab = "TrophyVolture"; @@ -62,9 +62,7 @@ namespace RacesOfValheim ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; shared.m_name = DisplayName; - shared.m_description = "A vulture's head, kept. Raise it and the bird comes back under you, " + - "and it will carry you as long as you care to stay up - though it only " + - "has so much haste in it before it settles into a glide."; + shared.m_description = "$rov_item_warvulture_desc"; shared.m_useDurability = false; // ItemType is left exactly as the vanilla staff has it: it decides the equip slot and From b0d18b0654976ddb1fe5d170e06c07658231d49c Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 26 Sep 2026 20:30:03 +0200 Subject: [PATCH 078/290] 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 --- JotunnModStub/Aswid/AswidBloodRefinery.cs | 2 +- JotunnModStub/Aswid/AswidPatches.cs | 2 +- JotunnModStub/Aswid/AswidRace.cs | 18 +- JotunnModStub/Aswid/AswidThrall.cs | 8 +- JotunnModStub/Aswid/BloodRefineryBehaviour.cs | 2 +- JotunnModStub/BossProgressionManager.cs | 20 ++ JotunnModStub/Butler/BoneServant.cs | 8 +- JotunnModStub/Butler/ServantTableBehaviour.cs | 8 +- JotunnModStub/Draugh/DraughFoodPatches.cs | 4 +- .../Draugh/DraughProgressionPatches.cs | 6 +- JotunnModStub/Draugh/DraughRace.cs | 2 +- JotunnModStub/Draugh/DraughSpawner.cs | 4 +- .../Draugh/DraughSpawnerBehaviour.cs | 12 +- JotunnModStub/Dvergar/DvergarAbilities.cs | 8 +- JotunnModStub/Dvergar/DvergarBanco.cs | 6 +- .../Dvergar/DvergarBancoBehaviour.cs | 14 +- JotunnModStub/Dvergar/DvergarBotte.cs | 2 +- .../Dvergar/DvergarBotteBehaviour.cs | 14 +- JotunnModStub/Dvergar/DvergarPatches.cs | 2 +- JotunnModStub/Fenrir/FenrirBehaviors.cs | 2 +- JotunnModStub/Fenrir/FenrirMangiatoia.cs | 2 +- .../Fenrir/FenrirMangiatoiaBehaviour.cs | 12 +- JotunnModStub/Fenrir/FenrirRace.cs | 19 +- JotunnModStub/Fenrir/FenrirStatusEffects.cs | 2 +- JotunnModStub/ModText.cs | 8 +- JotunnModStub/PieceDensityLimit.cs | 3 +- JotunnModStub/RaceCaveBuilding.cs | 2 +- JotunnModStub/RaceClaws.cs | 2 +- JotunnModStub/RaceMenuWard.cs | 8 +- JotunnModStub/RacesOfValheim.cs | 36 ++-- JotunnModStub/RaisedThrall.cs | 16 +- JotunnModStub/Skadi/DrakeFormBehavior.cs | 2 +- JotunnModStub/Skadi/SkadiGolem.cs | 10 +- JotunnModStub/Skadi/SkadiGolemBehaviour.cs | 2 +- JotunnModStub/Skadi/SkadiRace.cs | 16 +- JotunnModStub/Skeleton/SkeletonBonePile.cs | 4 +- .../Skeleton/SkeletonBonePileBehaviour.cs | 18 +- JotunnModStub/Skeleton/SkeletonPatches.cs | 6 +- JotunnModStub/Sverm/SvermBlisterTick.cs | 2 +- JotunnModStub/Sverm/SvermBrood.cs | 2 +- JotunnModStub/Sverm/SvermClawSlot.cs | 2 +- JotunnModStub/Sverm/SvermFood.cs | 2 +- JotunnModStub/Sverm/SvermHive.cs | 8 +- JotunnModStub/Sverm/SvermHiveGoods.cs | 2 +- JotunnModStub/Sverm/SvermHiveStore.cs | 18 +- JotunnModStub/Sverm/SvermMedicine.cs | 2 +- JotunnModStub/Sverm/SvermPatches.cs | 2 +- JotunnModStub/Sverm/SvermRavagerForm.cs | 8 +- .../Translations/English/messages.json | 193 ++++++++++++++++++ .../Translations/Italian/messages.json | 193 ++++++++++++++++++ JotunnModStub/Trenta/ComposterBehaviour.cs | 4 +- JotunnModStub/Trenta/GroveBehaviour.cs | 4 +- JotunnModStub/Trenta/TrentaComposter.cs | 8 +- JotunnModStub/Trenta/TrentaElderRoot.cs | 4 +- JotunnModStub/Trenta/TrentaFoodPatches.cs | 2 +- JotunnModStub/Trenta/TrentaHeartwoodGrove.cs | 2 +- JotunnModStub/Trenta/TrentaMuspell.cs | 4 +- JotunnModStub/Trol/TrolLogWeapon.cs | 6 +- JotunnModStub/Trol/TrolTotem.cs | 4 +- JotunnModStub/Trol/TrolTotemBehaviour.cs | 14 +- JotunnModStub/WarVulture/WarVultureMount.cs | 8 +- 61 files changed, 606 insertions(+), 200 deletions(-) create mode 100644 JotunnModStub/Translations/English/messages.json create mode 100644 JotunnModStub/Translations/Italian/messages.json diff --git a/JotunnModStub/Aswid/AswidBloodRefinery.cs b/JotunnModStub/Aswid/AswidBloodRefinery.cs index 0e8d711..78a9867 100644 --- a/JotunnModStub/Aswid/AswidBloodRefinery.cs +++ b/JotunnModStub/Aswid/AswidBloodRefinery.cs @@ -567,7 +567,7 @@ namespace RacesOfValheim if (!AswidBloodRefinery.IsEssence(item)) return true; if (AswidRace.IsAswid()) return true; - player.Message(MessageHud.MessageType.Center, "Living blood curdles in a living throat."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_living_blood_curdles_living_throat")); return false; } } diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index 0bc1753..9361df9 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -529,7 +529,7 @@ namespace RacesOfValheim { AswidRace.DevourEnabled = !AswidRace.DevourEnabled; AswidRace.AuraEnabled = AswidRace.DevourEnabled; - string msg = AswidRace.DevourEnabled ? "Vampiric Aura: ENABLED" : "Vampiric Aura: DISABLED"; + string msg = ModText.Get(AswidRace.DevourEnabled ? "rov_msg_aswid_aura_enabled" : "rov_msg_aswid_aura_disabled"); __instance.Message(MessageHud.MessageType.Center, msg); } diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index 2ca35de..edfbdc5 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -338,11 +338,11 @@ namespace RacesOfValheim { if (isNight) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "what a horrible night to have a curse"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_what_horrible_night_have_curse")); } else { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The morning sun has vanquished the horrible night"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_morning_sun_has_vanquished_horrible")); } } wasNight = isNight; @@ -431,7 +431,7 @@ namespace RacesOfValheim if (IsTransformed && !isTransformingSequence && activeRules != null && activeRules.NeedsNight && EnvMan.instance != null && EnvMan.IsDay()) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The morning sun drives the bat back into your body"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_morning_sun_drives_bat_back")); StartCoroutine(RevertToHumanRoutine()); } } @@ -534,7 +534,7 @@ namespace RacesOfValheim // sunrise must always be able to turn back. if (rules.NeedsNight && (EnvMan.instance == null || !EnvMan.IsNight())) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The sun burns. You can only take bat form at night."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_sun_burns_can_only_take")); return; } @@ -844,7 +844,7 @@ namespace RacesOfValheim c.SetTamed(true); HarmonyLib.Traverse.Create(tameable).Method("Tame").GetValue(); // attempt to call Tame for VFX if it exists tameable.Command(Player.m_localPlayer); - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Tamed!"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_tamed")); } } } @@ -863,7 +863,7 @@ namespace RacesOfValheim if (Time.time - lastEclipseTime < cooldown) { int remaining = (int)(cooldown - (Time.time - lastEclipseTime)); - Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Eclipse is on cooldown. Remaining: {remaining}s"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_eclipse_cooldown_remaining_s", remaining)); return; } @@ -915,7 +915,7 @@ namespace RacesOfValheim } // Lock player for the duration of the cast (approx 2 seconds) - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "An Eclipse descends..."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_eclipse_descends")); float castTimer = 0f; while(castTimer < AswidConfig.EclipseCastTime.Value) @@ -967,7 +967,7 @@ namespace RacesOfValheim if (Player.m_localPlayer != null) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The Eclipse has ended."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_eclipse_has_ended")); } } @@ -1160,7 +1160,7 @@ namespace RacesOfValheim if (successfullyEaten) { // Show the Vae Victis message in the center of the screen - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Vae Victis"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_vae_victis")); Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_ate " + addedItem.m_shared.m_name); // Vae Victis XP logic - similar to Dead Raiser diff --git a/JotunnModStub/Aswid/AswidThrall.cs b/JotunnModStub/Aswid/AswidThrall.cs index 35d1562..638ce4e 100644 --- a/JotunnModStub/Aswid/AswidThrall.cs +++ b/JotunnModStub/Aswid/AswidThrall.cs @@ -81,12 +81,12 @@ namespace RacesOfValheim if (m_ai.GetFollowTarget() == user.gameObject) { m_ai.SetFollowTarget(null); - user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} is staying."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_staying", m_character.m_name)); } else { m_ai.SetFollowTarget(user.gameObject); - user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} is following."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_following", m_character.m_name)); } } return true; @@ -98,7 +98,7 @@ namespace RacesOfValheim float cooldown = AswidRace.GetEnslaveCooldown(); if (cooldown > 0) { - user.Message(MessageHud.MessageType.Center, $"Dominate on cooldown ({Mathf.CeilToInt(cooldown / 60f)}m {Mathf.CeilToInt(cooldown % 60f)}s)"); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_dominate_cooldown_m_s", Mathf.CeilToInt(cooldown / 60f), Mathf.CeilToInt(cooldown % 60f))); return false; } @@ -123,7 +123,7 @@ namespace RacesOfValheim GameObject vfx = ZNetScene.instance.GetPrefab("vfx_corpse_destruction_medium"); if (vfx) Instantiate(vfx, m_character.transform.position, Quaternion.identity); - user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} dominated!"); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_dominated", m_character.m_name)); return true; } diff --git a/JotunnModStub/Aswid/BloodRefineryBehaviour.cs b/JotunnModStub/Aswid/BloodRefineryBehaviour.cs index d06b47b..ada6820 100644 --- a/JotunnModStub/Aswid/BloodRefineryBehaviour.cs +++ b/JotunnModStub/Aswid/BloodRefineryBehaviour.cs @@ -98,7 +98,7 @@ namespace RacesOfValheim if (item == null) item = FindUsable(inventory, isMeat); if (item == null) { - user.Message(MessageHud.MessageType.Center, isMeat ? "No raw flesh to render." : "No bone to grind."); + user.Message(MessageHud.MessageType.Center, (isMeat ? ModText.Get("rov_msg_aswid_no_raw_flesh_render") : ModText.Get("rov_msg_aswid_no_bone_grind"))); return false; } diff --git a/JotunnModStub/BossProgressionManager.cs b/JotunnModStub/BossProgressionManager.cs index 27e492e..cc7f2ad 100644 --- a/JotunnModStub/BossProgressionManager.cs +++ b/JotunnModStub/BossProgressionManager.cs @@ -39,6 +39,26 @@ namespace RacesOfValheim { "FaderDrop", 8 } // Fader - Fader relic }; + /// + /// The boss's name as the game's own localization token, for text shown to players: + /// Valheim translates it wherever it is localized, so "The Elder" arrives in every language. + /// GetBossNameForState stays English, for logs and anything not localized. + /// + public static string GetBossTokenForState(int state) + { + switch (state) + { + case 2: return "$enemy_eikthyr"; + case 3: return "$enemy_gdking"; + case 4: return "$enemy_bonemass"; + case 5: return "$enemy_dragon"; + case 6: return "$enemy_goblinking"; + case 7: return "$enemy_seekerqueen"; + case 8: return "$enemy_fader"; + default: return GetBossNameForState(state); + } + } + public static string GetBossNameForState(int state) { switch (state) diff --git a/JotunnModStub/Butler/BoneServant.cs b/JotunnModStub/Butler/BoneServant.cs index 8c7a0a3..6126d1d 100644 --- a/JotunnModStub/Butler/BoneServant.cs +++ b/JotunnModStub/Butler/BoneServant.cs @@ -94,7 +94,7 @@ namespace RacesOfValheim "Coal"); PieceDensityLimit.Register(SmithTableName, TableSpacing, 1, - "Another smith's table stands within forty paces. One smith to a yard."); + "rov_msg_build_limit_smithtable"); // Two races, and it is the wider of the two locks: the Skeleton raises the dead to work // for it, and Skadi's hold is a forge under ice. @@ -105,7 +105,7 @@ namespace RacesOfValheim if (player != null) { player.Message(MessageHud.MessageType.Center, - "The bones do not answer to your blood."); + ModText.Get("rov_msg_butler_bones_do_not_answer_blood")); } return false; }); @@ -118,7 +118,7 @@ namespace RacesOfValheim "CookedMeat"); PieceDensityLimit.Register(CookTableName, TableSpacing, 1, - "Another cook's table stands within forty paces. One cook to a yard."); + "rov_msg_build_limit_cooktable"); // Skadi alone. A hearth kept by something dead is hers, not the Skeleton's. PieceDensityLimit.RegisterGate(CookTableName, (player, position) => @@ -128,7 +128,7 @@ namespace RacesOfValheim if (player != null) { player.Message(MessageHud.MessageType.Center, - "Only Skadi's hearth is kept by the dead."); + ModText.Get("rov_msg_butler_only_skadi_s_hearth_kept")); } return false; }); diff --git a/JotunnModStub/Butler/ServantTableBehaviour.cs b/JotunnModStub/Butler/ServantTableBehaviour.cs index 6aab038..bac4a73 100644 --- a/JotunnModStub/Butler/ServantTableBehaviour.cs +++ b/JotunnModStub/Butler/ServantTableBehaviour.cs @@ -70,7 +70,7 @@ namespace RacesOfValheim if (Servant() != null) { - player.Message(MessageHud.MessageType.Center, "It is already at work."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_butler_already_at_work")); return false; } @@ -78,7 +78,7 @@ namespace RacesOfValheim if (wait > 0f) { player.Message(MessageHud.MessageType.Center, - $"The bones are not ready. {Mathf.CeilToInt(wait)}s."); + ModText.Get("rov_msg_butler_bones_are_not_ready_s", Mathf.CeilToInt(wait))); return false; } @@ -94,7 +94,7 @@ namespace RacesOfValheim if (prefab == null) { Jotunn.Logger.LogWarning($"[Butler] No '{m_servantPrefab}' in ZNetScene; nothing was raised."); - player.Message(MessageHud.MessageType.Center, "Nothing answers."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_butler_nothing_answers")); return false; } @@ -109,7 +109,7 @@ namespace RacesOfValheim if (ZNet.instance != null) m_nview.GetZDO().Set(KeyLastRaise, ZNet.instance.GetTime().Ticks); - player.Message(MessageHud.MessageType.Center, "The servant rises."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_butler_servant_rises")); return true; } diff --git a/JotunnModStub/Draugh/DraughFoodPatches.cs b/JotunnModStub/Draugh/DraughFoodPatches.cs index 847a615..f6d7fe7 100644 --- a/JotunnModStub/Draugh/DraughFoodPatches.cs +++ b/JotunnModStub/Draugh/DraughFoodPatches.cs @@ -42,7 +42,7 @@ namespace RacesOfValheim { if (!DraughRace.IsDraugh()) { - player.Message(MessageHud.MessageType.Center, "This rotting flesh is fatal to the living."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_this_rotting_flesh_fatal_living")); return false; // Block consumption } // If it IS a Draugh, let them consume it via native mechanics @@ -101,7 +101,7 @@ namespace RacesOfValheim bool isFood = item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0; if (isFood) { - player.Message(MessageHud.MessageType.Center, "Draugr consume only raw flesh, eyes, entrails or blood."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_draugr_consume_only_raw_flesh")); return false; // Block it } } diff --git a/JotunnModStub/Draugh/DraughProgressionPatches.cs b/JotunnModStub/Draugh/DraughProgressionPatches.cs index eaa8357..26743f5 100644 --- a/JotunnModStub/Draugh/DraughProgressionPatches.cs +++ b/JotunnModStub/Draugh/DraughProgressionPatches.cs @@ -153,7 +153,7 @@ namespace RacesOfValheim } } - Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "The northern wind blows"); + Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, ModText.Get("rov_msg_draugh_northern_wind_blows")); } } } @@ -312,7 +312,7 @@ namespace RacesOfValheim if (prefab != null) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Swarm of Terror!"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_swarm_terror")); for (int i = 0; i < DraughConfig.SwarmSpawnCount.Value; i++) { @@ -356,7 +356,7 @@ namespace RacesOfValheim float healAmount = Player.m_localPlayer.GetMaxHealth() * DraughConfig.StealBreathHealPercent.Value; Player.m_localPlayer.Heal(healAmount); - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Steal Their Breath! Death is denied."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_steal_their_breath_death_denied")); // Restore visuals immediately if (Player.m_localPlayer.GetComponent() != null) diff --git a/JotunnModStub/Draugh/DraughRace.cs b/JotunnModStub/Draugh/DraughRace.cs index 9362f5c..f654eac 100644 --- a/JotunnModStub/Draugh/DraughRace.cs +++ b/JotunnModStub/Draugh/DraughRace.cs @@ -133,7 +133,7 @@ namespace RacesOfValheim public System.Collections.IEnumerator UndyingWillRoutine(Player p) { - p.Message(MessageHud.MessageType.Center, "Zombie Ritual Activated! Your borrowed time is fading..."); + p.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_zombie_ritual_activated_borrowed_time")); // Trigger a re-evaluation of visuals to apply the ghost effect if (p.GetComponent() != null) diff --git a/JotunnModStub/Draugh/DraughSpawner.cs b/JotunnModStub/Draugh/DraughSpawner.cs index 9e00fd5..a2604b2 100644 --- a/JotunnModStub/Draugh/DraughSpawner.cs +++ b/JotunnModStub/Draugh/DraughSpawner.cs @@ -129,7 +129,7 @@ namespace RacesOfValheim PieceDensityLimit.Register(PieceName, PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange, - "The ground here already carries {0} of these. Find another country."); + "rov_msg_build_limit_draugh_bodypile"); } // ---------------------------------------------------------------- items @@ -201,7 +201,7 @@ namespace RacesOfValheim thrall.m_maxFollowers = maxFollowers; thrall.m_witherSeconds = OrphanWitherSeconds; thrall.m_homeCheckRange = HomeCheckRange; - thrall.m_refusalMessage = "The dead do not take orders from the living."; + thrall.m_refusalMessage = "$rov_msg_thrall_refusal_draugh"; PrefabManager.Instance.AddPrefab(prefab); } diff --git a/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs b/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs index faf40ee..39b1dd7 100644 --- a/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs +++ b/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs @@ -82,7 +82,7 @@ namespace RacesOfValheim if (item == null) item = FindAnyInput(inventory); if (item == null) { - user.Message(MessageHud.MessageType.Center, "It wants flesh, or the head of one of its own."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_wants_flesh_or_head_one")); return false; } @@ -93,7 +93,7 @@ namespace RacesOfValheim if (prefabName == DraughSpawner.TrophyDraugrElite && !IsUpgraded()) { - user.Message(MessageHud.MessageType.Center, "This pile keeps no officers yet."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_this_pile_keeps_no_officers")); return false; } @@ -162,19 +162,19 @@ namespace RacesOfValheim { if (IsUpgraded()) { - user.Message(MessageHud.MessageType.Center, "It has already had one."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_has_already_had_one")); return false; } if (BossProgressionManager.GetCurrentProgressionState() < DraughSpawner.UpgradeProgressionState) { - user.Message(MessageHud.MessageType.Center, "The bone will not wake. Something older has to fall first."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_bone_will_not_wake_something")); return false; } inventory.RemoveItem(item, 1); m_nview.InvokeRPC("RoV_DraughUpgrade"); - user.Message(MessageHud.MessageType.Center, "The pile stirs. It will keep officers now."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_pile_stirs_will_keep_officers")); return true; } @@ -294,7 +294,7 @@ namespace RacesOfValheim if (bound.Count > 0 && Player.m_localPlayer != null) { Player.m_localPlayer.Message(MessageHud.MessageType.Center, - $"The pile is broken. {bound.Count} will not outlast it by more than a minute."); + ModText.Get("rov_msg_draugh_pile_broken_will_not_outlast", bound.Count)); } SetFlesh(0f); diff --git a/JotunnModStub/Dvergar/DvergarAbilities.cs b/JotunnModStub/Dvergar/DvergarAbilities.cs index 11cc807..63daff3 100644 --- a/JotunnModStub/Dvergar/DvergarAbilities.cs +++ b/JotunnModStub/Dvergar/DvergarAbilities.cs @@ -45,7 +45,7 @@ namespace RacesOfValheim if (player.GetEitr() < DvergarConfig.RunicPingEitrCost) { - player.Message(MessageHud.MessageType.Center, "Not enough eitr"); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_enough_eitr")); return; } @@ -55,7 +55,7 @@ namespace RacesOfValheim int marked = MarkSurroundings(player); player.Message(MessageHud.MessageType.Center, - marked > 0 ? $"Runic Ping: {marked} echoes answer" : "Runic Ping: the stone is silent"); + (marked > 0 ? ModText.Get("rov_msg_dvergar_runic_ping_echoes_answer", marked) : ModText.Get("rov_msg_dvergar_runic_ping_stone_silent"))); } /// @@ -173,7 +173,7 @@ namespace RacesOfValheim if (player.GetEitr() < DvergarConfig.RunicOverchargeEitrCost) { - player.Message(MessageHud.MessageType.Center, "Not enough eitr"); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_enough_eitr")); return; } @@ -186,7 +186,7 @@ namespace RacesOfValheim // The charge is held, not permanent: it lapses if no favoured blow lands in time. if (se != null) se.m_ttl = DvergarConfig.RunicOverchargeWindow; - player.Message(MessageHud.MessageType.Center, "Runic Overcharge: your next blow is loaded"); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_runic_overcharge_next_blow_loaded")); } /// diff --git a/JotunnModStub/Dvergar/DvergarBanco.cs b/JotunnModStub/Dvergar/DvergarBanco.cs index b18e968..98559ee 100644 --- a/JotunnModStub/Dvergar/DvergarBanco.cs +++ b/JotunnModStub/Dvergar/DvergarBanco.cs @@ -195,7 +195,7 @@ namespace RacesOfValheim PieceDensityLimit.Register(PieceName, PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxBanksInRange, - "There is already {0} contract bank within a day's walk. One ledger per valley."); + "rov_msg_build_limit_dvergar_contractbank"); } // ---------------------------------------------------------------- the hired @@ -233,7 +233,7 @@ namespace RacesOfValheim thrall.m_maxFollowers = MaxFollowers; thrall.m_witherSeconds = WitherSeconds; thrall.m_homeCheckRange = HomeCheckRange; - thrall.m_refusalMessage = "Your name is not on the contract."; + thrall.m_refusalMessage = "$rov_msg_thrall_refusal_dvergar"; // Ten seconds unhurt, then two percent a second - the sentry's regeneration, shared with // the Trol's troops and the Fenrir's pack. A dead mercenary still stays dead. @@ -412,7 +412,7 @@ namespace RacesOfValheim if (Utils.GetPrefabName(__0.gameObject) != DvergarBanco.PieceName) return true; if (DvergarRace.IsDvergar()) return true; - __instance.Message(MessageHud.MessageType.Center, "The contract is in runic. You do not sign it."); + __instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_contract_runic_do_not_sign")); return false; } } diff --git a/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs b/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs index a0646a7..cb381e0 100644 --- a/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs +++ b/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs @@ -66,7 +66,7 @@ namespace RacesOfValheim if (!DvergarRace.IsDvergar()) { - player.Message(MessageHud.MessageType.Center, "The ledger is not written for you."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_ledger_not_written")); // With an item in hand, false makes Humanoid.UseItem cover this message with its // generic "$msg_cantuseon"; true tells it the use was handled here. return item != null; @@ -93,19 +93,19 @@ namespace RacesOfValheim { if (IsUpgraded()) { - player.Message(MessageHud.MessageType.Center, "It has already had one."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_has_already_had_one")); return true; } if (BossProgressionManager.GetCurrentProgressionState() < DvergarBanco.UpgradeProgressionState) { - player.Message(MessageHud.MessageType.Center, "Not while she still sits under the mist."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_while_she_still_sits")); return true; } player.GetInventory().RemoveItem(item, 1); m_nview.InvokeRPC("RoV_DvergarUpgrade"); - player.Message(MessageHud.MessageType.Center, "The ledger is rewritten. Better names sign it now."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_ledger_rewritten_better_names_sign")); return true; } @@ -119,7 +119,7 @@ namespace RacesOfValheim Trader trader = GetComponent(); if (trader == null || StoreGui.instance == null) { - player.Message(MessageHud.MessageType.Center, "The ledger is shut."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_ledger_shut")); return false; } @@ -144,7 +144,7 @@ namespace RacesOfValheim if (CountGroups() >= DvergarBanco.MaxTroops) { - player.Message(MessageHud.MessageType.Center, "Five contracts is all the ledger holds."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_five_contracts_all_ledger_holds")); return; } @@ -163,7 +163,7 @@ namespace RacesOfValheim TakeCoins(inventory, price); m_nview.InvokeRPC("RoV_DvergarHire", troop.Id); - player.Message(MessageHud.MessageType.Center, $"{troop.Display} signs on."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_signs", troop.Display)); } private const string CoinsPrefab = "Coins"; diff --git a/JotunnModStub/Dvergar/DvergarBotte.cs b/JotunnModStub/Dvergar/DvergarBotte.cs index 05ee712..e0a7953 100644 --- a/JotunnModStub/Dvergar/DvergarBotte.cs +++ b/JotunnModStub/Dvergar/DvergarBotte.cs @@ -203,7 +203,7 @@ namespace RacesOfValheim if (Utils.GetPrefabName(__0.gameObject) != DvergarBotte.PieceName) return true; if (DvergarRace.IsDvergar()) return true; - __instance.Message(MessageHud.MessageType.Center, "You do not know what goes in it."); + __instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_do_not_know_what_goes")); return false; } } diff --git a/JotunnModStub/Dvergar/DvergarBotteBehaviour.cs b/JotunnModStub/Dvergar/DvergarBotteBehaviour.cs index 84b810c..32d4a82 100644 --- a/JotunnModStub/Dvergar/DvergarBotteBehaviour.cs +++ b/JotunnModStub/Dvergar/DvergarBotteBehaviour.cs @@ -77,7 +77,7 @@ namespace RacesOfValheim ItemDrop.ItemData found = FindAnyBrew(inventory); if (found == null) { - player.Message(MessageHud.MessageType.Center, "It is empty, and so are you."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_empty_so_are")); return false; } @@ -106,7 +106,7 @@ namespace RacesOfValheim if (!string.IsNullOrEmpty(current) && current != prefabName && GetDoses() > 0) { player.Message(MessageHud.MessageType.Center, - $"There is still {DvergarBotte.BrewDisplayName(current)} in it."); + ModText.Get("rov_msg_dvergar_there_still", DvergarBotte.BrewDisplayName(current))); return false; } @@ -151,14 +151,14 @@ namespace RacesOfValheim StatusEffect effect = DvergarBotte.BrewEffect(brew); if (effect == null) { - player.Message(MessageHud.MessageType.Center, "Whatever is in it does nothing to anyone."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_whatever_does_nothing_anyone")); return false; } List drinkers = InRange(); if (drinkers.Count == 0) { - player.Message(MessageHud.MessageType.Center, "Nobody is at the barrel."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_nobody_at_barrel")); return false; } @@ -173,16 +173,14 @@ namespace RacesOfValheim if (served == 0) { - player.Message(MessageHud.MessageType.Center, "Not a drop went down."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_drop_went_down")); return false; } m_nview.InvokeRPC("RoV_DvergarBotteSpend", served); string what = DvergarBotte.BrewDisplayName(brew); - player.Message(MessageHud.MessageType.Center, served < drinkers.Count - ? $"{served} drink {what}. The barrel runs dry." - : $"{served} drink {what}."); + player.Message(MessageHud.MessageType.Center, (served < drinkers.Count ? ModText.Get("rov_msg_dvergar_drink_barrel_runs_dry", served, what) : ModText.Get("rov_msg_dvergar_drink", served, what))); return true; } diff --git a/JotunnModStub/Dvergar/DvergarPatches.cs b/JotunnModStub/Dvergar/DvergarPatches.cs index 6de3f31..de75252 100644 --- a/JotunnModStub/Dvergar/DvergarPatches.cs +++ b/JotunnModStub/Dvergar/DvergarPatches.cs @@ -110,7 +110,7 @@ namespace RacesOfValheim DvergarAbilities.ConsumeOvercharge(Player.m_localPlayer)) { ScalePhysical(hit, DvergarConfig.RunicOverchargeMultiplier); - Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "Runic Overcharge discharges"); + Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, ModText.Get("rov_msg_dvergar_runic_overcharge_discharges")); } } diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 9b13a35..9f71886 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -920,7 +920,7 @@ namespace RacesOfValheim lastNoEitrMessage = Time.time; Player.m_localPlayer.Message(MessageHud.MessageType.Center, - "Only breath comes out. The fire wants eitr."); + ModText.Get("rov_msg_fenrir_only_breath_comes_out_fire")); } private void StartFire() diff --git a/JotunnModStub/Fenrir/FenrirMangiatoia.cs b/JotunnModStub/Fenrir/FenrirMangiatoia.cs index b098f0a..8280607 100644 --- a/JotunnModStub/Fenrir/FenrirMangiatoia.cs +++ b/JotunnModStub/Fenrir/FenrirMangiatoia.cs @@ -155,7 +155,7 @@ namespace RacesOfValheim PieceDensityLimit.Register(PieceName, PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxTroughsInRange, - "There is already {0} of these within a day's walk. A pack needs room."); + "rov_msg_build_limit_fenrir_packtrough"); } // ---------------------------------------------------------------- items diff --git a/JotunnModStub/Fenrir/FenrirMangiatoiaBehaviour.cs b/JotunnModStub/Fenrir/FenrirMangiatoiaBehaviour.cs index a7e2bfb..8a54e0f 100644 --- a/JotunnModStub/Fenrir/FenrirMangiatoiaBehaviour.cs +++ b/JotunnModStub/Fenrir/FenrirMangiatoiaBehaviour.cs @@ -289,7 +289,7 @@ namespace RacesOfValheim if (item == null) item = FindAnyInput(inventory); if (item == null) { - user.Message(MessageHud.MessageType.Center, "It wants meat. Any meat."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_wants_meat_any_meat")); return false; } @@ -342,19 +342,19 @@ namespace RacesOfValheim { if (IsUpgraded()) { - user.Message(MessageHud.MessageType.Center, "It has already had one."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_has_already_had_one")); return false; } if (BossProgressionManager.GetCurrentProgressionState() < FenrirMangiatoia.UpgradeProgressionState) { - user.Message(MessageHud.MessageType.Center, "The blood will not take. Something in the plains has to fall first."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_blood_will_not_take_something")); return false; } if (inventory.CountItems(YagluthDropName()) < 1) { - user.Message(MessageHud.MessageType.Center, "It wants what Yagluth left behind."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_wants_what_yagluth_left_behind")); return false; } @@ -362,7 +362,7 @@ namespace RacesOfValheim inventory.RemoveItem(item, 1); m_nview.InvokeRPC("RoV_FenrirUpgrade"); - user.Message(MessageHud.MessageType.Center, "The trough takes it. The line runs deeper now."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_trough_takes_line_runs_deeper")); return true; } @@ -404,7 +404,7 @@ namespace RacesOfValheim if (bound.Count > 0 && Player.m_localPlayer != null) { Player.m_localPlayer.Message(MessageHud.MessageType.Center, - $"The trough is broken. {bound.Count} will not outlast it by long."); + ModText.Get("rov_msg_fenrir_trough_broken_will_not_outlast", bound.Count)); } SetFeed(0f); diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index 22c1ee6..f6ff044 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -176,7 +176,7 @@ namespace RacesOfValheim { // forms allowed by day would otherwise be locked out right after every sunrise. if (rules.NeedsNight && sunSicknessTimer > 0f) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The beast is tired"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_beast_tired")); return; } @@ -188,7 +188,7 @@ namespace RacesOfValheim { if (rules.NeedsNight && !EnvMan.IsNight()) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The beast rests. You can only transform at night."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_beast_rests_can_only_transform")); return; } @@ -203,8 +203,9 @@ namespace RacesOfValheim { if (remaining < 0) remaining = 0; int rMin = Mathf.FloorToInt(remaining / 60f); int rSec = Mathf.FloorToInt(remaining % 60f); - string formName = rules.Form == FenrirProgression.FormType.Cultist ? "Cultist" : "Fenrir"; - Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"{formName} form is on cooldown ({rMin}:{rSec:00})."); + // A token, which the message's own localization pass translates along with the rest. + string formName = rules.Form == FenrirProgression.FormType.Cultist ? "$rov_msg_fenrir_formname_cultist" : "$rov_msg_fenrir_formname_fenrir"; + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_form_cooldown", formName, rMin, (rSec).ToString("00"))); return; } } @@ -410,7 +411,7 @@ namespace RacesOfValheim { Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode()); if (se != null) se.m_ttl = ttl; - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are an Ulv!"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_ulv")); } else if (prefabName == "Wolf") { @@ -418,7 +419,7 @@ namespace RacesOfValheim { Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode()); if (se != null) se.m_ttl = ttl; - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Wolf!"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_wolf")); } else if (prefabName == "Fenring_Cultist") { @@ -426,7 +427,7 @@ namespace RacesOfValheim { Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_CultistForm".GetStableHashCode(), true); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode()); if (se != null) se.m_ttl = ttl; - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Cultist!"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_cultist")); } else { @@ -434,7 +435,7 @@ namespace RacesOfValheim { Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirForm".GetStableHashCode(), true); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode()); if (se != null) se.m_ttl = ttl; - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Fenring!"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_fenring")); } isTransformed = true; @@ -480,7 +481,7 @@ namespace RacesOfValheim { Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode()); isTransformed = false; - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You returned to human form."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_returned_human_form")); if (activeRules != null && activeRules.CooldownMinutes > 0) { diff --git a/JotunnModStub/Fenrir/FenrirStatusEffects.cs b/JotunnModStub/Fenrir/FenrirStatusEffects.cs index b519103..43de139 100644 --- a/JotunnModStub/Fenrir/FenrirStatusEffects.cs +++ b/JotunnModStub/Fenrir/FenrirStatusEffects.cs @@ -17,7 +17,7 @@ namespace RacesOfValheim base.Stop(); if (Player.m_localPlayer != null) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"{m_name} is Ready!"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_ready", m_name)); } } } diff --git a/JotunnModStub/ModText.cs b/JotunnModStub/ModText.cs index 4e43258..b5bb3e9 100644 --- a/JotunnModStub/ModText.cs +++ b/JotunnModStub/ModText.cs @@ -21,7 +21,13 @@ namespace RacesOfValheim { if (Localization.instance == null) return "[" + key + "]"; - string[] words = args.Select(a => a?.ToString() ?? "").ToArray(); + // Each argument is localized on its own before it goes in. An argument is often a token + // itself - a creature's m_name, a boss - and left for a later pass it would run into + // whatever follows the $1: "$enemy_eikthyr's power" reads as the token + // "enemy_eikthyr's", because an apostrophe does not end a token. + string[] words = args + .Select(a => Localization.instance.Localize(a?.ToString() ?? "")) + .ToArray(); return Localization.instance.Localize("$" + key, words); } diff --git a/JotunnModStub/PieceDensityLimit.cs b/JotunnModStub/PieceDensityLimit.cs index 1546e21..daf3047 100644 --- a/JotunnModStub/PieceDensityLimit.cs +++ b/JotunnModStub/PieceDensityLimit.cs @@ -62,6 +62,7 @@ namespace RacesOfValheim /// Caps a piece. Call once from the chain's Register(); calling twice just replaces the entry, /// so a Register() that runs more than once cannot stack limits. /// + /// A translation key, not text: its $1 is how many stand nearby, $2 the limit. public static void Register(string piecePrefabName, float radius, int max, string refusalMessage) { if (string.IsNullOrEmpty(piecePrefabName) || max < 1 || radius <= 0f) @@ -156,7 +157,7 @@ namespace RacesOfValheim if (player != null) { - player.Message(MessageHud.MessageType.Center, string.Format(limit.Message, nearby, limit.Max)); + player.Message(MessageHud.MessageType.Center, ModText.Get(limit.Message, nearby, limit.Max)); } return false; } diff --git a/JotunnModStub/RaceCaveBuilding.cs b/JotunnModStub/RaceCaveBuilding.cs index 4e026d7..e9ddb8f 100644 --- a/JotunnModStub/RaceCaveBuilding.cs +++ b/JotunnModStub/RaceCaveBuilding.cs @@ -155,7 +155,7 @@ namespace RacesOfValheim allowing = true; Jotunn.Logger.LogInfo($"[Races] In a troll cave: {flipped.Count} pieces temporarily allowed in dungeons."); - player.Message(MessageHud.MessageType.Center, "This cave will hold what you build in it."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_build_this_cave_will_hold_what")); } /// diff --git a/JotunnModStub/RaceClaws.cs b/JotunnModStub/RaceClaws.cs index 3fc2bbb..818ffc7 100644 --- a/JotunnModStub/RaceClaws.cs +++ b/JotunnModStub/RaceClaws.cs @@ -899,7 +899,7 @@ namespace RacesOfValheim if (owner == null) return true; if (Player.m_localPlayer == null || owner != RaceClawSet.For(Player.m_localPlayer)) return true; - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_claws_they_are_part_hands")); return false; } } diff --git a/JotunnModStub/RaceMenuWard.cs b/JotunnModStub/RaceMenuWard.cs index 5457560..94ef37a 100644 --- a/JotunnModStub/RaceMenuWard.cs +++ b/JotunnModStub/RaceMenuWard.cs @@ -201,20 +201,20 @@ namespace RacesOfValheim string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; if (prefabName == null || !BossProgressionManager.BossDropStates.TryGetValue(prefabName, out int state)) { - user.Message(MessageHud.MessageType.Center, "The ward has no use for that."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_ward_ward_has_no_use_that")); return true; } if (!BossProgressionManager.UsePersonalProgression) { - user.Message(MessageHud.MessageType.Center, "Switch to personal progression first."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_ward_switch_personal_progression_first")); return true; } if (BossProgressionManager.PersonalState >= state) { user.Message(MessageHud.MessageType.Center, - $"You already carry {BossProgressionManager.GetBossNameForState(state)}'s power."); + ModText.Get("rov_msg_ward_already_carry_s_power", BossProgressionManager.GetBossTokenForState(state))); return true; } @@ -223,7 +223,7 @@ namespace RacesOfValheim BossProgressionManager.PersonalState = state; user.Message(MessageHud.MessageType.Center, - $"{BossProgressionManager.GetBossNameForState(state)}'s power is yours."); + ModText.Get("rov_msg_ward_s_power_yours", BossProgressionManager.GetBossTokenForState(state))); RefreshRaceState(); return true; diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 7778632..f9d3462 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -199,16 +199,16 @@ namespace RacesOfValheim } int state = BossProgressionManager.GetCurrentProgressionState(); - string boss = BossProgressionManager.GetBossNameForState(state); + string boss = BossProgressionManager.GetBossTokenForState(state); if (clearedPersonal) - summary = $"Personal progression reset to {boss} ({state}/{BossProgressionManager.MaxState}). Claim your relics again."; + summary = ModText.Get("rov_msg_core_progression_reset", boss, state, BossProgressionManager.MaxState); else if (BossProgressionManager.UsePersonalProgression) - summary = $"Nothing to reset - you have claimed no relics yet ({state}/{BossProgressionManager.MaxState})."; + summary = ModText.Get("rov_msg_core_nothing_reset_personal", state, BossProgressionManager.MaxState); else - summary = $"Nothing to reset - you follow the world's progression: {boss} ({state}/{BossProgressionManager.MaxState})."; + summary = ModText.Get("rov_msg_core_nothing_reset_world", boss, state, BossProgressionManager.MaxState); - if (hadDebugOverride) summary += " Debug override cleared."; + if (hadDebugOverride) summary += " " + ModText.Get("rov_msg_core_debug_override_cleared"); Player player = Player.m_localPlayer; if (player != null) @@ -537,7 +537,7 @@ namespace RacesOfValheim Player.m_localPlayer.m_customData["Race"] = "Human"; ZNetView nview = Player.m_localPlayer.GetComponent(); if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Human"); - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose to remain Human."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_remain_human")); } CloseRaceSelectionMenu(); } @@ -552,7 +552,7 @@ namespace RacesOfValheim Player.m_localPlayer.m_customData["FenrirCurse_Active"] = "true"; Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirCurse".GetStableHashCode(), true); - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Fenrir."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_fenrir")); } CloseRaceSelectionMenu(); } @@ -565,7 +565,7 @@ namespace RacesOfValheim ZNetView nview = Player.m_localPlayer.GetComponent(); if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Skadi"); - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of Skadi."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_skadi")); // Force update skin colors VisEquipment visEq = Player.m_localPlayer.GetComponent(); @@ -594,7 +594,7 @@ namespace RacesOfValheim visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); } - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Skeleton."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_skeleton")); CloseRaceSelectionMenu(); } } @@ -624,7 +624,7 @@ namespace RacesOfValheim visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); } - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Aswid."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_aswid")); CloseRaceSelectionMenu(); } } @@ -652,7 +652,7 @@ namespace RacesOfValheim visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); } - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Furling."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_furling")); CloseRaceSelectionMenu(); } } @@ -694,7 +694,7 @@ namespace RacesOfValheim visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); } - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Trol."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_trol")); CloseRaceSelectionMenu(); } } @@ -740,7 +740,7 @@ namespace RacesOfValheim visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); } - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Draugh."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_draugh")); CloseRaceSelectionMenu(); } } @@ -777,7 +777,7 @@ namespace RacesOfValheim visEq.GetType().GetMethod("UpdateVisuals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); } - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Dvergar."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_dvergar")); CloseRaceSelectionMenu(); } } @@ -813,7 +813,7 @@ namespace RacesOfValheim visEq.GetType().GetMethod("UpdateVisuals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); } - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Sverm."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_sverm")); CloseRaceSelectionMenu(); } } @@ -868,7 +868,7 @@ namespace RacesOfValheim visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); } - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Trenta."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_trenta")); CloseRaceSelectionMenu(); } } @@ -1015,7 +1015,7 @@ namespace RacesOfValheim if (Player.m_localPlayer != null) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"World Progression State: {state}"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_world_progression_state", state)); } } } @@ -1038,7 +1038,7 @@ namespace RacesOfValheim Console.instance.Print($"[DEBUG] Progression state increased to: {BossProgressionManager.DebugState}"); if (Player.m_localPlayer != null) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Progression State: {BossProgressionManager.DebugState}"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_progression_state", BossProgressionManager.DebugState)); Traverse.Create(Player.m_localPlayer).Method("SetupEquipment").GetValue(); } } diff --git a/JotunnModStub/RaisedThrall.cs b/JotunnModStub/RaisedThrall.cs index f1ecd9c..c46aea5 100644 --- a/JotunnModStub/RaisedThrall.cs +++ b/JotunnModStub/RaisedThrall.cs @@ -53,7 +53,7 @@ namespace RacesOfValheim public float m_homeCheckRange = 20f; /// Shown in the refusal when a station is not this player's to command. - public string m_refusalMessage = "It does not answer to you."; + public string m_refusalMessage = "$rov_msg_thrall_refusal_default"; /// /// How many thralls of OTHER kinds, from the same station, come along when this one is @@ -298,7 +298,7 @@ namespace RacesOfValheim { m_monsterAI.SetFollowTarget(null); GoHome(); - if (announce) player.Message(MessageHud.MessageType.Center, $"{m_character.m_name} returns."); + if (announce) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_thrall_returns", m_character.m_name)); return true; } @@ -308,7 +308,7 @@ namespace RacesOfValheim { if (announce) { - player.Message(MessageHud.MessageType.Center, $"Only {m_maxFollowers} may walk with you."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_thrall_only_may_walk_with", m_maxFollowers)); } return false; } @@ -323,7 +323,7 @@ namespace RacesOfValheim if (m_ai != null) m_ai.ResetPatrolPoint(); m_monsterAI.SetFollowTarget(player.gameObject); - if (announce) player.Message(MessageHud.MessageType.Center, $"{m_character.m_name} follows."); + if (announce) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_thrall_follows", m_character.m_name)); return true; } @@ -355,9 +355,7 @@ namespace RacesOfValheim if (other.SetFollowing(player, follow, announce: false)) taken++; } - player.Message(MessageHud.MessageType.Center, follow - ? $"{m_character.m_name} rises with {taken}." - : $"{m_character.m_name} stands down with {taken}."); + player.Message(MessageHud.MessageType.Center, (follow ? ModText.Get("rov_msg_thrall_rises_with", m_character.m_name, taken) : ModText.Get("rov_msg_thrall_stands_down_with", m_character.m_name, taken))); } private static int CountFollowers(Player player, string kind) @@ -445,12 +443,12 @@ namespace RacesOfValheim if (came > 0) { - player.Message(MessageHud.MessageType.Center, $"{came} answer the call."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_thrall_answer_call", came)); } else if (refused > 0) { // The only way SetFollowing refuses a thrall that may be commanded is the cap. - player.Message(MessageHud.MessageType.Center, "No more may walk with you."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_thrall_no_more_may_walk_with")); } } diff --git a/JotunnModStub/Skadi/DrakeFormBehavior.cs b/JotunnModStub/Skadi/DrakeFormBehavior.cs index ffd3b74..53b9049 100644 --- a/JotunnModStub/Skadi/DrakeFormBehavior.cs +++ b/JotunnModStub/Skadi/DrakeFormBehavior.cs @@ -257,7 +257,7 @@ namespace RacesOfValheim float cost = Mathf.Min(STAMINA_PER_PROJECTILE * projCount, MAX_VOLLEY_STAMINA); if (!Player.m_localPlayer.HaveStamina(cost)) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Not enough stamina"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_not_enough_stamina")); return false; } Player.m_localPlayer.UseStamina(cost); diff --git a/JotunnModStub/Skadi/SkadiGolem.cs b/JotunnModStub/Skadi/SkadiGolem.cs index 9a1035e..99fca6a 100644 --- a/JotunnModStub/Skadi/SkadiGolem.cs +++ b/JotunnModStub/Skadi/SkadiGolem.cs @@ -306,21 +306,21 @@ namespace RacesOfValheim if (!SkadiRace.IsLocalSkadi()) { - player.Message(MessageHud.MessageType.Center, "The stone does not answer to you."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_stone_does_not_answer")); return false; } if (BossProgressionManager.GetCurrentProgressionState() < ModerProgressionState) { player.Message(MessageHud.MessageType.Center, - "The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen."); + ModText.Get("rov_msg_skadi_tear_cold_nothing_wakes_stone")); return false; } CraftingStation station = FindStonecutter(position); if (station == null) { - player.Message(MessageHud.MessageType.Center, "It needs a stonecutter to be cut at."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_needs_stonecutter_cut_at")); return false; } @@ -328,7 +328,7 @@ namespace RacesOfValheim if (bound >= MaxPerStation) { player.Message(MessageHud.MessageType.Center, - $"That stonecutter already holds {bound}. It will not hold more."); + ModText.Get("rov_msg_skadi_that_stonecutter_already_holds_will", bound)); return false; } @@ -336,7 +336,7 @@ namespace RacesOfValheim if (nearby >= MaxInArea) { player.Message(MessageHud.MessageType.Center, - $"There are already {nearby} of these within a day's walk. The stone is spent."); + ModText.Get("rov_msg_skadi_there_are_already_these_within", nearby)); return false; } diff --git a/JotunnModStub/Skadi/SkadiGolemBehaviour.cs b/JotunnModStub/Skadi/SkadiGolemBehaviour.cs index b21621a..36554c4 100644 --- a/JotunnModStub/Skadi/SkadiGolemBehaviour.cs +++ b/JotunnModStub/Skadi/SkadiGolemBehaviour.cs @@ -181,7 +181,7 @@ namespace RacesOfValheim Vector3.Distance(Player.m_localPlayer.transform.position, transform.position) < 30f) { Player.m_localPlayer.Message(MessageHud.MessageType.Center, - "The stonecutter is gone. What it cut will not outlast it by long."); + ModText.Get("rov_msg_skadi_stonecutter_gone_what_cut_will")); } } diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index fbdffb6..16744af 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -246,7 +246,7 @@ namespace RacesOfValheim if (isTransformed && formExpireTime > 0f && Time.time >= formExpireTime) { formExpireTime = 0f; - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Your dragon form fades."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_dragon_form_fades")); StartCoroutine(RevertToHumanRoutine()); return; } @@ -265,7 +265,7 @@ namespace RacesOfValheim DumpPrefabDebugInfo("Dragon"); DumpPrefabDebugInfo("Hatchling"); DumpPrefabDebugInfo("Fader"); - if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader debug info to console!"); + if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_dumped_dragon_drake_fader_debug")); } } @@ -438,7 +438,7 @@ namespace RacesOfValheim // the Mistlands onward, so the old HaveEitr gate left it unusable for five tiers. if (!Player.m_localPlayer.HaveStamina(SPELL_STAMINA_COST)) { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Not enough stamina"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_not_enough_stamina")); return; } @@ -710,7 +710,7 @@ namespace RacesOfValheim if (remaining < 0) remaining = 0; int rMin = Mathf.FloorToInt(remaining / 60f); int rSec = Mathf.FloorToInt(remaining % 60f); - Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Dragon Form is on cooldown ({rMin}:{rSec:00})."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_dragon_form_cooldown", rMin, (rSec).ToString("00"))); return; } } @@ -891,9 +891,9 @@ namespace RacesOfValheim DrakeFormBehavior behavior = currentTransformation.AddComponent(); behavior.Initialize(rules); - if (prefabName == "Hatchling") Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Drake!"); - else if (prefabName == "Dragon") Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are Moder!"); - else if (prefabName == "Fader") Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are Fader!"); + if (prefabName == "Hatchling") Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_are_drake")); + else if (prefabName == "Dragon") Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_are_moder")); + else if (prefabName == "Fader") Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_are_fader")); isTransformed = true; StartFormTimer(rules); @@ -943,7 +943,7 @@ namespace RacesOfValheim isTransformed = false; formExpireTime = 0f; Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_SkadiForm".GetStableHashCode(), true); - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You returned to human form."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_returned_human_form")); if (activeRules != null && activeRules.CooldownMinutes > 0) { diff --git a/JotunnModStub/Skeleton/SkeletonBonePile.cs b/JotunnModStub/Skeleton/SkeletonBonePile.cs index 35fcdd9..9c6d6c1 100644 --- a/JotunnModStub/Skeleton/SkeletonBonePile.cs +++ b/JotunnModStub/Skeleton/SkeletonBonePile.cs @@ -136,7 +136,7 @@ namespace RacesOfValheim PieceDensityLimit.Register(PieceName, PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange, - "There are already {0} of these listening nearby. Take it further out."); + "rov_msg_build_limit_skeleton_bonepile"); } // ---------------------------------------------------------------- items @@ -282,7 +282,7 @@ namespace RacesOfValheim thrall.m_maxFollowers = MaxFollowers; thrall.m_witherSeconds = OrphanWitherSeconds; thrall.m_homeCheckRange = HomeCheckRange; - thrall.m_refusalMessage = "These bones answer only to their own kind."; + thrall.m_refusalMessage = "$rov_msg_thrall_refusal_skeleton"; thrall.m_escortCount = escortCount; PrefabManager.Instance.AddPrefab(prefab); diff --git a/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs b/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs index 002e2a4..f65e631 100644 --- a/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs +++ b/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs @@ -108,7 +108,7 @@ namespace RacesOfValheim { if (!IsUpgraded()) { - player.Message(MessageHud.MessageType.Center, "This pile cannot hold the rotten yet."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_this_pile_cannot_hold_rotten")); return false; } room = RancidCap() - GetSlots(SkeletonBonePile.KindRancid); @@ -149,7 +149,7 @@ namespace RacesOfValheim List bound = RaisedThrall.BoundTo(transform.position); if (bound.Count == 0) { - player.Message(MessageHud.MessageType.Center, "Nothing is standing yet. It wants bone."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_nothing_standing_yet_wants_bone")); return false; } @@ -169,13 +169,11 @@ namespace RacesOfValheim if (moved == 0) { // Every one of them refused, which for these means the player is not a Skeleton. - player.Message(MessageHud.MessageType.Center, "These bones answer only to their own kind."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_these_bones_answer_only_their")); return false; } - player.Message(MessageHud.MessageType.Center, anyFollowing - ? $"{moved} return to the pile." - : $"{moved} rise and follow."); + player.Message(MessageHud.MessageType.Center, (anyFollowing ? ModText.Get("rov_msg_skeleton_return_pile", moved) : ModText.Get("rov_msg_skeleton_rise_follow", moved))); return true; } @@ -183,19 +181,19 @@ namespace RacesOfValheim { if (IsUpgraded()) { - player.Message(MessageHud.MessageType.Center, "It has already had one."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_has_already_had_one")); return false; } if (BossProgressionManager.GetCurrentProgressionState() < SkeletonBonePile.UpgradeProgressionState) { - player.Message(MessageHud.MessageType.Center, "The skull will not wake. Something older has to fall first."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_skull_will_not_wake_something")); return false; } inventory.RemoveItem(item, 1); m_nview.InvokeRPC("RoV_SkelUpgrade"); - player.Message(MessageHud.MessageType.Center, "The pile deepens. The rotten will stand here too."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_pile_deepens_rotten_will_stand")); return true; } @@ -332,7 +330,7 @@ namespace RacesOfValheim if (bound.Count > 0 && Player.m_localPlayer != null) { Player.m_localPlayer.Message(MessageHud.MessageType.Center, - $"The pile is broken. {bound.Count} fall where they stand."); + ModText.Get("rov_msg_skeleton_pile_broken_fall_where_they", bound.Count)); } } diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index 10fdf7d..6ffb291 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -80,7 +80,7 @@ namespace RacesOfValheim { if (SkeletonRace.IsSkeleton() && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0)) { - __instance.Message(MessageHud.MessageType.Center, "Skeletons do not need to eat."); + __instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_skeletons_do_not_need_eat")); __result = false; return false; } @@ -88,7 +88,7 @@ namespace RacesOfValheim // survive this blanket refusal - everything else mortal still bounces. else if (AswidRace.IsAswid() && !AswidRace.BypassAswidFoodCheck && !AswidBloodRefinery.IsAswidMeal(item) && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0)) { - __instance.Message(MessageHud.MessageType.Center, "Mortal food disgusts you."); + __instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_mortal_food_disgusts")); __result = false; return false; } @@ -630,7 +630,7 @@ namespace RacesOfValheim UnityEngine.Object.Instantiate(vfx, Player.m_localPlayer.transform.position, Quaternion.identity); } - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You have been resurrected by dark magic!"); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_have_been_resurrected_by_dark")); return false; // Skip applying this lethal damage } } diff --git a/JotunnModStub/Sverm/SvermBlisterTick.cs b/JotunnModStub/Sverm/SvermBlisterTick.cs index 507b97f..b0fd8ad 100644 --- a/JotunnModStub/Sverm/SvermBlisterTick.cs +++ b/JotunnModStub/Sverm/SvermBlisterTick.cs @@ -79,7 +79,7 @@ namespace RacesOfValheim thrall.m_maxFollowers = -1; thrall.m_witherSeconds = SvermConfig.TroopWitherSeconds; thrall.m_homeCheckRange = SvermConfig.TroopHomeCheckRange; - thrall.m_refusalMessage = "It does not smell your colony on you."; + thrall.m_refusalMessage = "$rov_msg_thrall_refusal_sverm"; // No SkeletonSentryBehaviour. A tick that healed itself would be a tick that never gets // round to exploding, which is its entire job. diff --git a/JotunnModStub/Sverm/SvermBrood.cs b/JotunnModStub/Sverm/SvermBrood.cs index f67c92d..be162e4 100644 --- a/JotunnModStub/Sverm/SvermBrood.cs +++ b/JotunnModStub/Sverm/SvermBrood.cs @@ -118,7 +118,7 @@ namespace RacesOfValheim thrall.m_maxFollowers = -1; // the cap is the colony's, counted at the nest, not per player thrall.m_witherSeconds = SvermConfig.TroopWitherSeconds; thrall.m_homeCheckRange = SvermConfig.TroopHomeCheckRange; - thrall.m_refusalMessage = "It does not smell your colony on you."; + thrall.m_refusalMessage = "$rov_msg_thrall_refusal_sverm"; // Section 11.2, reused whole: ten seconds untouched, then two percent a second. Healing // and not respawning - a dead troop is dead, and the egg it cost is already back. diff --git a/JotunnModStub/Sverm/SvermClawSlot.cs b/JotunnModStub/Sverm/SvermClawSlot.cs index 34bf82e..3d9212b 100644 --- a/JotunnModStub/Sverm/SvermClawSlot.cs +++ b/JotunnModStub/Sverm/SvermClawSlot.cs @@ -300,7 +300,7 @@ namespace RacesOfValheim if (!SvermClawSlot.IsClaws(item)) return true; if (Player.m_localPlayer == null || !SvermVisuals.IsSvermPlayer(Player.m_localPlayer)) return true; - Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands."); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_they_are_part_hands")); return false; } } diff --git a/JotunnModStub/Sverm/SvermFood.cs b/JotunnModStub/Sverm/SvermFood.cs index dad338b..21402c9 100644 --- a/JotunnModStub/Sverm/SvermFood.cs +++ b/JotunnModStub/Sverm/SvermFood.cs @@ -235,7 +235,7 @@ namespace RacesOfValheim if (item.m_dropPrefab != null && item.m_dropPrefab.name.StartsWith("SvermMeal_") == false && IsAswidBlood(item)) { - player.Message(MessageHud.MessageType.Center, "Alchemical blood is not food."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_alchemical_blood_not_food")); return false; } diff --git a/JotunnModStub/Sverm/SvermHive.cs b/JotunnModStub/Sverm/SvermHive.cs index 3c2266b..468846b 100644 --- a/JotunnModStub/Sverm/SvermHive.cs +++ b/JotunnModStub/Sverm/SvermHive.cs @@ -178,13 +178,13 @@ namespace RacesOfValheim if (!SvermVisuals.IsSvermPlayer(player)) { - player.Message(MessageHud.MessageType.Center, "Only the Sverm can raise a hive."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_only_sverm_can_raise_hive")); return false; } if (BossProgressionManager.GetCurrentProgressionState() < SvermConfig.HiveUnlockState) { - player.Message(MessageHud.MessageType.Center, "The colony will not wake until the Elder falls."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_colony_will_not_wake_until")); return false; } @@ -198,7 +198,7 @@ namespace RacesOfValheim private static void RegisterNestDensity() { PieceDensityLimit.Register(PieceName, SvermConfigManagement.NestRadius, SvermConfigManagement.NestMax, - "There is already a hive holding this ground."); + "rov_msg_build_limit_sverm_hive"); } /// @@ -437,7 +437,7 @@ namespace RacesOfValheim if (!SvermVisuals.IsSvermPlayer(player)) { - player.Message(MessageHud.MessageType.Center, "The hive does not know you."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_hive_does_not_know")); return true; } diff --git a/JotunnModStub/Sverm/SvermHiveGoods.cs b/JotunnModStub/Sverm/SvermHiveGoods.cs index 7962d3c..7ba51e6 100644 --- a/JotunnModStub/Sverm/SvermHiveGoods.cs +++ b/JotunnModStub/Sverm/SvermHiveGoods.cs @@ -297,7 +297,7 @@ namespace RacesOfValheim // stage it was not paid for cannot be undone. if (!SvermBiomass.Spend(hive.transform, good.Price)) { - player?.Message(MessageHud.MessageType.Center, "Not enough biomass in the bank."); + player?.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_not_enough_biomass_bank")); return false; } diff --git a/JotunnModStub/Sverm/SvermHiveStore.cs b/JotunnModStub/Sverm/SvermHiveStore.cs index f63f642..fe7a064 100644 --- a/JotunnModStub/Sverm/SvermHiveStore.cs +++ b/JotunnModStub/Sverm/SvermHiveStore.cs @@ -128,7 +128,7 @@ namespace RacesOfValheim float room = SvermBiomass.Space(hive.transform); if (room <= 0f) { - player.Message(MessageHud.MessageType.Center, "The hive is full. Give it time to digest."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_hive_full_give_time_digest")); return true; } @@ -149,12 +149,12 @@ namespace RacesOfValheim inventory.RemoveItem(item, units); player.Message(MessageHud.MessageType.TopLeft, - $"{name} x{units} -> +{fed:0} biomass, digesting"); + ModText.Get("rov_msg_sverm_x_biomass_digesting", name, units, (fed).ToString("0"))); return true; } player.Message(MessageHud.MessageType.Center, - "Nothing here it will eat. Food, wood and resin - honey and royal jelly are medicine."); + ModText.Get("rov_msg_sverm_nothing_here_will_eat_food")); return true; } } @@ -202,7 +202,7 @@ namespace RacesOfValheim if (!SvermVisuals.IsSvermPlayer(player)) { - player.Message(MessageHud.MessageType.Center, "The hive does not know you."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_hive_does_not_know")); return true; } @@ -389,14 +389,14 @@ namespace RacesOfValheim if (!SvermVisuals.IsSvermPlayer(player)) { - player.Message(MessageHud.MessageType.Center, "Only the Sverm can raise a market."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_only_sverm_can_raise_market")); return false; } if (SvermHive.NearestNest(position, SvermConfigManagement.AuraRadius) == null) { player.Message(MessageHud.MessageType.Center, - $"A market has to stand within {SvermConfigManagement.AuraRadius:0} metres of a hive."); + ModText.Get("rov_msg_sverm_market_has_stand_within_metres", (SvermConfigManagement.AuraRadius).ToString("0"))); return false; } @@ -410,7 +410,7 @@ namespace RacesOfValheim private static void RegisterMarketDensity() { PieceDensityLimit.Register(PieceName, SvermConfigManagement.AuraRadius, 1, - "This hive already has a market."); + "rov_msg_build_limit_sverm_market"); } } @@ -428,7 +428,7 @@ namespace RacesOfValheim if (!SvermVisuals.IsSvermPlayer(player)) { - player.Message(MessageHud.MessageType.Center, "The hive does not know you."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_hive_does_not_know")); return true; } @@ -439,7 +439,7 @@ namespace RacesOfValheim if (nest == null) { player.Message(MessageHud.MessageType.Center, - $"No hive within {SvermConfigManagement.AuraRadius:0} metres. This counter is dead."); + ModText.Get("rov_msg_sverm_no_hive_within_metres_this", (SvermConfigManagement.AuraRadius).ToString("0"))); return true; } diff --git a/JotunnModStub/Sverm/SvermMedicine.cs b/JotunnModStub/Sverm/SvermMedicine.cs index 5fa46cd..3605304 100644 --- a/JotunnModStub/Sverm/SvermMedicine.cs +++ b/JotunnModStub/Sverm/SvermMedicine.cs @@ -54,7 +54,7 @@ namespace RacesOfValheim // Localized, because a creature's m_name is a token: printing it raw would put // "$enemy_seeker is not hurt" on the screen. string who = Localization.instance.Localize(patient.m_name); - player.Message(MessageHud.MessageType.Center, $"{who} is not hurt."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_not_hurt", who)); return true; } diff --git a/JotunnModStub/Sverm/SvermPatches.cs b/JotunnModStub/Sverm/SvermPatches.cs index 5d909f1..8d43fcc 100644 --- a/JotunnModStub/Sverm/SvermPatches.cs +++ b/JotunnModStub/Sverm/SvermPatches.cs @@ -76,7 +76,7 @@ namespace RacesOfValheim if (player == Player.m_localPlayer) { - player.Message(MessageHud.MessageType.Center, "Your carapace has no room for that."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_carapace_has_no_room_that")); } __result = false; diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index a8b9b88..91055b1 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -149,7 +149,7 @@ namespace RacesOfValheim if (IsActive && Time.time >= expiresAt) { - RunExit(player, spendCooldown: true, "The shell recedes."); + RunExit(player, spendCooldown: true, "$rov_msg_sverm_shell_recedes"); return; } @@ -165,13 +165,13 @@ namespace RacesOfValheim if (!SvermProgression.Current.RavagerForm) { - player.Message(MessageHud.MessageType.Center, "The strain has not taken yet."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_strain_has_not_taken_yet")); return; } if (Time.time < nextAllowedAt) { - player.Message(MessageHud.MessageType.Center, "The strain is spent."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_strain_spent")); return; } @@ -285,7 +285,7 @@ namespace RacesOfValheim PlayEffect(SvermConfig.RavagerMorphInEffects, player.transform.position); - player.Message(MessageHud.MessageType.Center, "The Ravager Strain takes hold."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_ravager_strain_takes_hold")); } private static void PlayEffect(string[] candidates, Vector3 where) diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json new file mode 100644 index 0000000..a8b69c1 --- /dev/null +++ b/JotunnModStub/Translations/English/messages.json @@ -0,0 +1,193 @@ +{ + "rov_msg_aswid_aura_disabled": "Vampiric Aura: DISABLED", + "rov_msg_aswid_aura_enabled": "Vampiric Aura: ENABLED", + "rov_msg_aswid_dominate_cooldown_m_s": "Dominate on cooldown ($1m $2s)", + "rov_msg_aswid_dominated": "$1 dominated!", + "rov_msg_aswid_eclipse_cooldown_remaining_s": "Eclipse is on cooldown. Remaining: $1s", + "rov_msg_aswid_eclipse_descends": "An Eclipse descends...", + "rov_msg_aswid_eclipse_has_ended": "The Eclipse has ended.", + "rov_msg_aswid_following": "$1 is following.", + "rov_msg_aswid_living_blood_curdles_living_throat": "Living blood curdles in a living throat.", + "rov_msg_aswid_morning_sun_drives_bat_back": "The morning sun drives the bat back into your body", + "rov_msg_aswid_morning_sun_has_vanquished_horrible": "The morning sun has vanquished the horrible night", + "rov_msg_aswid_no_bone_grind": "No bone to grind.", + "rov_msg_aswid_no_raw_flesh_render": "No raw flesh to render.", + "rov_msg_aswid_staying": "$1 is staying.", + "rov_msg_aswid_sun_burns_can_only_take": "The sun burns. You can only take bat form at night.", + "rov_msg_aswid_tamed": "Tamed!", + "rov_msg_aswid_vae_victis": "Vae Victis", + "rov_msg_aswid_what_horrible_night_have_curse": "what a horrible night to have a curse", + "rov_msg_build_limit_cooktable": "Another cook's table stands within forty paces. One cook to a yard.", + "rov_msg_build_limit_draugh_bodypile": "The ground here already carries $1 of these. Find another country.", + "rov_msg_build_limit_dvergar_contractbank": "There is already $1 contract bank within a day's walk. One ledger per valley.", + "rov_msg_build_limit_fenrir_packtrough": "There is already $1 of these within a day's walk. A pack needs room.", + "rov_msg_build_limit_skeleton_bonepile": "There are already $1 of these listening nearby. Take it further out.", + "rov_msg_build_limit_smithtable": "Another smith's table stands within forty paces. One smith to a yard.", + "rov_msg_build_limit_sverm_hive": "There is already a hive holding this ground.", + "rov_msg_build_limit_sverm_market": "This hive already has a market.", + "rov_msg_build_limit_trenta_grove": "This country already answers to $1 of these. Plant it somewhere else.", + "rov_msg_build_this_cave_will_hold_what": "This cave will hold what you build in it.", + "rov_msg_butler_already_at_work": "It is already at work.", + "rov_msg_butler_bones_are_not_ready_s": "The bones are not ready. $1s.", + "rov_msg_butler_bones_do_not_answer_blood": "The bones do not answer to your blood.", + "rov_msg_butler_nothing_answers": "Nothing answers.", + "rov_msg_butler_only_skadi_s_hearth_kept": "Only Skadi's hearth is kept by the dead.", + "rov_msg_butler_servant_rises": "The servant rises.", + "rov_msg_claws_they_are_part_hands": "They are part of your hands.", + "rov_msg_core_chose_path_aswid": "You chose the path of the Aswid.", + "rov_msg_core_chose_path_draugh": "You chose the path of the Draugh.", + "rov_msg_core_chose_path_dvergar": "You chose the path of the Dvergar.", + "rov_msg_core_chose_path_fenrir": "You chose the path of the Fenrir.", + "rov_msg_core_chose_path_furling": "You chose the path of the Furling.", + "rov_msg_core_chose_path_skadi": "You chose the path of Skadi.", + "rov_msg_core_chose_path_skeleton": "You chose the path of the Skeleton.", + "rov_msg_core_chose_path_sverm": "You chose the path of the Sverm.", + "rov_msg_core_chose_path_trenta": "You chose the path of the Trenta.", + "rov_msg_core_chose_path_trol": "You chose the path of the Trol.", + "rov_msg_core_chose_remain_human": "You chose to remain Human.", + "rov_msg_core_debug_override_cleared": "Debug override cleared.", + "rov_msg_core_nothing_reset_personal": "Nothing to reset - you have claimed no relics yet ($1/$2).", + "rov_msg_core_nothing_reset_world": "Nothing to reset - you follow the world's progression: $1 ($2/$3).", + "rov_msg_core_progression_reset": "Personal progression reset to $1 ($2/$3). Claim your relics again.", + "rov_msg_core_progression_state": "Progression State: $1", + "rov_msg_core_world_progression_state": "World Progression State: $1", + "rov_msg_draugh_bone_will_not_wake_something": "The bone will not wake. Something older has to fall first.", + "rov_msg_draugh_draugr_consume_only_raw_flesh": "Draugr consume only raw flesh, eyes, entrails or blood.", + "rov_msg_draugh_has_already_had_one": "It has already had one.", + "rov_msg_draugh_northern_wind_blows": "The northern wind blows", + "rov_msg_draugh_pile_broken_will_not_outlast": "The pile is broken. $1 will not outlast it by more than a minute.", + "rov_msg_draugh_pile_stirs_will_keep_officers": "The pile stirs. It will keep officers now.", + "rov_msg_draugh_steal_their_breath_death_denied": "Steal Their Breath! Death is denied.", + "rov_msg_draugh_swarm_terror": "Swarm of Terror!", + "rov_msg_draugh_this_pile_keeps_no_officers": "This pile keeps no officers yet.", + "rov_msg_draugh_this_rotting_flesh_fatal_living": "This rotting flesh is fatal to the living.", + "rov_msg_draugh_wants_flesh_or_head_one": "It wants flesh, or the head of one of its own.", + "rov_msg_draugh_zombie_ritual_activated_borrowed_time": "Zombie Ritual Activated! Your borrowed time is fading...", + "rov_msg_dvergar_contract_runic_do_not_sign": "The contract is in runic. You do not sign it.", + "rov_msg_dvergar_do_not_know_what_goes": "You do not know what goes in it.", + "rov_msg_dvergar_drink": "$1 drink $2.", + "rov_msg_dvergar_drink_barrel_runs_dry": "$1 drink $2. The barrel runs dry.", + "rov_msg_dvergar_empty_so_are": "It is empty, and so are you.", + "rov_msg_dvergar_five_contracts_all_ledger_holds": "Five contracts is all the ledger holds.", + "rov_msg_dvergar_has_already_had_one": "It has already had one.", + "rov_msg_dvergar_ledger_not_written": "The ledger is not written for you.", + "rov_msg_dvergar_ledger_rewritten_better_names_sign": "The ledger is rewritten. Better names sign it now.", + "rov_msg_dvergar_ledger_shut": "The ledger is shut.", + "rov_msg_dvergar_nobody_at_barrel": "Nobody is at the barrel.", + "rov_msg_dvergar_not_drop_went_down": "Not a drop went down.", + "rov_msg_dvergar_not_enough_eitr": "Not enough eitr", + "rov_msg_dvergar_not_while_she_still_sits": "Not while she still sits under the mist.", + "rov_msg_dvergar_runic_overcharge_discharges": "Runic Overcharge discharges", + "rov_msg_dvergar_runic_overcharge_next_blow_loaded": "Runic Overcharge: your next blow is loaded", + "rov_msg_dvergar_runic_ping_echoes_answer": "Runic Ping: $1 echoes answer", + "rov_msg_dvergar_runic_ping_stone_silent": "Runic Ping: the stone is silent", + "rov_msg_dvergar_signs": "$1 signs on.", + "rov_msg_dvergar_there_still": "There is still $1 in it.", + "rov_msg_dvergar_whatever_does_nothing_anyone": "Whatever is in it does nothing to anyone.", + "rov_msg_fenrir_are_cultist": "You are a Cultist!", + "rov_msg_fenrir_are_fenring": "You are a Fenring!", + "rov_msg_fenrir_are_ulv": "You are an Ulv!", + "rov_msg_fenrir_are_wolf": "You are a Wolf!", + "rov_msg_fenrir_beast_rests_can_only_transform": "The beast rests. You can only transform at night.", + "rov_msg_fenrir_beast_tired": "The beast is tired", + "rov_msg_fenrir_blood_will_not_take_something": "The blood will not take. Something in the plains has to fall first.", + "rov_msg_fenrir_form_cooldown": "$1 form is on cooldown ($2:$3).", + "rov_msg_fenrir_formname_cultist": "Cultist", + "rov_msg_fenrir_formname_fenrir": "Fenrir", + "rov_msg_fenrir_has_already_had_one": "It has already had one.", + "rov_msg_fenrir_only_breath_comes_out_fire": "Only breath comes out. The fire wants eitr.", + "rov_msg_fenrir_ready": "$1 is Ready!", + "rov_msg_fenrir_returned_human_form": "You returned to human form.", + "rov_msg_fenrir_trough_broken_will_not_outlast": "The trough is broken. $1 will not outlast it by long.", + "rov_msg_fenrir_trough_takes_line_runs_deeper": "The trough takes it. The line runs deeper now.", + "rov_msg_fenrir_wants_meat_any_meat": "It wants meat. Any meat.", + "rov_msg_fenrir_wants_what_yagluth_left_behind": "It wants what Yagluth left behind.", + "rov_msg_skadi_are_drake": "You are a Drake!", + "rov_msg_skadi_are_fader": "You are Fader!", + "rov_msg_skadi_are_moder": "You are Moder!", + "rov_msg_skadi_dragon_form_cooldown": "Dragon Form is on cooldown ($1:$2).", + "rov_msg_skadi_dragon_form_fades": "Your dragon form fades.", + "rov_msg_skadi_dumped_dragon_drake_fader_debug": "Dumped Dragon/Drake/Fader debug info to console!", + "rov_msg_skadi_needs_stonecutter_cut_at": "It needs a stonecutter to be cut at.", + "rov_msg_skadi_not_enough_stamina": "Not enough stamina", + "rov_msg_skadi_returned_human_form": "You returned to human form.", + "rov_msg_skadi_stone_does_not_answer": "The stone does not answer to you.", + "rov_msg_skadi_stonecutter_gone_what_cut_will": "The stonecutter is gone. What it cut will not outlast it by long.", + "rov_msg_skadi_tear_cold_nothing_wakes_stone": "The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.", + "rov_msg_skadi_that_stonecutter_already_holds_will": "That stonecutter already holds $1. It will not hold more.", + "rov_msg_skadi_there_are_already_these_within": "There are already $1 of these within a day's walk. The stone is spent.", + "rov_msg_skeleton_has_already_had_one": "It has already had one.", + "rov_msg_skeleton_have_been_resurrected_by_dark": "You have been resurrected by dark magic!", + "rov_msg_skeleton_mortal_food_disgusts": "Mortal food disgusts you.", + "rov_msg_skeleton_nothing_standing_yet_wants_bone": "Nothing is standing yet. It wants bone.", + "rov_msg_skeleton_pile_broken_fall_where_they": "The pile is broken. $1 fall where they stand.", + "rov_msg_skeleton_pile_deepens_rotten_will_stand": "The pile deepens. The rotten will stand here too.", + "rov_msg_skeleton_return_pile": "$1 return to the pile.", + "rov_msg_skeleton_rise_follow": "$1 rise and follow.", + "rov_msg_skeleton_skeletons_do_not_need_eat": "Skeletons do not need to eat.", + "rov_msg_skeleton_skull_will_not_wake_something": "The skull will not wake. Something older has to fall first.", + "rov_msg_skeleton_these_bones_answer_only_their": "These bones answer only to their own kind.", + "rov_msg_skeleton_this_pile_cannot_hold_rotten": "This pile cannot hold the rotten yet.", + "rov_msg_sverm_alchemical_blood_not_food": "Alchemical blood is not food.", + "rov_msg_sverm_carapace_has_no_room_that": "Your carapace has no room for that.", + "rov_msg_sverm_colony_will_not_wake_until": "The colony will not wake until the Elder falls.", + "rov_msg_sverm_hive_does_not_know": "The hive does not know you.", + "rov_msg_sverm_hive_full_give_time_digest": "The hive is full. Give it time to digest.", + "rov_msg_sverm_market_has_stand_within_metres": "A market has to stand within $1 metres of a hive.", + "rov_msg_sverm_no_hive_within_metres_this": "No hive within $1 metres. This counter is dead.", + "rov_msg_sverm_not_enough_biomass_bank": "Not enough biomass in the bank.", + "rov_msg_sverm_not_hurt": "$1 is not hurt.", + "rov_msg_sverm_nothing_here_will_eat_food": "Nothing here it will eat. Food, wood and resin - honey and royal jelly are medicine.", + "rov_msg_sverm_only_sverm_can_raise_hive": "Only the Sverm can raise a hive.", + "rov_msg_sverm_only_sverm_can_raise_market": "Only the Sverm can raise a market.", + "rov_msg_sverm_ravager_strain_takes_hold": "The Ravager Strain takes hold.", + "rov_msg_sverm_shell_recedes": "The shell recedes.", + "rov_msg_sverm_strain_has_not_taken_yet": "The strain has not taken yet.", + "rov_msg_sverm_strain_spent": "The strain is spent.", + "rov_msg_sverm_they_are_part_hands": "They are part of your hands.", + "rov_msg_sverm_x_biomass_digesting": "$1 x$2 -> +$3 biomass, digesting", + "rov_msg_thrall_answer_call": "$1 answer the call.", + "rov_msg_thrall_follows": "$1 follows.", + "rov_msg_thrall_no_more_may_walk_with": "No more may walk with you.", + "rov_msg_thrall_only_may_walk_with": "Only $1 may walk with you.", + "rov_msg_thrall_refusal_default": "It does not answer to you.", + "rov_msg_thrall_refusal_draugh": "The dead do not take orders from the living.", + "rov_msg_thrall_refusal_dvergar": "Your name is not on the contract.", + "rov_msg_thrall_refusal_skeleton": "These bones answer only to their own kind.", + "rov_msg_thrall_refusal_sverm": "It does not smell your colony on you.", + "rov_msg_thrall_refusal_trol": "They were not paid by you.", + "rov_msg_thrall_returns": "$1 returns.", + "rov_msg_thrall_rises_with": "$1 rises with $2.", + "rov_msg_thrall_stands_down_with": "$1 stands down with $2.", + "rov_msg_trenta_are_muspell_ash_ember_given": "You are Muspell, ash and ember given shape.", + "rov_msg_trenta_elder_has_not_fallen_yet": "The Elder has not fallen yet.", + "rov_msg_trenta_grows": "It grows.", + "rov_msg_trenta_no_raw_flesh_rot": "No raw flesh to rot.", + "rov_msg_trenta_nothing_feed_wants_fertilizer": "Nothing to feed it. It wants Fertilizer.", + "rov_msg_trenta_nothing_there_feed": "Nothing there to feed.", + "rov_msg_trenta_return_rooted_form": "You return to your rooted form.", + "rov_msg_trenta_ripe_already": "It is ripe already.", + "rov_msg_trenta_root_will_not_take_hold": "The root will not take hold for you.", + "rov_msg_trenta_still_growing_minutes": "Still growing. $1 minutes.", + "rov_msg_trenta_still_rotting_minutes": "Still rotting. $1 minutes.", + "rov_msg_trenta_this_one_not_well_nothing": "This one is not well. Nothing will hurry it.", + "rov_msg_trenta_trenta_eat_only_what_grows": "The Trenta eat only what grows from root and leaf - no meat, fish, egg or honey.", + "rov_msg_trol_answers": "$1 answers.", + "rov_msg_trol_are_already_holding_log": "You are already holding a log!", + "rov_msg_trol_five_warbands_all_can_shout": "Five warbands is all it can shout for.", + "rov_msg_trol_has_already_had_one": "It has already had one.", + "rov_msg_trol_head_has_nothing_say": "The head has nothing to say.", + "rov_msg_trol_head_will_not_shout": "The head will not shout for you.", + "rov_msg_trol_must_true_form_lift_this": "You must be in True Form to lift this!", + "rov_msg_trol_no_room_lift": "No room to lift it!", + "rov_msg_trol_not_until_one_belonged_has": "Not until the one it belonged to has fallen.", + "rov_msg_trol_totem_wears_king_now": "The totem wears a king now.", + "rov_msg_ward_already_carry_s_power": "You already carry $1's power.", + "rov_msg_ward_s_power_yours": "$1's power is yours.", + "rov_msg_ward_switch_personal_progression_first": "Switch to personal progression first.", + "rov_msg_ward_ward_has_no_use_that": "The ward has no use for that.", + "rov_msg_warvulture_bird_does_not_know": "The bird does not know you.", + "rov_msg_warvulture_vulture_does_not_answer": "The vulture does not answer.", + "rov_msg_warvulture_vulture_settles_into_glide": "The vulture settles into a glide.", + "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down." +} diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json new file mode 100644 index 0000000..b03faf1 --- /dev/null +++ b/JotunnModStub/Translations/Italian/messages.json @@ -0,0 +1,193 @@ +{ + "rov_msg_aswid_aura_disabled": "Aura vampirica: DISATTIVATA", + "rov_msg_aswid_aura_enabled": "Aura vampirica: ATTIVATA", + "rov_msg_aswid_dominate_cooldown_m_s": "Dominio in ricarica ($1m $2s)", + "rov_msg_aswid_dominated": "$1 dominato!", + "rov_msg_aswid_eclipse_cooldown_remaining_s": "L'Eclissi è in ricarica. Mancano: $1s", + "rov_msg_aswid_eclipse_descends": "Un'Eclissi discende...", + "rov_msg_aswid_eclipse_has_ended": "L'Eclissi è finita.", + "rov_msg_aswid_following": "$1 ti segue.", + "rov_msg_aswid_living_blood_curdles_living_throat": "Il sangue vivo si rapprende in una gola viva.", + "rov_msg_aswid_morning_sun_drives_bat_back": "Il sole del mattino ricaccia il pipistrello nel tuo corpo", + "rov_msg_aswid_morning_sun_has_vanquished_horrible": "Il sole del mattino ha sconfitto l'orribile notte", + "rov_msg_aswid_no_bone_grind": "Nessun osso da macinare.", + "rov_msg_aswid_no_raw_flesh_render": "Nessuna carne cruda da raffinare.", + "rov_msg_aswid_staying": "$1 resta qui.", + "rov_msg_aswid_sun_burns_can_only_take": "Il sole brucia. Puoi prendere la forma di pipistrello solo di notte.", + "rov_msg_aswid_tamed": "Addomesticato!", + "rov_msg_aswid_vae_victis": "Vae Victis", + "rov_msg_aswid_what_horrible_night_have_curse": "che notte orribile per avere una maledizione", + "rov_msg_build_limit_cooktable": "C'è già un altro tavolo del cuoco entro quaranta passi. Un cuoco per cortile.", + "rov_msg_build_limit_draugh_bodypile": "Questo terreno ne porta già $1. Trova un'altra contrada.", + "rov_msg_build_limit_dvergar_contractbank": "C'è già $1 banca dei contratti a una giornata di cammino. Un registro per valle.", + "rov_msg_build_limit_fenrir_packtrough": "Ce n'è già $1 a una giornata di cammino. Un branco ha bisogno di spazio.", + "rov_msg_build_limit_skeleton_bonepile": "Ce ne sono già $1 in ascolto qui vicino. Portalo più lontano.", + "rov_msg_build_limit_smithtable": "C'è già un altro tavolo del fabbro entro quaranta passi. Un fabbro per cortile.", + "rov_msg_build_limit_sverm_hive": "C'è già un alveare che occupa questo terreno.", + "rov_msg_build_limit_sverm_market": "Questo alveare ha già un mercato.", + "rov_msg_build_limit_trenta_grove": "Questa contrada ne ospita già $1. Piantalo altrove.", + "rov_msg_build_this_cave_will_hold_what": "Questa grotta terrà ciò che vi costruisci.", + "rov_msg_butler_already_at_work": "È già al lavoro.", + "rov_msg_butler_bones_are_not_ready_s": "Le ossa non sono pronte. $1s.", + "rov_msg_butler_bones_do_not_answer_blood": "Le ossa non rispondono al tuo sangue.", + "rov_msg_butler_nothing_answers": "Niente risponde.", + "rov_msg_butler_only_skadi_s_hearth_kept": "Solo il focolare di Skadi è tenuto dai morti.", + "rov_msg_butler_servant_rises": "Il servitore si alza.", + "rov_msg_claws_they_are_part_hands": "Fanno parte delle tue mani.", + "rov_msg_core_chose_path_aswid": "Hai scelto la via degli Aswid.", + "rov_msg_core_chose_path_draugh": "Hai scelto la via dei Draugh.", + "rov_msg_core_chose_path_dvergar": "Hai scelto la via dei Dvergar.", + "rov_msg_core_chose_path_fenrir": "Hai scelto la via dei Fenrir.", + "rov_msg_core_chose_path_furling": "Hai scelto la via dei Furling.", + "rov_msg_core_chose_path_skadi": "Hai scelto la via di Skadi.", + "rov_msg_core_chose_path_skeleton": "Hai scelto la via degli Scheletri.", + "rov_msg_core_chose_path_sverm": "Hai scelto la via degli Sverm.", + "rov_msg_core_chose_path_trenta": "Hai scelto la via dei Trenta.", + "rov_msg_core_chose_path_trol": "Hai scelto la via dei Trol.", + "rov_msg_core_chose_remain_human": "Hai scelto di restare Umano.", + "rov_msg_core_debug_override_cleared": "Override di debug rimosso.", + "rov_msg_core_nothing_reset_personal": "Niente da azzerare: non hai ancora reclamato reliquie ($1/$2).", + "rov_msg_core_nothing_reset_world": "Niente da azzerare: segui la progressione del mondo: $1 ($2/$3).", + "rov_msg_core_progression_reset": "Progressione personale azzerata a $1 ($2/$3). Reclama di nuovo le tue reliquie.", + "rov_msg_core_progression_state": "Stato di progressione: $1", + "rov_msg_core_world_progression_state": "Stato di progressione del mondo: $1", + "rov_msg_draugh_bone_will_not_wake_something": "L'osso non si sveglia. Qualcosa di più antico deve cadere prima.", + "rov_msg_draugh_draugr_consume_only_raw_flesh": "I Draugr consumano solo carne cruda, occhi, interiora o sangue.", + "rov_msg_draugh_has_already_had_one": "Ne ha già avuto uno.", + "rov_msg_draugh_northern_wind_blows": "Soffia il vento del nord", + "rov_msg_draugh_pile_broken_will_not_outlast": "Il mucchio è distrutto. $1 non gli sopravviveranno più di un minuto.", + "rov_msg_draugh_pile_stirs_will_keep_officers": "Il mucchio si agita. Ora terrà anche degli ufficiali.", + "rov_msg_draugh_steal_their_breath_death_denied": "Ruba il loro respiro! La morte è negata.", + "rov_msg_draugh_swarm_terror": "Sciame del terrore!", + "rov_msg_draugh_this_pile_keeps_no_officers": "Questo mucchio non tiene ancora ufficiali.", + "rov_msg_draugh_this_rotting_flesh_fatal_living": "Questa carne putrefatta è letale per i vivi.", + "rov_msg_draugh_wants_flesh_or_head_one": "Vuole carne, o la testa di uno dei suoi.", + "rov_msg_draugh_zombie_ritual_activated_borrowed_time": "Rituale zombie attivato! Il tuo tempo in prestito sta svanendo...", + "rov_msg_dvergar_contract_runic_do_not_sign": "Il contratto è in runico. Non lo firmi.", + "rov_msg_dvergar_do_not_know_what_goes": "Non sai cosa ci va dentro.", + "rov_msg_dvergar_drink": "$1 bevono $2.", + "rov_msg_dvergar_drink_barrel_runs_dry": "$1 bevono $2. Il barile si svuota.", + "rov_msg_dvergar_empty_so_are": "È vuoto, e lo sei anche tu.", + "rov_msg_dvergar_five_contracts_all_ledger_holds": "Cinque contratti è tutto ciò che il registro contiene.", + "rov_msg_dvergar_has_already_had_one": "Ne ha già avuto uno.", + "rov_msg_dvergar_ledger_not_written": "Il registro non è scritto per te.", + "rov_msg_dvergar_ledger_rewritten_better_names_sign": "Il registro è riscritto. Ora lo firmano nomi migliori.", + "rov_msg_dvergar_ledger_shut": "Il registro è chiuso.", + "rov_msg_dvergar_nobody_at_barrel": "Non c'è nessuno al barile.", + "rov_msg_dvergar_not_drop_went_down": "Non è andata giù nemmeno una goccia.", + "rov_msg_dvergar_not_enough_eitr": "Eitr insufficiente", + "rov_msg_dvergar_not_while_she_still_sits": "Non finché lei siede ancora sotto la nebbia.", + "rov_msg_dvergar_runic_overcharge_discharges": "Il sovraccarico runico si scarica", + "rov_msg_dvergar_runic_overcharge_next_blow_loaded": "Sovraccarico runico: il tuo prossimo colpo è carico", + "rov_msg_dvergar_runic_ping_echoes_answer": "Richiamo runico: rispondono $1 echi", + "rov_msg_dvergar_runic_ping_stone_silent": "Richiamo runico: la pietra tace", + "rov_msg_dvergar_signs": "$1 firma.", + "rov_msg_dvergar_there_still": "C'è ancora $1 dentro.", + "rov_msg_dvergar_whatever_does_nothing_anyone": "Qualunque cosa ci sia dentro, non fa niente a nessuno.", + "rov_msg_fenrir_are_cultist": "Sei un Cultista!", + "rov_msg_fenrir_are_fenring": "Sei un Fenring!", + "rov_msg_fenrir_are_ulv": "Sei un Ulv!", + "rov_msg_fenrir_are_wolf": "Sei un Lupo!", + "rov_msg_fenrir_beast_rests_can_only_transform": "La bestia riposa. Puoi trasformarti solo di notte.", + "rov_msg_fenrir_beast_tired": "La bestia è stanca", + "rov_msg_fenrir_blood_will_not_take_something": "Il sangue non attecchisce. Qualcosa nelle pianure deve cadere prima.", + "rov_msg_fenrir_form_cooldown": "La forma $1 è in ricarica ($2:$3).", + "rov_msg_fenrir_formname_cultist": "Cultista", + "rov_msg_fenrir_formname_fenrir": "Fenrir", + "rov_msg_fenrir_has_already_had_one": "Ne ha già avuto uno.", + "rov_msg_fenrir_only_breath_comes_out_fire": "Esce solo fiato. Il fuoco vuole eitr.", + "rov_msg_fenrir_ready": "$1 è pronto!", + "rov_msg_fenrir_returned_human_form": "Sei tornato in forma umana.", + "rov_msg_fenrir_trough_broken_will_not_outlast": "La mangiatoia è distrutta. $1 non le sopravviveranno a lungo.", + "rov_msg_fenrir_trough_takes_line_runs_deeper": "La mangiatoia lo accetta. Ora la discendenza va più a fondo.", + "rov_msg_fenrir_wants_meat_any_meat": "Vuole carne. Qualsiasi carne.", + "rov_msg_fenrir_wants_what_yagluth_left_behind": "Vuole ciò che Yagluth ha lasciato.", + "rov_msg_skadi_are_drake": "Sei un Drake!", + "rov_msg_skadi_are_fader": "Sei Fader!", + "rov_msg_skadi_are_moder": "Sei Moder!", + "rov_msg_skadi_dragon_form_cooldown": "La forma di drago è in ricarica ($1:$2).", + "rov_msg_skadi_dragon_form_fades": "La tua forma di drago svanisce.", + "rov_msg_skadi_dumped_dragon_drake_fader_debug": "Info di debug Dragon/Drake/Fader scritte nella console!", + "rov_msg_skadi_needs_stonecutter_cut_at": "Ha bisogno di uno scalpellino per essere tagliato.", + "rov_msg_skadi_not_enough_stamina": "Stamina insufficiente", + "rov_msg_skadi_returned_human_form": "Sei tornato in forma umana.", + "rov_msg_skadi_stone_does_not_answer": "La pietra non ti risponde.", + "rov_msg_skadi_stonecutter_gone_what_cut_will": "Lo scalpellino non c'è più. Ciò che ha tagliato non gli sopravviverà a lungo.", + "rov_msg_skadi_tear_cold_nothing_wakes_stone": "La lacrima è fredda. Niente si sveglia nella pietra finché la regina della montagna non è caduta.", + "rov_msg_skadi_that_stonecutter_already_holds_will": "Quello scalpellino ne tiene già $1. Non ne terrà altri.", + "rov_msg_skadi_there_are_already_these_within": "Ce ne sono già $1 a una giornata di cammino. La pietra è esaurita.", + "rov_msg_skeleton_has_already_had_one": "Ne ha già avuto uno.", + "rov_msg_skeleton_have_been_resurrected_by_dark": "Sei stato resuscitato dalla magia oscura!", + "rov_msg_skeleton_mortal_food_disgusts": "Il cibo dei mortali ti disgusta.", + "rov_msg_skeleton_nothing_standing_yet_wants_bone": "Non c'è ancora niente in piedi. Vuole ossa.", + "rov_msg_skeleton_pile_broken_fall_where_they": "Il mucchio è distrutto. $1 cadono dove si trovano.", + "rov_msg_skeleton_pile_deepens_rotten_will_stand": "Il mucchio si fa più profondo. Anche i rancidi si alzeranno qui.", + "rov_msg_skeleton_return_pile": "$1 tornano al mucchio.", + "rov_msg_skeleton_rise_follow": "$1 si alzano e ti seguono.", + "rov_msg_skeleton_skeletons_do_not_need_eat": "Gli scheletri non hanno bisogno di mangiare.", + "rov_msg_skeleton_skull_will_not_wake_something": "Il teschio non si sveglia. Qualcosa di più antico deve cadere prima.", + "rov_msg_skeleton_these_bones_answer_only_their": "Queste ossa rispondono solo ai loro simili.", + "rov_msg_skeleton_this_pile_cannot_hold_rotten": "Questo mucchio non può ancora tenere i rancidi.", + "rov_msg_sverm_alchemical_blood_not_food": "Il sangue alchemico non è cibo.", + "rov_msg_sverm_carapace_has_no_room_that": "Il tuo carapace non ha spazio per quello.", + "rov_msg_sverm_colony_will_not_wake_until": "La colonia non si sveglierà finché l'Antico non sarà caduto.", + "rov_msg_sverm_hive_does_not_know": "L'alveare non ti conosce.", + "rov_msg_sverm_hive_full_give_time_digest": "L'alveare è pieno. Dagli tempo di digerire.", + "rov_msg_sverm_market_has_stand_within_metres": "Un mercato deve stare entro $1 metri da un alveare.", + "rov_msg_sverm_no_hive_within_metres_this": "Nessun alveare entro $1 metri. Questo bancone è morto.", + "rov_msg_sverm_not_enough_biomass_bank": "Non c'è abbastanza biomassa nella riserva.", + "rov_msg_sverm_not_hurt": "$1 non è ferito.", + "rov_msg_sverm_nothing_here_will_eat_food": "Qui non c'è niente che mangerebbe. Cibo, legno e resina: miele e pappa reale sono medicine.", + "rov_msg_sverm_only_sverm_can_raise_hive": "Solo gli Sverm possono far sorgere un alveare.", + "rov_msg_sverm_only_sverm_can_raise_market": "Solo gli Sverm possono far sorgere un mercato.", + "rov_msg_sverm_ravager_strain_takes_hold": "Il Ceppo Devastatore attecchisce.", + "rov_msg_sverm_shell_recedes": "Il guscio si ritrae.", + "rov_msg_sverm_strain_has_not_taken_yet": "Il ceppo non ha ancora attecchito.", + "rov_msg_sverm_strain_spent": "Il ceppo è esaurito.", + "rov_msg_sverm_they_are_part_hands": "Fanno parte delle tue mani.", + "rov_msg_sverm_x_biomass_digesting": "$1 x$2 -> +$3 biomassa, in digestione", + "rov_msg_thrall_answer_call": "$1 rispondono alla chiamata.", + "rov_msg_thrall_follows": "$1 ti segue.", + "rov_msg_thrall_no_more_may_walk_with": "Nessun altro può camminare con te.", + "rov_msg_thrall_only_may_walk_with": "Solo $1 possono camminare con te.", + "rov_msg_thrall_refusal_default": "Non ti risponde.", + "rov_msg_thrall_refusal_draugh": "I morti non prendono ordini dai vivi.", + "rov_msg_thrall_refusal_dvergar": "Il tuo nome non è sul contratto.", + "rov_msg_thrall_refusal_skeleton": "Queste ossa rispondono solo ai loro simili.", + "rov_msg_thrall_refusal_sverm": "Non sente l'odore della tua colonia su di te.", + "rov_msg_thrall_refusal_trol": "Non li hai pagati tu.", + "rov_msg_thrall_returns": "$1 torna indietro.", + "rov_msg_thrall_rises_with": "$1 si alza con $2.", + "rov_msg_thrall_stands_down_with": "$1 si ritira con $2.", + "rov_msg_trenta_are_muspell_ash_ember_given": "Sei Muspell, cenere e brace fatte forma.", + "rov_msg_trenta_elder_has_not_fallen_yet": "L'Antico non è ancora caduto.", + "rov_msg_trenta_grows": "Cresce.", + "rov_msg_trenta_no_raw_flesh_rot": "Nessuna carne cruda da far marcire.", + "rov_msg_trenta_nothing_feed_wants_fertilizer": "Niente con cui nutrirlo. Vuole fertilizzante.", + "rov_msg_trenta_nothing_there_feed": "Non c'è niente da nutrire.", + "rov_msg_trenta_return_rooted_form": "Torni alla tua forma radicata.", + "rov_msg_trenta_ripe_already": "È già maturo.", + "rov_msg_trenta_root_will_not_take_hold": "La radice non attecchisce per te.", + "rov_msg_trenta_still_growing_minutes": "Sta ancora crescendo. $1 minuti.", + "rov_msg_trenta_still_rotting_minutes": "Sta ancora marcendo. $1 minuti.", + "rov_msg_trenta_this_one_not_well_nothing": "Questo non sta bene. Niente lo farà affrettare.", + "rov_msg_trenta_trenta_eat_only_what_grows": "I Trenta mangiano solo ciò che nasce da radice e foglia: niente carne, pesce, uova o miele.", + "rov_msg_trol_answers": "$1 risponde.", + "rov_msg_trol_are_already_holding_log": "Stai già tenendo un tronco!", + "rov_msg_trol_five_warbands_all_can_shout": "Cinque bande da guerra è tutto ciò che può chiamare.", + "rov_msg_trol_has_already_had_one": "Ne ha già avuto uno.", + "rov_msg_trol_head_has_nothing_say": "La testa non ha niente da dire.", + "rov_msg_trol_head_will_not_shout": "La testa non urlerà per te.", + "rov_msg_trol_must_true_form_lift_this": "Devi essere nella Vera forma per sollevarlo!", + "rov_msg_trol_no_room_lift": "Non c'è spazio per sollevarlo!", + "rov_msg_trol_not_until_one_belonged_has": "Non finché colui a cui apparteneva non sarà caduto.", + "rov_msg_trol_totem_wears_king_now": "Ora il totem porta un re.", + "rov_msg_ward_already_carry_s_power": "Porti già il potere di $1.", + "rov_msg_ward_s_power_yours": "Il potere di $1 è tuo.", + "rov_msg_ward_switch_personal_progression_first": "Passa prima alla progressione personale.", + "rov_msg_ward_ward_has_no_use_that": "Al sigillo non serve.", + "rov_msg_warvulture_bird_does_not_know": "L'uccello non ti conosce.", + "rov_msg_warvulture_vulture_does_not_answer": "L'avvoltoio non risponde.", + "rov_msg_warvulture_vulture_settles_into_glide": "L'avvoltoio si mette a planare.", + "rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale." +} diff --git a/JotunnModStub/Trenta/ComposterBehaviour.cs b/JotunnModStub/Trenta/ComposterBehaviour.cs index 4dd7524..82c9871 100644 --- a/JotunnModStub/Trenta/ComposterBehaviour.cs +++ b/JotunnModStub/Trenta/ComposterBehaviour.cs @@ -98,7 +98,7 @@ namespace RacesOfValheim if (state == State.Composting) { - user.Message(MessageHud.MessageType.Center, $"Still rotting. {MinutesLeft()} minutes."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_still_rotting_minutes", MinutesLeft())); return false; } @@ -108,7 +108,7 @@ namespace RacesOfValheim if (item == null) item = FindFlesh(inventory); if (item == null) { - user.Message(MessageHud.MessageType.Center, "No raw flesh to rot."); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_no_raw_flesh_rot")); return false; } diff --git a/JotunnModStub/Trenta/GroveBehaviour.cs b/JotunnModStub/Trenta/GroveBehaviour.cs index 0d0fde3..64f3989 100644 --- a/JotunnModStub/Trenta/GroveBehaviour.cs +++ b/JotunnModStub/Trenta/GroveBehaviour.cs @@ -274,9 +274,7 @@ namespace RacesOfValheim if (item == null) item = FindFertilizer(inventory); if (item == null) { - user.Message(MessageHud.MessageType.Center, IsGrown() - ? "Nothing to feed it. It wants Fertilizer." - : $"Still growing. {MinutesLeft()} minutes."); + user.Message(MessageHud.MessageType.Center, (IsGrown() ? ModText.Get("rov_msg_trenta_nothing_feed_wants_fertilizer") : ModText.Get("rov_msg_trenta_still_growing_minutes", MinutesLeft()))); return false; } diff --git a/JotunnModStub/Trenta/TrentaComposter.cs b/JotunnModStub/Trenta/TrentaComposter.cs index 914ec5e..64bcf5d 100644 --- a/JotunnModStub/Trenta/TrentaComposter.cs +++ b/JotunnModStub/Trenta/TrentaComposter.cs @@ -387,19 +387,19 @@ namespace RacesOfValheim { case GrowOutcome.Grown: if (inventory != null) inventory.RemoveItem(item, 1); - player.Message(MessageHud.MessageType.Center, "It grows."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_grows")); break; case GrowOutcome.AlreadyRipe: - player.Message(MessageHud.MessageType.Center, "It is ripe already."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_ripe_already")); break; case GrowOutcome.Unhealthy: - player.Message(MessageHud.MessageType.Center, "This one is not well. Nothing will hurry it."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_this_one_not_well_nothing")); break; case GrowOutcome.NoTarget: - player.Message(MessageHud.MessageType.Center, "Nothing there to feed."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_nothing_there_feed")); break; default: diff --git a/JotunnModStub/Trenta/TrentaElderRoot.cs b/JotunnModStub/Trenta/TrentaElderRoot.cs index d36d67c..ba21936 100644 --- a/JotunnModStub/Trenta/TrentaElderRoot.cs +++ b/JotunnModStub/Trenta/TrentaElderRoot.cs @@ -291,13 +291,13 @@ namespace RacesOfValheim if (!TrentaRace.IsTrenta()) { - __instance.Message(MessageHud.MessageType.Center, "The root will not take hold for you."); + __instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_root_will_not_take_hold")); return false; } if (BossProgressionManager.GetCurrentProgressionState() < TrentaConfig.ElderRootUnlockState) { - __instance.Message(MessageHud.MessageType.Center, "The Elder has not fallen yet."); + __instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_elder_has_not_fallen_yet")); return false; } diff --git a/JotunnModStub/Trenta/TrentaFoodPatches.cs b/JotunnModStub/Trenta/TrentaFoodPatches.cs index f083369..bc17d19 100644 --- a/JotunnModStub/Trenta/TrentaFoodPatches.cs +++ b/JotunnModStub/Trenta/TrentaFoodPatches.cs @@ -81,7 +81,7 @@ namespace RacesOfValheim if (TrentaConfig.VeganFoodPrefabNames.Contains(prefabName)) return true; - player.Message(MessageHud.MessageType.Center, "The Trenta eat only what grows from root and leaf - no meat, fish, egg or honey."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_trenta_eat_only_what_grows")); return false; // Block consumption } } diff --git a/JotunnModStub/Trenta/TrentaHeartwoodGrove.cs b/JotunnModStub/Trenta/TrentaHeartwoodGrove.cs index a8ca08c..ce9f741 100644 --- a/JotunnModStub/Trenta/TrentaHeartwoodGrove.cs +++ b/JotunnModStub/Trenta/TrentaHeartwoodGrove.cs @@ -39,7 +39,7 @@ namespace RacesOfValheim PieceDensityLimit.Register(TrentaConfig.GrovePieceName, PieceDensityLimit.RadiusForArea(TrentaConfig.GroveDensityAreaKm2), TrentaConfig.GroveMaxInRange, - "This country already answers to {0} of these. Plant it somewhere else."); + "rov_msg_build_limit_trenta_grove"); } // ---------------------------------------------------------------- the seed diff --git a/JotunnModStub/Trenta/TrentaMuspell.cs b/JotunnModStub/Trenta/TrentaMuspell.cs index 6f7fbf6..2864acf 100644 --- a/JotunnModStub/Trenta/TrentaMuspell.cs +++ b/JotunnModStub/Trenta/TrentaMuspell.cs @@ -185,7 +185,7 @@ namespace RacesOfValheim IsTransformed = true; - player.Message(MessageHud.MessageType.Center, "You are Muspell, ash and ember given shape."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_are_muspell_ash_ember_given")); } private static void ExecuteReversion(Player player) @@ -208,7 +208,7 @@ namespace RacesOfValheim IsTransformed = false; - player.Message(MessageHud.MessageType.Center, "You return to your rooted form."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_return_rooted_form")); } } diff --git a/JotunnModStub/Trol/TrolLogWeapon.cs b/JotunnModStub/Trol/TrolLogWeapon.cs index fa42538..f315494 100644 --- a/JotunnModStub/Trol/TrolLogWeapon.cs +++ b/JotunnModStub/Trol/TrolLogWeapon.cs @@ -19,7 +19,7 @@ namespace RacesOfValheim if (!seman.HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode())) { - user.Message(MessageHud.MessageType.Center, "You must be in True Form to lift this!"); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trol_must_true_form_lift_this")); return; } @@ -47,7 +47,7 @@ namespace RacesOfValheim ItemDrop.ItemData rightItem = HarmonyLib.Traverse.Create(user).Field("m_rightItem").Value; if (rightItem != null && rightItem.m_dropPrefab != null && rightItem.m_dropPrefab.name.StartsWith("TrolWeapon_")) { - user.Message(MessageHud.MessageType.Center, "You are already holding a log!"); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trol_are_already_holding_log")); return; } @@ -80,7 +80,7 @@ namespace RacesOfValheim Vector2i gridPos = HarmonyLib.Traverse.Create(user.GetInventory()).Method("FindEmptySlot", false).GetValue(); if (gridPos.x == -1) { - user.Message(MessageHud.MessageType.Center, "No room to lift it!"); + user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trol_no_room_lift")); return; } newItem.m_gridPos = gridPos; diff --git a/JotunnModStub/Trol/TrolTotem.cs b/JotunnModStub/Trol/TrolTotem.cs index 512437b..9187631 100644 --- a/JotunnModStub/Trol/TrolTotem.cs +++ b/JotunnModStub/Trol/TrolTotem.cs @@ -190,7 +190,7 @@ namespace RacesOfValheim thrall.m_maxFollowers = MaxFollowers; thrall.m_witherSeconds = WitherSeconds; thrall.m_homeCheckRange = HomeCheckRange; - thrall.m_refusalMessage = "They were not paid by you."; + thrall.m_refusalMessage = "$rov_msg_thrall_refusal_trol"; // The sentry's regeneration, reused whole: untouched for ten seconds, then two percent a // second. "Rigenerarsi come i nostri scheletri" is the healing, not a respawn - a dead @@ -374,7 +374,7 @@ namespace RacesOfValheim if (Utils.GetPrefabName(__0.gameObject) != TrolTotem.PieceName) return true; if (TrolRace.IsTrol()) return true; - __instance.Message(MessageHud.MessageType.Center, "The head will not shout for you."); + __instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trol_head_will_not_shout")); return false; } } diff --git a/JotunnModStub/Trol/TrolTotemBehaviour.cs b/JotunnModStub/Trol/TrolTotemBehaviour.cs index 4543646..b567f9d 100644 --- a/JotunnModStub/Trol/TrolTotemBehaviour.cs +++ b/JotunnModStub/Trol/TrolTotemBehaviour.cs @@ -70,7 +70,7 @@ namespace RacesOfValheim if (!TrolRace.IsTrol()) { - player.Message(MessageHud.MessageType.Center, "The head will not shout for you."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trol_head_will_not_shout")); // With an item in hand, false makes Humanoid.UseItem cover this message with its // generic "$msg_cantuseon"; true tells it the use was handled here. return item != null; @@ -97,19 +97,19 @@ namespace RacesOfValheim { if (IsUpgraded()) { - player.Message(MessageHud.MessageType.Center, "It has already had one."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trol_has_already_had_one")); return true; } if (BossProgressionManager.GetCurrentProgressionState() < TrolTotem.UpgradeProgressionState) { - player.Message(MessageHud.MessageType.Center, "Not until the one it belonged to has fallen."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trol_not_until_one_belonged_has")); return true; } player.GetInventory().RemoveItem(item, 1); m_nview.InvokeRPC("RoV_TrolUpgrade"); - player.Message(MessageHud.MessageType.Center, "The totem wears a king now."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trol_totem_wears_king_now")); return true; } @@ -123,7 +123,7 @@ namespace RacesOfValheim Trader trader = GetComponent(); if (trader == null || StoreGui.instance == null) { - player.Message(MessageHud.MessageType.Center, "The head has nothing to say."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trol_head_has_nothing_say")); return false; } @@ -148,7 +148,7 @@ namespace RacesOfValheim if (CountGroups() >= TrolTotem.MaxTroops) { - player.Message(MessageHud.MessageType.Center, "Five warbands is all it can shout for."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trol_five_warbands_all_can_shout")); return; } @@ -163,7 +163,7 @@ namespace RacesOfValheim TakeCoins(inventory, troop.Price); m_nview.InvokeRPC("RoV_TrolHire", troop.Id); - player.Message(MessageHud.MessageType.Center, $"{troop.Display} answers."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trol_answers", troop.Display)); } private const string CoinsPrefab = "Coins"; diff --git a/JotunnModStub/WarVulture/WarVultureMount.cs b/JotunnModStub/WarVulture/WarVultureMount.cs index 1d8646a..3667b5d 100644 --- a/JotunnModStub/WarVulture/WarVultureMount.cs +++ b/JotunnModStub/WarVulture/WarVultureMount.cs @@ -113,13 +113,13 @@ namespace RacesOfValheim if (!WarVultureConfig.RaceAllowed(race)) { - rider.Message(MessageHud.MessageType.Center, "The bird does not know you."); + rider.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_warvulture_bird_does_not_know")); return; } if (!WarVultureVisual.Ready) { - rider.Message(MessageHud.MessageType.Center, "The vulture does not answer."); + rider.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_warvulture_vulture_does_not_answer")); Jotunn.Logger.LogWarning($"[{Label}] Call refused: the stripped model template was never built, " + "so there is no bird to show. The reason is logged at startup - and " + "refusing is deliberate, because the alternative is putting an unstripped " + @@ -245,7 +245,7 @@ namespace RacesOfValheim { landing = true; landingStartedAt = Time.time; - player.Message(MessageHud.MessageType.Center, "The vulture spirals down."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_warvulture_vulture_spirals_down")); } private void UpdateLanding() @@ -304,7 +304,7 @@ namespace RacesOfValheim wind = Mathf.Max(0f, wind - dt); if (wind <= 0f) { - player.Message(MessageHud.MessageType.Center, "The vulture settles into a glide."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_warvulture_vulture_settles_into_glide")); } } else if (wind < WarVultureConfig.SprintSeconds.Value) From 0a0d9410e76a3b6bae2aab06cb65776614ed8469 Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 27 Sep 2026 00:52:01 +0200 Subject: [PATCH 079/290] fix(skadi): Middle Mouse in Drake form no longer spends the attack cooldown on nothing PerformAttackCoroutine starts the cooldown and shows its icon before it looks at the form, and the Drake has no Middle Mouse attack, so the press cost a cooldown and fired nothing. HasAttackForButton now answers for the Drake too and guards all three buttons, as it already did Left Mouse. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Skadi/DrakeFormBehavior.cs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/Skadi/DrakeFormBehavior.cs b/JotunnModStub/Skadi/DrakeFormBehavior.cs index 53b9049..b86a59e 100644 --- a/JotunnModStub/Skadi/DrakeFormBehavior.cs +++ b/JotunnModStub/Skadi/DrakeFormBehavior.cs @@ -221,14 +221,14 @@ namespace RacesOfValheim } else if (SkadiConfig.BreathAttackKey.Value.IsDownIgnoringHeldKeys() || RaceInput.PadAttackDown(2)) { - if (Time.time - lastAttackTime >= ATTACK_COOLDOWN) + if (HasAttackForButton(2) && Time.time - lastAttackTime >= ATTACK_COOLDOWN) { StartCoroutine(PerformAttackCoroutine(2)); } } else if ((SkadiConfig.SpinAttackKey.Value.IsDownIgnoringHeldKeys() || RaceInput.PadAttackDown(1)) && formRules.Form == SkadiProgression.FormType.SkeletonDragon) // Fader Spin { - if (Time.time - lastAttackTime >= ATTACK_COOLDOWN) + if (HasAttackForButton(1) && Time.time - lastAttackTime >= ATTACK_COOLDOWN) { StartCoroutine(PerformAttackCoroutine(1)); } @@ -236,13 +236,23 @@ namespace RacesOfValheim } } + // Whether this form has an attack on this button right now. Asked before the cooldown for + // every button, because PerformAttackCoroutine starts the cooldown and shows its icon before + // it looks at the form: a button with nothing behind it used to spend both and fire nothing. + // + // The Drake has only its Left Mouse volley; Middle Mouse is Moder's and Fader's breath. // Airborne Moder keeps the same hand as the ground: the ranged breath is Middle Mouse, and // Left Mouse has no attack in the air (its ground bite and claws cannot reach from up - // there). Checked before the cooldown so a stray left click does not eat the next volley. + // there). private bool HasAttackForButton(int button) { if (formRules == null) return false; + if (formRules.Form == SkadiProgression.FormType.Drake && button != 0) + { + return false; + } + bool airborne = isFlying || isLanding; if (airborne && formRules.Form == SkadiProgression.FormType.Moder && button != 2) { From 99a1817eb0c59e933a5dc19b5d9db33e9b98eaeb Mon Sep 17 00:00:00 2001 From: kanym Date: Mon, 28 Sep 2026 13:55:14 +0200 Subject: [PATCH 080/290] feat(text): hover texts come from translation files What the stations, thralls, the ward and the hive show under the crosshair now reads its text through ModText.Get, and hover.json holds 50 texts in English and Italian. The Aswid thralls and the Race Menu Ward wrote the use key as a literal E; they now use $KEY_Use, which shows the key the player actually bound. For that to work, ModText.Get runs a second localization pass when a $ is left in the result: Valheim resolves tokens once and never looks inside what it inserted, and hover texts go to the HUD without another pass. The Sverm hive stage names stay English for now: the compendium and the hive's goods show them too, and those come with the merchants step. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Aswid/AswidThrall.cs | 6 +-- JotunnModStub/Butler/ServantTableBehaviour.cs | 5 +- .../Draugh/DraughSpawnerBehaviour.cs | 9 ++-- .../Dvergar/DvergarBancoBehaviour.cs | 8 +-- .../Dvergar/DvergarBotteBehaviour.cs | 6 +-- .../Fenrir/FenrirMangiatoiaBehaviour.cs | 15 ++---- JotunnModStub/ModText.cs | 9 +++- JotunnModStub/RaceMenuWard.cs | 8 ++- .../Skeleton/SkeletonBonePileBehaviour.cs | 14 ++--- JotunnModStub/Sverm/SvermHive.cs | 6 +-- JotunnModStub/Sverm/SvermHiveStore.cs | 23 ++++---- JotunnModStub/Translations/English/hover.json | 52 +++++++++++++++++++ JotunnModStub/Translations/Italian/hover.json | 52 +++++++++++++++++++ JotunnModStub/Trenta/ComposterBehaviour.cs | 8 ++- JotunnModStub/Trenta/GroveBehaviour.cs | 16 +++--- JotunnModStub/Trol/TrolTotemBehaviour.cs | 6 +-- 16 files changed, 164 insertions(+), 79 deletions(-) create mode 100644 JotunnModStub/Translations/English/hover.json create mode 100644 JotunnModStub/Translations/Italian/hover.json diff --git a/JotunnModStub/Aswid/AswidThrall.cs b/JotunnModStub/Aswid/AswidThrall.cs index 638ce4e..9566bd9 100644 --- a/JotunnModStub/Aswid/AswidThrall.cs +++ b/JotunnModStub/Aswid/AswidThrall.cs @@ -142,15 +142,15 @@ namespace RacesOfValheim if (isEnslaved) { bool following = m_ai != null && m_ai.GetFollowTarget() != null; - return following ? "[E] Stay" : "[E] Follow"; + return (following ? ModText.Get("rov_hover_aswid_stay") : ModText.Get("rov_hover_aswid_follow")); } else { if (BossProgressionManager.GetCurrentProgressionState() < 6) return ""; float cd = AswidRace.GetEnslaveCooldown(); - if (cd > 0) return $"[E] Dominate (Cooldown: {Mathf.CeilToInt(cd / 60f)}m)"; - return "[E] Dominate"; + if (cd > 0) return ModText.Get("rov_hover_aswid_dominate_cooldown_m", Mathf.CeilToInt(cd / 60f)); + return ModText.Get("rov_hover_aswid_dominate"); } } diff --git a/JotunnModStub/Butler/ServantTableBehaviour.cs b/JotunnModStub/Butler/ServantTableBehaviour.cs index bac4a73..e4964e6 100644 --- a/JotunnModStub/Butler/ServantTableBehaviour.cs +++ b/JotunnModStub/Butler/ServantTableBehaviour.cs @@ -137,12 +137,11 @@ namespace RacesOfValheim if (servant == null) { - return m_title + "\nNo servant stands here.\n" + - "[$KEY_Use] Raise one"; + return ModText.Get("rov_hover_butler_no_servant_stands_here_raise", m_title); } string status = servant.Status; - if (string.IsNullOrEmpty(status)) status = "Waiting."; + if (string.IsNullOrEmpty(status)) status = ModText.Get("rov_hover_butler_waiting"); return m_title + "\n" + status; } diff --git a/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs b/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs index 39b1dd7..e7a6a10 100644 --- a/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs +++ b/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs @@ -328,21 +328,20 @@ namespace RacesOfValheim if (thrall.Kind == DraughSpawner.KindElite) aliveElite++; else aliveNormal++; } - string body = $"flesh {Mathf.Floor(GetFlesh())}/{DraughSpawner.FleshPerThrall}, " + - $"risen {aliveNormal}/{AliveCap()}, waiting {GetReserve()}/{DraughSpawner.ReserveCap}"; + string body = ModText.Get("rov_hover_draugh_flesh_risen_waiting", Mathf.Floor(GetFlesh()), DraughSpawner.FleshPerThrall, aliveNormal, AliveCap(), GetReserve(), DraughSpawner.ReserveCap); if (IsUpgraded()) { - body += $"\nofficers {aliveElite}/{EliteCap()}, waiting {GetReserveElite()}/{DraughSpawner.ReserveCapElite}"; + body += ModText.Get("rov_hover_draugh_officers_waiting", aliveElite, EliteCap(), GetReserveElite(), DraughSpawner.ReserveCapElite); } if (m_respawnTimer > 0f) { int left = Mathf.Max(1, Mathf.CeilToInt(DraughSpawner.RespawnSeconds - m_respawnTimer)); - body += $"\nnext rises in {left}s"; + body += ModText.Get("rov_hover_draugh_next_rises_s", left); } - body += "\n[$KEY_Use] Feed it flesh, or a draugr's head"; + body += ModText.Get("rov_hover_draugh_feed_flesh_or_draugr_s"); return Localization.instance.Localize($"{DraughSpawner.PieceDisplayName} ({body})"); } diff --git a/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs b/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs index cb381e0..444b065 100644 --- a/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs +++ b/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs @@ -277,16 +277,16 @@ namespace RacesOfValheim private string Hover() { - string body = $"contracts {CountGroups()}/{DvergarBanco.MaxTroops}"; + string body = ModText.Get("rov_hover_dvergar_contracts", CountGroups(), DvergarBanco.MaxTroops); // Said in as many words: a player who cannot see their own discount will read the lower // number in the window as a mistake. float discount = Mathf.Clamp01(DvergarProgression.Current.TraderBuyDiscount); - if (discount > 0f) body += $"\nyour seal is worth {Mathf.RoundToInt(discount * 100f)}% off"; + if (discount > 0f) body += ModText.Get("rov_hover_dvergar_seal_worth_off", Mathf.RoundToInt(discount * 100f)); - if (!IsUpgraded()) body += "\n(what the Queen left behind buys two more crews)"; + if (!IsUpgraded()) body += ModText.Get("rov_hover_dvergar_what_queen_left_behind_buys"); - body += "\n[$KEY_Use] Read the ledger"; + body += ModText.Get("rov_hover_dvergar_read_ledger"); return Localization.instance.Localize($"{DvergarBanco.PieceDisplayName} ({body})"); } diff --git a/JotunnModStub/Dvergar/DvergarBotteBehaviour.cs b/JotunnModStub/Dvergar/DvergarBotteBehaviour.cs index 32d4a82..de506db 100644 --- a/JotunnModStub/Dvergar/DvergarBotteBehaviour.cs +++ b/JotunnModStub/Dvergar/DvergarBotteBehaviour.cs @@ -252,14 +252,12 @@ namespace RacesOfValheim string body; if (doses <= 0 || string.IsNullOrEmpty(brew)) { - body = "empty\n[$KEY_Use] Pour a brew in"; + body = ModText.Get("rov_hover_dvergar_empty_pour_brew"); } else { int waiting = InRange().Count; - body = $"{DvergarBotte.BrewDisplayName(brew)} {doses}/{DvergarBotte.MaxDoses}" + - $"\n{waiting} at the barrel" + - $"\n[$KEY_Use] Pour a round"; + body = ModText.Get("rov_hover_dvergar_at_barrel_pour_round", DvergarBotte.BrewDisplayName(brew), doses, DvergarBotte.MaxDoses, waiting); } return Localization.instance.Localize($"{DvergarBotte.PieceDisplayName} ({body})"); diff --git a/JotunnModStub/Fenrir/FenrirMangiatoiaBehaviour.cs b/JotunnModStub/Fenrir/FenrirMangiatoiaBehaviour.cs index 8a54e0f..94fce8c 100644 --- a/JotunnModStub/Fenrir/FenrirMangiatoiaBehaviour.cs +++ b/JotunnModStub/Fenrir/FenrirMangiatoiaBehaviour.cs @@ -440,13 +440,10 @@ namespace RacesOfValheim { Count(out int wolves, out int ulv, out int fenrir); - string body = $"meat {Mathf.Floor(GetFeed())}/{FenrirMangiatoia.TankCap}" + - $"\nwolves {wolves}/{WolfCap()}, ulv {ulv}/{UlvCap()}"; + string body = ModText.Get("rov_hover_fenrir_meat_wolves_ulv", Mathf.Floor(GetFeed()), FenrirMangiatoia.TankCap, wolves, WolfCap(), ulv, UlvCap()); // Said in as many words, because the upgrade is deliberately invisible on the model. - body += IsUpgraded() - ? $", fenrir {fenrir}/{FenrirCap()}" - : "\nthe blood is thin here - it raises no fenrir yet"; + body += (IsUpgraded() ? ModText.Get("rov_hover_fenrir_fenrir", fenrir, FenrirCap()) : ModText.Get("rov_hover_fenrir_blood_thin_here_raises_no")); if (m_waitingFor != null) { @@ -458,16 +455,14 @@ namespace RacesOfValheim : m_waitingFor == FenrirMangiatoia.KindUlv ? FenrirMangiatoia.UlvCost : FenrirMangiatoia.FenrirCost; - body += GetFeed() < cost - ? $"\nnot enough meat for the next one ({cost} needed)" - : $"\nnext in {Mathf.Max(1, Mathf.CeilToInt(wait - m_timer))}s"; + body += (GetFeed() < cost ? ModText.Get("rov_hover_fenrir_not_enough_meat_next_one", cost) : ModText.Get("rov_hover_fenrir_next_s", Mathf.Max(1, Mathf.CeilToInt(wait - m_timer)))); } else { - body += "\nthe pack is whole"; + body += ModText.Get("rov_hover_fenrir_pack_whole"); } - body += "\n[$KEY_Use] Fill it with meat"; + body += ModText.Get("rov_hover_fenrir_fill_with_meat"); return Localization.instance.Localize($"{FenrirMangiatoia.PieceDisplayName} ({body})"); } diff --git a/JotunnModStub/ModText.cs b/JotunnModStub/ModText.cs index b5bb3e9..a60f631 100644 --- a/JotunnModStub/ModText.cs +++ b/JotunnModStub/ModText.cs @@ -28,7 +28,14 @@ namespace RacesOfValheim string[] words = args .Select(a => Localization.instance.Localize(a?.ToString() ?? "")) .ToArray(); - return Localization.instance.Localize("$" + key, words); + string text = Localization.instance.Localize("$" + key, words); + + // Valheim resolves tokens in one pass and never looks inside what it put in, so a + // "$KEY_Use" written in a translation came out as it was. Places that localize the + // result again (MessageHud, the stations' own Localize) hid that; hover texts returned + // straight to the HUD did not. A second pass costs nothing when there is no $ left. + if (text.IndexOf('$') >= 0) text = Localization.instance.Localize(text); + return text; } /// diff --git a/JotunnModStub/RaceMenuWard.cs b/JotunnModStub/RaceMenuWard.cs index 94ef37a..e59b237 100644 --- a/JotunnModStub/RaceMenuWard.cs +++ b/JotunnModStub/RaceMenuWard.cs @@ -171,13 +171,11 @@ namespace RacesOfValheim public string GetHoverText() { - string mode = BossProgressionManager.UsePersonalProgression ? "Personal" : "World"; + string mode = (BossProgressionManager.UsePersonalProgression ? ModText.Get("rov_hover_ward_personal") : ModText.Get("rov_hover_ward_world")); int state = BossProgressionManager.GetCurrentProgressionState(); - string boss = BossProgressionManager.GetBossNameForState(state); + string boss = BossProgressionManager.GetBossTokenForState(state); - return $"Race Menu Ward\n{mode} progression - {boss} ({state}/{BossProgressionManager.MaxState})\n" + - "[E] Open\n" + - "[Use item] Offer a boss relic"; + return ModText.Get("rov_hover_ward_race_menu_ward_progression_open", mode, boss, state, BossProgressionManager.MaxState); } public bool Interact(Humanoid user, bool hold, bool alt) diff --git a/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs b/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs index f65e631..aaa454f 100644 --- a/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs +++ b/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs @@ -362,25 +362,21 @@ namespace RacesOfValheim // upgraded, so there was no way to know the cap was two until ten trophies had gone in. // Every shelf is now visible whether or not it can be used yet, and says why when it cannot. string body = - $"\nmelee {alive[SkeletonBonePile.KindMelee]}/{GetSlots(SkeletonBonePile.KindMelee)} of {MeleeCap()}" + - $"\narchers {alive[SkeletonBonePile.KindRanged]}/{GetSlots(SkeletonBonePile.KindRanged)} of {RangedCap()}" + - $"\nrotten {alive[SkeletonBonePile.KindRancid]}/{GetSlots(SkeletonBonePile.KindRancid)} of {RancidCap()}"; + ModText.Get("rov_hover_skeleton_melee_archers_rotten", alive[SkeletonBonePile.KindMelee], GetSlots(SkeletonBonePile.KindMelee), MeleeCap(), alive[SkeletonBonePile.KindRanged], GetSlots(SkeletonBonePile.KindRanged), RangedCap(), alive[SkeletonBonePile.KindRancid], GetSlots(SkeletonBonePile.KindRancid), RancidCap()); - if (!IsUpgraded()) body += " (needs a Greater Cursed Skull)"; + if (!IsUpgraded()) body += ModText.Get("rov_hover_skeleton_needs_greater_cursed_skull"); int bonesToward = m_nview.GetZDO().GetInt(KeyBones); int placesLeft = TotalCap() - PaidSlots(); - body += placesLeft > 0 - ? $"\nbone {bonesToward}/{SkeletonBonePile.BonesPerSlot} toward the next of {placesLeft} places" - : "\nevery place is bought"; + body += (placesLeft > 0 ? ModText.Get("rov_hover_skeleton_bone_toward_next_places", bonesToward, SkeletonBonePile.BonesPerSlot, placesLeft) : ModText.Get("rov_hover_skeleton_every_place_bought")); if (m_respawnTimer > 0f) { int left = Mathf.Max(1, Mathf.CeilToInt(RespawnSeconds() - m_respawnTimer)); - body += $"\nnext rises in {left}s"; + body += ModText.Get("rov_hover_skeleton_next_rises_s", left); } - body += "\n[$KEY_Use] Bone in hand to buy a place, empty hands to move the line"; + body += ModText.Get("rov_hover_skeleton_bone_hand_buy_place_empty"); return Localization.instance.Localize($"{SkeletonBonePile.PieceDisplayName} ({body})"); } diff --git a/JotunnModStub/Sverm/SvermHive.cs b/JotunnModStub/Sverm/SvermHive.cs index 468846b..5470162 100644 --- a/JotunnModStub/Sverm/SvermHive.cs +++ b/JotunnModStub/Sverm/SvermHive.cs @@ -461,11 +461,7 @@ namespace RacesOfValheim // Both numbers, always, even when nothing is going down. A line that appears and // disappears is one the player has to notice twice before they believe it. - return $"{SvermHiveStage.NameOf(SvermHiveStage.Of(transform))}\n" + - SvermHiveReadout.Tank(transform) + - $"Beehives {infected} taken of {SvermConfigManagement.Beehives} allowed, {beehives} in range\n" + - SvermWorker.Readout(transform.position) + - "[$KEY_Use] Feed it a stack"; + return ModText.Get("rov_hover_sverm_beehives_taken_allowed_range_feed", SvermHiveStage.NameOf(SvermHiveStage.Of(transform)), SvermHiveReadout.Tank(transform), infected, SvermConfigManagement.Beehives, beehives, SvermWorker.Readout(transform.position)); } // New in Valheim 1.0: Hoverable gained this. Every vanilla implementation returns a diff --git a/JotunnModStub/Sverm/SvermHiveStore.cs b/JotunnModStub/Sverm/SvermHiveStore.cs index fe7a064..ef96cc7 100644 --- a/JotunnModStub/Sverm/SvermHiveStore.cs +++ b/JotunnModStub/Sverm/SvermHiveStore.cs @@ -222,17 +222,15 @@ namespace RacesOfValheim SvermHiveBehaviour hive = Hive; if (hive == null) return Title; - return $"{Title}\n" + - SvermHiveReadout.Tank(hive.transform) + - $"[$KEY_Use] {Prompt}"; + return ModText.Get("rov_hover_sverm_msg", Title, SvermHiveReadout.Tank(hive.transform), Prompt); } } /// The hive at the foot of the nest. Press E, a stack goes in. public class SvermHiveStomach : SvermHiveMouth { - protected override string Title => "Hive Stomach"; - protected override string Prompt => "Feed it a stack"; + protected override string Title => "$rov_hover_sverm_stomach_title"; + protected override string Prompt => "$rov_hover_sverm_stomach_prompt"; protected override bool Use(SvermHiveBehaviour hive, Player player) { @@ -459,13 +457,11 @@ namespace RacesOfValheim SvermHiveBehaviour nest = Nest; if (nest == null) { - return $"{SvermHiveMarketPiece.DisplayName}\n" + - $"No hive within {SvermConfigManagement.AuraRadius:0} metres."; + return ModText.Get("rov_hover_sverm_market_no_hive", SvermHiveMarketPiece.DisplayName, + SvermConfigManagement.AuraRadius.ToString("0")); } - return $"{SvermHiveMarketPiece.DisplayName}\n" + - SvermHiveReadout.Tank(nest.transform) + - "[$KEY_Use] Trade with the hive"; + return ModText.Get("rov_hover_sverm_trade_with_hive", SvermHiveMarketPiece.DisplayName, SvermHiveReadout.Tank(nest.transform)); } } @@ -474,9 +470,10 @@ namespace RacesOfValheim { public static string Tank(Transform nest) { - return $"Biomass {SvermBiomass.Bank(nest):0} / {SvermBiomass.Capacity(nest):0}\n" + - $"Digesting {SvermBiomass.Digesting(nest):0}\n" + - $"Brood eggs {SvermBroodEggs.Count(nest)} / {SvermBroodEggs.Cap(nest)}\n"; + return ModText.Get("rov_hover_sverm_tank", + SvermBiomass.Bank(nest).ToString("0"), SvermBiomass.Capacity(nest).ToString("0"), + SvermBiomass.Digesting(nest).ToString("0"), + SvermBroodEggs.Count(nest), SvermBroodEggs.Cap(nest)); } } diff --git a/JotunnModStub/Translations/English/hover.json b/JotunnModStub/Translations/English/hover.json new file mode 100644 index 0000000..9c09cb6 --- /dev/null +++ b/JotunnModStub/Translations/English/hover.json @@ -0,0 +1,52 @@ +{ + "rov_hover_aswid_dominate": "[$KEY_Use] Dominate", + "rov_hover_aswid_dominate_cooldown_m": "[$KEY_Use] Dominate (Cooldown: $1m)", + "rov_hover_aswid_follow": "[$KEY_Use] Follow", + "rov_hover_aswid_stay": "[$KEY_Use] Stay", + "rov_hover_butler_no_servant_stands_here_raise": "$1\nNo servant stands here.\n[$KEY_Use] Raise one", + "rov_hover_butler_waiting": "Waiting.", + "rov_hover_draugh_feed_flesh_or_draugr_s": "\n[$KEY_Use] Feed it flesh, or a draugr's head", + "rov_hover_draugh_flesh_risen_waiting": "flesh $1/$2, risen $3/$4, waiting $5/$6", + "rov_hover_draugh_next_rises_s": "\nnext rises in $1s", + "rov_hover_draugh_officers_waiting": "\nofficers $1/$2, waiting $3/$4", + "rov_hover_dvergar_at_barrel_pour_round": "$1 $2/$3\n$4 at the barrel\n[$KEY_Use] Pour a round", + "rov_hover_dvergar_contracts": "contracts $1/$2", + "rov_hover_dvergar_empty_pour_brew": "empty\n[$KEY_Use] Pour a brew in", + "rov_hover_dvergar_read_ledger": "\n[$KEY_Use] Read the ledger", + "rov_hover_dvergar_seal_worth_off": "\nyour seal is worth $1% off", + "rov_hover_dvergar_what_queen_left_behind_buys": "\n(what the Queen left behind buys two more crews)", + "rov_hover_fenrir_blood_thin_here_raises_no": "\nthe blood is thin here - it raises no fenrir yet", + "rov_hover_fenrir_fenrir": ", fenrir $1/$2", + "rov_hover_fenrir_fill_with_meat": "\n[$KEY_Use] Fill it with meat", + "rov_hover_fenrir_meat_wolves_ulv": "meat $1/$2\nwolves $3/$4, ulv $5/$6", + "rov_hover_fenrir_next_s": "\nnext in $1s", + "rov_hover_fenrir_not_enough_meat_next_one": "\nnot enough meat for the next one ($1 needed)", + "rov_hover_fenrir_pack_whole": "\nthe pack is whole", + "rov_hover_skeleton_bone_hand_buy_place_empty": "\n[$KEY_Use] Bone in hand to buy a place, empty hands to move the line", + "rov_hover_skeleton_bone_toward_next_places": "\nbone $1/$2 toward the next of $3 places", + "rov_hover_skeleton_every_place_bought": "\nevery place is bought", + "rov_hover_skeleton_melee_archers_rotten": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\nrotten $7/$8 of $9", + "rov_hover_skeleton_needs_greater_cursed_skull": " (needs a Greater Cursed Skull)", + "rov_hover_skeleton_next_rises_s": "\nnext rises in $1s", + "rov_hover_sverm_beehives_taken_allowed_range_feed": "$1\n$2Beehives $3 taken of $4 allowed, $5 in range\n$6[$KEY_Use] Feed it a stack", + "rov_hover_sverm_market_no_hive": "$1\nNo hive within $2 metres.", + "rov_hover_sverm_msg": "$1\n$2[$KEY_Use] $3", + "rov_hover_sverm_stomach_prompt": "Feed it a stack", + "rov_hover_sverm_stomach_title": "Hive Stomach", + "rov_hover_sverm_tank": "Biomass $1 / $2\nDigesting $3\nBrood eggs $4 / $5\n", + "rov_hover_sverm_trade_with_hive": "$1\n$2[$KEY_Use] Trade with the hive", + "rov_hover_trenta_flesh_feed_raw_flesh": "flesh $1/$2\n[$KEY_Use] Feed it raw flesh", + "rov_hover_trenta_grove_growing": "$1 (growing, $2 minutes left)", + "rov_hover_trenta_grove_grown": "$1 ($2 $3/$4, honey $5)\n[$KEY_Use] Feed it Fertilizer", + "rov_hover_trenta_honey_full": "$1, full", + "rov_hover_trenta_honey_next": "$1, next in $2 min", + "rov_hover_trenta_honey_none": "none (no honey item found)", + "rov_hover_trenta_ready_empty": "ready: $1 $2\n[$KEY_Use] Empty it", + "rov_hover_trenta_rotting_minutes_left": "rotting, $1 minutes left", + "rov_hover_trol_call_warbands": "\n[$KEY_Use] Call the warbands", + "rov_hover_trol_warbands": "warbands $1/$2", + "rov_hover_trol_yagluth_drop_hand_buys_king": "\n(a Yagluth drop in hand buys a king's head, and two more bands)", + "rov_hover_ward_personal": "Personal", + "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 progression - $2 ($3/$4)\n[$KEY_Use] Open\n[Use item] Offer a boss relic", + "rov_hover_ward_world": "World" +} diff --git a/JotunnModStub/Translations/Italian/hover.json b/JotunnModStub/Translations/Italian/hover.json new file mode 100644 index 0000000..d332961 --- /dev/null +++ b/JotunnModStub/Translations/Italian/hover.json @@ -0,0 +1,52 @@ +{ + "rov_hover_aswid_dominate": "[$KEY_Use] Domina", + "rov_hover_aswid_dominate_cooldown_m": "[$KEY_Use] Domina (ricarica: $1m)", + "rov_hover_aswid_follow": "[$KEY_Use] Segui", + "rov_hover_aswid_stay": "[$KEY_Use] Resta", + "rov_hover_butler_no_servant_stands_here_raise": "$1\nQui non c'è nessun servitore.\n[$KEY_Use] Fanne alzare uno", + "rov_hover_butler_waiting": "In attesa.", + "rov_hover_draugh_feed_flesh_or_draugr_s": "\n[$KEY_Use] Nutrilo di carne, o della testa di un draugr", + "rov_hover_draugh_flesh_risen_waiting": "carne $1/$2, risorti $3/$4, in attesa $5/$6", + "rov_hover_draugh_next_rises_s": "\nil prossimo si alza tra $1s", + "rov_hover_draugh_officers_waiting": "\nufficiali $1/$2, in attesa $3/$4", + "rov_hover_dvergar_at_barrel_pour_round": "$1 $2/$3\n$4 al barile\n[$KEY_Use] Versa un giro", + "rov_hover_dvergar_contracts": "contratti $1/$2", + "rov_hover_dvergar_empty_pour_brew": "vuoto\n[$KEY_Use] Versaci una bevanda", + "rov_hover_dvergar_read_ledger": "\n[$KEY_Use] Leggi il registro", + "rov_hover_dvergar_seal_worth_off": "\nil tuo sigillo vale uno sconto del $1%", + "rov_hover_dvergar_what_queen_left_behind_buys": "\n(ciò che la Regina ha lasciato compra altre due squadre)", + "rov_hover_fenrir_blood_thin_here_raises_no": "\nqui il sangue è debole: non fa ancora nascere fenrir", + "rov_hover_fenrir_fenrir": ", fenrir $1/$2", + "rov_hover_fenrir_fill_with_meat": "\n[$KEY_Use] Riempila di carne", + "rov_hover_fenrir_meat_wolves_ulv": "carne $1/$2\nlupi $3/$4, ulv $5/$6", + "rov_hover_fenrir_next_s": "\nil prossimo tra $1s", + "rov_hover_fenrir_not_enough_meat_next_one": "\nnon c'è abbastanza carne per il prossimo (ne serve $1)", + "rov_hover_fenrir_pack_whole": "\nil branco è al completo", + "rov_hover_skeleton_bone_hand_buy_place_empty": "\n[$KEY_Use] Osso in mano per comprare un posto, mani vuote per muovere la fila", + "rov_hover_skeleton_bone_toward_next_places": "\nossa $1/$2 per il prossimo dei $3 posti", + "rov_hover_skeleton_every_place_bought": "\nogni posto è comprato", + "rov_hover_skeleton_melee_archers_rotten": "\nmischia $1/$2 di $3\narcieri $4/$5 di $6\nrancidi $7/$8 di $9", + "rov_hover_skeleton_needs_greater_cursed_skull": " (serve un teschio maledetto superiore)", + "rov_hover_skeleton_next_rises_s": "\nil prossimo si alza tra $1s", + "rov_hover_sverm_beehives_taken_allowed_range_feed": "$1\n$2Alveari $3 occupati su $4 consentiti, $5 nel raggio\n$6[$KEY_Use] Dagli da mangiare una pila", + "rov_hover_sverm_market_no_hive": "$1\nNessun alveare entro $2 metri.", + "rov_hover_sverm_msg": "$1\n$2[$KEY_Use] $3", + "rov_hover_sverm_stomach_prompt": "Dagli da mangiare una pila", + "rov_hover_sverm_stomach_title": "Stomaco dell'alveare", + "rov_hover_sverm_tank": "Biomassa $1 / $2\nIn digestione $3\nUova della covata $4 / $5\n", + "rov_hover_sverm_trade_with_hive": "$1\n$2[$KEY_Use] Commercia con l'alveare", + "rov_hover_trenta_flesh_feed_raw_flesh": "carne $1/$2\n[$KEY_Use] Nutrila di carne cruda", + "rov_hover_trenta_grove_growing": "$1 (in crescita, mancano $2 minuti)", + "rov_hover_trenta_grove_grown": "$1 ($2 $3/$4, miele $5)\n[$KEY_Use] Nutrilo di fertilizzante", + "rov_hover_trenta_honey_full": "$1, pieno", + "rov_hover_trenta_honey_next": "$1, il prossimo tra $2 min", + "rov_hover_trenta_honey_none": "nessuno (oggetto miele non trovato)", + "rov_hover_trenta_ready_empty": "pronto: $1 $2\n[$KEY_Use] Svuotala", + "rov_hover_trenta_rotting_minutes_left": "sta marcendo, mancano $1 minuti", + "rov_hover_trol_call_warbands": "\n[$KEY_Use] Chiama le bande da guerra", + "rov_hover_trol_warbands": "bande da guerra $1/$2", + "rov_hover_trol_yagluth_drop_hand_buys_king": "\n(un bottino di Yagluth in mano compra la testa di un re, e altre due bande)", + "rov_hover_ward_personal": "Personale", + "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\nProgressione $1 - $2 ($3/$4)\n[$KEY_Use] Apri\n[Usa oggetto] Offri una reliquia di boss", + "rov_hover_ward_world": "del mondo" +} diff --git a/JotunnModStub/Trenta/ComposterBehaviour.cs b/JotunnModStub/Trenta/ComposterBehaviour.cs index 82c9871..df7caf1 100644 --- a/JotunnModStub/Trenta/ComposterBehaviour.cs +++ b/JotunnModStub/Trenta/ComposterBehaviour.cs @@ -243,17 +243,15 @@ namespace RacesOfValheim switch (GetState()) { case State.Ready: - body = $"ready: {m_yield} {TrentaConfig.FertilizerDisplayName}\n" + - "[$KEY_Use] Empty it"; + body = ModText.Get("rov_hover_trenta_ready_empty", m_yield, TrentaConfig.FertilizerDisplayName); break; case State.Composting: - body = $"rotting, {MinutesLeft()} minutes left"; + body = ModText.Get("rov_hover_trenta_rotting_minutes_left", MinutesLeft()); break; default: - body = $"flesh {Mathf.Floor(GetFlesh())}/{m_capacity}\n" + - "[$KEY_Use] Feed it raw flesh"; + body = ModText.Get("rov_hover_trenta_flesh_feed_raw_flesh", Mathf.Floor(GetFlesh()), m_capacity); break; } diff --git a/JotunnModStub/Trenta/GroveBehaviour.cs b/JotunnModStub/Trenta/GroveBehaviour.cs index 64f3989..a40c1ce 100644 --- a/JotunnModStub/Trenta/GroveBehaviour.cs +++ b/JotunnModStub/Trenta/GroveBehaviour.cs @@ -318,34 +318,32 @@ namespace RacesOfValheim { if (!IsGrown()) { - return Localization.instance.Localize( - $"{TrentaConfig.GroveDisplayName} (growing, {MinutesLeft()} minutes left)"); + return ModText.Get("rov_hover_trenta_grove_growing", TrentaConfig.GroveDisplayName, MinutesLeft()); } // The honey line is here because it was missing, and its absence is why a grove that // was quietly producing nothing looked exactly like one that was working. - return Localization.instance.Localize( - $"{TrentaConfig.GroveDisplayName} ({TrentaConfig.FertilizerDisplayName} " + - $"{GetFertilizer()}/{TrentaConfig.GroveFertilizerCapacity}, honey {HoneyStatus()})\n" + - "[$KEY_Use] Feed it Fertilizer"); + return ModText.Get("rov_hover_trenta_grove_grown", TrentaConfig.GroveDisplayName, + TrentaConfig.FertilizerDisplayName, GetFertilizer(), TrentaConfig.GroveFertilizerCapacity, + HoneyStatus()); } /// How much honey is in the crate and how long until the next drop of it. private string HoneyStatus() { - if (m_honeyPrefab == null) return "none (no honey item found)"; + if (m_honeyPrefab == null) return ModText.Get("rov_hover_trenta_honey_none"); Inventory inventory = m_container != null ? m_container.GetInventory() : null; int stored = inventory != null ? CountHoney(inventory) : 0; string status = $"{stored}/{m_honeyCapacity}"; - if (stored >= m_honeyCapacity) return status + ", full"; + if (stored >= m_honeyCapacity) return ModText.Get("rov_hover_trenta_honey_full", status); long stamp = m_nview.GetZDO().GetLong(KeyHoneyTime, 0L); if (stamp == 0L || ZNet.instance == null) return status; double left = m_secPerHoney - (ZNet.instance.GetTime() - new DateTime(stamp)).TotalSeconds; - return status + $", next in {Mathf.Max(1, Mathf.CeilToInt((float)left / 60f))} min"; + return ModText.Get("rov_hover_trenta_honey_next", status, Mathf.Max(1, Mathf.CeilToInt((float)left / 60f))); } // ---------------------------------------------------------------- state diff --git a/JotunnModStub/Trol/TrolTotemBehaviour.cs b/JotunnModStub/Trol/TrolTotemBehaviour.cs index b567f9d..cf040b6 100644 --- a/JotunnModStub/Trol/TrolTotemBehaviour.cs +++ b/JotunnModStub/Trol/TrolTotemBehaviour.cs @@ -276,14 +276,14 @@ namespace RacesOfValheim private string Hover() { - string body = $"warbands {CountGroups()}/{TrolTotem.MaxTroops}"; + string body = ModText.Get("rov_hover_trol_warbands", CountGroups(), TrolTotem.MaxTroops); - if (!IsUpgraded()) body += "\n(a Yagluth drop in hand buys a king's head, and two more bands)"; + if (!IsUpgraded()) body += ModText.Get("rov_hover_trol_yagluth_drop_hand_buys_king"); // The roster lives in the window now, not in the hover - so this only has to get the player // to open it. The hold gesture it used to advertise was unreadable: it cycled faster than // anyone could see what was selected. - body += "\n[$KEY_Use] Call the warbands"; + body += ModText.Get("rov_hover_trol_call_warbands"); return Localization.instance.Localize($"{TrolTotem.PieceDisplayName} ({body})"); } From b555da99f266b9da2700290bb818bf347e950a9e Mon Sep 17 00:00:00 2001 From: kanym Date: Mon, 28 Sep 2026 13:55:45 +0200 Subject: [PATCH 081/290] feat(text): the Tame and Grab Log hover prompts come from translation files Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Aswid/AswidPatches.cs | 2 +- JotunnModStub/Translations/English/hover.json | 2 ++ JotunnModStub/Translations/Italian/hover.json | 2 ++ JotunnModStub/Trol/TrolLogWeapon.cs | 2 +- 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index 9361df9..e2bb353 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -463,7 +463,7 @@ namespace RacesOfValheim // AswidConfig.TameKey) - the hint never matched the working key, and would have // gone stale again the moment that key was rebound. MainKey.ToString() reads back // whatever is actually bound. - __result += $"\n[{AswidConfig.TameKey.Value.MainKey}] Tame"; + __result += ModText.Get("rov_hover_aswid_tame", AswidConfig.TameKey.Value.MainKey); } } } diff --git a/JotunnModStub/Translations/English/hover.json b/JotunnModStub/Translations/English/hover.json index 9c09cb6..daaefdf 100644 --- a/JotunnModStub/Translations/English/hover.json +++ b/JotunnModStub/Translations/English/hover.json @@ -3,6 +3,7 @@ "rov_hover_aswid_dominate_cooldown_m": "[$KEY_Use] Dominate (Cooldown: $1m)", "rov_hover_aswid_follow": "[$KEY_Use] Follow", "rov_hover_aswid_stay": "[$KEY_Use] Stay", + "rov_hover_aswid_tame": "\n[$1] Tame", "rov_hover_butler_no_servant_stands_here_raise": "$1\nNo servant stands here.\n[$KEY_Use] Raise one", "rov_hover_butler_waiting": "Waiting.", "rov_hover_draugh_feed_flesh_or_draugr_s": "\n[$KEY_Use] Feed it flesh, or a draugr's head", @@ -44,6 +45,7 @@ "rov_hover_trenta_ready_empty": "ready: $1 $2\n[$KEY_Use] Empty it", "rov_hover_trenta_rotting_minutes_left": "rotting, $1 minutes left", "rov_hover_trol_call_warbands": "\n[$KEY_Use] Call the warbands", + "rov_hover_trol_grab_log": "\n[$1] Grab Log", "rov_hover_trol_warbands": "warbands $1/$2", "rov_hover_trol_yagluth_drop_hand_buys_king": "\n(a Yagluth drop in hand buys a king's head, and two more bands)", "rov_hover_ward_personal": "Personal", diff --git a/JotunnModStub/Translations/Italian/hover.json b/JotunnModStub/Translations/Italian/hover.json index d332961..01d1d9f 100644 --- a/JotunnModStub/Translations/Italian/hover.json +++ b/JotunnModStub/Translations/Italian/hover.json @@ -3,6 +3,7 @@ "rov_hover_aswid_dominate_cooldown_m": "[$KEY_Use] Domina (ricarica: $1m)", "rov_hover_aswid_follow": "[$KEY_Use] Segui", "rov_hover_aswid_stay": "[$KEY_Use] Resta", + "rov_hover_aswid_tame": "\n[$1] Addomestica", "rov_hover_butler_no_servant_stands_here_raise": "$1\nQui non c'è nessun servitore.\n[$KEY_Use] Fanne alzare uno", "rov_hover_butler_waiting": "In attesa.", "rov_hover_draugh_feed_flesh_or_draugr_s": "\n[$KEY_Use] Nutrilo di carne, o della testa di un draugr", @@ -44,6 +45,7 @@ "rov_hover_trenta_ready_empty": "pronto: $1 $2\n[$KEY_Use] Svuotala", "rov_hover_trenta_rotting_minutes_left": "sta marcendo, mancano $1 minuti", "rov_hover_trol_call_warbands": "\n[$KEY_Use] Chiama le bande da guerra", + "rov_hover_trol_grab_log": "\n[$1] Afferra il tronco", "rov_hover_trol_warbands": "bande da guerra $1/$2", "rov_hover_trol_yagluth_drop_hand_buys_king": "\n(un bottino di Yagluth in mano compra la testa di un re, e altre due bande)", "rov_hover_ward_personal": "Personale", diff --git a/JotunnModStub/Trol/TrolLogWeapon.cs b/JotunnModStub/Trol/TrolLogWeapon.cs index f315494..5480273 100644 --- a/JotunnModStub/Trol/TrolLogWeapon.cs +++ b/JotunnModStub/Trol/TrolLogWeapon.cs @@ -137,7 +137,7 @@ namespace RacesOfValheim if (rightItem != null && rightItem.m_dropPrefab != null && rightItem.m_dropPrefab.name.StartsWith("TrolWeapon_")) return; string key = TrolConfig.GrabLogKey.Value.MainKey.ToString(); - __result += $"\n[{key}] Grab Log"; + __result += ModText.Get("rov_hover_trol_grab_log", key); } } } From 83bade65cbb01b32a949b20280b801bfb0279d0f Mon Sep 17 00:00:00 2001 From: kanym Date: Mon, 28 Sep 2026 15:06:21 +0200 Subject: [PATCH 082/290] fix(trol): True Form no longer switches itself off as it comes on The plugin adds TrolRace itself, but Instance did not know that and built a second copy on first read, so two Updates read every key. Past Fader the True Form key is a toggle: one copy put the form on, the other saw it on in the same frame and took it off. The Trol grew and shrank back with no status. Awake now registers the plugin's copy and removes any other. FurlingRace had the same pattern, harmless there, and gets the same fix. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Furling/FurlingRace.cs | 15 +++++++++++++++ JotunnModStub/Trol/TrolRace.cs | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/JotunnModStub/Furling/FurlingRace.cs b/JotunnModStub/Furling/FurlingRace.cs index bf33e7e..da3c59d 100644 --- a/JotunnModStub/Furling/FurlingRace.cs +++ b/JotunnModStub/Furling/FurlingRace.cs @@ -8,6 +8,21 @@ namespace RacesOfValheim public class FurlingRace : MonoBehaviour { private static FurlingRace _instance; + + // The plugin adds this component itself, so Instance must find that copy rather than build + // a second one on first read. Same fault as TrolRace's, where two Updates reading one key + // switched the True Form off as it came on; here the only per-frame work is idempotent, so + // it had no visible effect, but two copies of a race component is never intended. + private void Awake() + { + if (_instance != null && _instance != this) + { + Destroy(this); + return; + } + _instance = this; + } + public static FurlingRace Instance { get diff --git a/JotunnModStub/Trol/TrolRace.cs b/JotunnModStub/Trol/TrolRace.cs index 591ca5b..e1894ec 100644 --- a/JotunnModStub/Trol/TrolRace.cs +++ b/JotunnModStub/Trol/TrolRace.cs @@ -10,6 +10,24 @@ namespace RacesOfValheim public class TrolRace : MonoBehaviour { private static TrolRace _instance; + + // THE PLUGIN ADDS THIS COMPONENT ITSELF, in RacesOfValheim.Awake, and nothing used to tell + // Instance so. The first read of Instance - CreateModAssets, on every start - found _instance + // empty and built a second TrolRace on a GameObject of its own, and from then on two Updates + // read every key. At Fader and past it the True Form key is a toggle: one copy put the form + // on and began to grow, the other saw the form already on in the same frame, was not itself + // transforming, and took it straight off. The Trol grew and shrank back, with no status and + // - since past Fader there is none - no cooldown. + private void Awake() + { + if (_instance != null && _instance != this) + { + Destroy(this); + return; + } + _instance = this; + } + public static TrolRace Instance { get From 2c5079bf8ce7b24690013d2e3d3110648d070c61 Mon Sep 17 00:00:00 2001 From: kanym Date: Mon, 28 Sep 2026 15:06:22 +0200 Subject: [PATCH 083/290] fix(build): the mod's stations appear under Crafting in Valheim 1.0's build menu Valheim 1.0 lists pieces by Piece.m_usage tags. Jotunn sets only the old category, so a cloned piece kept its source's tags: the Crystal Golem and the Bound Sentry, cloned from guard_stone, landed under Decorations. A postfix on PieceManager.AddPiece now sets the tag from the category for every Hammer piece of this mod. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/PieceUsageTags.cs | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 JotunnModStub/PieceUsageTags.cs diff --git a/JotunnModStub/PieceUsageTags.cs b/JotunnModStub/PieceUsageTags.cs new file mode 100644 index 0000000..d72d926 --- /dev/null +++ b/JotunnModStub/PieceUsageTags.cs @@ -0,0 +1,42 @@ +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; + +namespace RacesOfValheim +{ + /// + /// Puts every Hammer piece of this mod under the right entry of Valheim 1.0's build menu. + /// + /// The 1.0 menu lists pieces by Piece.m_usage, a set of tags (Crafting, Decor, Defense...), and + /// no longer by the old m_category alone. Jotunn's PieceConfig.Category still sets m_category and + /// leaves m_usage untouched, so a cloned piece keeps the tags of whatever it was cloned from. The + /// Crystal Golem and the Bound Sentry are cloned from guard_stone, a decoration, and turned up + /// under Decorations while every other race station sat under Crafting only because their own + /// source pieces happened to be crafting ones. + /// + /// One patch rather than a line at each of the eighteen registrations: every piece goes through + /// PieceManager.AddPiece, and Jotunn has already applied the config's category by then, so the + /// tag is read off that. Other mods' pieces and the cultivator's are left alone. + /// + [HarmonyPatch(typeof(PieceManager), nameof(PieceManager.AddPiece))] + public static class PieceUsageTags + { + public static void Postfix(CustomPiece customPiece) + { + if (customPiece?.Piece == null || customPiece.SourceMod == null) return; + if (customPiece.SourceMod.GUID != RacesOfValheim.PluginGUID) return; + if (customPiece.PieceTable != PieceTables.Hammer) return; + + switch (customPiece.Piece.m_category) + { + case Piece.PieceCategory.Crafting: + customPiece.Piece.m_usage = Piece.UsageTagFlags.Crafting; + break; + case Piece.PieceCategory.Misc: + customPiece.Piece.m_usage = Piece.UsageTagFlags.Misc; + break; + } + } + } +} From 1bd09ed31d072c5b8efdcc5229cc1364ba8abf96 Mon Sep 17 00:00:00 2001 From: kanym Date: Mon, 28 Sep 2026 18:50:54 +0200 Subject: [PATCH 084/290] feat(text): merchants, troops and the hive's shelf come from translation files The faction merchants' 90 jokes, their generic lines and their names now read from merchants.json. Merchant names use the game's own creature tokens where one matches, so they arrive translated in every language Valheim ships; the Dverg keeps a key of its own, since vanilla's token reads "Dvergr Rogue". The Dvergar and Trol troop names and terms, and the Sverm hive's goods, refusals, stage names and brood kinds, follow. Their panels fill TMP texts themselves, so they localize the names where they draw them. The jokes have English text only for now. Co-Authored-By: Claude Opus 5.5 --- JotunnModStub/Dvergar/DvergarBanco.cs | 10 +- JotunnModStub/Dvergar/DvergarBancoStore.cs | 9 +- .../Factions/FactionMerchantCatalog.cs | 24 +-- .../Factions/FactionMerchantJokes.cs | 180 +++++++++--------- .../Factions/FactionMerchantSetup.cs | 6 +- JotunnModStub/Sverm/SvermBrood.cs | 8 +- JotunnModStub/Sverm/SvermHive.cs | 2 +- JotunnModStub/Sverm/SvermHiveGoods.cs | 58 +++--- JotunnModStub/Sverm/SvermHiveStage.cs | 9 +- .../Translations/English/merchants.json | 133 +++++++++++++ .../Translations/Italian/merchants.json | 43 +++++ JotunnModStub/Trol/TrolTotem.cs | 10 +- JotunnModStub/Trol/TrolTotemStore.cs | 7 +- 13 files changed, 332 insertions(+), 167 deletions(-) create mode 100644 JotunnModStub/Translations/English/merchants.json create mode 100644 JotunnModStub/Translations/Italian/merchants.json diff --git a/JotunnModStub/Dvergar/DvergarBanco.cs b/JotunnModStub/Dvergar/DvergarBanco.cs index 98559ee..34ab389 100644 --- a/JotunnModStub/Dvergar/DvergarBanco.cs +++ b/JotunnModStub/Dvergar/DvergarBanco.cs @@ -99,7 +99,7 @@ namespace RacesOfValheim { new Troop { - Id = "escort", Display = "Escort", Price = 400, NeedsUpgrade = false, Icon = "TrophyDvergr", + Id = "escort", Display = "$rov_troop_dvergar_escort", Price = 400, NeedsUpgrade = false, Icon = "TrophyDvergr", Members = new[] { new KeyValuePair("Dverger", 1), @@ -108,7 +108,7 @@ namespace RacesOfValheim }, new Troop { - Id = "yard_patrol", Display = "Yard Patrol", Price = 700, NeedsUpgrade = false, Icon = "TrophyDvergr", + Id = "yard_patrol", Display = "$rov_troop_dvergar_yard_patrol", Price = 700, NeedsUpgrade = false, Icon = "TrophyDvergr", Members = new[] { new KeyValuePair("Dverger", 2), @@ -117,7 +117,7 @@ namespace RacesOfValheim }, new Troop { - Id = "fire_crew", Display = "Fire Crew", Price = 1000, NeedsUpgrade = false, Icon = "TrophyDvergr", + Id = "fire_crew", Display = "$rov_troop_dvergar_fire_crew", Price = 1000, NeedsUpgrade = false, Icon = "TrophyDvergr", Members = new[] { new KeyValuePair("Dverger", 1), @@ -127,7 +127,7 @@ namespace RacesOfValheim }, new Troop { - Id = "runic_crew", Display = "Runic Crew", Price = 1500, NeedsUpgrade = true, Icon = "TrophyDvergr", + Id = "runic_crew", Display = "$rov_troop_dvergar_runic_crew", Price = 1500, NeedsUpgrade = true, Icon = "TrophyDvergr", Members = new[] { new KeyValuePair("Dverger", 2), @@ -137,7 +137,7 @@ namespace RacesOfValheim }, new Troop { - Id = "ash_guard", Display = "Ash Guard", Price = 2000, NeedsUpgrade = true, Icon = "TrophySeekerBrute", + Id = "ash_guard", Display = "$rov_troop_dvergar_ash_guard", Price = 2000, NeedsUpgrade = true, Icon = "TrophySeekerBrute", Members = new[] { new KeyValuePair("DvergerAshlands", 2), diff --git a/JotunnModStub/Dvergar/DvergarBancoStore.cs b/JotunnModStub/Dvergar/DvergarBancoStore.cs index e225ae0..a313f86 100644 --- a/JotunnModStub/Dvergar/DvergarBancoStore.cs +++ b/JotunnModStub/Dvergar/DvergarBancoStore.cs @@ -123,14 +123,14 @@ namespace RacesOfValheim else Jotunn.Logger.LogWarning($"[Dvergar] No icon on '{troop.Icon}' for {troop.Display}; the row " + "keeps whatever the cloned element was showing."); - element.transform.Find("name").GetComponent().text = troop.Display; + element.transform.Find("name").GetComponent().text = Localization.instance.Localize(troop.Display); // The DISCOUNTED price, because that is what will actually leave the player's pocket. TMP_Text price = FindDescendant(element.transform, "price"); if (price != null) price.text = DvergarBanco.PriceFor(troop).ToString(); UITooltip tooltip = element.GetComponent(); - if (tooltip != null) tooltip.Set(troop.Display, Composition(troop), gui.m_tooltipAnchor, default(Vector2)); + if (tooltip != null) tooltip.Set(Localization.instance.Localize(troop.Display), Composition(troop), gui.m_tooltipAnchor, default(Vector2)); string id = troop.Id; element.GetComponent private static readonly ShopDefinition UlvShop = new ShopDefinition { - DisplayName = "Ulv", + DisplayName = "$enemy_ulv", JokeCategory = JokeLupoLicantropo, Items = WithDefaults(new List { @@ -203,7 +203,7 @@ namespace RacesOfValheim private static readonly ShopDefinition FenringShop = new ShopDefinition { - DisplayName = "Fenring", + DisplayName = "$enemy_fenring", JokeCategory = JokeLupoLicantropo, Items = WithDefaults(new List { @@ -216,7 +216,7 @@ namespace RacesOfValheim private static readonly ShopDefinition CultistShop = new ShopDefinition { - DisplayName = "Cultist", + DisplayName = "$enemy_fenringcultist", JokeCategory = JokeStrega, Items = WithDefaults(new List { @@ -228,7 +228,7 @@ namespace RacesOfValheim private static readonly ShopDefinition DvergShop = new ShopDefinition { - DisplayName = "Dverg", + DisplayName = "$rov_merchant_dverg_name", JokeCategory = JokeNano, Items = WithDefaults(new List { @@ -241,7 +241,7 @@ namespace RacesOfValheim private static readonly ShopDefinition DraugrShop = new ShopDefinition { - DisplayName = "Draugr", + DisplayName = "$enemy_draugr", JokeCategory = JokeNonMortoZombie, Items = WithDefaults(new List { @@ -266,7 +266,7 @@ namespace RacesOfValheim private static readonly ShopDefinition SkeletonShop = new ShopDefinition { - DisplayName = "Skeleton", + DisplayName = "$enemy_skeleton", JokeCategory = JokeScheletro, Items = WithDefaults(new List { @@ -284,7 +284,7 @@ namespace RacesOfValheim private static readonly ShopDefinition GhostShop = new ShopDefinition { - DisplayName = "Ghost", + DisplayName = "$enemy_ghost", JokeCategory = JokeFantasma, Items = WithDefaults(new List { @@ -295,7 +295,7 @@ namespace RacesOfValheim private static readonly ShopDefinition WraithShop = new ShopDefinition { - DisplayName = "Wraith", + DisplayName = "$enemy_wraith", JokeCategory = JokeFantasma, Items = WithDefaults(new List { diff --git a/JotunnModStub/Factions/FactionMerchantJokes.cs b/JotunnModStub/Factions/FactionMerchantJokes.cs index ca811e9..8c38aaa 100644 --- a/JotunnModStub/Factions/FactionMerchantJokes.cs +++ b/JotunnModStub/Factions/FactionMerchantJokes.cs @@ -11,120 +11,120 @@ namespace RacesOfValheim { [FactionMerchantCatalog.JokeScheletro] = new[] { - "What do you call a skeleton who never does his chores? Lazy bones.", - "Why did the skeleton quit his job? His heart wasn't in it.", - "What skeleton was the first emperor of France? Napoleon Bone-aparte.", - "Who is the world's most famous skeleton detective? Sherlock Bones.", - "What did the French skeletons say before eating their dinner? Bone appetit!", - "What do skeletons always order when they go to a restaurant? Spare ribs.", - "How do skeletons call each other? On their tele-bone.", - "What's a skeleton's favorite fruit? Bone-ana!", - "Why are skeletons bad at lying? You can see right through them!", - "Why don't skeletons fight each other? They don't have the guts.", + "$rov_joke_scheletro_01", + "$rov_joke_scheletro_02", + "$rov_joke_scheletro_03", + "$rov_joke_scheletro_04", + "$rov_joke_scheletro_05", + "$rov_joke_scheletro_06", + "$rov_joke_scheletro_07", + "$rov_joke_scheletro_08", + "$rov_joke_scheletro_09", + "$rov_joke_scheletro_10", }, [FactionMerchantCatalog.JokeNonMortoZombie] = new[] { - "When do zombies go to sleep? When they are dead tired.", - "What streets do zombies live on? Dead ends.", - "Where do zombies go sailing? Lake Eerie.", - "What do you call a zombie in pajamas? The sleepwalking dead.", - "How are zombies like computers? They use mega-bites!", - "Why did the zombie lose his lawsuit? He had no leg to stand on!", - "Why did the zombie eat a light bulb? Because he wanted a light snack.", - "Why don't zombies eat clowns? Because they taste funny!", - "Why did the zombie go to school? To improve his brainpower.", - "Zombies are hopeless romantics, seeking their ghoul-mate.", + "$rov_joke_nonmortozombie_01", + "$rov_joke_nonmortozombie_02", + "$rov_joke_nonmortozombie_03", + "$rov_joke_nonmortozombie_04", + "$rov_joke_nonmortozombie_05", + "$rov_joke_nonmortozombie_06", + "$rov_joke_nonmortozombie_07", + "$rov_joke_nonmortozombie_08", + "$rov_joke_nonmortozombie_09", + "$rov_joke_nonmortozombie_10", }, [FactionMerchantCatalog.JokeFantasma] = new[] { - "Why was the ghost lonely? It had no-body.", - "What's the most useless room in a house for a ghost? A living room.", - "What's a ghost's favourite cheese? Ghoul-da cheese.", - "What's a ghost's favourite food? Boo-rritos.", - "What's a ghost's favourite dessert? I-scream.", - "What's a ghost's favourite game? Hide and Shriek.", - "What do you call a ghost with a broken leg? A hoblin goblin.", - "What happens when a ghost gets lost in the fog? He is mist.", - "Ghosts love elevators because it lifts their spirits.", - "Why did the ghost cross the road? Because it was a poultry-geist.", + "$rov_joke_fantasma_01", + "$rov_joke_fantasma_02", + "$rov_joke_fantasma_03", + "$rov_joke_fantasma_04", + "$rov_joke_fantasma_05", + "$rov_joke_fantasma_06", + "$rov_joke_fantasma_07", + "$rov_joke_fantasma_08", + "$rov_joke_fantasma_09", + "$rov_joke_fantasma_10", }, [FactionMerchantCatalog.JokeTroll] = new[] { - "Why do trolls love bridges? They're always crossing into new territory.", - "Why did the troll get a bad grade? He was always under the bridge of understanding.", - "Trolls don't watch TV - they stream mischief.", - "Trolls love parties - they bring the bridge snacks.", - "Trolls hate Mondays - they bridge the gap to Friday.", - "Where do trolls keep their money? Under the bridge, of course.", - "What's a troll's favorite candy? Bridge bars.", - "Why did the troll go to school? To bridge the knowledge gap.", - "What's a troll's favorite movie? The Bridge Runner.", - "What makes a troll laugh? Someone taking it seriously.", + "$rov_joke_troll_01", + "$rov_joke_troll_02", + "$rov_joke_troll_03", + "$rov_joke_troll_04", + "$rov_joke_troll_05", + "$rov_joke_troll_06", + "$rov_joke_troll_07", + "$rov_joke_troll_08", + "$rov_joke_troll_09", + "$rov_joke_troll_10", }, [FactionMerchantCatalog.JokeNano] = new[] { - "A dwarf who loved gardening had a real green thumbelina.", - "Dwarves make excellent bakers; their scone courses are always the shortest.", - "Why do dwarfs make great secret agents? They can really keep things low-key.", - "A dwarf walks into a bar and hits his head - the bar was set too low.", - "Why are dwarfs so good at math? Because it's the little things that count.", - "I saw a dwarf climbing down a prison wall - it was a little condescending.", - "What do dwarfs use to fight trolls? Short swords.", - "What's a dwarf warrior's motto? Small but deadly.", - "A dwarf opened a bakery because he kneaded dough at his level.", - "What do you call a dwarf who can be invisible? A short circuit!", + "$rov_joke_nano_01", + "$rov_joke_nano_02", + "$rov_joke_nano_03", + "$rov_joke_nano_04", + "$rov_joke_nano_05", + "$rov_joke_nano_06", + "$rov_joke_nano_07", + "$rov_joke_nano_08", + "$rov_joke_nano_09", + "$rov_joke_nano_10", }, [FactionMerchantCatalog.JokeLupoLicantropo] = new[] { - "Why did the werewolf laugh while chewing on the skeleton? He got to the funny bone.", - "Why did the werewolf need to talk with the skeleton? He had a bone to pick with him.", - "A what-to-wear-wolf.", - "My werewolf skills are claw-some.", - "'Howl'-oween, hands down - a werewolf's favorite holiday.", - "Why don't werewolves use cell phones? Because they prefer to roam.", - "Why did the werewolf sit in the corner? He didn't want to be spotted.", - "Why don't werewolves gossip? They can't keep a straight paw.", - "You're fur-ociously awesome.", - "Howl you doin' tonight?", + "$rov_joke_lupolicantropo_01", + "$rov_joke_lupolicantropo_02", + "$rov_joke_lupolicantropo_03", + "$rov_joke_lupolicantropo_04", + "$rov_joke_lupolicantropo_05", + "$rov_joke_lupolicantropo_06", + "$rov_joke_lupolicantropo_07", + "$rov_joke_lupolicantropo_08", + "$rov_joke_lupolicantropo_09", + "$rov_joke_lupolicantropo_10", }, [FactionMerchantCatalog.JokeStrega] = new[] { - "Resting witch face.", - "Hag a nice day.", - "What do you call a mage in the desert? A sand-witch.", - "What happens to witches who break the rules at school? They get ex-spelled.", - "What do witches put in their hair? Scare spray.", - "Why did three witches call in the plumber? Hubble, bubble, toilet trouble.", - "Why couldn't the little witch read her spellbook? It was written in curse-ive.", - "Why did the witch become a lawyer? She wanted to practice witchcraft.", - "Witches don't fart. They cast smells.", - "A witch tells the time by looking at her witch watch.", + "$rov_joke_strega_01", + "$rov_joke_strega_02", + "$rov_joke_strega_03", + "$rov_joke_strega_04", + "$rov_joke_strega_05", + "$rov_joke_strega_06", + "$rov_joke_strega_07", + "$rov_joke_strega_08", + "$rov_joke_strega_09", + "$rov_joke_strega_10", }, [FactionMerchantCatalog.JokeLegnoFalegname] = new[] { - "Carpenters nail it every time: that's their true calling.", - "I told my saw a joke: it couldn't handle the cut.", - "I dated a carpenter once: it was a solid relationship.", - "Carpenters have great timing: they always measure up.", - "My friend builds furniture: he really wood make you laugh.", - "A good carpenter never quits: he just saws what he started.", - "I asked the wood if it was okay: it said, 'I'm board.'", - "I made a joke about a piece of wood, but it was too plane.", - "How do trees access the internet? They just log on!", - "Why did the plank cross the road? To get to the other siding!", + "$rov_joke_legnofalegname_01", + "$rov_joke_legnofalegname_02", + "$rov_joke_legnofalegname_03", + "$rov_joke_legnofalegname_04", + "$rov_joke_legnofalegname_05", + "$rov_joke_legnofalegname_06", + "$rov_joke_legnofalegname_07", + "$rov_joke_legnofalegname_08", + "$rov_joke_legnofalegname_09", + "$rov_joke_legnofalegname_10", }, [FactionMerchantCatalog.JokeGoblin] = new[] { - "Those goblin fingers are dexter-gnome-us.", - "Why did the goblin break the vase? He wanted to smash expectations.", - "That goblin really gnome-napped my sandwich.", - "Just goblin around.", - "They love orc-strating trouble.", - "If a goblin smiles at you, check your pockets.", - "Why don't goblins shower? They prefer natural grime.", - "What's a goblin's favorite sport? Lootball.", - "How do goblins shop? Five-finger discount only.", - "What's a goblin's password? 'MineMineMine!'", + "$rov_joke_goblin_01", + "$rov_joke_goblin_02", + "$rov_joke_goblin_03", + "$rov_joke_goblin_04", + "$rov_joke_goblin_05", + "$rov_joke_goblin_06", + "$rov_joke_goblin_07", + "$rov_joke_goblin_08", + "$rov_joke_goblin_09", + "$rov_joke_goblin_10", }, }; } diff --git a/JotunnModStub/Factions/FactionMerchantSetup.cs b/JotunnModStub/Factions/FactionMerchantSetup.cs index abe283a..6c973db 100644 --- a/JotunnModStub/Factions/FactionMerchantSetup.cs +++ b/JotunnModStub/Factions/FactionMerchantSetup.cs @@ -16,9 +16,9 @@ namespace RacesOfValheim private static readonly string[] GenericGreets = { "..." }; private static readonly string[] GenericGoodbye = { "..." }; - private static readonly string[] GenericStartTrade = { "What do you need?" }; - private static readonly string[] GenericBuy = { "Deal." }; - private static readonly string[] GenericSell = { "Thanks." }; + private static readonly string[] GenericStartTrade = { "$rov_merchant_start_trade" }; + private static readonly string[] GenericBuy = { "$rov_merchant_buy" }; + private static readonly string[] GenericSell = { "$rov_merchant_sell" }; public static void Postfix(Character __instance) { diff --git a/JotunnModStub/Sverm/SvermBrood.cs b/JotunnModStub/Sverm/SvermBrood.cs index be162e4..a77e0ac 100644 --- a/JotunnModStub/Sverm/SvermBrood.cs +++ b/JotunnModStub/Sverm/SvermBrood.cs @@ -51,10 +51,10 @@ namespace RacesOfValheim /// public static readonly List Roster = new List { - new Kind { Id = "brood", Display = "Brood", Source = "SeekerBrood", Icon = "TrophySeeker", Price = 100f, Stage = 1, Cooldown = 60f }, - new Kind { Id = "seeker", Display = "Seeker", Source = "Seeker", Icon = "TrophySeeker", Price = 250f, Stage = 2, Cooldown = 150f }, - new Kind { Id = "soldier", Display = "Soldier", Source = "SeekerBrute", Icon = "TrophySeekerBrute", Price = 500f, Stage = 3, Cooldown = 300f }, - new Kind { Id = "gjall", Display = "Gjall", Source = "Gjall", Icon = "TrophyGjall", Price = 1000f, Stage = 4, Cooldown = 600f, SpawnHeight = 10f }, + new Kind { Id = "brood", Display = "$rov_troop_sverm_brood", Source = "SeekerBrood", Icon = "TrophySeeker", Price = 100f, Stage = 1, Cooldown = 60f }, + new Kind { Id = "seeker", Display = "$rov_troop_sverm_seeker", Source = "Seeker", Icon = "TrophySeeker", Price = 250f, Stage = 2, Cooldown = 150f }, + new Kind { Id = "soldier", Display = "$rov_troop_sverm_soldier", Source = "SeekerBrute", Icon = "TrophySeekerBrute", Price = 500f, Stage = 3, Cooldown = 300f }, + new Kind { Id = "gjall", Display = "$rov_troop_sverm_gjall", Source = "Gjall", Icon = "TrophyGjall", Price = 1000f, Stage = 4, Cooldown = 600f, SpawnHeight = 10f }, }; private static int CapOf(string id) diff --git a/JotunnModStub/Sverm/SvermHive.cs b/JotunnModStub/Sverm/SvermHive.cs index 5470162..cc30a09 100644 --- a/JotunnModStub/Sverm/SvermHive.cs +++ b/JotunnModStub/Sverm/SvermHive.cs @@ -468,7 +468,7 @@ namespace RacesOfValheim // serialised m_hoverOffset, which is 0 unless the prefab sets one, so 0 is vanilla behaviour. public float GetHoverOffset() => 0f; - public string GetHoverName() => SvermHiveStage.NameOf(SvermHiveStage.Of(transform)); + public string GetHoverName() => Localization.instance.Localize(SvermHiveStage.NameOf(SvermHiveStage.Of(transform))); private ZNetView nview; private float nextSweep; diff --git a/JotunnModStub/Sverm/SvermHiveGoods.cs b/JotunnModStub/Sverm/SvermHiveGoods.cs index 7ba51e6..6284a2d 100644 --- a/JotunnModStub/Sverm/SvermHiveGoods.cs +++ b/JotunnModStub/Sverm/SvermHiveGoods.cs @@ -68,13 +68,11 @@ namespace RacesOfValheim StageUpgrade(3, "TrophySeekerBrute"), StageUpgrade(4, "TrophySeekerQueen"), - Star(1, "Surrenal Glands", 800f, "TrophySeeker", - "Every troop hatched from now on is born with one star.\n\n" + - "It does nothing for the ones already walking around: what is born is born."), + Star(1, ModText.Get("rov_sverm_good_glands_name"), 800f, "TrophySeeker", + ModText.Get("rov_sverm_good_glands_desc")), - Star(2, "Hyperplasia", 1600f, "TrophySeekerQueen", - "Every troop hatched from now on is born with two stars.\n\n" + - "The colony has to have grown the glands first."), + Star(2, ModText.Get("rov_sverm_good_hyperplasia_name"), 1600f, "TrophySeekerQueen", + ModText.Get("rov_sverm_good_hyperplasia_desc")), }; foreach (SvermBrood.Kind kind in SvermBrood.Roster) shelf.Add(Troop(kind)); @@ -94,23 +92,20 @@ namespace RacesOfValheim return new Good { Id = "blistertick", - Name = SvermBlisterTick.DisplayName, + Name = Localization.instance.Localize(SvermBlisterTick.DisplayName), Price = SvermConfig.TickPrice, Icon = "TrophyTick", - Description = "Buys a PERMANENT slot in the colony. What stands in it runs at whatever " + - "the colony is fighting and bursts, and thirty seconds later the nest " + - "grows another one - no egg, no biomass, forever.\n\n" + - "The blast spares you, your tames and the rest of the colony.", + Description = ModText.Get("rov_sverm_good_tick_desc"), Refusal = hive => { int slots = SvermBlisterTick.SlotsOf(hive.transform); if (slots >= SvermConfigManagement.BlisterTick) { - return $"The colony already keeps {slots} of them."; + return ModText.Get("rov_sverm_refusal_keeps", slots); } - if (SvermBroodEggs.Count(hive.transform) < 1) return "No brood egg ready."; + if (SvermBroodEggs.Count(hive.transform) < 1) return ModText.Get("rov_sverm_refusal_no_egg"); return null; }, @@ -143,20 +138,17 @@ namespace RacesOfValheim return new Good { Id = "stage" + target, - Name = SvermHiveStage.NameOf(target), + Name = Localization.instance.Localize(SvermHiveStage.NameOf(target)), Price = SvermHiveStage.PriceToLeave(from), Icon = icon, - Description = $"Grows the nest into a {SvermHiveStage.NameOf(target)}: it holds " + - $"{SvermHiveStage.Capacity(target):0} biomass instead of " + - $"{SvermHiveStage.Capacity(from):0}, and stands half again as tall.\n\n" + - "It costs this stage's whole tankful, so it leaves the hive all but " + - "empty. Grow or field an army - never both in the same breath.", + Description = ModText.Get("rov_sverm_good_stage_desc", SvermHiveStage.NameOf(target), + SvermHiveStage.Capacity(target).ToString("0"), SvermHiveStage.Capacity(from).ToString("0")), Refusal = hive => { int stage = SvermHiveStage.Of(hive.transform); - if (stage > from) return "Already grown past this."; - if (stage < from) return $"The nest has to be a {SvermHiveStage.NameOf(from)} first."; + if (stage > from) return ModText.Get("rov_sverm_refusal_grown_past"); + if (stage < from) return ModText.Get("rov_sverm_refusal_stage_first", SvermHiveStage.NameOf(from)); return null; }, @@ -187,8 +179,8 @@ namespace RacesOfValheim Refusal = hive => { int have = SvermBroodStars.Of(hive.transform); - if (have >= stars) return "The colony already breeds like this."; - if (have < stars - 1) return "One star at a time."; + if (have >= stars) return ModText.Get("rov_sverm_refusal_already_breeds"); + if (have < stars - 1) return ModText.Get("rov_sverm_refusal_one_star"); return null; }, @@ -208,25 +200,23 @@ namespace RacesOfValheim return new Good { Id = "troop_" + kind.Id, - Name = kind.Display, + Name = Localization.instance.Localize(kind.Display), Price = kind.Price, Icon = kind.Icon, - Description = $"Hatches a {kind.Display}, bound to this nest: it follows when you ask, " + - $"walks home when you let it go, and mends itself.\n\n" + - $"Costs one brood egg as well as the biomass. At most {kind.Cap} of them alive at once.", + Description = ModText.Get("rov_sverm_good_troop_desc", kind.Display, kind.Cap), Refusal = hive => { int stage = SvermHiveStage.Of(hive.transform); if (stage < kind.Stage) { - return $"The nest has to be a {SvermHiveStage.NameOf(kind.Stage)} first."; + return ModText.Get("rov_sverm_refusal_stage_first", SvermHiveStage.NameOf(kind.Stage)); } int alive = SvermBrood.CountAlive(hive, kind); - if (alive >= kind.Cap) return $"The colony is already keeping {alive} of them."; + if (alive >= kind.Cap) return ModText.Get("rov_sverm_refusal_keeping", alive); - if (SvermBroodEggs.Count(hive.transform) < 1) return "No brood egg ready."; + if (SvermBroodEggs.Count(hive.transform) < 1) return ModText.Get("rov_sverm_refusal_no_egg"); return null; }, @@ -265,7 +255,7 @@ namespace RacesOfValheim /// public static string RefusalFor(Good good, SvermHiveBehaviour hive) { - if (good == null || hive == null) return "No hive."; + if (good == null || hive == null) return ModText.Get("rov_sverm_refusal_no_hive"); string ownRefusal = good.Refusal != null ? good.Refusal(hive) : null; if (ownRefusal != null) return ownRefusal; @@ -274,11 +264,11 @@ namespace RacesOfValheim if (waitingSeconds > 0L) { return waitingSeconds >= 60L - ? $"The hive is still working on the last one ({waitingSeconds / 60}m)." - : $"The hive is still working on the last one ({waitingSeconds}s)."; + ? ModText.Get("rov_sverm_refusal_working_m", waitingSeconds / 60) + : ModText.Get("rov_sverm_refusal_working_s", waitingSeconds); } - if (SvermBiomass.Bank(hive.transform) < good.Price) return "Not enough biomass in the bank."; + if (SvermBiomass.Bank(hive.transform) < good.Price) return ModText.Get("rov_msg_sverm_not_enough_biomass_bank"); return null; } diff --git a/JotunnModStub/Sverm/SvermHiveStage.cs b/JotunnModStub/Sverm/SvermHiveStage.cs index 1ccbb8a..09f8b32 100644 --- a/JotunnModStub/Sverm/SvermHiveStage.cs +++ b/JotunnModStub/Sverm/SvermHiveStage.cs @@ -27,12 +27,13 @@ namespace RacesOfValheim public const int Last = 4; /// The four names from section 2. The piece is registered under the first one. + /// Translation tokens, not text: localize them wherever they are shown. public static readonly string[] Names = { - "Brood Mound", - "Gorged Hive", - "Nesting Spire", - "Hive Citadel", + "$rov_piece_sverm_broodmound_name", + "$rov_sverm_stage_gorgedhive", + "$rov_sverm_stage_nestingspire", + "$rov_sverm_stage_hivecitadel", }; public static int Of(Transform nest) diff --git a/JotunnModStub/Translations/English/merchants.json b/JotunnModStub/Translations/English/merchants.json new file mode 100644 index 0000000..3b40204 --- /dev/null +++ b/JotunnModStub/Translations/English/merchants.json @@ -0,0 +1,133 @@ +{ + "rov_joke_fantasma_01": "Why was the ghost lonely? It had no-body.", + "rov_joke_fantasma_02": "What's the most useless room in a house for a ghost? A living room.", + "rov_joke_fantasma_03": "What's a ghost's favourite cheese? Ghoul-da cheese.", + "rov_joke_fantasma_04": "What's a ghost's favourite food? Boo-rritos.", + "rov_joke_fantasma_05": "What's a ghost's favourite dessert? I-scream.", + "rov_joke_fantasma_06": "What's a ghost's favourite game? Hide and Shriek.", + "rov_joke_fantasma_07": "What do you call a ghost with a broken leg? A hoblin goblin.", + "rov_joke_fantasma_08": "What happens when a ghost gets lost in the fog? He is mist.", + "rov_joke_fantasma_09": "Ghosts love elevators because it lifts their spirits.", + "rov_joke_fantasma_10": "Why did the ghost cross the road? Because it was a poultry-geist.", + "rov_joke_goblin_01": "Those goblin fingers are dexter-gnome-us.", + "rov_joke_goblin_02": "Why did the goblin break the vase? He wanted to smash expectations.", + "rov_joke_goblin_03": "That goblin really gnome-napped my sandwich.", + "rov_joke_goblin_04": "Just goblin around.", + "rov_joke_goblin_05": "They love orc-strating trouble.", + "rov_joke_goblin_06": "If a goblin smiles at you, check your pockets.", + "rov_joke_goblin_07": "Why don't goblins shower? They prefer natural grime.", + "rov_joke_goblin_08": "What's a goblin's favorite sport? Lootball.", + "rov_joke_goblin_09": "How do goblins shop? Five-finger discount only.", + "rov_joke_goblin_10": "What's a goblin's password? 'MineMineMine!'", + "rov_joke_legnofalegname_01": "Carpenters nail it every time: that's their true calling.", + "rov_joke_legnofalegname_02": "I told my saw a joke: it couldn't handle the cut.", + "rov_joke_legnofalegname_03": "I dated a carpenter once: it was a solid relationship.", + "rov_joke_legnofalegname_04": "Carpenters have great timing: they always measure up.", + "rov_joke_legnofalegname_05": "My friend builds furniture: he really wood make you laugh.", + "rov_joke_legnofalegname_06": "A good carpenter never quits: he just saws what he started.", + "rov_joke_legnofalegname_07": "I asked the wood if it was okay: it said, 'I'm board.'", + "rov_joke_legnofalegname_08": "I made a joke about a piece of wood, but it was too plane.", + "rov_joke_legnofalegname_09": "How do trees access the internet? They just log on!", + "rov_joke_legnofalegname_10": "Why did the plank cross the road? To get to the other siding!", + "rov_joke_lupolicantropo_01": "Why did the werewolf laugh while chewing on the skeleton? He got to the funny bone.", + "rov_joke_lupolicantropo_02": "Why did the werewolf need to talk with the skeleton? He had a bone to pick with him.", + "rov_joke_lupolicantropo_03": "A what-to-wear-wolf.", + "rov_joke_lupolicantropo_04": "My werewolf skills are claw-some.", + "rov_joke_lupolicantropo_05": "'Howl'-oween, hands down - a werewolf's favorite holiday.", + "rov_joke_lupolicantropo_06": "Why don't werewolves use cell phones? Because they prefer to roam.", + "rov_joke_lupolicantropo_07": "Why did the werewolf sit in the corner? He didn't want to be spotted.", + "rov_joke_lupolicantropo_08": "Why don't werewolves gossip? They can't keep a straight paw.", + "rov_joke_lupolicantropo_09": "You're fur-ociously awesome.", + "rov_joke_lupolicantropo_10": "Howl you doin' tonight?", + "rov_joke_nano_01": "A dwarf who loved gardening had a real green thumbelina.", + "rov_joke_nano_02": "Dwarves make excellent bakers; their scone courses are always the shortest.", + "rov_joke_nano_03": "Why do dwarfs make great secret agents? They can really keep things low-key.", + "rov_joke_nano_04": "A dwarf walks into a bar and hits his head - the bar was set too low.", + "rov_joke_nano_05": "Why are dwarfs so good at math? Because it's the little things that count.", + "rov_joke_nano_06": "I saw a dwarf climbing down a prison wall - it was a little condescending.", + "rov_joke_nano_07": "What do dwarfs use to fight trolls? Short swords.", + "rov_joke_nano_08": "What's a dwarf warrior's motto? Small but deadly.", + "rov_joke_nano_09": "A dwarf opened a bakery because he kneaded dough at his level.", + "rov_joke_nano_10": "What do you call a dwarf who can be invisible? A short circuit!", + "rov_joke_nonmortozombie_01": "When do zombies go to sleep? When they are dead tired.", + "rov_joke_nonmortozombie_02": "What streets do zombies live on? Dead ends.", + "rov_joke_nonmortozombie_03": "Where do zombies go sailing? Lake Eerie.", + "rov_joke_nonmortozombie_04": "What do you call a zombie in pajamas? The sleepwalking dead.", + "rov_joke_nonmortozombie_05": "How are zombies like computers? They use mega-bites!", + "rov_joke_nonmortozombie_06": "Why did the zombie lose his lawsuit? He had no leg to stand on!", + "rov_joke_nonmortozombie_07": "Why did the zombie eat a light bulb? Because he wanted a light snack.", + "rov_joke_nonmortozombie_08": "Why don't zombies eat clowns? Because they taste funny!", + "rov_joke_nonmortozombie_09": "Why did the zombie go to school? To improve his brainpower.", + "rov_joke_nonmortozombie_10": "Zombies are hopeless romantics, seeking their ghoul-mate.", + "rov_joke_scheletro_01": "What do you call a skeleton who never does his chores? Lazy bones.", + "rov_joke_scheletro_02": "Why did the skeleton quit his job? His heart wasn't in it.", + "rov_joke_scheletro_03": "What skeleton was the first emperor of France? Napoleon Bone-aparte.", + "rov_joke_scheletro_04": "Who is the world's most famous skeleton detective? Sherlock Bones.", + "rov_joke_scheletro_05": "What did the French skeletons say before eating their dinner? Bone appetit!", + "rov_joke_scheletro_06": "What do skeletons always order when they go to a restaurant? Spare ribs.", + "rov_joke_scheletro_07": "How do skeletons call each other? On their tele-bone.", + "rov_joke_scheletro_08": "What's a skeleton's favorite fruit? Bone-ana!", + "rov_joke_scheletro_09": "Why are skeletons bad at lying? You can see right through them!", + "rov_joke_scheletro_10": "Why don't skeletons fight each other? They don't have the guts.", + "rov_joke_strega_01": "Resting witch face.", + "rov_joke_strega_02": "Hag a nice day.", + "rov_joke_strega_03": "What do you call a mage in the desert? A sand-witch.", + "rov_joke_strega_04": "What happens to witches who break the rules at school? They get ex-spelled.", + "rov_joke_strega_05": "What do witches put in their hair? Scare spray.", + "rov_joke_strega_06": "Why did three witches call in the plumber? Hubble, bubble, toilet trouble.", + "rov_joke_strega_07": "Why couldn't the little witch read her spellbook? It was written in curse-ive.", + "rov_joke_strega_08": "Why did the witch become a lawyer? She wanted to practice witchcraft.", + "rov_joke_strega_09": "Witches don't fart. They cast smells.", + "rov_joke_strega_10": "A witch tells the time by looking at her witch watch.", + "rov_joke_troll_01": "Why do trolls love bridges? They're always crossing into new territory.", + "rov_joke_troll_02": "Why did the troll get a bad grade? He was always under the bridge of understanding.", + "rov_joke_troll_03": "Trolls don't watch TV - they stream mischief.", + "rov_joke_troll_04": "Trolls love parties - they bring the bridge snacks.", + "rov_joke_troll_05": "Trolls hate Mondays - they bridge the gap to Friday.", + "rov_joke_troll_06": "Where do trolls keep their money? Under the bridge, of course.", + "rov_joke_troll_07": "What's a troll's favorite candy? Bridge bars.", + "rov_joke_troll_08": "Why did the troll go to school? To bridge the knowledge gap.", + "rov_joke_troll_09": "What's a troll's favorite movie? The Bridge Runner.", + "rov_joke_troll_10": "What makes a troll laugh? Someone taking it seriously.", + "rov_merchant_buy": "Deal.", + "rov_merchant_dverg_name": "Dverg", + "rov_merchant_sell": "Thanks.", + "rov_merchant_start_trade": "What do you need?", + "rov_sverm_good_glands_desc": "Every troop hatched from now on is born with one star.\n\nIt does nothing for the ones already walking around: what is born is born.", + "rov_sverm_good_glands_name": "Surrenal Glands", + "rov_sverm_good_hyperplasia_desc": "Every troop hatched from now on is born with two stars.\n\nThe colony has to have grown the glands first.", + "rov_sverm_good_hyperplasia_name": "Hyperplasia", + "rov_sverm_good_stage_desc": "Grows the nest into a $1: it holds $2 biomass instead of $3, and stands half again as tall.\n\nIt costs this stage's whole tankful, so it leaves the hive all but empty. Grow or field an army - never both in the same breath.", + "rov_sverm_good_tick_desc": "Buys a PERMANENT slot in the colony. What stands in it runs at whatever the colony is fighting and bursts, and thirty seconds later the nest grows another one - no egg, no biomass, forever.\n\nThe blast spares you, your tames and the rest of the colony.", + "rov_sverm_good_troop_desc": "Hatches a $1, bound to this nest: it follows when you ask, walks home when you let it go, and mends itself.\n\nCosts one brood egg as well as the biomass. At most $2 of them alive at once.", + "rov_sverm_refusal_already_breeds": "The colony already breeds like this.", + "rov_sverm_refusal_grown_past": "Already grown past this.", + "rov_sverm_refusal_keeping": "The colony is already keeping $1 of them.", + "rov_sverm_refusal_keeps": "The colony already keeps $1 of them.", + "rov_sverm_refusal_no_egg": "No brood egg ready.", + "rov_sverm_refusal_no_hive": "No hive.", + "rov_sverm_refusal_one_star": "One star at a time.", + "rov_sverm_refusal_stage_first": "The nest has to be a $1 first.", + "rov_sverm_refusal_working_m": "The hive is still working on the last one ($1m).", + "rov_sverm_refusal_working_s": "The hive is still working on the last one ($1s).", + "rov_sverm_stage_gorgedhive": "Gorged Hive", + "rov_sverm_stage_hivecitadel": "Hive Citadel", + "rov_sverm_stage_nestingspire": "Nesting Spire", + "rov_troop_dvergar_ash_guard": "Ash Guard", + "rov_troop_dvergar_escort": "Escort", + "rov_troop_dvergar_fire_crew": "Fire Crew", + "rov_troop_dvergar_runic_crew": "Runic Crew", + "rov_troop_dvergar_seal_price": "List price $1 - your seal takes it to $2.", + "rov_troop_dvergar_terms": "They answer the follow command, knit their own wounds shut, keep your truce with the mountain's dvergr, drop nothing, and do not come back. A dead crew is money spent.", + "rov_troop_dvergar_yard_patrol": "Yard Patrol", + "rov_troop_sverm_brood": "Brood", + "rov_troop_sverm_gjall": "Gjall", + "rov_troop_sverm_seeker": "Seeker", + "rov_troop_sverm_soldier": "Soldier", + "rov_troop_trol_goblin_band": "Fuling War Band", + "rov_troop_trol_goblin_patrol": "Fuling Patrol", + "rov_troop_trol_greydwarf_patrol": "Greydwarf Patrol", + "rov_troop_trol_terms": "They answer the follow command, knit their own wounds shut, drop nothing, and do not come back. A dead warband is money spent.", + "rov_troop_trol_troll": "Troll", + "rov_troop_trol_troll_summoned": "Staff Troll" +} diff --git a/JotunnModStub/Translations/Italian/merchants.json b/JotunnModStub/Translations/Italian/merchants.json new file mode 100644 index 0000000..2c9fc31 --- /dev/null +++ b/JotunnModStub/Translations/Italian/merchants.json @@ -0,0 +1,43 @@ +{ + "rov_merchant_buy": "Affare fatto.", + "rov_merchant_dverg_name": "Dverg", + "rov_merchant_sell": "Grazie.", + "rov_merchant_start_trade": "Di cosa hai bisogno?", + "rov_sverm_good_glands_desc": "Da ora ogni truppa che si schiude nasce con una stella.\n\nNon cambia niente per quelle che già camminano: ciò che è nato è nato.", + "rov_sverm_good_glands_name": "Ghiandole surrenali", + "rov_sverm_good_hyperplasia_desc": "Da ora ogni truppa che si schiude nasce con due stelle.\n\nPrima la colonia deve aver sviluppato le ghiandole.", + "rov_sverm_good_hyperplasia_name": "Iperplasia", + "rov_sverm_good_stage_desc": "Fa crescere il nido fino a $1: contiene $2 di biomassa invece di $3, ed è alto una volta e mezza.\n\nCosta l'intera riserva di questo stadio, quindi lascia l'alveare quasi vuoto. Cresci o schiera un esercito: mai entrambe le cose insieme.", + "rov_sverm_good_tick_desc": "Compra un posto PERMANENTE nella colonia. Ciò che lo occupa corre contro chiunque la colonia stia combattendo ed esplode, e trenta secondi dopo il nido ne fa crescere un altro: niente uovo, niente biomassa, per sempre.\n\nL'esplosione risparmia te, le tue creature addomesticate e il resto della colonia.", + "rov_sverm_good_troop_desc": "Fa schiudere: $1, legato a questo nido. Ti segue quando glielo chiedi, torna a casa quando lo lasci andare e si ripara da solo.\n\nCosta un uovo della covata oltre alla biomassa. Al massimo $2 vivi alla volta.", + "rov_sverm_refusal_already_breeds": "La colonia si riproduce già così.", + "rov_sverm_refusal_grown_past": "Già cresciuto oltre questo stadio.", + "rov_sverm_refusal_keeping": "La colonia ne sta già tenendo $1.", + "rov_sverm_refusal_keeps": "La colonia ne tiene già $1.", + "rov_sverm_refusal_no_egg": "Nessun uovo della covata pronto.", + "rov_sverm_refusal_no_hive": "Nessun alveare.", + "rov_sverm_refusal_one_star": "Una stella alla volta.", + "rov_sverm_refusal_stage_first": "Prima il nido deve diventare: $1.", + "rov_sverm_refusal_working_m": "L'alveare sta ancora lavorando all'ultimo ($1m).", + "rov_sverm_refusal_working_s": "L'alveare sta ancora lavorando all'ultimo ($1s).", + "rov_sverm_stage_gorgedhive": "Alveare rigonfio", + "rov_sverm_stage_hivecitadel": "Cittadella dell'alveare", + "rov_sverm_stage_nestingspire": "Guglia del nido", + "rov_troop_dvergar_ash_guard": "Guardia di cenere", + "rov_troop_dvergar_escort": "Scorta", + "rov_troop_dvergar_fire_crew": "Squadra del fuoco", + "rov_troop_dvergar_runic_crew": "Squadra runica", + "rov_troop_dvergar_seal_price": "Prezzo di listino $1: il tuo sigillo lo porta a $2.", + "rov_troop_dvergar_terms": "Rispondono al comando di seguirti, si ricuciono da soli le ferite, rispettano la tua tregua con i dvergr della montagna, non lasciano bottino e non tornano. Una squadra morta è denaro speso.", + "rov_troop_dvergar_yard_patrol": "Ronda del cortile", + "rov_troop_sverm_brood": "Covata", + "rov_troop_sverm_gjall": "Gjall", + "rov_troop_sverm_seeker": "Cercatore", + "rov_troop_sverm_soldier": "Soldato", + "rov_troop_trol_goblin_band": "Banda da guerra Fuling", + "rov_troop_trol_goblin_patrol": "Pattuglia Fuling", + "rov_troop_trol_greydwarf_patrol": "Pattuglia di nani grigi", + "rov_troop_trol_terms": "Rispondono al comando di seguirti, si ricuciono da soli le ferite, non lasciano bottino e non tornano. Una banda morta è denaro speso.", + "rov_troop_trol_troll": "Troll", + "rov_troop_trol_troll_summoned": "Troll del bastone" +} diff --git a/JotunnModStub/Trol/TrolTotem.cs b/JotunnModStub/Trol/TrolTotem.cs index 9187631..99f94c9 100644 --- a/JotunnModStub/Trol/TrolTotem.cs +++ b/JotunnModStub/Trol/TrolTotem.cs @@ -93,7 +93,7 @@ namespace RacesOfValheim { new Troop { - Id = "greydwarf_patrol", Display = "Greydwarf Patrol", Price = 400, NeedsUpgrade = false, Icon = "TrophyGreydwarfBrute", + Id = "greydwarf_patrol", Display = "$rov_troop_trol_greydwarf_patrol", Price = 400, NeedsUpgrade = false, Icon = "TrophyGreydwarfBrute", Members = new[] { new KeyValuePair("Greydwarf", 4), @@ -103,17 +103,17 @@ namespace RacesOfValheim }, new Troop { - Id = "troll", Display = "Troll", Price = 700, NeedsUpgrade = false, Icon = "TrophyForestTroll", + Id = "troll", Display = "$rov_troop_trol_troll", Price = 700, NeedsUpgrade = false, Icon = "TrophyForestTroll", Members = new[] { new KeyValuePair("Troll", 1) } }, new Troop { - Id = "troll_summoned", Display = "Staff Troll", Price = 900, NeedsUpgrade = false, Icon = "TrophyForestTroll", + Id = "troll_summoned", Display = "$rov_troop_trol_troll_summoned", Price = 900, NeedsUpgrade = false, Icon = "TrophyForestTroll", Members = new[] { new KeyValuePair("Troll_Summoned", 1) } }, new Troop { - Id = "goblin_patrol", Display = "Fuling Patrol", Price = 1400, NeedsUpgrade = true, Icon = "TrophyGoblinBrute", + Id = "goblin_patrol", Display = "$rov_troop_trol_goblin_patrol", Price = 1400, NeedsUpgrade = true, Icon = "TrophyGoblinBrute", Members = new[] { new KeyValuePair("Goblin", 4), @@ -123,7 +123,7 @@ namespace RacesOfValheim }, new Troop { - Id = "goblin_band", Display = "Fuling War Band", Price = 2000, NeedsUpgrade = true, Icon = "TrophyGoblin", + Id = "goblin_band", Display = "$rov_troop_trol_goblin_band", Price = 2000, NeedsUpgrade = true, Icon = "TrophyGoblin", Members = new[] { new KeyValuePair("Goblin", 4), diff --git a/JotunnModStub/Trol/TrolTotemStore.cs b/JotunnModStub/Trol/TrolTotemStore.cs index 2bb61f1..c361c1e 100644 --- a/JotunnModStub/Trol/TrolTotemStore.cs +++ b/JotunnModStub/Trol/TrolTotemStore.cs @@ -128,13 +128,13 @@ namespace RacesOfValheim else Jotunn.Logger.LogWarning($"[Trol] No icon on '{troop.Icon}' for {troop.Display}; the row keeps " + "whatever the cloned element was showing."); - element.transform.Find("name").GetComponent().text = troop.Display; + element.transform.Find("name").GetComponent().text = Localization.instance.Localize(troop.Display); TMP_Text price = FindDescendant(element.transform, "price"); if (price != null) price.text = troop.Price.ToString(); UITooltip tooltip = element.GetComponent(); - if (tooltip != null) tooltip.Set(troop.Display, Composition(troop), gui.m_tooltipAnchor, default(Vector2)); + if (tooltip != null) tooltip.Set(Localization.instance.Localize(troop.Display), Composition(troop), gui.m_tooltipAnchor, default(Vector2)); string id = troop.Id; element.GetComponent
@@ -451,6 +451,11 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.15 +- **Balance - Skeleton max health:** lower in the early and middle game. The bonus over the base 25 is now +25 / +45 / +65 / +90 / +125 / +165 / +215 / +275, from no bosses to Fader (it was +50 / +80 / +110 / +140 / +170 / +200 / +230 / +275). A fresh Skeleton starts at 50 instead of 75; from Yagluth on the gap closes, and Fader is unchanged at 300. A Skeleton never needs food and never spends stamina, so it was well ahead of a fed viking at every tier. Thanks to Jondar Korric and everyone else who asked for this. +- **Fix - Auto-Resurrect on any hit:** a Skeleton's Auto-Resurrect now triggers only on a hit that would actually kill you. It used to compare the raw hit, before armour and blocking, with its poison and fire counted all at once, so with good armour it fired on almost any hit. On dedicated servers it could also miss a real deathblow when the server or another player controlled the attacker. Thanks to akira for the report. +- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy dead shall rise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. + ### v1.5.14 - **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. - **Fix - Fenrir forms and adrenaline:** in Wolf, Ulv, Fenring and Cultist form, hits now build adrenaline the way a weapon does. Before, only staggering an enemy did, so Lox, Tar, Brutes and Furlings gave almost none. The Cultist's fire breath builds it too, about one hit's worth per second. Thanks to lexsonn for the report. diff --git a/manifest.json b/manifest.json index 6c5a7ef..7418483 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.14", + "version_number": "1.5.15", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 0a843bad415f99cb306a5e9e908ade29d991a5ff Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 23:53:53 +0200 Subject: [PATCH 192/290] fix(skeleton): the Summon on Kill "on" line is "Thy shall raise again." MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As written by the author; Italian "Tu rialzerai ancora.", Russian "Ты вновь поднимешь.". README changelog line too. --- JotunnModStub/Translations/English/messages.json | 2 +- JotunnModStub/Translations/Italian/messages.json | 2 +- JotunnModStub/Translations/Russian/messages.json | 2 +- README.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index 1edf32c..a764b92 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.", "rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.", "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it.", - "rov_msg_skeleton_summon_on": "Thy dead shall rise again.", + "rov_msg_skeleton_summon_on": "Thy shall raise again.", "rov_msg_skeleton_summon_off": "Raising... nevermore.", "rov_msg_skeleton_summon_locked": "Summon on Kill awakens once The Queen falls." } diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index 20caf0b..2c6ed4c 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale.", "rov_msg_boneship_no_shore": "Nessuna riva a portata. Restano ai remi.", "rov_msg_boneship_sunk": "La nave affonda, e con lei $1.", - "rov_msg_skeleton_summon_on": "I tuoi morti risorgeranno ancora.", + "rov_msg_skeleton_summon_on": "Tu rialzerai ancora.", "rov_msg_skeleton_summon_off": "Risorgere... mai più.", "rov_msg_skeleton_summon_locked": "Evoca all'uccisione si risveglia quando cade la Regina." } diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 5b0f03e..c4f2975 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "Стервятник кружит, спускаясь по спирали.", "rov_msg_boneship_no_shore": "Берега не видно. Они остаются на веслах.", "rov_msg_boneship_sunk": "Корабль идет ко дну, и $1 вместе с ним.", - "rov_msg_skeleton_summon_on": "Твои мёртвые вновь восстанут.", + "rov_msg_skeleton_summon_on": "Ты вновь поднимешь.", "rov_msg_skeleton_summon_off": "Восстание... никогда более.", "rov_msg_skeleton_summon_locked": "Призыв при убийстве пробудится, когда падёт Королева." } diff --git a/README.md b/README.md index cb169ae..35bd680 100644 --- a/README.md +++ b/README.md @@ -454,7 +454,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ### v1.5.15 - **Balance - Skeleton max health:** lower in the early and middle game. The bonus over the base 25 is now +25 / +45 / +65 / +90 / +125 / +165 / +215 / +275, from no bosses to Fader (it was +50 / +80 / +110 / +140 / +170 / +200 / +230 / +275). A fresh Skeleton starts at 50 instead of 75; from Yagluth on the gap closes, and Fader is unchanged at 300. A Skeleton never needs food and never spends stamina, so it was well ahead of a fed viking at every tier. Thanks to Jondar Korric and everyone else who asked for this. - **Fix - Auto-Resurrect on any hit:** a Skeleton's Auto-Resurrect now triggers only on a hit that would actually kill you. It used to compare the raw hit, before armour and blocking, with its poison and fire counted all at once, so with good armour it fired on almost any hit. On dedicated servers it could also miss a real deathblow when the server or another player controlled the attacker. Thanks to akira for the report. -- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy dead shall rise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. +- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy shall raise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. ### v1.5.14 - **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. From 9e9790d1e99730970e2e30f3e3b632f058f48dd4 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 23:55:26 +0200 Subject: [PATCH 193/290] docs(readme): the v1.5.15 entry quotes the line that shipped The new line goes out in v1.5.16 and is listed for that release. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35bd680..cb169ae 100644 --- a/README.md +++ b/README.md @@ -454,7 +454,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ### v1.5.15 - **Balance - Skeleton max health:** lower in the early and middle game. The bonus over the base 25 is now +25 / +45 / +65 / +90 / +125 / +165 / +215 / +275, from no bosses to Fader (it was +50 / +80 / +110 / +140 / +170 / +200 / +230 / +275). A fresh Skeleton starts at 50 instead of 75; from Yagluth on the gap closes, and Fader is unchanged at 300. A Skeleton never needs food and never spends stamina, so it was well ahead of a fed viking at every tier. Thanks to Jondar Korric and everyone else who asked for this. - **Fix - Auto-Resurrect on any hit:** a Skeleton's Auto-Resurrect now triggers only on a hit that would actually kill you. It used to compare the raw hit, before armour and blocking, with its poison and fire counted all at once, so with good armour it fired on almost any hit. On dedicated servers it could also miss a real deathblow when the server or another player controlled the attacker. Thanks to akira for the report. -- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy shall raise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. +- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy dead shall rise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. ### v1.5.14 - **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. From 3f8cf1ee27b0ee48badd7fdd34d6ffcea0bce9e2 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Sun, 25 Oct 2026 17:38:28 +0100 Subject: [PATCH 194/290] feat(alfar): v1.6.0 - the Alfar, an eleventh race Grey, tall and thin, with black eyes. Eitr is armour and fuel (shield, diet, soft fall, levitation), Heimkall sends a lethal blow home at one health every 20 minutes. Caster powers from Skrid to the archon Sameining, with on-screen cooldowns. Automated base around the Ljoskjarne: drones, three constructs, crystals, Ljosgard, Prismavard. Compendium page in EN/IT/RU. README: New in block, race section, progression, station line, changelog. Co-Authored-By: Claude Sonnet 5.5 --- JotunnModStub/Alfar/AlfarArchon.cs | 176 ++ JotunnModStub/Alfar/AlfarChests.cs | 134 ++ JotunnModStub/Alfar/AlfarCommands.cs | 110 + JotunnModStub/Alfar/AlfarConfig.cs | 159 ++ JotunnModStub/Alfar/AlfarConstructs.cs | 397 ++++ JotunnModStub/Alfar/AlfarDroneAI.cs | 1950 +++++++++++++++++ JotunnModStub/Alfar/AlfarDrones.cs | 365 +++ JotunnModStub/Alfar/AlfarEitr.cs | 166 ++ JotunnModStub/Alfar/AlfarHeimkall.cs | 171 ++ JotunnModStub/Alfar/AlfarLevitation.cs | 120 + JotunnModStub/Alfar/AlfarLjosgard.cs | 108 + JotunnModStub/Alfar/AlfarMark.cs | 149 ++ JotunnModStub/Alfar/AlfarMiners.cs | 104 + JotunnModStub/Alfar/AlfarNexus.cs | 576 +++++ JotunnModStub/Alfar/AlfarNexusConfig.cs | 144 ++ JotunnModStub/Alfar/AlfarNexusStore.cs | 171 ++ JotunnModStub/Alfar/AlfarPatches.cs | 149 ++ JotunnModStub/Alfar/AlfarPowerConfig.cs | 170 ++ JotunnModStub/Alfar/AlfarPowers.cs | 616 ++++++ JotunnModStub/Alfar/AlfarProbe.cs | 434 ++++ JotunnModStub/Alfar/AlfarRace.cs | 40 + JotunnModStub/Alfar/AlfarStatusEffects.cs | 169 ++ JotunnModStub/Alfar/AlfarTowers.cs | 239 ++ JotunnModStub/Alfar/AlfarVisuals.cs | 495 +++++ JotunnModStub/ConfigSync.cs | 1 + JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RaceCompendium.cs | 57 +- JotunnModStub/RaceRadial.cs | 13 + JotunnModStub/RaceScale.cs | 2 + JotunnModStub/RaceStationLock.cs | 5 + JotunnModStub/RacesOfValheim.cs | 51 +- .../Translations/English/compendium.json | 24 + JotunnModStub/Translations/English/items.json | 35 + .../Translations/English/messages.json | 30 +- JotunnModStub/Translations/English/races.json | 4 +- .../Translations/English/status_effects.json | 12 +- .../Translations/Italian/compendium.json | 24 + JotunnModStub/Translations/Italian/items.json | 35 + .../Translations/Italian/messages.json | 30 +- JotunnModStub/Translations/Italian/races.json | 4 +- .../Translations/Italian/status_effects.json | 12 +- .../Translations/Russian/compendium.json | 24 + JotunnModStub/Translations/Russian/items.json | 35 + .../Translations/Russian/messages.json | 30 +- JotunnModStub/Translations/Russian/races.json | 4 +- .../Translations/Russian/status_effects.json | 12 +- README.md | 35 +- manifest.json | 2 +- 48 files changed, 7779 insertions(+), 16 deletions(-) create mode 100644 JotunnModStub/Alfar/AlfarArchon.cs create mode 100644 JotunnModStub/Alfar/AlfarChests.cs create mode 100644 JotunnModStub/Alfar/AlfarCommands.cs create mode 100644 JotunnModStub/Alfar/AlfarConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarConstructs.cs create mode 100644 JotunnModStub/Alfar/AlfarDroneAI.cs create mode 100644 JotunnModStub/Alfar/AlfarDrones.cs create mode 100644 JotunnModStub/Alfar/AlfarEitr.cs create mode 100644 JotunnModStub/Alfar/AlfarHeimkall.cs create mode 100644 JotunnModStub/Alfar/AlfarLevitation.cs create mode 100644 JotunnModStub/Alfar/AlfarLjosgard.cs create mode 100644 JotunnModStub/Alfar/AlfarMark.cs create mode 100644 JotunnModStub/Alfar/AlfarMiners.cs create mode 100644 JotunnModStub/Alfar/AlfarNexus.cs create mode 100644 JotunnModStub/Alfar/AlfarNexusConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarNexusStore.cs create mode 100644 JotunnModStub/Alfar/AlfarPatches.cs create mode 100644 JotunnModStub/Alfar/AlfarPowerConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarPowers.cs create mode 100644 JotunnModStub/Alfar/AlfarProbe.cs create mode 100644 JotunnModStub/Alfar/AlfarRace.cs create mode 100644 JotunnModStub/Alfar/AlfarStatusEffects.cs create mode 100644 JotunnModStub/Alfar/AlfarTowers.cs create mode 100644 JotunnModStub/Alfar/AlfarVisuals.cs diff --git a/JotunnModStub/Alfar/AlfarArchon.cs b/JotunnModStub/Alfar/AlfarArchon.cs new file mode 100644 index 0000000..0be4415 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarArchon.cs @@ -0,0 +1,176 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// SAMEINING, the archon (Alfar_Progettazione.txt sec. 13.8): Fader's power, an all-or-nothing form. + /// + /// - needs 75% of the maximum eitr and a READY Heimkall, and spends ALL the eitr; + /// - lasts up to three minutes: bigger (x1.5), glowing, +20% speed; + /// - instead of armour there is a POOL of points, three per eitr spent: every blow lands on it, + /// and when it is gone the form ends early; + /// - no weapons: a psionic pulse strikes everything hostile around the body, once a second; + /// - Ljosstorm and Geisli cost nothing in the form, but wait a few seconds between uses; + /// - it ENDS (time up, pool gone) with a teleport home at one hit point, eitr at zero, and the + /// Heimkall wait starting. The form IS a Heimkall spent on purpose. + /// + /// The form is published in the ZDO so other players see the size and the glow. + /// + public static class AlfarArchon + { + public const string ZdoKey = "Alfar_Archon"; + + public static bool Active { get; private set; } + public static float Pool { get; private set; } + public static float EndsAt { get; private set; } + public static float StartedAt { get; private set; } + + private static float nextPulse; + + /// True for any player in range: the form is read off the ZDO, not local state. + public static bool IsArchon(Player player) + { + if (player == null) return false; + ZNetView nview = player.GetComponent(); + return nview != null && nview.IsValid() && nview.GetZDO().GetInt(ZdoKey, 0) == 1; + } + + public static bool IsLocalActive => Active && Player.m_localPlayer != null; + + private static void Publish(Player player, bool on) + { + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(ZdoKey, on ? 1 : 0); + } + + // ─── Entering ──────────────────────────────────────────────────────── + + public static bool TryActivate(Player player) + { + if (Active || player == null) return false; + + float max = player.GetMaxEitr(); + float eitr = player.GetEitr(); + if (max <= 0f || eitr < max * AlfarPowerConfig.ArchonThreshold.Value) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_charged")); + return false; + } + + if (!AlfarHeimkall.IsReady(player)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_ready")); + return false; + } + + // Everything goes in: the strength of the form is what the Alfr had eaten. + Pool = eitr * AlfarPowerConfig.ArchonPoolPerEitr.Value; + AlfarEitr.Spend(player, eitr); + + Active = true; + StartedAt = Time.time; + EndsAt = Time.time + AlfarPowerConfig.ArchonSeconds.Value; + AlfarStatusEffects.ShowTimer("archon", AlfarPowerConfig.ArchonSeconds.Value); + nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value; + Publish(player, true); + + Jotunn.Logger.LogInfo($"[Alfar] Sameining on: pool {Pool:0} for {AlfarPowerConfig.ArchonSeconds.Value:0}s."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_on")); + return true; + } + + // ─── In the form ───────────────────────────────────────────────────── + + /// + /// Takes a blow into the pool. Called from the shield prefix before anything else, because in + /// the form the pool IS the defence: every type of damage, drowning and the edge of the world + /// included, since nothing else can end the form but the pool and the clock. + /// + public static void Absorb(Player player, HitData hit) + { + if (!Active || hit == null) return; + + float total = hit.m_damage.GetTotalDamage(); + hit.m_damage = default(HitData.DamageTypes); + if (total <= 0f) return; + + Pool -= total; + // The exit itself is done in Tick, outside the damage call. + } + + public static void Tick(Player player) + { + if (!Active) return; + + if (player == null || player.IsDead()) + { + // The body is gone (or the world is): nothing to teleport, only the state to drop. + Active = false; + if (player != null) Publish(player, false); + return; + } + + if (Pool <= 0f || Time.time >= EndsAt) + { + Exit(player, Pool <= 0f ? "pool gone" : "time up"); + return; + } + + if (Time.time >= nextPulse) + { + nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value; + AlfarPowers.Pulse(player, AlfarPowerConfig.ArchonPulseRadius.Value, AlfarPowerConfig.ArchonPulseDamage.Value); + } + } + + // ─── Leaving ───────────────────────────────────────────────────────── + + public static void Exit(Player player, string reason) + { + if (!Active) return; + + Active = false; + Pool = 0f; + Publish(player, false); + AlfarStatusEffects.ClearTimer("archon"); + + // Eitr to zero, then the Heimkall: the form spends the one that was ready. + AlfarEitr.Spend(player, player.GetEitr()); + AlfarHeimkall.TryTrigger(player, "Sameining " + reason, force: true); + + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_off")); + Jotunn.Logger.LogInfo($"[Alfar] Sameining off ({reason})."); + } + + /// The cooldown Ljosstorm and Geisli wait in the form, instead of costing eitr. + public static float FreePowerCooldown => AlfarPowerConfig.ArchonFreePowerCooldown.Value; + + /// + /// NO WEAPONS in the form: the psionic pulse is the attack. Humanoid.StartAttack is the one + /// door every swing, shot and draw goes through (verified, doc sec. 16B); returning false + /// with a false result is "nothing started". + /// + [HarmonyLib.HarmonyPatch(typeof(Humanoid), "StartAttack")] + public static class Alfar_Archon_NoWeapons_Patch + { + public static bool Prefix(Humanoid __instance, ref bool __result) + { + if (Active && __instance == Player.m_localPlayer) + { + __result = false; + return false; + } + return true; + } + } + + /// Clears the state without teleporting (used by the reset command). + public static void ForceClear(Player player) + { + Active = false; + Pool = 0f; + if (player != null) Publish(player, false); + AlfarStatusEffects.ClearTimer("archon"); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarChests.cs b/JotunnModStub/Alfar/AlfarChests.cs new file mode 100644 index 0000000..e8fc1d9 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarChests.cs @@ -0,0 +1,134 @@ +using System.Collections.Generic; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The EIRINNSIGLI, the verdigris seal (Alfar_Progettazione.txt sec. 9.2c): a bronze nail turned at + /// the forge. Put inside a chest it tells the drones NOT to look there - the inverse of the + /// Butler's, where the seal says "this one is yours". Only the colour differs from the nail: a model + /// recolour does not touch the inventory icon (guide 5.2), so in the pack it looks like a bronze + /// nail and only the name tells it apart. + /// + public static class AlfarSigil + { + public const string PrefabName = "AlfarSigil"; + public const string DisplayName = "$rov_item_alfar_sigil_name"; + + public static void Register() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, "BronzeNails"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Alfar] Could not clone BronzeNails: no verdigris seal."); + return; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = DisplayName; + shared.m_description = "$rov_item_alfar_sigil_desc"; + + AlfarConstructs.Tint(prefab, new Color(0.36f, 0.68f, 0.58f, 1f)); + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + + ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig + { + Item = PrefabName, + Amount = 1, + CraftingStation = CraftingStations.Forge, + MinStationLevel = 1, + Requirements = new[] { new RequirementConfig("BronzeNails", 1, 0, true) }, + })); + } + } + + /// + /// The two special chests (sec. 9.2c): built like an ordinary chest with Greydwarf eyes added to + /// the price. The ENTRY chest is where everything is thrown and where the drones sort from; the + /// WOOD chest holds the wood the drones may burn - the only wood they ever consume. + /// + public static class AlfarChests + { + public const string EntryName = "AlfarInngangskista"; + public const string WoodName = "AlfarEldividarkista"; + + public static void Register() + { + RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc", + new Color(0.62f, 0.80f, 1f, 1f)); + RegisterOne(WoodName, "$rov_piece_alfar_eldividarkista_name", "$rov_piece_alfar_eldividarkista_desc", + new Color(0.85f, 0.62f, 0.36f, 1f)); + } + + private static void RegisterOne(string pieceName, string display, string description, Color tint) + { + GameObject source = PrefabManager.Cache.GetPrefab("piece_chest_wood"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] No 'piece_chest_wood': the chest " + pieceName + " is not registered."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, source); + if (prefab == null) return; + + // The price of a plain chest, read from the game (guide 3.2), plus the eyes. + var requirements = new List(); + Piece vanilla = source.GetComponent(); + if (vanilla != null && vanilla.m_resources != null) + { + foreach (Piece.Requirement r in vanilla.m_resources) + { + if (r.m_resItem == null) continue; + requirements.Add(new RequirementConfig(r.m_resItem.gameObject.name, r.m_amount, 0, true)); + } + } + requirements.Add(new RequirementConfig("GreydwarfEye", AlfarNexusConfig.ChestEyes.Value, 0, true)); + + Container container = prefab.GetComponent(); + if (container != null) container.m_name = display; + + Piece piece = prefab.GetComponent(); + if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; } + piece.m_name = display; + piece.m_description = description; + + AlfarConstructs.Tint(prefab, tint); + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = display, + Description = description, + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = piece.m_icon, + Requirements = requirements.ToArray(), + })); + + // One of each inside the reach of a Ljoskjarne, and only for the Alfar, and only where a core stands. + PieceDensityLimit.Register(pieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_chest"); + PieceDensityLimit.RegisterGate(pieceName, (player, position) => + { + if (!AlfarRace.IsLocalAlfar()) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + } + if (AlfarNexusBehaviour.Covering(position) == null) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_chest_needs_nexus")); + return false; + } + return true; + }); + + AlfarPieces.Extra.Add(pieceName); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarCommands.cs b/JotunnModStub/Alfar/AlfarCommands.cs new file mode 100644 index 0000000..a0f4785 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarCommands.cs @@ -0,0 +1,110 @@ +using Jotunn.Entities; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Test helpers for the Alfar, in the F5 console. They exist so the phases of Alfar_Test.txt can + /// be walked through without waiting twenty minutes between steps. + /// + /// alfarstatus what the race is doing right now (eitr, Heimkall timer, SE, form...) + /// alfarreset clears every Alfar timer and cooldown + /// alfareitr sets the eitr pool: a number, "full", or 0 + /// alfarhp sets the current health, to try the lethal-blow case without dying + /// + public class AlfarStatusCommand : ConsoleCommand + { + public override string Name => "alfarstatus"; + public override string Help => "[DEBUG] Prints the Alfar's eitr, health, Heimkall timer and passive."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null) { Console.instance.Print("No local player."); return; } + + string race = AlfarVisuals.GetPlayerRace(player); + Print($"race={race} progression state={BossProgressionManager.GetCurrentProgressionState()}"); + Print($"health={player.GetHealth():0}/{player.GetMaxHealth():0} eitr={player.GetEitr():0.0}/{player.GetMaxEitr():0}"); + + float left = AlfarHeimkall.Remaining(player); + Print($"Heimkall: {(left <= 0f ? "READY" : (left / 60f).ToString("0.0") + " min left")} " + + $"(cooldown now {AlfarHeimkall.CooldownSeconds() / 60f:0} min)"); + + bool se = player.GetSEMan().HaveStatusEffect(SE_AlfarStats.EffectName.GetStableHashCode()); + Print($"passive status effect: {(se ? "on" : "OFF")}"); + } + + private static void Print(string text) + { + Console.instance.Print("[Alfar] " + text); + Jotunn.Logger.LogInfo("[Alfar] " + text); + } + } + + public class AlfarResetCommand : ConsoleCommand + { + public override string Name => "alfarreset"; + public override string Help => "[DEBUG] Clears the Alfar's Heimkall timer and every power cooldown."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null) return; + + AlfarHeimkall.ResetTimer(player); + AlfarHeimkall.InvulnerableUntil = 0f; + AlfarPowers.ResetCooldowns(player); + Console.instance.Print("[Alfar] Heimkall timer and power cooldowns cleared."); + } + } + + public class AlfarEitrCommand : ConsoleCommand + { + public override string Name => "alfareitr"; + public override string Help => "[DEBUG] alfareitr - sets the Alfr's current eitr."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null || args.Length == 0) { Console.instance.Print("alfareitr "); return; } + + float target; + if (args[0].ToLower() == "full") target = player.GetMaxEitr(); + else if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out target)) + { + Console.instance.Print("alfareitr "); + return; + } + + target = Mathf.Clamp(target, 0f, player.GetMaxEitr()); + float delta = target - player.GetEitr(); + if (delta > 0f) player.AddEitr(delta); + else if (delta < 0f) AlfarEitr.Spend(player, -delta); + + Console.instance.Print($"[Alfar] eitr = {player.GetEitr():0.0}/{player.GetMaxEitr():0}"); + } + } + + public class AlfarHpCommand : ConsoleCommand + { + public override string Name => "alfarhp"; + public override string Help => "[DEBUG] alfarhp - sets the current health, to test the lethal-blow case."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null || args.Length == 0) { Console.instance.Print("alfarhp "); return; } + + if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out float hp)) + { + Console.instance.Print("alfarhp "); + return; + } + + player.SetHealth(Mathf.Clamp(hp, 1f, player.GetMaxHealth())); + Console.instance.Print($"[Alfar] health = {player.GetHealth():0}/{player.GetMaxHealth():0}"); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarConfig.cs b/JotunnModStub/Alfar/AlfarConfig.cs new file mode 100644 index 0000000..1769a1a --- /dev/null +++ b/JotunnModStub/Alfar/AlfarConfig.cs @@ -0,0 +1,159 @@ +using BepInEx.Configuration; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Every number the Alfar use. Nothing numeric lives in the logic files (guide 3.4), and every + /// value here is a STARTING value: Alfar_Progettazione.txt sec. 19 says they will all be + /// corrected in play. + /// + /// Only the look is bound so far. The shield, the powers and the base add their own sections as + /// they are written. + /// + public static class AlfarConfig + { + /// + /// Written into m_customData["Race"] and the ZDO. Chosen once and never changed: renaming it + /// later leaves every saved Alfar character unrecognised and back to human (the Brandr + /// lesson, design doc sec. 2). + /// + public const string RaceId = "Alfar"; + + // ─── Look ──────────────────────────────────────────────────────────── + + /// The tint written into _SkinColor. Ash grey: low saturation, a hair cool. + public static ConfigEntry SkinColor; + + /// + /// Height against a normal Viking: +5%, design doc sec. 7.1. Applied to the Visual child's Y, + /// never the root (RaceEyeHeight explains why). + /// + public static ConfigEntry HeightScale; + + /// + /// Width and depth: "barely visibly thinner", about -8%. Together with HeightScale this is a + /// NON-UNIFORM scale, which is where held weapons and the first-person camera tend to look + /// squashed - doc sec. 7.2. If it does, raise this toward 1 before touching anything else. + /// + public static ConfigEntry WidthScale; + + /// + /// 1 is the Sverm's size, which is what the design asked to try first ("se non va li + /// allarghiamo"). Raise it to enlarge the eyes: 1.6 is roughly a grey from the films. + /// + public static ConfigEntry EyeSizeMultiplier; + + // The eye geometry is the Sverm's, unchanged (SvermVisuals): offsets are metres in the head + // bone's OWN frame, so they land on the same part of the face at any body scale. + public const float EyeSeparation = 0.032f; + public const float EyeForward = 0.081f; + public const float EyeHeight = 0.181f; + public const float EyeSize = 0.062f; + + // ─── Eitr: diet, shield, soft fall ─────────────────────────────────── + + /// + /// What each food adds to the maximum eitr besides its own: min(hp, stamina) times this. + /// 1 is the design (sec. 3): native eitr plus the lower of hp and stamina. + /// + public static ConfigEntry DietMultiplier; + + /// + /// Eitr spent per point of damage. 1:1, FIXED, for ever (sec. 4.1): progression comes from + /// the food raising the pool, not from a better rate. + /// + public static ConfigEntry ShieldRate; + + /// Lightning and spirit cost this many times the rate (sec. 5.1: the double cost). + public static ConfigEntry ConductiveMultiplier; + + /// + /// Falls cost nothing while there is any eitr (sec. 4.5: soft fall). Off, a fall is shielded + /// like any other blow. + /// + public static ConfigEntry SoftFall; + + /// + /// The fastest an Alfr falls while there is eitr, in metres per second. The vanilla Feather + /// Cape caps at 5; a little under that reads as floating. + /// + public static ConfigEntry FeatherFallSpeed; + + // ─── Heimkall: the death that costs a wait ─────────────────────────── + + /// Minutes before a second Heimkall is possible, before Yagluth (sec. 6). + public static ConfigEntry HeimkallMinutes; + + /// The same, once Yagluth is down. + public static ConfigEntry HeimkallMinutesAfterYagluth; + + /// The same, once Fader is down. + public static ConfigEntry HeimkallMinutesAfterFader; + + /// + /// Seconds of invulnerability on arrival, so a lethal blow does not simply repeat at the + /// bed. Without it a burning or drowning death would loop. + /// + public static ConfigEntry HeimkallInvulnerableSeconds; + + public static void Bind(ConfigFile config) + { + const string heimkall = "Alfar - Heimkall"; + + HeimkallMinutes = config.Bind(heimkall, "Cooldown Minutes", 20f, + new ConfigDescription("Minutes between two Heimkalls (the lethal-blow teleport to the bed). Inside this wait, a lethal blow kills normally.", + new AcceptableValueRange(0f, 120f))); + + HeimkallMinutesAfterYagluth = config.Bind(heimkall, "Cooldown Minutes After Yagluth", 15f, + new ConfigDescription("The cooldown once Yagluth is defeated.", + new AcceptableValueRange(0f, 120f))); + + HeimkallMinutesAfterFader = config.Bind(heimkall, "Cooldown Minutes After Fader", 10f, + new ConfigDescription("The cooldown once Fader is defeated.", + new AcceptableValueRange(0f, 120f))); + + HeimkallInvulnerableSeconds = config.Bind(heimkall, "Invulnerable Seconds", 5f, + new ConfigDescription("Seconds nothing can hurt the Alfr after arriving.", + new AcceptableValueRange(0f, 30f))); + + const string eitr = "Alfar - Eitr"; + + DietMultiplier = config.Bind(eitr, "Diet Multiplier", 1f, + new ConfigDescription("Each food adds its native eitr plus min(hp, stamina) times this to the maximum eitr.", + new AcceptableValueRange(0f, 3f))); + + ShieldRate = config.Bind(eitr, "Shield Rate", 1f, + new ConfigDescription("Eitr spent per point of damage absorbed (1 = 1:1).", + new AcceptableValueRange(0.1f, 5f))); + + ConductiveMultiplier = config.Bind(eitr, "Lightning And Spirit Multiplier", 2f, + new ConfigDescription("Lightning and spirit damage cost this many times the shield rate.", + new AcceptableValueRange(1f, 5f))); + + SoftFall = config.Bind(eitr, "Soft Fall", true, + new ConfigDescription("Falling does no damage, and is slowed, while the Alfr has any eitr.")); + + FeatherFallSpeed = config.Bind(eitr, "Feather Fall Speed", 4f, + new ConfigDescription("Maximum falling speed (m/s) while the Alfr has eitr. Lower floats more.", + new AcceptableValueRange(1f, 20f))); + + const string look = "Alfar - Look"; + + SkinColor = config.Bind(look, "Skin Color", new Color(0.86f, 0.88f, 0.88f, 1f), + new ConfigDescription("How light the ash-grey skin is. The skin texture itself is made grey; this only sets its brightness.")); + + HeightScale = config.Bind(look, "Height Scale", 1.05f, + new ConfigDescription("Body height against a normal Viking (1.05 = +5%).", + new AcceptableValueRange(0.8f, 1.3f))); + + WidthScale = config.Bind(look, "Width Scale", 0.92f, + new ConfigDescription("Body width and depth against a normal Viking (0.92 = 8% thinner).", + new AcceptableValueRange(0.7f, 1.2f))); + + EyeSizeMultiplier = config.Bind(look, "Eye Size Multiplier", 0.8f, + new ConfigDescription("1 = the Sverm's eye size; 0.8 is slightly smaller. Raise to enlarge the black eyes.", + new AcceptableValueRange(0.5f, 3f))); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarConstructs.cs b/JotunnModStub/Alfar/AlfarConstructs.cs new file mode 100644 index 0000000..80fe2a5 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarConstructs.cs @@ -0,0 +1,397 @@ +using System.Collections.Generic; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The three constructs, the Alfar's only troops (Alfar_Progettazione.txt sec. 8.5): + /// + /// Neistvordr a Surtling: hp 60 and a shield of 60 (the vanilla Surtling has 20), fire thrower + /// Steinvordr the StoneGolem: hp 800, the tank, ONE per Nexus + /// Eldingvordr a smaller Abomination at half its hp, which fires a lightning sphere every 8 s + /// + /// Everything that makes them the Alfar's is done by what is added, not by rewriting attacks: + /// AlfarMark turns whatever they deal into lightning and keeps it off friends and buildings, + /// AlfarCreatureShield gives them a shield that returns by itself, and RaisedThrall gives them + /// the follow and stay orders every other race's troops already have. + /// + /// They are NOT repaired and do not heal: the damage to the body is permanent. RaisedThrall's + /// sentinel regeneration (SkeletonSentryBehaviour) is therefore left off, and the creature's own + /// slow vanilla regeneration is switched off too. + /// + public static class AlfarConstructs + { + public const string Neistvordr = "AlfarNeistvordr"; + public const string Steinvordr = "AlfarSteinvordr"; + public const string Eldingvordr = "AlfarEldingvordr"; + + public const string SphereProjectile = "AlfarLightningSphere"; + public const string SphereWeapon = "AlfarSphereAttack"; + + public class Kind + { + public string PrefabName; + public string Display; + public string Source; + public float Health; // 0 = keep the vanilla creature's + public float HealthFactor; // applied after Health when Health is 0 + public float Scale; // 1 = the vanilla size + } + + public static readonly Kind[] Roster = + { + new Kind { PrefabName = Neistvordr, Display = "$rov_creature_alfar_neistvordr_name", Source = "Surtling", Health = 60f, Scale = 1f }, + new Kind { PrefabName = Steinvordr, Display = "$rov_creature_alfar_steinvordr_name", Source = "StoneGolem", Health = 0f, HealthFactor = 1f, Scale = 0.6f }, + new Kind { PrefabName = Eldingvordr, Display = "$rov_creature_alfar_eldingvordr_name", Source = "Abomination", Health = 0f, HealthFactor = 0.5f, Scale = 0.4f }, + }; + + public static Kind Find(string prefabName) + { + foreach (Kind kind in Roster) if (kind.PrefabName == prefabName) return kind; + return null; + } + + // ─── Registration ──────────────────────────────────────────────────── + + public static void Register() + { + // The sphere first: the Eldingvordr's weapon needs it. + bool sphere = RegisterSphere(); + + foreach (Kind kind in Roster) + { + if (kind.PrefabName == Eldingvordr && !sphere) + { + Jotunn.Logger.LogWarning("[Alfar] No lightning sphere: the Eldingvordr keeps the Abomination's melee."); + } + RegisterOne(kind, sphere); + } + } + + private static void RegisterOne(Kind kind, bool sphere) + { + GameObject source = PrefabManager.Cache.GetPrefab(kind.Source); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{kind.Source}' to build {kind.Display} from."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source); + if (prefab == null) return; + + Character character = prefab.GetComponent(); + if (character != null) + { + character.m_name = kind.Display; + character.m_faction = Character.Faction.Players; + if (kind.Health > 0f) character.m_health = kind.Health; + else character.m_health *= kind.HealthFactor; + + // The damage to the body is permanent: no slow regeneration either. + character.m_regenAllHPTime = 0f; + } + + if (!Mathf.Approximately(kind.Scale, 1f)) + { + prefab.transform.localScale = Vector3.one * kind.Scale; + ZNetView nview = prefab.GetComponent(); + if (nview != null) nview.m_syncInitialScale = true; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = AlfarNexusConfig.ConstructLeash.Value; + + MonsterAI monster = prefab.GetComponent(); + if (monster != null) + { + // The vanilla creatures attack player-built objects. Ours never touch a building. + monster.m_attackPlayerObjects = false; + monster.m_alertRange = AlfarNexusConfig.ConstructAlertRange.Value; + monster.m_maxChaseDistance = AlfarNexusConfig.ConstructAlertRange.Value; + } + + // A construct that dropped Coal, a Surtling core or a trophy would be a loot farm. + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + if (kind.PrefabName == Eldingvordr && sphere) GiveSphereWeapon(prefab); + if (kind.PrefabName == Neistvordr) BlueFlames(prefab); + else Tint(prefab, new Color(0.85f, 0.52f, 0.2f, 1f)); + + AlfarMark mark = prefab.AddComponent(); + mark.Role = "construct"; + + // What a destroyed construct gives back: the METAL it was built from, and nothing else - the + // crystals and the refined eitr are spent for good (design sec. 8.5). + AlfarRefund refund = prefab.AddComponent(); + refund.Item = kind.PrefabName == Neistvordr ? "Bronze" : kind.PrefabName == Eldingvordr ? "Iron" : "BlackMetal"; + refund.Amount = kind.PrefabName == Neistvordr ? AlfarNexusConfig.NeistMetal.Value + : kind.PrefabName == Eldingvordr ? AlfarNexusConfig.EldingMetal.Value + : AlfarNexusConfig.SteinMetal.Value; + + AlfarCreatureShield shield = prefab.AddComponent(); + shield.MaxShield = character != null ? character.m_health : 0f; + shield.Shield = shield.MaxShield; + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = kind.PrefabName; + thrall.m_commandingRace = AlfarConfig.RaceId; + thrall.m_maxFollowers = -1; // the cap is the Nexus's, per type, counted at the Nexus + thrall.m_witherSeconds = AlfarNexusConfig.WitherSeconds.Value; + thrall.m_homeCheckRange = AlfarNexusConfig.NexusRadius.Value; + thrall.m_refusalMessage = "$rov_msg_thrall_refusal_alfar"; + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Alfar] Registered '{kind.PrefabName}' from '{kind.Source}'."); + } + + // ─── The lightning sphere ──────────────────────────────────────────── + + /// + /// The Eldingvordr's shot: a sphere that bursts in a small area, hurts only enemies, and never + /// touches a building (doc sec. 8.5 and 16B V12). Cloned from the Dverger ice projectile, the + /// clean base the probe found: an area burst and NO lingering effect spawned on impact (the + /// fire one drops a fire field and also spawns on buildings). + /// + private static bool RegisterSphere() + { + GameObject source = PrefabManager.Cache.GetPrefab("DvergerStaffIce_projectile"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] DvergerStaffIce_projectile not found: no lightning sphere."); + return false; + } + + GameObject projectile = PrefabManager.Instance.CreateClonedPrefab(SphereProjectile, source); + if (projectile == null) return false; + + Projectile settings = projectile.GetComponent(); + if (settings == null) return false; + + settings.m_gravity = 0f; + settings.m_ttl = 4f; + settings.m_aoe = 3f; + settings.m_aoeSkipWearNTear = true; + settings.m_hitFriendly = false; + settings.m_noDamageFriendly = true; + settings.m_hitOwner = false; + settings.m_statusEffect = ""; + + Tint(projectile, new Color(0.55f, 0.85f, 1f, 1f)); + PrefabManager.Instance.AddPrefab(projectile); + + // The weapon that fires it: the Surtling's own fireball weapon, because a creature that + // shoots needs an item with a projectile attack, and that is the one that exists. + GameObject surtling = PrefabManager.Cache.GetPrefab("Surtling"); + Humanoid surtlingHumanoid = surtling != null ? surtling.GetComponent() : null; + GameObject fireball = surtlingHumanoid != null && surtlingHumanoid.m_defaultItems != null && + surtlingHumanoid.m_defaultItems.Length > 0 + ? surtlingHumanoid.m_defaultItems[0] + : null; + if (fireball == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Surtling's fireball weapon was not found: no sphere weapon."); + return false; + } + + GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(SphereWeapon, fireball); + if (weapon == null) return false; + + ItemDrop drop = weapon.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = "$rov_item_alfar_sphere_name"; + + // One shot every eight seconds (design): the AI waits this long between uses. + shared.m_aiAttackInterval = AlfarNexusConfig.SphereIntervalSeconds.Value; + shared.m_aiAttackRange = AlfarNexusConfig.SphereRange.Value; + shared.m_aiAttackRangeMin = 4f; + + HitData.DamageTypes damage = default(HitData.DamageTypes); + damage.m_lightning = AlfarNexusConfig.SphereDamage.Value; + shared.m_damages = damage; + + if (shared.m_attack != null) + { + shared.m_attack.m_attackProjectile = projectile; + // The Abomination's right hand: where the sphere leaves from. + shared.m_attack.m_attackOriginJoint = "r.hand"; + } + + ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false)); + return true; + } + + private static void GiveSphereWeapon(GameObject prefab) + { + Humanoid humanoid = prefab.GetComponent(); + GameObject weapon = PrefabManager.Instance.GetPrefab(SphereWeapon); + if (humanoid == null || weapon == null) return; + + humanoid.m_defaultItems = new[] { weapon }; + humanoid.m_randomWeapon = new GameObject[0]; + humanoid.m_randomArmor = new GameObject[0]; + humanoid.m_randomShield = new GameObject[0]; + humanoid.m_randomSets = new Humanoid.ItemSet[0]; + } + + // ─── Colour ────────────────────────────────────────────────────────── + + /// + /// A tint on every mesh, through renderer.materials (an instanced copy) and NEVER .material or + /// sharedMaterial: the vanilla creature uses the same asset and must stay as it is (guide 3.5). + /// This is a recolour and not a retexture: a true repaint of the golem and the Abomination is + /// still to do (test file, phase 6). + /// + public static void Tint(GameObject prefab, Color color) + { + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + if (renderer is ParticleSystemRenderer || renderer is TrailRenderer || renderer is LineRenderer) continue; + + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material == null) continue; + if (material.HasProperty("_Color")) material.color = color; + if (material.HasProperty("_EmissionColor")) + { + material.SetColor("_EmissionColor", color * 0.08f); + material.EnableKeyword("_EMISSION"); + } + } + renderer.materials = materials; + } + + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = color; + } + + /// + /// The Surtling is made of particles and lights, not textures, and the vanilla prefab ALREADY + /// carries blue variants of its flames, switched off (probe, doc 16C P2): turn those on, turn + /// the red ones off, and recolour the glow of the body and the point light. + /// + private static void BlueFlames(GameObject prefab) + { + foreach (Transform child in prefab.GetComponentsInChildren(true)) + { + if (child.name == "flames_world_BLUE") child.gameObject.SetActive(true); + else if (child.name == "flames" || child.name == "flames_world" || child.name == "flames_world_Purple") + { + child.gameObject.SetActive(false); + } + } + + Color blue = new Color(0.25f, 0.55f, 1f, 1f); + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = blue; + + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material != null && material.HasProperty("_EmissionColor")) + { + // The vanilla emission is white-hot (73): keep the strength, change the hue. + material.SetColor("_EmissionColor", new Color(0.25f, 0.55f, 1f, 1f) * 30f); + } + } + renderer.materials = materials; + } + } + + // ─── Counting and spawning (called by the Nexus) ───────────────────── + + /// + /// A destroyed construct drops the metal it cost, on the ground where it fell. Only a DEATH: + /// a zone unloading destroys the object too and must not pay anyone (the same rule as the + /// Butler's payload). + /// + public class AlfarRefund : MonoBehaviour + { + public string Item = ""; + public int Amount; + } + + [HarmonyLib.HarmonyPatch(typeof(Character), "OnDeath")] + public static class Alfar_Refund_Patch + { + public static void Postfix(Character __instance) + { + AlfarRefund refund = __instance != null ? __instance.GetComponent() : null; + if (refund == null || refund.Amount <= 0 || ObjectDB.instance == null) return; + + GameObject prefab = ObjectDB.instance.GetItemPrefab(refund.Item); + ItemDrop template = prefab != null ? prefab.GetComponent() : null; + if (template == null || template.m_itemData == null) return; + + int left = refund.Amount; + int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize); + Vector3 at = __instance.transform.position + Vector3.up * 0.5f; + + while (left > 0) + { + int stack = Mathf.Min(left, max); + ItemDrop.ItemData clone = template.m_itemData.Clone(); + clone.m_dropPrefab = prefab; + ItemDrop.DropItem(clone, stack, at + Random.insideUnitSphere * 0.3f, Quaternion.identity); + left -= stack; + } + refund.Amount = 0; // once only + } + } + + public static int CountAlive(Vector3 anchor, string prefabName) + { + int count = 0; + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(anchor)) + { + if (thrall != null && thrall.Kind == prefabName) count++; + } + return count; + } + + public static bool Spawn(Vector3 anchor, string prefabName) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{prefabName}' in ZNetScene: it cannot be built."); + return false; + } + + Vector3 where = SpawnSpot(anchor); + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f)); + RaisedThrall thrall = spawned != null ? spawned.GetComponent() : null; + if (thrall != null) thrall.Bind(anchor); + return spawned != null; + } + + /// A free spot on a ring around the Nexus, on the ground, or due south as a last resort. + public static Vector3 SpawnSpot(Vector3 centre) + { + const float radius = 3.5f; + int obstacleMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "vehicle"); + float start = Random.Range(0f, 360f); + + for (int i = 0; i < 12; i++) + { + float angle = (start + i * 30f) * Mathf.Deg2Rad; + Vector3 candidate = centre + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius; + if (ZoneSystem.instance != null) candidate.y = ZoneSystem.instance.GetGroundHeight(candidate); + if (Physics.CheckSphere(candidate + Vector3.up * 1.5f, 1f, obstacleMask)) continue; + return candidate + Vector3.up * 0.3f; + } + + Vector3 fallback = centre + new Vector3(0f, 0f, -radius); + if (ZoneSystem.instance != null) fallback.y = ZoneSystem.instance.GetGroundHeight(fallback); + return fallback + Vector3.up * 0.3f; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarDroneAI.cs b/JotunnModStub/Alfar/AlfarDroneAI.cs new file mode 100644 index 0000000..59d8fea --- /dev/null +++ b/JotunnModStub/Alfar/AlfarDroneAI.cs @@ -0,0 +1,1950 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Alfar drone's own head (Alfar_Progettazione.txt sec. 9): a FORK of the Butler's BoneServantAI, + /// kept as a separate class so nothing that ships with the Skeleton, Skadi or Sverm can be broken + /// from here. What it keeps: the movement, the payload in the ZDO, the three families of stations, + /// the burn protection and the one-stage rule. What it changes: ONE drone does both trades; chests + /// are read the other way round (the sigil marks the ones NOT to touch); stations are fed only from + /// the entry chest, wood only from the wood chest; the product goes back to the entry chest and is + /// SORTED from there into the chest that already holds the same thing; and three jobs are new - + /// repair, farming (with the replant rule) and sorting. + /// + /// The Bone Servant's own head, as it was written: everything it does is here; vanilla's MonsterAI + /// never runs on it. + /// + /// HOW IT MOVES, which was the one open question in the design and is answered here rather than in + /// the doc. Three candidates were on the table: a ghost follow-target, pinning m_patrolPoint the way + /// RaisedThrall does, and calling BaseAI.MoveTo directly. The IL settled it: + /// + /// - BaseAI has NO Update and NO FixedUpdate. UpdateAI(dt) is driven centrally by + /// MonoUpdaters.FixedUpdate over BaseAI.Instances, and that list is maintained by OnEnable / + /// OnDisable. So "disable the AI and drive MoveTo yourself" kills the only thing that would + /// call anything: a disabled BaseAI is not ticked at all. That candidate is dead. + /// - BaseAI.UpdateAI itself does almost nothing - IsOwner, UpdateTakeoffLanding, + /// UpdateRegeneration - so skipping it costs a flying check we do not need and a regeneration + /// we already have from SkeletonSentryBehaviour. + /// + /// So: a PREFIX on MonsterAI.UpdateAI that hands the tick to this class and returns false. The + /// servant keeps its place in the central tick, keeps vanilla pathing through BaseAI.MoveTo, and + /// vanilla's own AI - targeting, fleeing, wandering, attacking - never executes a single line. That + /// is also why the servant cannot fight: not because its weapon was taken (it was), but because the + /// code that would swing it is never reached. + /// + /// MoveTo(dt, point, dist, run) is private, hence the cached MethodInfo. It returns TRUE on arrival + /// (read in the IL: DistanceXZ under the threshold calls StopMoving and returns 1), which is the + /// whole arrival test - no distance maths of our own. + /// + /// THE PAYLOAD IS VIRTUAL. The servant has no inventory. Every station's input RPC takes a STRING, + /// so what it carries is a list of prefab names and counts in its own ZDO, which survives saving, + /// zone reload and - the case that matters - a change of owner mid-job in multiplayer. The one + /// thing this costs is that the goods do not exist as objects while in transit, so they have to be + /// put back into the world by hand if the servant dies holding them. That is , + /// and it is the reason nothing here can quietly delete a player's ore. + /// + public class AlfarDroneAI : MonoBehaviour + { + // ─── ZDO keys ──────────────────────────────────────────────────────── + public const string KeyAnchor = "RoV_alfarAnchor"; + public const string KeyOrphanAt = "RoV_alfarOrphanAt"; + public const string KeyLoad = "RoV_alfarLoad"; + public const string KeySource = "RoV_alfarSource"; + public const string KeyTarget = "RoV_alfarTarget"; + public const string KeyStatus = "RoV_alfarStatus"; + public const string KeyDest = "RoV_alfarDest"; + + /// Every drone alive in the loaded zones: the repairs look at each other through it. + public static readonly List All = new List(); + + /// Written into a STATION's ZDO: the chest whose material is in it right now, so the + /// product goes home to where the raw came from even after a reload, and even if a different + /// client collects it. + public const string KeyFedBy = "RoV_alfarFedBy"; + + // ─── numbers that are not worth a config entry ─────────────────────── + private const float PlanInterval = 1.5f; + + /// + /// How close is close enough. Measured to the piece's ORIGIN, which on a furnace or a kiln sits + /// inside a metre or so of solid collider - so anything tight enough to look like hugging the + /// thing is a distance the servant can never actually reach, and it would time out and put a + /// perfectly good station in the penalty box. Two and a half metres is roughly where a player + /// stands to use one. + /// + private const float ArriveDistance = 2.5f; + + private const float CollectRadius = 3.5f; + private const float JobTimeout = 25f; + private const float PenaltySeconds = 180f; + + /// Set aside briefly when a job was reached but achieved nothing. Without this, a job + /// that arrives and finds nothing to do is re-planned identically on the next tick and the + /// servant stands there deciding the same thing forever. + private const float ShortPenaltySeconds = 20f; + private const float FleeSeconds = 6f; + private const float WitherSeconds = 30f; + private const float HomeCheckRange = 25f; + + /// A cooking slot inside this many seconds of burning outranks everything else. Twelve + /// seconds is a walk of about twenty metres with room to spare, which is the whole radius. + private const float SpoilPanicSeconds = 12f; + + /// How long a station may sit unserved before its wait starts outweighing distance. + /// This is what stops a furnace at the edge of the circle from starving while the servant + /// shuttles between two closer ones. + private const float WaitToMetres = 0.25f; + + private const int PayloadCap = 120; + + private static readonly System.Reflection.MethodInfo MoveToMethod = + AccessTools.Method(typeof(BaseAI), "MoveTo", + new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); + + private static readonly System.Reflection.FieldInfo AllPiecesField = + AccessTools.Field(typeof(Piece), "s_allPieces"); + + private static readonly System.Reflection.MethodInfo ContainerSaveMethod = + AccessTools.Method(typeof(Container), "Save"); + + private static int s_itemMask = -1; + + /// Which stations this one serves. Set on the prefab at registration, so it travels + /// with every instance the table raises. + public ButlerFamily m_family = ButlerFamily.Forge; + + /// + /// Whether this one stands and fights instead of walking home when trouble comes. Off for the + /// Bone Servants, which are pacifists by decision; on for the Sverm's Seeker Workers, which + /// keep the forge AND defend the nest. See . + /// + public bool m_fightsBack = false; + + /// + /// How close to the anchor counts as home, and how far past the configured radius it works. + /// 2.5 and 0 for a table. A Sverm nest is metres of collider that grows with its stage, so + /// SvermWorkerBehaviour sets both to the nest's measured edge - otherwise an idle worker would + /// spend its life walking into the trunk, and the work circle would be mostly nest. + /// + public float m_homeDistance = 2.5f; + public float m_radiusBonus = 0f; + + /// For a servant that fights back: how close an enemy has to be to stop the work, how + /// often that is asked, and how long the fight holds after the last sign of one. + private const float FightRange = 12f; + private const float FightScanInterval = 1f; + private const float FightLinger = 5f; + + private float m_nextFightScan; + private float m_fightUntil; + + private ZNetView m_nview; + private Character m_character; + private MonsterAI m_ai; + + private readonly object[] m_moveArgs = new object[4]; + private readonly List m_payload = new List(); + private readonly Dictionary m_penalties = new Dictionary(); + private readonly Dictionary m_idleSince = new Dictionary(); + + private readonly List m_stations = new List(); + private readonly List m_chests = new List(); // the storage chests + private Container m_entry; // the entry chest + private Container m_wood; // the wood-to-burn chest + private readonly List m_damaged = new List(); + + // Farming: where the last harvest was, and what to put back there. + private Vector3? m_farmSpot; + private Quaternion m_farmRot; + private PlantInfo m_farmInfo; + private float m_farmReadyAt; + + // Sorting: what was chosen at the entry chest and where it is going. + private string m_sortItem; + private ZDOID m_sortDest; + private float m_scannedAt = -99f; + + private Job m_job; + private float m_nextPlan; + private float m_jobDeadline; + private float m_fleeUntil; + private string m_status = ""; + + private class Load + { + public string Name; + public int Count; + } + + private class Job + { + public string Kind; // load | fuel | collect | deposit | drop + public ZDOID Target; + public Vector3 Point; + public bool Hurry; + public string Label; + public ZDOID Claim; // the one target other drones must leave alone + } + + // ================================================================ life + + private void Awake() + { + m_nview = GetComponent(); + m_character = GetComponent(); + m_ai = GetComponent(); + + All.Add(this); + ReadPayload(); + } + + private void OnDestroy() + { + All.Remove(this); + + // Only a DEATH scatters the load. A zone unloading destroys this object too, and there the + // payload must stay in the ZDO where it will be read again on the way back in - dropping it + // would mint a copy every time the player walked away. + if (m_character != null && m_character.IsDead()) DropPayload(); + } + + /// Called by the table the moment it raises one. + public void Bind(Vector3 anchor) + { + if (m_nview == null || !m_nview.IsValid()) return; + + m_nview.GetZDO().Set(KeyAnchor, anchor); + + if (m_ai != null) m_ai.MakeTame(); + if (m_character != null) m_character.SetTamed(true); + } + + public Vector3? Anchor + { + get + { + if (m_nview == null || !m_nview.IsValid()) return null; + + Vector3 anchor = m_nview.GetZDO().GetVec3(KeyAnchor, Vector3.zero); + return anchor == Vector3.zero ? (Vector3?)null : anchor; + } + } + + public bool IsBoundTo(Vector3 anchor) + { + Vector3? own = Anchor; + return own != null && Vector3.SqrMagnitude(own.Value - anchor) < 0.25f; + } + + /// The one line the table's hover shows. Read from the ZDO so a client that does not + /// own the servant still sees what it is doing. + public string Status + { + get + { + if (m_nview == null || !m_nview.IsValid()) return m_status; + return m_nview.GetZDO().GetString(KeyStatus, m_status); + } + } + + private void SetStatus(string text) + { + if (text == m_status) return; + + m_status = text; + if (m_nview != null && m_nview.IsValid() && m_nview.IsOwner()) + { + m_nview.GetZDO().Set(KeyStatus, text); + } + } + + /// Hit by something: stop working and walk home. It never fights back - there is + /// nothing in this class that could. A servant that fights back ignores this: vanilla already + /// holds the attacker as its target (MonsterAI.OnDamaged calls SetTarget, read off the IL), and + /// gives it the tick on the next frame. + public void NoteDamage() + { + if (m_fightsBack) return; + + m_fleeUntil = Time.time + FleeSeconds; + m_job = null; + } + + /// + /// True while vanilla's MonsterAI should have the tick instead of the work - only ever for a + /// servant that fights back, and only on the client that runs it. + /// + /// VANILLA DOES THE FIGHTING, this only decides when. Two things start a fight: a target the + /// MonsterAI already holds - which covers being hit, see NoteDamage - and an enemy inside + /// FightRange, found with BaseAI.FindClosestEnemy. That one is a static sweep of distance and + /// IsEnemy with no line of sight (IL), which is why the range is short. Either holds the fight + /// for FightLinger seconds, so the worker does not flicker between swinging and walking to the + /// chest on alternate ticks. + /// + /// The job is dropped, not the payload: whatever it was carrying stays in the ZDO, and the + /// first plan after the fight carries it on to where it was going. + /// + public bool HandsToVanilla() + { + if (!m_fightsBack || m_ai == null || m_character == null || m_character.IsDead()) return false; + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false; + + Character target = m_ai.GetTargetCreature(); + if (target != null && !target.IsDead()) + { + m_fightUntil = Time.time + FightLinger; + } + else if (Time.time >= m_nextFightScan) + { + m_nextFightScan = Time.time + FightScanInterval; + if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null) + { + m_fightUntil = Time.time + FightLinger; + } + } + + if (Time.time >= m_fightUntil) return false; + + m_job = null; + m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back + SetStatus("Fighting."); + return true; + } + + // ================================================================ the tick + + /// Everything. Returns what MonsterAI.UpdateAI would have returned. + public bool Tick(float dt) + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false; + if (m_character == null || m_character.IsDead()) return false; + + if (TickWither()) return true; + + if (Time.time < m_fleeUntil) + { + SetStatus("Driven off."); + GoHome(dt); + return true; + } + + if (Time.time >= m_nextPlan) + { + m_nextPlan = Time.time + PlanInterval; + Plan(); + } + + Execute(dt); + return true; + } + + /// + /// The table is gone: start the clock, and stop when it runs out. Same shape as RaisedThrall's, + /// and deliberately only asked near home - further out the table's zone is simply not loaded, so + /// "nothing there" would be a lie. + /// + private bool TickWither() + { + Vector3? anchor = Anchor; + if (anchor == null || ZNet.instance == null) return false; + + long stamp = m_nview.GetZDO().GetLong(KeyOrphanAt, 0L); + + if (stamp == 0L) + { + if (Vector3.SqrMagnitude(transform.position - anchor.Value) > + HomeCheckRange * HomeCheckRange) return false; + if (RaisedThrall.StationStandsAt(anchor.Value)) return false; + + m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks); + return false; + } + + if (RaisedThrall.StationStandsAt(anchor.Value)) + { + m_nview.GetZDO().Set(KeyOrphanAt, 0L); + return false; + } + + double elapsed = (ZNet.instance.GetTime() - new System.DateTime(stamp)).TotalSeconds; + if (elapsed < WitherSeconds) return false; + + HitData hit = new HitData(); + hit.m_damage.m_damage = 1E+10f; + hit.m_hitType = HitData.HitType.Undefined; + m_character.ApplyDamage(hit, true, false); + return true; + } + + // ================================================================ planning + + private void Plan() + { + Vector3? anchor = Anchor; + if (anchor == null) { m_job = null; return; } + + Scan(anchor.Value); + ExpirePenalties(); + + // A harvest is in progress: wait for the drops to land, then gather them and replant. + if (m_farmSpot != null) + { + m_job = Time.time < m_farmReadyAt + ? new Job { Kind = "wait", Point = transform.position, Label = "Waiting" } + : new Job { Kind = "farm_finish", Point = m_farmSpot.Value, Label = "Gathering" }; + return; + } + + if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; } + + // The forge has no clock: a smelter holds its ore indefinitely and puts its own output on + // the floor, so PlanRescue would ask a question whose answer is always no. The smith is a + // four-state machine and the cook is a five-state one, and that is the whole of the + // simplification the split bought. + // REFUEL BEFORE LOAD, and that order is the whole of the blast furnace fix. FreeSlots goes + // back above zero the instant a furnace eats one ore, so while there is scrap left in any + // chest PlanLoad always has an answer and PlanFuel, sitting behind it, never got a turn - + // the furnace was topped up forever and burned down to nothing. Fuel cannot starve loading + // in return, because FuelWanted is zero for a station with no work: an empty furnace asks + // for no coal, gets filled, and only then becomes worth stoking. + // One drone does both trades, so the burn protection is always on. Stations first, then the + // base: repairs, the fields, and last the tidying of the entry chest. + Job job = PlanRescue(); + job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad(); + job = job ?? PlanRepair(anchor.Value) ?? PlanFarm(anchor.Value) ?? PlanSort(); + + if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target)) + { + m_jobDeadline = Time.time + JobTimeout; + } + if (m_job != null && !ReferenceEquals(m_job, job)) Release(m_job.Claim); + if (job != null) Claim(job.Claim); + m_job = job; + } + + /// + /// Everything within the radius, once every planning tick. Piece.s_allPieces is the cheap way in + /// - it is the list the game already keeps of every built piece - so there is no OverlapSphere + /// and no guessing at layer masks for the part that runs constantly. + /// + private void Scan(Vector3 anchor) + { + if (Time.time - m_scannedAt < PlanInterval * 0.5f) return; + m_scannedAt = Time.time; + + m_stations.Clear(); + m_chests.Clear(); + m_damaged.Clear(); + m_entry = null; + m_wood = null; + + List pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List : null; + if (pieces == null) return; + + float radius = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus; + float radiusSq = radius * radius; + + for (int i = 0; i < pieces.Count; i++) + { + Piece piece = pieces[i]; + if (piece == null) continue; + if (Vector3.SqrMagnitude(piece.transform.position - anchor) > radiusSq) continue; + + // A station of the other trade is not this servant's business, but it is still not a + // chest - hence the continue either way. + // Both trades: the drone serves the smelters AND the kitchens. + ButlerStation station = ButlerStation.From(piece.gameObject); + if (station != null) + { + m_stations.Add(station); + continue; + } + + // Every chest in reach is the drone's, EXCEPT one holding the sigil. The two special + // chests are told apart by prefab name. + Container container = piece.GetComponent(); + if (container != null && !IsMarkedOff(container)) + { + string chestName = Utils.GetPrefabName(piece.gameObject); + if (chestName == AlfarChests.EntryName) m_entry = container; + else if (chestName == AlfarChests.WoodName) m_wood = container; + else m_chests.Add(container); + } + + // Anything damaged is for the drones to mend, towers and chests and walls alike. + WearNTear wear = piece.GetComponent(); + if (wear != null && wear.GetHealthPercentage() < 0.999f) m_damaged.Add(wear); + } + } + + /// + /// The sigil is INVERTED from the Butler's: it marks the chests the drones must NOT look at. A + /// chest in use by a player is left alone too. The sigil itself is never counted as material and + /// never carried away - see TakeFrom. + /// + private static bool IsMarkedOff(Container container) + { + if (container == null || container.IsInUse()) return true; + + Inventory inventory = container.GetInventory(); + if (inventory == null) return true; + + string sigil = SigilSharedName(); + return !string.IsNullOrEmpty(sigil) && inventory.CountItems(sigil) > 0; + } + + private static string s_sigilShared; + private static string s_sigilFor; + + /// Inventory.CountItems matches on the SHARED name ($item_...), not on the prefab name + /// the stations use, so the configured prefab is resolved once into the other kind of name. + private static string SigilSharedName() + { + string wanted = AlfarSigil.PrefabName; + if (s_sigilFor == wanted) return s_sigilShared; + + s_sigilFor = wanted; + s_sigilShared = null; + + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(wanted) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null) + { + s_sigilShared = drop.m_itemData.m_shared.m_name; + } + else + { + Jotunn.Logger.LogWarning($"[AlfarDrone] No item '{wanted}' to use as the sigil; " + + "no chest can be marked until that name is right."); + } + + return s_sigilShared; + } + + // ---------------------------------------------------------------- the five states + + /// 1. SAVE. A slot about to burn beats everything, and it is the only job it runs to. + private Job PlanRescue() + { + ButlerStation best = null; + float soonest = SpoilPanicSeconds; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.HasOutput) continue; // nothing pullable yet, panic changes nothing + + float left = station.SecondsToSpoil; + if (left >= soonest) continue; + + soonest = left; + best = station; + } + + if (best == null) return null; + + return new Job + { + Kind = "collect", + Target = best.Id, + Claim = best.Id, + Point = best.Position, + Hurry = true, + Label = "Saving the food", + }; + } + + /// 2. COLLECT. Anything finished, and anything already lying under a station. + private Job PlanCollect() + { + ButlerStation best = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.HasOutput && !HasDropsNear(station.Position)) continue; + + float score = Vector3.Distance(transform.position, station.Position); + if (score >= bestScore) continue; + + bestScore = score; + best = station; + } + + if (best == null) return null; + + return new Job + { + Kind = "collect", + Target = best.Id, + Claim = best.Id, + Point = best.Position, + Label = "Collecting", + }; + } + + /// + /// 4. LOAD. Urgency, then distance - and the urgency of a station with nothing wrong with it is + /// how long it has been waiting. A metre of walking is worth four seconds of a station standing + /// idle, so the far furnace wins eventually instead of never. + /// + private Job PlanLoad() + { + ButlerStation best = null; + string bestItem = null; + Container bestChest = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable || station.FreeSlots <= 0) continue; + + Container chest; + string item = FindMaterialFor(station, out chest); + if (item == null) { m_idleSince.Remove(station.Id); continue; } + + float waited = NoteIdle(station.Id); + float score = Vector3.Distance(transform.position, chest.transform.position) + + Vector3.Distance(chest.transform.position, station.Position) - + waited * WaitToMetres; + + if (score >= bestScore) continue; + + bestScore = score; + best = station; + bestItem = item; + bestChest = chest; + } + + if (best == null) return null; + + // The chest first - the station is where the payload goes afterwards, and PlanDelivery + // works that out from the target written on the load. + return new Job + { + Kind = "load", + Target = ZdoOf(bestChest), + Claim = best.Id, + Point = bestChest.transform.position, + Label = "Fetching " + bestItem, + }; + } + + /// + /// 3. REFUEL. Only stations that actually have something to work on. + /// + /// Scored by the walk, the same way PlanLoad is, and for a reason that only appeared once this + /// moved up the list: taking the first station in scan order was harmless while refuelling was + /// the job of last resort, but ahead of loading it lets one furnace at the edge of the circle + /// hold the servant while a cold one two metres away waits. + /// + private Job PlanFuel() + { + Container bestChest = null; + string bestFuel = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable) continue; + + int wanted = station.FuelWanted; + if (wanted <= 0) continue; + + string fuel = station.FuelPrefab; + if (string.IsNullOrEmpty(fuel)) continue; + + Container chest = FindChestWith(fuel); + if (chest == null) continue; + + float score = Vector3.Distance(transform.position, chest.transform.position) + + Vector3.Distance(chest.transform.position, station.Position); + if (score >= bestScore) continue; + + bestScore = score; + bestChest = chest; + bestFuel = fuel; + } + + if (bestChest == null) return null; + + return new Job + { + Kind = "fuel", + Target = ZdoOf(bestChest), + Point = bestChest.transform.position, + Label = "Fetching " + bestFuel, + }; + } + + /// Where the load in hand is going: on to its station, or back into a chest. + private Job PlanDelivery(Vector3 anchor) + { + // A sorting trip has a destination chosen at the entry chest: take it there. + ZDOID dest = m_nview.GetZDO().GetZDOID(KeyDest); + if (dest != ZDOID.None) + { + Container destination = ContainerById(dest); + if (destination != null && !IsMarkedOff(destination) && !IsPenalised(dest) && HasRoomFor(destination)) + { + return new Job + { + Kind = "deposit", + Target = dest, + Point = destination.transform.position, + Label = "Sorting " + Describe(), + }; + } + m_nview.GetZDO().Set(KeyDest, ZDOID.None); + } + + ZDOID target = m_nview.GetZDO().GetZDOID(KeyTarget); + if (target != ZDOID.None) + { + // NO FreeSlots CHECK HERE, and that was the first bug found in play: fuel does not go + // into a slot. A furnace filled to m_maxOre with copper has FreeSlots 0 and still wants + // coal, so gating the delivery on free slots sent the servant back to the chest with + // the coal it had just fetched - and then PlanFuel sent it out for the same coal again, + // forever. AcceptsAnything already asks the right question of both doors. + ButlerStation station = StationById(target); + if (station != null && station.Alive && station.Operable && AcceptsAnything(station)) + { + return new Job + { + Kind = "deposit_station", + Target = target, + Point = station.Position, + Label = "Loading " + Describe(), + }; + } + + // The station is gone, full or cold. The goods are ours to put back, not to hold. + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + } + + Container chest = ChestForProduct(); + if (chest != null) + { + return new Job + { + Kind = "deposit", + Target = ZdoOf(chest), + Point = chest.transform.position, + Label = "Storing " + Describe(), + }; + } + + // Every sealed chest is full - but a chest is not the only place a thing can go. A station + // that BURNS what is in hand is a destination too, and for the smith it is usually the + // right one: the charcoal kiln releases its whole batch in one go (verified in the IL - + // UpdateSmelter only calls SpawnProcessed once the ore queue empties), which is exactly the + // delivery a nearly full chest cannot absorb, and the coal it makes is what the furnace + // beside it is waiting for. Offering the load to a consumer before giving up is what turns + // "nowhere to put 20x Coal" into a full blast furnace. + // + // It comes AFTER the chest and not before, so a product still goes home to the chest that + // paid for it whenever there is room; this is the step before the floor, not instead of + // storing. + ButlerStation consumer = StationWanting(); + if (consumer != null) + { + return new Job + { + Kind = "deposit_station", + Target = consumer.Id, + Point = consumer.Position, + Label = "Loading " + Describe(), + }; + } + + // Nothing will take it. Beside the table it goes: a stalled chain is worse than a tidy + // floor, and nothing may vanish (sec. 7.3). + return new Job + { + Kind = "drop", + Target = ZDOID.None, + Point = anchor, + Label = "Nowhere to put " + Describe(), + }; + } + + /// The nearest station that will take something out of the payload, as material or as + /// fuel. No FreeSlots check, for the reason spelled out above the KeyTarget branch: fuel does + /// not go into a slot, and AcceptsAnything already asks the right question of both doors. + private ButlerStation StationWanting() + { + ButlerStation best = null; + float bestDistance = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable || !AcceptsAnything(station)) continue; + + float distance = Vector3.Distance(transform.position, station.Position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = station; + } + + return best; + } + + // ================================================================ execution + + private void Execute(float dt) + { + if (m_job == null) + { + SetStatus(m_stations.Count == 0 ? "Nothing to serve." : "Nothing to do."); + GoHome(dt); + return; + } + + SetStatus(m_job.Label); + + if (!MoveToPoint(dt, m_job.Point, ArriveDistance, m_job.Hurry)) + { + // Doors do not open for pathfinding. A target it cannot reach goes into the penalty box + // and the servant gets on with something it can do. + if (Time.time > m_jobDeadline) + { + Penalise(m_job.Target); + Jotunn.Logger.LogInfo($"[AlfarDrone] Could not reach {m_job.Kind} target; " + + "setting it aside for a few minutes."); + m_job = null; + m_nextPlan = 0f; + } + return; + } + + bool achieved; + switch (m_job.Kind) + { + case "load": achieved = DoLoad(); break; + case "fuel": achieved = DoFuel(); break; + case "collect": achieved = DoCollect(); break; + case "deposit_station": achieved = DoDepositStation(); break; + case "deposit": achieved = DoDeposit(); break; + case "drop": DropPayload(); achieved = true; break; + case "wait": achieved = true; break; + case "repair": achieved = DoRepair(); break; + case "farm": achieved = DoFarm(); break; + case "farm_finish": achieved = DoFarmFinish(); break; + case "sortfetch": achieved = DoSortFetch(); break; + default: achieved = true; break; + } + + // Arrived and nothing happened: the world moved while it walked. Set that target aside for + // twenty seconds so the next plan picks something else instead of re-deciding the same + // errand on every tick. + if (!achieved) PenaliseShort(m_job.Target); + + m_job = null; + m_nextPlan = 0f; // arriving changes the world; re-plan on the next tick rather than in 1.5 s + } + + /// At the chest: take what the chosen station will eat, and remember where it came from. + private bool DoLoad() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + // The station is chosen again here rather than carried on the job, because the walk took + // time and the world may have moved on. + ButlerStation station = null; + string item = null; + + foreach (ButlerStation candidate in m_stations) + { + if (!candidate.Alive || !candidate.Operable || candidate.FreeSlots <= 0) continue; + if (IsPenalised(candidate.Id)) continue; + + string found = FirstAccepted(candidate, chest); + if (found == null) continue; + + station = candidate; + item = found; + break; + } + + if (station == null || item == null) return false; + + int taken = TakeFrom(chest, item, station.FreeSlots); + if (taken <= 0) return false; + + AddToPayload(item, taken); + m_nview.GetZDO().Set(KeySource, ZdoOf(chest)); + m_nview.GetZDO().Set(KeyTarget, station.Id); + WritePayload(); + return true; + } + + /// At the chest, for fuel. Same shape as DoLoad, and kept separate because fuel goes in + /// through a different door and is never the thing being processed. + private bool DoFuel() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || !station.Operable || IsPenalised(station.Id)) continue; + + int wanted = station.FuelWanted; + string fuel = station.FuelPrefab; + if (wanted <= 0 || string.IsNullOrEmpty(fuel)) continue; + + int taken = TakeFrom(chest, fuel, wanted); + if (taken <= 0) continue; + + AddToPayload(fuel, taken); + m_nview.GetZDO().Set(KeySource, ZdoOf(chest)); + m_nview.GetZDO().Set(KeyTarget, station.Id); + WritePayload(); + return true; + } + + return false; + } + + /// + /// At a station with something finished. Pull first, sweep second - and the sweep is the only + /// place the servant ever picks anything up off the ground, which is what keeps it from tidying + /// away things the player left lying about on purpose. + /// + /// THE ORDER IS THE POINT, and it used to be the other way round. Sweeping first meant every + /// visit collected what the LAST visit had thrown on the floor and then threw a fresh one down; + /// since Plan() hands the servant to PlanDelivery the moment it is carrying anything, it walked + /// off to the chest the instant the sweep landed and abandoned the item it had just pulled. + /// While a hearth kept working there was therefore always exactly one cooked meat lying on the + /// ground - the "loses one per batch, whether that is two or five" the testers reported. + /// + /// The loop is the other half of it. RPC_RemoveDoneItem empties ONE slot per call, so a hearth + /// with five done slots needs five calls; one per visit turned one batch into five round trips + /// to the chest. It runs against OutputPulls rather than against HasOutput alone because the + /// fermenter's Ready survives its own tap for the length of the animation. + /// + private bool DoCollect() + { + ButlerStation station = StationById(m_job.Target); + if (station == null || !station.Alive) return false; + + bool pulled = false; + for (int i = 0; i < station.OutputPulls && station.HasOutput; i++) + { + station.PullOutput(transform.position); + pulled = true; + } + + int before = PayloadCount(); + SweepDrops(station.Position); + bool swept = PayloadCount() > before; + + if (swept) + { + // The product belongs to whoever fed the station. If nothing was written there - the + // player loaded it by hand - it goes to the nearest sealed chest instead, which is the + // "yes, it collects your work too" decision paying its own way. + ZDOID fedBy = station.Nview.GetZDO().GetZDOID(KeyFedBy); + m_nview.GetZDO().Set(KeySource, fedBy); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + } + + return swept || pulled; + } + + /// At the station, with raw material in hand. + private bool DoDepositStation() + { + ButlerStation station = StationById(m_job.Target); + if (station == null || !station.Alive || !station.Operable) return false; + + bool loadedAny = false; + + for (int i = m_payload.Count - 1; i >= 0; i--) + { + Load load = m_payload[i]; + + while (load.Count > 0 && station.FreeSlots > 0 && station.Accepts(load.Name)) + { + station.Add(load.Name); + load.Count--; + loadedAny = true; + } + + // Fuel goes in through its own door, and only for as long as it is wanted. + if (load.Count > 0 && load.Name == station.FuelPrefab) + { + int wanted = station.FuelWanted; + while (load.Count > 0 && wanted > 0) + { + station.AddFuel(); + load.Count--; + wanted--; + loadedAny = true; + } + } + + if (load.Count <= 0) m_payload.RemoveAt(i); + } + + if (loadedAny) + { + // Whoever fed it, gets it back. + ZDOID source = m_nview.GetZDO().GetZDOID(KeySource); + if (source != ZDOID.None && station.Nview.IsValid()) + { + if (!station.Nview.IsOwner()) station.Nview.ClaimOwnership(); + station.Nview.GetZDO().Set(KeyFedBy, source); + } + } + + if (m_payload.Count == 0) m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + return loadedAny; + } + + /// At a chest, with the finished goods. + private bool DoDeposit() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + ZNetView nview = chest.GetComponent(); + if (nview == null || !nview.IsValid()) return false; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return false; + + bool wrote = false; + + for (int i = m_payload.Count - 1; i >= 0; i--) + { + Load load = m_payload[i]; + + GameObject prefab = ObjectDB.instance != null + ? ObjectDB.instance.GetItemPrefab(load.Name) + : null; + if (prefab == null) continue; + + // One at a time: it stacks correctly, it stops exactly when the chest is full, and the + // counts are small enough that being tidy costs nothing. + while (load.Count > 0 && inventory.CanAddItem(prefab, 1) && inventory.AddItem(prefab, 1)) + { + load.Count--; + wrote = true; + } + + if (load.Count <= 0) m_payload.RemoveAt(i); + } + + if (wrote && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null); + WritePayload(); + + // Still holding something: that chest is full, so do not choose it again on the next pass. + if (m_payload.Count > 0) Penalise(m_job.Target); + else m_nview.GetZDO().Set(KeyDest, ZDOID.None); + return wrote; + } + + // ================================================================ claims + + // Two drones must not take the same station or chest in the same moment. The Butler forbids a + // second table nearby; with N drones to a Nexus that is impossible, so the choice is made + // visible between them: a target is CLAIMED by the drone that picked it for a short while. This + // is the local-client form of the dispatcher the design asks for; two clients owning two + // drones still cannot see each other's claims (doc 17.14). + private static readonly Dictionary> s_claims = + new Dictionary>(); + private const float ClaimSeconds = 30f; + + private bool ClaimedByOther(ZDOID id) + { + if (id == ZDOID.None) return false; + KeyValuePair claim; + if (!s_claims.TryGetValue(id, out claim)) return false; + + if (claim.Key == null || Time.time >= claim.Value) { s_claims.Remove(id); return false; } + return claim.Key != this; + } + + private void Claim(ZDOID id) + { + if (id != ZDOID.None) s_claims[id] = new KeyValuePair(this, Time.time + ClaimSeconds); + } + + private void Release(ZDOID id) + { + KeyValuePair claim; + if (id != ZDOID.None && s_claims.TryGetValue(id, out claim) && claim.Key == this) s_claims.Remove(id); + } + + // ================================================================ repair + + /// + /// Anything damaged in the base, and any other drone that is hurt. Free, like the hammer. NOT the + /// constructs: their damage is permanent by design (they are Characters and not pieces, and + /// they are not drones, so they never come up here). + /// + private Job PlanRepair(Vector3 anchor) + { + WearNTear bestPiece = null; + AlfarDroneAI bestDrone = null; + float bestDistance = float.MaxValue; + + foreach (WearNTear wear in m_damaged) + { + if (wear == null) continue; + ZDOID id = ZdoOf(wear); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + float distance = Vector3.Distance(transform.position, wear.transform.position); + if (distance >= bestDistance) continue; + bestDistance = distance; + bestPiece = wear; + } + + foreach (AlfarDroneAI other in All) + { + if (other == null || other == this || other.m_character == null || other.m_character.IsDead()) continue; + if (other.m_character.GetHealth() >= other.m_character.GetMaxHealth() - 0.5f) continue; + if (Vector3.Distance(other.transform.position, anchor) > AlfarNexusConfig.NexusRadius.Value) continue; + + ZDOID id = ZdoOf(other); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + float distance = Vector3.Distance(transform.position, other.transform.position); + if (distance >= bestDistance) continue; + bestDistance = distance; + bestDrone = other; + bestPiece = null; + } + + if (bestPiece != null) + { + ZDOID id = ZdoOf(bestPiece); + return new Job { Kind = "repair", Target = id, Claim = id, Point = bestPiece.transform.position, Label = "Repairing" }; + } + if (bestDrone != null) + { + ZDOID id = ZdoOf(bestDrone); + return new Job { Kind = "repair", Target = id, Claim = id, Point = bestDrone.transform.position, Label = "Mending a drone" }; + } + return null; + } + + private bool DoRepair() + { + if (ZNetScene.instance == null) return false; + + GameObject go = ZNetScene.instance.FindInstance(m_job.Target); + if (go == null) return false; + + WearNTear wear = go.GetComponent(); + if (wear != null) return wear.Repair(); + + Character character = go.GetComponent(); + if (character != null && !character.IsDead() && go.GetComponent() != null) + { + character.Heal(character.GetMaxHealth(), true); + return true; + } + return false; + } + + // ================================================================ farming + + private class PlantInfo + { + public GameObject Sapling; // the piece that grows the plant + public string Item; // the item that piece costs, and so the item to put back + } + + // pickable prefab name -> the sapling that grows it and the item that sapling costs + private static readonly Dictionary s_plants = new Dictionary(); + private static bool s_plantsBuilt; + private static float s_pickScanAt = -99f; + private static readonly List s_pickables = new List(); + private static readonly System.Reflection.FieldInfo PickedField = AccessTools.Field(typeof(Pickable), "m_picked"); + + /// + /// Built from the game, not from a list: every Plant in ZNetScene names the pickable it grows + /// into and costs one of an item through its Piece. The drone ONLY works plants it can put back + /// (rule R2): it never harvests something it could not replant. + /// + private static void BuildPlants() + { + if (s_plantsBuilt || ZNetScene.instance == null) return; + s_plantsBuilt = true; + + foreach (GameObject prefab in ZNetScene.instance.m_prefabs) + { + if (prefab == null) continue; + + Plant plant = prefab.GetComponent(); + Piece piece = prefab.GetComponent(); + if (plant == null || piece == null || plant.m_grownPrefabs == null) continue; + if (piece.m_resources == null || piece.m_resources.Length == 0 || piece.m_resources[0].m_resItem == null) continue; + + string item = piece.m_resources[0].m_resItem.gameObject.name; + foreach (GameObject grown in plant.m_grownPrefabs) + { + if (grown != null && !s_plants.ContainsKey(grown.name)) + { + s_plants[grown.name] = new PlantInfo { Sapling = prefab, Item = item }; + } + } + } + Jotunn.Logger.LogInfo($"[AlfarDrone] {s_plants.Count} replantable crops known."); + } + + private static void RefreshPickables() + { + if (Time.time - s_pickScanAt < 4f) return; + s_pickScanAt = Time.time; + + s_pickables.Clear(); + s_pickables.AddRange(Object.FindObjectsByType(FindObjectsSortMode.None)); + } + + private static bool IsPicked(Pickable pickable) + { + return PickedField != null && (bool)PickedField.GetValue(pickable); + } + + /// Does picking it give back the item the sapling costs? + private static bool Yields(Pickable pickable, string item) + { + if (pickable.m_itemPrefab != null && pickable.m_itemPrefab.name == item) return true; + + if (pickable.m_extraDrops != null && pickable.m_extraDrops.m_drops != null) + { + foreach (DropTable.DropData drop in pickable.m_extraDrops.m_drops) + { + if (drop.m_item != null && drop.m_item.name == item) return true; + } + } + return false; + } + + private static string[] s_wild; + private static bool IsWildTarget(string prefabName) + { + if (s_wild == null) s_wild = AlfarNexusConfig.WildPickables.Value.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries); + foreach (string part in s_wild) + { + if (prefabName.IndexOf(part.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true; + } + return false; + } + + /// + /// FARMING, with the iron rule (doc 9.4): a cultivated plant is harvested only if the drone can + /// replant one of what it gives; the replant is made RIGHT AWAY, in the SAME place, out of what + /// was just picked, and the rest is stored. Wild mushrooms, berry bushes and flowers on the list + /// are picked and NOT replanted (they grow back by themselves, and trees are never touched). + /// + private Job PlanFarm(Vector3 anchor) + { + BuildPlants(); + RefreshPickables(); + + float radius = AlfarNexusConfig.NexusRadius.Value; + Pickable best = null; + PlantInfo bestInfo = null; + float bestDistance = float.MaxValue; + + foreach (Pickable pickable in s_pickables) + { + if (pickable == null || !pickable.gameObject.activeInHierarchy) continue; + if (Vector3.Distance(pickable.transform.position, anchor) > radius) continue; + if (IsPicked(pickable)) continue; + + ZDOID id = ZdoOf(pickable); + if (id == ZDOID.None || IsPenalised(id) || ClaimedByOther(id)) continue; + + string name = Utils.GetPrefabName(pickable.gameObject); + PlantInfo info = null; + + if (pickable.m_respawnTimeMinutes > 0f) + { + if (!IsWildTarget(name)) continue; // wild and regrowing: only the listed ones + } + else + { + if (!s_plants.TryGetValue(name, out info) || !Yields(pickable, info.Item)) continue; + } + + float distance = Vector3.Distance(transform.position, pickable.transform.position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = pickable; + bestInfo = info; + } + + if (best == null) return null; + + m_farmInfo = bestInfo; + ZDOID target = ZdoOf(best); + return new Job { Kind = "farm", Target = target, Claim = target, Point = best.transform.position, Label = "Harvesting" }; + } + + private bool DoFarm() + { + if (ZNetScene.instance == null) return false; + + GameObject go = ZNetScene.instance.FindInstance(m_job.Target); + Pickable pickable = go != null ? go.GetComponent() : null; + if (pickable == null || IsPicked(pickable)) return false; + + Humanoid hands = m_character as Humanoid; + if (hands == null) return false; + + Vector3 spot = pickable.transform.position; + Quaternion rot = pickable.transform.rotation; + + if (!pickable.Interact(hands, false, false)) return false; + + m_farmSpot = spot; + m_farmRot = rot; + m_farmReadyAt = Time.time + 0.8f; // the drops need a moment to land + return true; + } + + private bool DoFarmFinish() + { + Vector3? spot = m_farmSpot; + PlantInfo info = m_farmInfo; + m_farmSpot = null; + m_farmInfo = null; + if (spot == null) return false; + + SweepDrops(spot.Value); + + if (info != null) + { + // R6: the replant comes OUT OF what was just picked, never out of anyone's stock. + bool have = false; + foreach (Load load in m_payload) + { + if (load.Name == info.Item && load.Count > 0) { load.Count--; have = true; break; } + } + m_payload.RemoveAll(l => l.Count <= 0); + WritePayload(); + + if (have && info.Sapling != null) + { + Object.Instantiate(info.Sapling, spot.Value, m_farmRot); + } + else + { + Jotunn.Logger.LogWarning($"[AlfarDrone] Harvested a crop but found no '{info.Item}' to put back."); + } + } + + m_nview.GetZDO().Set(KeySource, ZDOID.None); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + return true; + } + + // ================================================================ sorting + + private bool AnyStationAccepts(string prefabName) + { + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || !station.Operable) continue; + if (station.Accepts(prefabName) || prefabName == station.FuelPrefab) return true; + } + return false; + } + + /// The storage chest that already holds this item and has room; else the first EMPTY one. + private Container DestinationFor(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + if (prefab == null) return null; + + Container firstEmpty = null; + foreach (Container chest in m_chests) + { + if (chest == null || chest.IsInUse()) continue; + + ZDOID id = ZdoOf(chest); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + Inventory inventory = chest.GetInventory(); + if (inventory == null || !inventory.CanAddItem(prefab, 1)) continue; + + if (inventory.GetAllItems().Count == 0) + { + if (firstEmpty == null) firstEmpty = chest; + continue; + } + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName) return chest; + } + } + return firstEmpty; + } + + /// + /// Tidying the entry chest, last of all. What a station will take is the WORK QUEUE and stays; the + /// rest (and any wood, which is stock unless it is in the wood chest) goes to the chest that + /// already holds the same thing, or to an empty one. With nowhere to go it stays where it is. + /// + private Job PlanSort() + { + if (m_entry == null || m_entry.IsInUse()) return null; + + ZDOID entryId = ZdoOf(m_entry); + if (IsPenalised(entryId)) return null; + + Inventory inventory = m_entry.GetInventory(); + if (inventory == null) return null; + + string sigil = AlfarSigil.PrefabName; + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + + string name = item.m_dropPrefab.name; + if (name == sigil) continue; + if (!IsWood(name) && AnyStationAccepts(name)) continue; + + Container destination = DestinationFor(name); + if (destination == null) continue; + + m_sortItem = name; + m_sortDest = ZdoOf(destination); + return new Job + { + Kind = "sortfetch", + Target = entryId, + Claim = m_sortDest, + Point = m_entry.transform.position, + Label = "Sorting " + name, + }; + } + return null; + } + + private bool DoSortFetch() + { + if (m_sortItem == null || m_sortDest == ZDOID.None) return false; + + Container entry = ContainerById(m_job.Target); + if (entry == null) return false; + + int taken = TakeFrom(entry, m_sortItem, 40); + if (taken <= 0) return false; + + AddToPayload(m_sortItem, taken); + m_nview.GetZDO().Set(KeyDest, m_sortDest); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + return true; + } + + // ================================================================ moving + + /// Vanilla pathing, through the private MoveTo. True the moment it has arrived. + private bool MoveToPoint(float dt, Vector3 point, float distance, bool run) + { + if (m_ai == null || MoveToMethod == null) return true; // cannot walk: act in place + + m_moveArgs[0] = dt; + m_moveArgs[1] = point; + m_moveArgs[2] = distance; + m_moveArgs[3] = run; + + return (bool)MoveToMethod.Invoke(m_ai, m_moveArgs); + } + + private void GoHome(float dt) + { + Vector3? anchor = Anchor; + if (anchor == null) + { + if (m_ai != null) m_ai.StopMoving(); + return; + } + + MoveToPoint(dt, anchor.Value, m_homeDistance, false); + } + + // ================================================================ the ground + + private static int ItemMask() + { + if (s_itemMask >= 0) return s_itemMask; + + int mask = LayerMask.GetMask("item"); + s_itemMask = mask != 0 ? mask : ~0; + return s_itemMask; + } + + private bool HasDropsNear(Vector3 point) + { + Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask()); + foreach (Collider hit in hits) + { + if (hit == null) continue; + ItemDrop drop = hit.GetComponentInParent(); + if (drop != null && drop.m_itemData != null) return true; + } + return false; + } + + /// + /// Picks up everything lying around a station. The drop is destroyed and its contents become + /// entries in the virtual payload, which is the same road the smelter's bars, the oven's bread + /// and the fermenter's bottles all arrive by - one pickup routine for three families. + /// + private void SweepDrops(Vector3 point) + { + Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask()); + + foreach (Collider hit in hits) + { + if (hit == null) continue; + if (PayloadCount() >= PayloadCap) return; + + ItemDrop drop = hit.GetComponentInParent(); + if (drop == null || drop.m_itemData == null) continue; + + ZNetView nview = drop.GetComponent(); + if (nview == null || !nview.IsValid()) continue; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + string name = drop.m_itemData.m_dropPrefab != null + ? drop.m_itemData.m_dropPrefab.name + : Utils.GetPrefabName(drop.gameObject); + if (string.IsNullOrEmpty(name)) continue; + + AddToPayload(name, Mathf.Max(1, drop.m_itemData.m_stack)); + if (ZNetScene.instance != null) ZNetScene.instance.Destroy(drop.gameObject); + } + } + + /// + /// Puts the virtual load back into the world as real objects. Called when the servant dies and + /// when there is nowhere left to put anything - the two ends of the same promise, which is that + /// nothing the player owns is ever deleted by this feature. + /// + public void DropPayload() + { + if (m_payload.Count == 0) return; + if (ObjectDB.instance == null) { m_payload.Clear(); return; } + + Vector3 at = transform.position + Vector3.up * 0.4f; + + foreach (Load load in m_payload) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name); + ItemDrop template = prefab != null ? prefab.GetComponent() : null; + if (template == null || template.m_itemData == null) continue; + + int left = load.Count; + int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize); + + while (left > 0) + { + int stack = Mathf.Min(left, max); + + // ItemDrop.DropItem instantiates item.m_dropPrefab - a clone off a raw ObjectDB + // prefab does not carry that (see AswidBloodPotions.MakeFood for the same fix). + // Without this, dropping a payload throws instantiating null and never clears + // it, so the same broken load is retried - and crashes - on every AI tick after. + ItemDrop.ItemData clone = template.m_itemData.Clone(); + clone.m_dropPrefab = prefab; + + ItemDrop.DropItem(clone, stack, + at + Random.insideUnitSphere * 0.3f, Quaternion.identity); + left -= stack; + } + } + + m_payload.Clear(); + WritePayload(); + } + + // ================================================================ chests + + /// + /// Takes up to of a prefab out of a chest. The sigil is skipped by name, + /// which is the one thing in here that must never be got wrong: carrying it off would unmark the + /// chest halfway through a job. + /// + private int TakeFrom(Container chest, string prefabName, int want) + { + if (chest == null || want <= 0) return 0; + if (prefabName == AlfarSigil.PrefabName) return 0; + + ZNetView nview = chest.GetComponent(); + if (nview == null || !nview.IsValid()) return 0; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return 0; + + List matches = new List(); + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + if (item.m_dropPrefab.name != prefabName) continue; + matches.Add(item); + } + + int taken = 0; + foreach (ItemDrop.ItemData item in matches) + { + if (taken >= want) break; + + int amount = Mathf.Min(item.m_stack, want - taken); + if (amount <= 0) continue; + + inventory.RemoveItem(item, amount); + taken += amount; + } + + if (taken > 0 && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null); + return taken; + } + + // The wood that may be burnt. Only the wood chest's wood is ever consumed: the same wood in the + // entry chest is stock to be sorted, never fuel or charcoal. + private static readonly HashSet s_woodFamily = new HashSet + { + "Wood", "FineWood", "RoundLog", "ElderBark", "YggdrasilWood", "Blackwood", + }; + + private static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName); + + /// + /// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest + /// (never its wood), and wood only from the WOOD chest. + /// + private string FindMaterialFor(ButlerStation station, out Container chest) + { + foreach (Container candidate in new[] { m_entry, m_wood }) + { + if (candidate == null || candidate.IsInUse()) continue; + + string item = FirstAccepted(station, candidate); + if (item == null) continue; + + chest = candidate; + return item; + } + + chest = null; + return null; + } + + private string FirstAccepted(ButlerStation station, Container chest) + { + Inventory inventory = chest != null ? chest.GetInventory() : null; + if (inventory == null) return null; + + bool woodChest = chest == m_wood; + string sigil = AlfarSigil.PrefabName; + string fuel = station.FuelPrefab; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + + string name = item.m_dropPrefab.name; + if (name == sigil) continue; + if (name == fuel) continue; // fuel has its own errand + if (IsWood(name) != woodChest) continue; // wood from the wood chest, the rest from the entry + if (!station.Accepts(name)) continue; + + return name; + } + + return null; + } + + /// Fuel: wood-type fuel from the wood chest, anything else (coal) from the entry chest. + private Container FindChestWith(string prefabName) + { + Container chest = IsWood(prefabName) ? m_wood : m_entry; + if (chest == null || chest.IsInUse()) return null; + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return null; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName) return chest; + } + return null; + } + + /// + /// Where the finished goods go: back to the ENTRY chest, which is both the inbox and the outbox; + /// they are sorted from there. If it is full, the nearest storage chest with room. + /// + private Container ChestForProduct() + { + if (m_entry != null && !m_entry.IsInUse() && !IsPenalised(ZdoOf(m_entry)) && HasRoomFor(m_entry)) return m_entry; + + Container best = null; + float bestDistance = float.MaxValue; + + foreach (Container chest in m_chests) + { + if (chest == null || chest.IsInUse()) continue; + if (IsPenalised(ZdoOf(chest))) continue; + if (!HasRoomFor(chest)) continue; + + float distance = Vector3.Distance(transform.position, chest.transform.position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = chest; + } + + return best; + } + + private bool HasRoomFor(Container chest) + { + Inventory inventory = chest != null ? chest.GetInventory() : null; + if (inventory == null || ObjectDB.instance == null) return false; + + foreach (Load load in m_payload) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name); + if (prefab != null && inventory.CanAddItem(prefab, 1)) return true; + } + + return false; + } + + // ================================================================ payload + + private bool AcceptsAnything(ButlerStation station) + { + foreach (Load load in m_payload) + { + if (station.Accepts(load.Name)) return true; + if (load.Name == station.FuelPrefab && station.FuelWanted > 0) return true; + } + return false; + } + + private void AddToPayload(string name, int count) + { + if (string.IsNullOrEmpty(name) || count <= 0) return; + + foreach (Load load in m_payload) + { + if (load.Name != name) continue; + load.Count += count; + WritePayload(); + return; + } + + m_payload.Add(new Load { Name = name, Count = count }); + WritePayload(); + } + + private int PayloadCount() + { + int total = 0; + foreach (Load load in m_payload) total += load.Count; + return total; + } + + private string Describe() + { + if (m_payload.Count == 0) return "nothing"; + if (m_payload.Count == 1) return m_payload[0].Count + "x " + m_payload[0].Name; + + return PayloadCount() + " items"; + } + + /// "Copper:8;Coal:12". Small, readable in a ZDO dump, and enough to survive a handover + /// mid-job - which is the whole reason the payload lives in the ZDO instead of in this class. + private void WritePayload() + { + if (m_nview == null || !m_nview.IsValid()) return; + + StringBuilder builder = new StringBuilder(); + foreach (Load load in m_payload) + { + if (load.Count <= 0) continue; + if (builder.Length > 0) builder.Append(';'); + builder.Append(load.Name).Append(':').Append(load.Count); + } + + m_nview.GetZDO().Set(KeyLoad, builder.ToString()); + } + + private void ReadPayload() + { + m_payload.Clear(); + if (m_nview == null || !m_nview.IsValid()) return; + + string raw = m_nview.GetZDO().GetString(KeyLoad, ""); + if (string.IsNullOrEmpty(raw)) return; + + foreach (string entry in raw.Split(';')) + { + if (string.IsNullOrEmpty(entry)) continue; + + int split = entry.LastIndexOf(':'); + if (split <= 0) continue; + + int count; + if (!int.TryParse(entry.Substring(split + 1), out count) || count <= 0) continue; + + m_payload.Add(new Load { Name = entry.Substring(0, split), Count = count }); + } + } + + // ================================================================ small change + + private static ZDOID ZdoOf(Component component) + { + ZNetView nview = component != null ? component.GetComponent() : null; + return nview != null && nview.IsValid() ? nview.GetZDO().m_uid : ZDOID.None; + } + + private Container ContainerById(ZDOID id) + { + if (id == ZDOID.None || ZNetScene.instance == null) return null; + + GameObject go = ZNetScene.instance.FindInstance(id); + return go != null ? go.GetComponent() : null; + } + + private ButlerStation StationById(ZDOID id) + { + foreach (ButlerStation station in m_stations) + { + if (station.Id == id) return station; + } + + if (id == ZDOID.None || ZNetScene.instance == null) return null; + + GameObject go = ZNetScene.instance.FindInstance(id); + return go != null ? ButlerStation.From(go) : null; + } + + private void Penalise(ZDOID id) + { + if (id == ZDOID.None) return; + m_penalties[id] = Time.time + PenaltySeconds; + } + + /// Never shortens a penalty already running: a target set aside for three minutes + /// because it could not be reached must not be let back in after twenty seconds. + private void PenaliseShort(ZDOID id) + { + if (id == ZDOID.None) return; + + float until; + float wanted = Time.time + ShortPenaltySeconds; + if (m_penalties.TryGetValue(id, out until) && until > wanted) return; + + m_penalties[id] = wanted; + } + + private bool IsPenalised(ZDOID id) + { + float until; + return m_penalties.TryGetValue(id, out until) && Time.time < until; + } + + private void ExpirePenalties() + { + if (m_penalties.Count == 0) return; + + List done = null; + foreach (KeyValuePair entry in m_penalties) + { + if (Time.time < entry.Value) continue; + if (done == null) done = new List(); + done.Add(entry.Key); + } + + if (done == null) return; + foreach (ZDOID id in done) m_penalties.Remove(id); + } + + /// Seconds this station has been waiting with work available. + private float NoteIdle(ZDOID id) + { + float since; + if (!m_idleSince.TryGetValue(id, out since)) + { + m_idleSince[id] = Time.time; + return 0f; + } + + return Time.time - since; + } + } + + /// + /// The whole of the servant's mind, in one prefix. + /// + /// Returning false skips MonsterAI.UpdateAI entirely - targeting, alerting, fleeing, wandering and + /// attacking with it - so the servant is peaceful by construction rather than by having its weapon + /// confiscated. __result is legitimate here and not the old PlacePiece trap: that one threw because + /// the patched method was VOID. This one returns bool, which is exactly what a prefix may write. + /// + /// Bound positionally (__0) so a parameter rename in a future patch cannot stop the mod from + /// applying its patches at startup. + /// + [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] + public static class AlfarDroneUpdateAIPatch + { + public static bool Prefix(MonsterAI __instance, float __0, ref bool __result) + { + if (__instance == null) return true; + + AlfarDroneAI servant = __instance.GetComponent(); + if (servant == null) return true; + + // The one way back into vanilla: a servant that fights back hands over the whole tick for + // as long as there is a fight. Always false for the Bone Servants themselves. + if (servant.HandsToVanilla()) return true; + + __result = servant.Tick(__0); + return false; + } + } + + /// Hit and it walks home. The same postfix shape the sentry's regeneration uses, on the + /// same method, which is a shape known to work in this project. + [HarmonyPatch(typeof(Character), "Damage")] + public static class AlfarDroneDamagePatch + { + public static void Postfix(Character __instance) + { + if (__instance == null) return; + + AlfarDroneAI servant = __instance.GetComponent(); + if (servant != null) servant.NoteDamage(); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarDrones.cs b/JotunnModStub/Alfar/AlfarDrones.cs new file mode 100644 index 0000000..7cef524 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarDrones.cs @@ -0,0 +1,365 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSVAETTIR, the Alfar's drones (Alfar_Progettazione.txt sec. 9): a Deathsquito without legs, + /// stinger or buzz, bronze, with blue light. One kind of drone does every job (the work itself is + /// AlfarDroneWork); the only thing apart is the GRAFVAETTIR, the same creature thrown like a + /// grenade to dig the precious ores around a point for two minutes and then vanish. + /// + /// What a drone is by itself: 25 hp and a shield of 25, tamed, tied to its Ljoskjarne, and able to + /// defend itself with a lightning zap of 1 damage every two seconds. It never attacks anything + /// outside the Nexus's radius and never goes after anything: it is a worker, not a soldier. + /// + /// The Deathsquito is ONE skinned mesh with one material (probe, doc 16C P1): the legs are bones, so + /// they are hidden by scaling the bones to zero, and the blue is an emission on a bronze body, not + /// separate eyes and wings - a true repaint is still to do. + /// + public static class AlfarDrones + { + public const string DroneName = "AlfarDrone"; + public const string MinerName = "AlfarGrafvaettir"; + public const string ZapWeapon = "AlfarDroneZap"; + + private static readonly Color Bronze = new Color(1f, 0.62f, 0.25f, 1f); + private static readonly Color ElectricBlue = new Color(0.25f, 0.65f, 1f, 1f); + + public static void Register() + { + GameObject source = PrefabManager.Cache.GetPrefab("Deathsquito"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] No 'Deathsquito' to build the drones from."); + return; + } + + bool zap = RegisterZap(source); + RegisterOne(source, DroneName, "$rov_creature_alfar_drone_name", zap, miner: false); + RegisterOne(source, MinerName, "$rov_creature_alfar_grafvaettir_name", zap, miner: true); + } + + /// The Deathsquito's sting turned into a zap: 1 lightning, every two seconds. + private static bool RegisterZap(GameObject deathsquito) + { + Humanoid humanoid = deathsquito.GetComponent(); + GameObject sting = humanoid != null && humanoid.m_defaultItems != null && humanoid.m_defaultItems.Length > 0 + ? humanoid.m_defaultItems[0] + : null; + if (sting == null) return false; + + GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(ZapWeapon, sting); + if (weapon == null) return false; + + ItemDrop drop = weapon.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = "$rov_item_alfar_zap_name"; + + HitData.DamageTypes damage = default(HitData.DamageTypes); + damage.m_lightning = AlfarNexusConfig.DroneZapDamage.Value; + shared.m_damages = damage; + shared.m_aiAttackInterval = AlfarNexusConfig.DroneZapInterval.Value; + + ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false)); + return true; + } + + private static void RegisterOne(GameObject source, string prefabName, string display, bool zap, bool miner) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) return; + + Character character = prefab.GetComponent(); + if (character != null) + { + character.m_name = display; + character.m_faction = Character.Faction.Players; + character.m_health = AlfarNexusConfig.DroneHealth.Value; + } + + Humanoid humanoid = prefab.GetComponent(); + if (humanoid != null) + { + GameObject weapon = zap ? PrefabManager.Instance.GetPrefab(ZapWeapon) : null; + // A miner does not fight at all; the worker only defends itself. + humanoid.m_defaultItems = !miner && weapon != null ? new[] { weapon } : new GameObject[0]; + humanoid.m_randomWeapon = new GameObject[0]; + humanoid.m_randomArmor = new GameObject[0]; + humanoid.m_randomShield = new GameObject[0]; + humanoid.m_randomSets = new Humanoid.ItemSet[0]; + } + + MonsterAI monster = prefab.GetComponent(); + if (monster != null) + { + monster.m_attackPlayerObjects = false; + monster.m_alertRange = AlfarNexusConfig.NexusRadius.Value; + monster.m_maxChaseDistance = AlfarNexusConfig.NexusRadius.Value; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = 5f; + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + // The buzz: the continuous sound child, and the flying loop effect. + foreach (Transform child in prefab.GetComponentsInChildren(true)) + { + if (child != null && child.name == "SFX") Object.DestroyImmediate(child.gameObject); + } + if (character != null) character.m_flyingContinuousEffect = new EffectList { m_effectPrefabs = new EffectList.EffectData[0] }; + + HideLegs(prefab); + Look(prefab); + prefab.AddComponent(); + + AlfarMark mark = prefab.AddComponent(); + mark.Role = miner ? "miner" : "drone"; + + AlfarCreatureShield shield = prefab.AddComponent(); + shield.MaxShield = AlfarNexusConfig.DroneHealth.Value; + shield.Shield = shield.MaxShield; + + if (miner) + { + // The mining drone has no anchor and no leash: it lives two minutes and vanishes. + prefab.AddComponent(); + } + else + { + // The worker is NOT a RaisedThrall: that brings the follow command on E, and a drone + // that can be walked out of the base stops working (the Butler's reasoning, Butler 9). + // AlfarDroneAI keeps its own anchor to the Nexus and its own wither. + AlfarDroneAI work = prefab.AddComponent(); + work.m_fightsBack = true; // it defends itself with the zap + work.m_homeDistance = 4f; + } + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Alfar] Registered '{prefabName}'."); + } + + /// + /// No legs: the mesh is one skinned body, so the leg bones are scaled to zero and take their + /// part of the mesh with them. The stinger has no bone of its own and is left (doc 16C P1). + /// + private static void HideLegs(GameObject prefab) + { + foreach (Transform bone in prefab.GetComponentsInChildren(true)) + { + string n = bone.name; + if (n == "L.leg1" || n == "R.leg1") bone.localScale = Vector3.zero; + } + } + + private static void Look(GameObject prefab) + { + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material == null) continue; + if (material.HasProperty("_Color")) material.color = Bronze; + if (material.HasProperty("_EmissionColor")) + { + material.SetColor("_EmissionColor", ElectricBlue * 0.15f); + material.EnableKeyword("_EMISSION"); + } + } + renderer.materials = materials; + } + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = ElectricBlue; + } + + /// + /// The same look, applied to the LIVE body at spawn and re-applied after the animator every + /// frame for the bones: edits made on the registered clone may not reach the instance, and the + /// animator can write the leg scale back. + /// + public class AlfarDroneLook : MonoBehaviour + { + private Transform[] legs; + + private void Awake() + { + var list = new System.Collections.Generic.List(); + foreach (Transform bone in GetComponentsInChildren(true)) + { + if (bone.name == "L.leg1" || bone.name == "R.leg1") list.Add(bone); + } + legs = list.ToArray(); + Look(gameObject); + } + + private void LateUpdate() + { + foreach (Transform leg in legs) if (leg != null) leg.localScale = Vector3.zero; + } + } + + // ─── Counting and spawning ─────────────────────────────────────────── + + public static int CountAlive(Vector3 anchor) + { + int count = 0; + foreach (AlfarDroneAI drone in AlfarDroneAI.All) + { + if (drone != null && drone.IsBoundTo(anchor)) count++; + } + return count; + } + + public static bool Spawn(Vector3 anchor) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(DroneName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{DroneName}' in ZNetScene: no drone can be made."); + return false; + } + + Vector3 where = AlfarConstructs.SpawnSpot(anchor) + Vector3.up * 1.5f; + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity); + AlfarDroneAI work = spawned != null ? spawned.GetComponent() : null; + if (work != null) work.Bind(anchor); + return spawned != null; + } + } + + /// + /// A MINING DRONE: thrown to a point, it digs the precious ores around that point for a fixed time + /// and then vanishes (design sec. 9.3). It takes over its own AI tick like the Butler's servants do + /// (a prefix on MonsterAI.UpdateAI), flies to the nearest deposit on the list and strikes it with + /// pickaxe damage at a tool tier high enough for any of them. The ore falls where it stands. + /// + /// Whatever it breaks is on the list in AlfarMiner.Deposits; a name list in the config so a + /// wrong or missing name is a config edit, not a rebuild. + /// + public class AlfarMiner : MonoBehaviour + { + public Vector3 Centre; + public float Radius = 12f; + public float LiveSeconds = 120f; + + private float born; + private float nextStrike; + private Component target; + + private static readonly System.Reflection.MethodInfo MoveToMethod = + AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); + + private void Start() + { + born = Time.time; + } + + public bool Tick(MonsterAI ai, float dt) + { + if (Time.time - born >= LiveSeconds) + { + ZNetView nview = GetComponent(); + if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject); + return true; + } + + if (target == null || !target.gameObject.activeInHierarchy) target = FindDeposit(); + if (target == null) { ai.StopMoving(); return true; } + + Vector3 point = target.transform.position; + float distance = Vector3.Distance(transform.position, point); + + if (distance > 3.5f) + { + if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true }); + return true; + } + + ai.StopMoving(); + if (Time.time < nextStrike) return true; + nextStrike = Time.time + 1f; + Strike(target); + return true; + } + + private static string[] names; + private static string[] Deposits => names ?? (names = AlfarNexusConfig.MinerDeposits.Value.Split( + new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries)); + + private bool IsPrecious(string prefabName) + { + foreach (string wanted in Deposits) + { + if (prefabName.IndexOf(wanted.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true; + } + return false; + } + + private Component FindDeposit() + { + Component best = null; + float bestDistance = float.MaxValue; + foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore)) + { + Component deposit = collider.GetComponentInParent(); + if (deposit == null) deposit = collider.GetComponentInParent(); + if (deposit == null) deposit = collider.GetComponentInParent(); + if (deposit == null) continue; + + string prefabName = Utils.GetPrefabName(deposit.gameObject); + if (!IsPrecious(prefabName)) continue; + + float distance = Vector3.Distance(transform.position, deposit.transform.position); + if (distance < bestDistance) { best = deposit; bestDistance = distance; } + } + return best; + } + + private void Strike(Component deposit) + { + IDestructible destructible = deposit as IDestructible; + if (destructible == null) return; + + HitData hit = new HitData(); + hit.m_damage.m_pickaxe = AlfarNexusConfig.MinerDamage.Value; + hit.m_toolTier = 100; + hit.m_dodgeable = false; + hit.m_blockable = false; + hit.m_point = deposit.transform.position; + hit.m_dir = (deposit.transform.position - transform.position).normalized; + + // MineRock5 picks the piece of the rock to hurt from the collider that was hit. + Collider collider = deposit.GetComponentInChildren(); + if (collider != null) + { + hit.m_hitCollider = collider; + hit.m_point = collider.bounds.center; + } + + destructible.Damage(hit); + } + + [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] + public static class Alfar_Miner_UpdateAI_Patch + { + public static bool Prefix(MonsterAI __instance, float __0, ref bool __result) + { + if (__instance == null) return true; + AlfarMiner miner = __instance.GetComponent(); + if (miner == null) return true; + + __result = miner.Tick(__instance, __0); + return false; + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarEitr.cs b/JotunnModStub/Alfar/AlfarEitr.cs new file mode 100644 index 0000000..5d79655 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarEitr.cs @@ -0,0 +1,166 @@ +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Alfar's one resource (Alfar_Progettazione.txt sec. 3, 4 and 5.1): food becomes eitr, and + /// eitr is the shield. + /// + /// Every signature and call order here was read from assembly_valheim.dll (doc sec. 16B V1-V4), + /// not remembered: + /// - Character.ApplyDamage is the single final stage for direct hits, burning and poison + /// ticks AND falls, so one prefix on it covers all three; + /// - Player.RPC_UseEitr spends eitr and arms the vanilla regeneration delay, which is the + /// only brake the shield has - writing m_eitr by hand would skip the delay; + /// - Player.GetTotalFoodValue is what UpdateFood hands to SetMaxEitr. + /// + public static class AlfarEitr + { + private static readonly MethodInfo UseEitrRpc = + AccessTools.Method(typeof(Player), "RPC_UseEitr", new[] { typeof(long), typeof(float) }); + + /// + /// Spends eitr WITHOUT Game.m_eitrRate scaling, so the rate is exactly the configured one. + /// UseEitr would multiply by the world modifier first; the RPC does not, and it is what + /// arms the regeneration delay (V3). + /// + public static void Spend(Player player, float amount) + { + if (player == null || amount <= 0f) return; + + if (UseEitrRpc == null) + { + Jotunn.Logger.LogWarning("[Alfar] Player.RPC_UseEitr not found: the shield cannot spend eitr."); + return; + } + UseEitrRpc.Invoke(player, new object[] { 0L, amount }); + } + + // ─── Diet ──────────────────────────────────────────────────────────── + + /// + /// Each food adds min(hp, stamina) to the maximum eitr, on top of the eitr it already has. + /// Clarified by the user: the minimum is between hp and stamina ONLY, so a plain cooked + /// meat (40 / 30 / 0) is worth +30 eitr and a balanced food is better than a lopsided one. + /// + /// Locally only: GetTotalFoodValue is the owner's own bookkeeping. Positional parameters + /// (guide 5.16): __0 hp, __1 stamina, __2 eitr. + /// + [HarmonyPatch(typeof(Player), "GetTotalFoodValue")] + public static class Alfar_FoodValue_Patch + { + public static void Postfix(Player __instance, ref float __2) + { + if (__instance == null || !AlfarVisuals.IsAlfarPlayer(__instance)) return; + + float bonus = 0f; + foreach (Player.Food food in __instance.GetFoods()) + { + bonus += Mathf.Min(food.m_health, food.m_stamina); + } + + __2 += bonus * AlfarConfig.DietMultiplier.Value; + } + } + + // ─── Shield and soft fall ──────────────────────────────────────────── + + /// + /// Blows land on the eitr first, 1 for 1. + /// + /// - No cooldown: the shield absorbs for as long as one point of eitr remains. + /// - Lightning and spirit cost double (the cost, not the damage: DamageModifier.Weak is a + /// flat +50% and cannot be made to double anything). + /// - A blow bigger than the pool is shared out: the eitr takes the share it can, the body + /// takes the rest. + /// - Drowning and the edge of the world skip the shield altogether; falls are free while + /// there is eitr and shielded like anything else once there is none left. + /// + /// The prefix edits the HitData and lets ApplyDamage run: with nothing left in it, + /// ApplyDamage returns at once ("took no damage"). Positional parameters, and the argument + /// types are in the attribute so the patch binds to the real overload (guide 5.16). + /// + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_ApplyDamage_Patch + { + public static void Prefix(Character __instance, HitData __0) + { + Player player = __instance as Player; + if (player == null || __0 == null) return; + if (!AlfarVisuals.IsAlfarPlayer(player)) return; + + // The shield belongs to whoever owns the body: ApplyDamage runs on the owner, and a + // remote copy must not spend eitr it does not hold. + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + // The same early exits ApplyDamage has: nothing to absorb, nothing to spend. + if (player.IsDead() || player.IsTeleporting() || player.InCutscene() || player.InGodMode()) return; + + // Just arrived by Heimkall: nothing hurts for a few seconds, or a burning death would + // simply repeat at the bed. + if (Time.time < AlfarHeimkall.InvulnerableUntil) + { + __0.m_damage = default(HitData.DamageTypes); + return; + } + + // In the archon form the pool IS the defence: it takes every blow, drowning and the + // edge of the world included, and the eitr is already spent (AlfarArchon). + if (AlfarArchon.Active) + { + AlfarArchon.Absorb(player, __0); + return; + } + + HitData.HitType type = __0.m_hitType; + if (type == HitData.HitType.Drowning || type == HitData.HitType.EdgeOfWorld) return; + + float available = player.GetEitr(); + + if (type == HitData.HitType.Fall && AlfarConfig.SoftFall.Value) + { + // Soft fall: free while there is eitr, a normal fall once there is none. + if (available > 0f) __0.m_damage = default(HitData.DamageTypes); + return; + } + + float cost = Cost(__0.m_damage); + if (cost <= 0f || available <= 0f) return; + + if (available >= cost) + { + Spend(player, cost); + __0.m_damage = default(HitData.DamageTypes); + return; + } + + // Shared out: the eitr absorbs the fraction it can pay for, the body takes the rest. + float covered = available / cost; + HitData.DamageTypes remaining = __0.m_damage; + remaining.Modify(1f - covered); + __0.m_damage = remaining; + Spend(player, available); + } + + /// + /// The eitr a blow costs. Every damage type that wounds a person counts; chop and + /// pickaxe are tool damage (trees, rocks) and do not. Lightning and spirit are doubled. + /// + private static float Cost(HitData.DamageTypes damage) + { + float rate = AlfarConfig.ShieldRate.Value; + float conductive = AlfarConfig.ConductiveMultiplier.Value; + + float ordinary = damage.m_damage + damage.m_blunt + damage.m_slash + damage.m_pierce + + damage.m_fire + damage.m_frost + damage.m_poison; + float double_ = damage.m_lightning + damage.m_spirit; + + return (ordinary + double_ * conductive) * rate; + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarHeimkall.cs b/JotunnModStub/Alfar/AlfarHeimkall.cs new file mode 100644 index 0000000..49a7dc4 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarHeimkall.cs @@ -0,0 +1,171 @@ +using System.Globalization; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// HEIMKALL: a lethal blow does not kill an Alfr, it sends them to their bed with one hit point + /// (Alfar_Progettazione.txt sec. 6). Then a wait: 20 minutes, 15 after Yagluth, 10 after Fader. + /// Inside the wait a lethal blow kills like it does anyone. + /// + /// HOW IT AVOIDS DEATH (read from the IL, doc sec. 16B V5): + /// Character.ApplyDamage ends with the health at zero, and the death itself is not decided + /// there but in Character.CheckDeath, which Character.CustomFixedUpdate calls on its next step. + /// So a POSTFIX on ApplyDamage that puts one hit point back, the same frame, means the check + /// finds a living body and there is no death routine, no tomb, no skill loss, no message. + /// + /// The timer lives in m_customData as a world-time stamp, so it survives a logout. + /// + public static class AlfarHeimkall + { + private const string TimerKey = "Alfar_HeimkallAt"; + + /// Time.time until which nothing may hurt the local Alfr (the arrival grace). + public static float InvulnerableUntil; + + // ─── The timer ─────────────────────────────────────────────────────── + + /// The cooldown for the current boss progress, in seconds. + public static float CooldownSeconds() + { + int state = BossProgressionManager.GetCurrentProgressionState(); + float minutes = state >= 8 ? AlfarConfig.HeimkallMinutesAfterFader.Value + : state >= 6 ? AlfarConfig.HeimkallMinutesAfterYagluth.Value + : AlfarConfig.HeimkallMinutes.Value; + return minutes * 60f; + } + + /// Seconds left before the next Heimkall; 0 when it is ready. + public static float Remaining(Player player) + { + if (player == null || player.m_customData == null || ZNet.instance == null) return 0f; + if (!player.m_customData.TryGetValue(TimerKey, out string stamp)) return 0f; + if (!double.TryParse(stamp, NumberStyles.Float, CultureInfo.InvariantCulture, out double at)) return 0f; + + double elapsed = ZNet.instance.GetTimeSeconds() - at; + + // A stamp from a different world (its clock is another clock) reads as the future, or as + // a wait longer than any cooldown. Either way the timer is not this world's: ready. + float cooldown = CooldownSeconds(); + if (elapsed < 0d || elapsed > 1e9) return 0f; + + return Mathf.Max(0f, cooldown - (float)elapsed); + } + + public static bool IsReady(Player player) => Remaining(player) <= 0f; + + public static void StartTimer(Player player) + { + if (player == null || ZNet.instance == null) return; + player.m_customData[TimerKey] = + ZNet.instance.GetTimeSeconds().ToString("R", CultureInfo.InvariantCulture); + } + + public static void ResetTimer(Player player) + { + if (player != null && player.m_customData != null) player.m_customData.Remove(TimerKey); + AlfarStatusEffects.ClearTimer("heimkall"); + } + + private static float nextIconSync; + + /// + /// Keeps the on-screen Heimkall countdown honest: status effects are not saved, so after a + /// reload the wait is put back on screen with what is really left of it, and removed when over. + /// + public static void SyncIcon(Player player) + { + if (Time.time < nextIconSync) return; + nextIconSync = Time.time + 2f; + + float left = Remaining(player); + bool shown = AlfarStatusEffects.HasTimer("heimkall"); + if (left > 0f && !shown) AlfarStatusEffects.ShowTimer("heimkall", left); + else if (left <= 0f && shown) AlfarStatusEffects.ClearTimer("heimkall"); + } + + // ─── The call home ─────────────────────────────────────────────────── + + /// + /// Teleports to the bed (or the world spawn when there is none) at one hit point, clears what + /// was killing the body, and starts the wait. Returns false when it is not ready. + /// + public static bool TryTrigger(Player player, string reason, bool force = false) + { + // force: the archon form ends with a Heimkall that it already paid for at the start. + if (player == null || (!force && !IsReady(player))) return false; + + bool bed; + Vector3 destination = FindDestination(out bed); + + // distantTeleport tells Valheim to stream the destination zone in first. Anything past a + // couple of zone-widths needs it. + bool distant = Vector3.Distance(player.transform.position, destination) > 100f; + bool teleported = player.TeleportTo(destination, player.transform.rotation, distant); + + // Whether or not the teleport was accepted (it refuses for two seconds after another + // one), the body must not die this frame. + player.SetHealth(1f); + + // What was killing the body goes with it: burning, poison, the cold, being wet. Cleared + // before the passive is put back, since RemoveAll takes that too. + player.GetSEMan().RemoveAllStatusEffects(true); + AlfarStatusEffects.Ensure(player); + + InvulnerableUntil = Time.time + AlfarConfig.HeimkallInvulnerableSeconds.Value; + StartTimer(player); + AlfarStatusEffects.ShowTimer("heimkall", CooldownSeconds()); + + Jotunn.Logger.LogInfo($"[Alfar] Heimkall ({reason}): teleported={teleported} to {destination}; " + + $"next in {CooldownSeconds() / 60f:0} min."); + player.Message(MessageHud.MessageType.Center, ModText.Get(bed ? "rov_msg_alfar_heimkall" : "rov_msg_alfar_heimkall_nobed")); + return true; + } + + /// + /// The bed the player set, else the world's original spawn. A bed point already has its height; + /// the world spawn is stored with a placeholder height (50), so its ground is worked out from the + /// world generator, which answers even when the zone there is not loaded yet - the first version + /// stood the Alfr at 50.5 m in the air or inside a hill. A bed counts only after the player has + /// SET it (sleeping in it, or interacting with it); an unused bed is not a spawn point. + /// + private static Vector3 FindDestination(out bool bed) + { + PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null; + + bed = profile != null && profile.HaveCustomSpawnPoint(); + if (bed) return profile.GetCustomSpawnPoint() + Vector3.up * 0.5f; + + Vector3 point = PlayerProfile.m_originalSpawnPoint; + if (WorldGenerator.instance != null) + { + float ground = WorldGenerator.instance.GetHeight(point.x, point.z); + point.y = Mathf.Max(ground, 30f) + 1f; // 30 is the sea level: never under the water + } + return point; + } + + // ─── The patch ─────────────────────────────────────────────────────── + + /// + /// After the blow has landed: if it left the body at zero, call it home instead. The shield + /// prefix has already taken what it could, so this only fires for the blow the eitr could + /// not cover (or a fall at eitr zero, a drowning, the edge of the world). + /// + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_Heimkall_Patch + { + public static void Postfix(Character __instance) + { + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return; + if (!AlfarVisuals.IsAlfarPlayer(player)) return; + if (player.IsDead() || player.GetHealth() > 0f) return; + + TryTrigger(player, "lethal blow"); + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarLevitation.cs b/JotunnModStub/Alfar/AlfarLevitation.cs new file mode 100644 index 0000000..77f6b9d --- /dev/null +++ b/JotunnModStub/Alfar/AlfarLevitation.cs @@ -0,0 +1,120 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// LEVITATION (Alfar_Progettazione.txt sec. 4.6): in the air, hold the jump key and the Alfr rises + /// slowly, burning eitr slowly. Let go and the soft fall takes over. + /// + /// There is no hover in vanilla. This pushes the rigidbody's vertical speed up toward a small + /// target while the key is held, and nothing else: no horizontal speed is added, so it is a way + /// over a ledge or out of a pit and not flight (the pool of an early Alfr lasts about half a + /// minute of it). + /// + /// It runs on the owner's FixedUpdate, where the rigidbody is read, and the position syncs like + /// any other movement. The eitr is spent in small batches, not every physics step: each spend arms + /// the regeneration delay and goes through an RPC call. + /// + public static class AlfarLevitation + { + // A short moment in the air before it starts, so a normal jump (a tap) is just a jump. + private const float AirDelay = 0.2f; + private const float SpendInterval = 0.25f; + + private static float airTime; + private static float owed; + private static float nextSpend; + + public static bool Rising { get; private set; } + + [HarmonyPatch(typeof(Player), "FixedUpdate")] + public static class Alfar_Levitation_Patch + { + public static void Postfix(Player __instance) + { + if (__instance == null || __instance != Player.m_localPlayer) return; + if (!AlfarVisuals.IsAlfarPlayer(__instance) || __instance.IsDead()) { Reset(); return; } + + // THE ARCHON FLIES for as long as the form lasts: it hovers where it is, climbs while + // jump is held and sinks while crouch is held. The eitr is already gone, so nothing is + // spent. Horizontal movement stays the normal controls. + if (AlfarArchon.Active) + { + Rigidbody flyer = Traverse.Create(__instance).Field("m_body").GetValue(); + if (flyer != null) + { + float speed = AlfarPowerConfig.LevitationRise.Value * 2f; + float target = 0f; + if (Time.time - AlfarArchon.StartedAt < 0.6f) target = 4f; // lift off + else if (RaceInput.Allowed && JumpHeld()) target = speed; + else if (RaceInput.Allowed && ZInput.GetButton("Crouch")) target = -speed; + + Vector3 velocity = flyer.linearVelocity; + velocity.y = Mathf.Lerp(velocity.y, target, 0.25f); + flyer.linearVelocity = velocity; + } + Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y); + Rising = true; + return; + } + + bool wants = RaceInput.Allowed && JumpHeld(); + bool airborne = !__instance.IsOnGround() && !__instance.IsSwimming() && !__instance.IsAttached() && + !__instance.IsFlying(); + + airTime = airborne ? airTime + Time.fixedDeltaTime : 0f; + + float cost = AlfarPowerConfig.LevitationCostPerSecond.Value; + bool canPay = AlfarArchon.Active || __instance.GetEitr() > 0f; + + if (!wants || !airborne || airTime < AirDelay || !canPay) + { + Rising = false; + FlushSpend(__instance); + return; + } + + Rising = true; + + Rigidbody body = Traverse.Create(__instance).Field("m_body").GetValue(); + if (body != null) + { + Vector3 velocity = body.linearVelocity; + velocity.y = Mathf.Lerp(velocity.y, AlfarPowerConfig.LevitationRise.Value, 0.25f); + body.linearVelocity = velocity; + } + + // Rising resets the fall: the point of the soft fall is that the way down starts at + // the top, and a long climb must not count as a long drop at eitr zero. + Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y); + + // In the archon form the eitr is already gone and the pool pays for nothing here. + if (!AlfarArchon.Active) owed += cost * Time.fixedDeltaTime; + if (Time.time >= nextSpend) FlushSpend(__instance); + } + } + + private static bool JumpHeld() + { + // ZInput's "Jump" covers the space bar and the pad's jump button alike, and respects the + // controls the player picked in the settings. + return ZInput.GetButton("Jump"); + } + + private static void FlushSpend(Player player) + { + nextSpend = Time.time + SpendInterval; + if (owed <= 0f) return; + AlfarEitr.Spend(player, owed); + owed = 0f; + } + + private static void Reset() + { + airTime = 0f; + owed = 0f; + Rising = false; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarLjosgard.cs b/JotunnModStub/Alfar/AlfarLjosgard.cs new file mode 100644 index 0000000..e70c5cb --- /dev/null +++ b/JotunnModStub/Alfar/AlfarLjosgard.cs @@ -0,0 +1,108 @@ +using System.Collections.Generic; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSGARD, the garden of light (Alfar_Progettazione.txt sec. 8.6 and 12): the module of the + /// Nexus that mixes the two mushrooms of the Mistlands into SAP, very slowly. + /// + /// It is a clone of the stone furnace with its recipe turned: MAGECAP is the "ore" and JOTUN PUFFS + /// the "fuel", one of each per sap, so mixing the two is exactly what a smelter already does with + /// its two inputs. Being a Smelter it needs no new code to be served: the drones feed it (a + /// Smelter-family station) and carry the sap away, and the refinery (vanilla, sap as fuel and soft + /// tissue as ore) is served by them too. Output falls where a furnace's does. + /// + public static class AlfarLjosgard + { + public const string PieceName = "AlfarLjosgard"; + public const string PieceDisplay = "$rov_piece_alfar_ljosgard_name"; + + public static void Register() + { + GameObject source = PrefabManager.Cache.GetPrefab("smelter"); + ItemDrop magecap = PrefabManager.Cache.GetPrefab("MushroomMagecap"); + ItemDrop puffs = PrefabManager.Cache.GetPrefab("MushroomJotunPuffs"); + ItemDrop sap = PrefabManager.Cache.GetPrefab("Sap"); + + if (source == null || magecap == null || puffs == null || sap == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Ljosgard needs the 'smelter' piece and the Magecap, Jotun Puffs and Sap items: not registered."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source); + if (prefab == null) return; + + // The furnace's heat and its fire: the Ljosgard is cool to the touch (guide 5.1). + AswidBloodRefinery.StripOffensive(prefab, "Ljosgard"); + + Smelter smelter = prefab.GetComponent(); + if (smelter == null) + { + Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Smelter component: no Ljosgard."); + return; + } + + smelter.m_name = PieceDisplay; + smelter.m_conversion = new List + { + new Smelter.ItemConversion { m_from = magecap, m_to = sap }, + }; + smelter.m_fuelItem = puffs; + smelter.m_fuelPerProduct = 1; + smelter.m_maxOre = AlfarNexusConfig.GardCapacity.Value; + smelter.m_maxFuel = AlfarNexusConfig.GardCapacity.Value; + smelter.m_secPerProduct = AlfarNexusConfig.GardSecondsPerSap.Value; + smelter.m_requiresRoof = false; + smelter.m_spawnStack = false; + smelter.m_windmill = null; + + AlfarConstructs.Tint(prefab, new Color(0.55f, 0.85f, 0.7f, 1f)); + + Piece piece = prefab.GetComponent(); + if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Piece."); return; } + + piece.m_craftingStation = null; + piece.m_name = PieceDisplay; + piece.m_description = "$rov_piece_alfar_ljosgard_desc"; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = PieceDisplay, + Description = "$rov_piece_alfar_ljosgard_desc", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = piece.m_icon, + Requirements = new[] + { + new RequirementConfig("Bronze", AlfarNexusConfig.GardBronze.Value, 0, true), + new RequirementConfig("MushroomJotunPuffs", AlfarNexusConfig.GardMushrooms.Value, 0, true), + new RequirementConfig("MushroomMagecap", AlfarNexusConfig.GardMushrooms.Value, 0, true), + }, + })); + + // One per Ljoskjarne, inside its reach, and only for the Alfar. + PieceDensityLimit.Register(PieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_ljosgard"); + PieceDensityLimit.RegisterGate(PieceName, (player, position) => + { + if (!AlfarRace.IsLocalAlfar()) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + } + if (AlfarNexusBehaviour.Covering(position) == null) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_gard_needs_nexus")); + return false; + } + return true; + }); + + AlfarPieces.Extra.Add(PieceName); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarMark.cs b/JotunnModStub/Alfar/AlfarMark.cs new file mode 100644 index 0000000..2bfc3ae --- /dev/null +++ b/JotunnModStub/Alfar/AlfarMark.cs @@ -0,0 +1,149 @@ +using System.Collections.Generic; +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Marks a creature or a piece as one of the Alfar's own: a construct, a drone or a tower. + /// + /// What the mark does is decided in ONE place, the patches below, instead of editing every attack + /// of every cloned creature (Alfar_Progettazione.txt sec. 8.5 and 16C P4): + /// - everything the marked thing deals becomes LIGHTNING, with the same total; chop and pickaxe + /// are tool damage and are dropped; + /// - it never hurts an ally; + /// - it never hurts a building, a tree or a rock. + /// Intercepting the hit covers melee, projectiles and area attacks alike, whatever the vanilla + /// creature does with its weapons. + /// + public class AlfarMark : MonoBehaviour + { + /// "drone", "construct" or "tower": only for logs and the status command. + public string Role = ""; + + /// The attacker's mark, or null when the hit is not from one of ours. + public static AlfarMark Of(HitData hit) + { + if (hit == null) return null; + Character attacker = hit.GetAttacker(); + return attacker != null ? attacker.GetComponent() : null; + } + + /// All the damage that can wound a person, moved into lightning. Chop and pickaxe go. + public static void ConvertToLightning(HitData hit) + { + HitData.DamageTypes d = hit.m_damage; + float total = d.m_damage + d.m_blunt + d.m_slash + d.m_pierce + d.m_fire + d.m_frost + + d.m_poison + d.m_spirit + d.m_lightning; + + HitData.DamageTypes converted = default(HitData.DamageTypes); + converted.m_lightning = total; + hit.m_damage = converted; + } + } + + /// The blows of an Alfar creature: lightning only, and never on a friend. + [HarmonyPatch(typeof(Character), "Damage")] + public static class AlfarMark_CharacterDamage_Patch + { + public static bool Prefix(Character __instance, HitData __0) + { + AlfarMark mark = AlfarMark.Of(__0); + if (mark == null) return true; + + Character attacker = __0.GetAttacker(); + if (__instance == attacker) return false; + + // Nobody on our side is ever hurt by us: players, their tames, the other constructs. + if (!BaseAI.IsEnemy(attacker, __instance)) return false; + + AlfarMark.ConvertToLightning(__0); + return true; + } + } + + /// + /// Buildings, trees and rocks take nothing from the Alfar's creatures: the golem that razed its + /// owner's base would be a bug. One prefix on every kind of thing that can be struck. + /// + [HarmonyPatch] + public static class AlfarMark_StructureDamage_Patch + { + public static IEnumerable TargetMethods() + { + System.Type[] types = + { + typeof(WearNTear), typeof(Destructible), typeof(MineRock5), typeof(MineRock), + typeof(TreeBase), typeof(TreeLog), + }; + + foreach (System.Type type in types) + { + MethodBase method = AccessTools.Method(type, "Damage", new[] { typeof(HitData) }); + if (method != null) yield return method; + else Jotunn.Logger.LogWarning($"[Alfar] {type.Name}.Damage(HitData) not found: that structure is not protected from the Alfar's creatures."); + } + } + + public static bool Prefix(HitData __0) + { + return AlfarMark.Of(__0) == null; + } + } + + /// + /// A shield equal to the creature's health that comes back by itself: 1% of it per second once it + /// has gone five seconds without being hit (design sec. 8.5 and 9.6). Health does NOT come back: + /// the damage to the body is permanent, which is why a construct is rebuilt and not repaired. + /// + /// Its own absorption and not SE_Shield: the blow arrives at ApplyDamage, and what is left after + /// the shield is what reaches the health (the same stage the Alfr's own eitr shield uses). + /// + public class AlfarCreatureShield : MonoBehaviour + { + public float MaxShield; + public float Shield; + public float RegenPerSecondFraction = 0.01f; + public float QuietSeconds = 5f; + + private float lastHit = -999f; + + private void Awake() + { + if (Shield <= 0f) Shield = MaxShield; + } + + private void Update() + { + if (Shield >= MaxShield || Time.time - lastHit < QuietSeconds) return; + Shield = Mathf.Min(MaxShield, Shield + MaxShield * RegenPerSecondFraction * Time.deltaTime); + } + + public void Absorb(HitData hit) + { + float total = hit.m_damage.GetTotalDamage(); + if (total <= 0f) return; + + lastHit = Time.time; + float absorbed = Mathf.Min(Shield, total); + Shield -= absorbed; + + HitData.DamageTypes rest = hit.m_damage; + rest.Modify((total - absorbed) / total); + hit.m_damage = rest; + } + + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_CreatureShield_Patch + { + public static void Prefix(Character __instance, HitData __0) + { + if (__0 == null || __instance is Player) return; + AlfarCreatureShield shield = __instance.GetComponent(); + if (shield != null) shield.Absorb(__0); + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarMiners.cs b/JotunnModStub/Alfar/AlfarMiners.cs new file mode 100644 index 0000000..59b3b22 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarMiners.cs @@ -0,0 +1,104 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// GRAFVAETTIR, the mining grenade (Alfar_Progettazione.txt sec. 9.3): unlocked at Eikthyr, thrown + /// like a grenade at a point; five drones dig the precious ores around it for two minutes and + /// vanish. The ore falls where it stands, and nothing else limits it but its cost (eitr, a little + /// stone and flint) and a five minute wait. + /// + /// The thrown part is only the spawn; the digging is AlfarMiner on the drones themselves. + /// + public static class AlfarMiners + { + private static float readyAt; + + public static void Tick(Player player) + { + // Nothing to tick per frame: the miners run themselves. Kept so the power loop treats + // every power the same way. + } + + public static void Throw(Player player) + { + if (Time.time < readyAt) return; + + Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform; + Vector3 origin = aim.position; + Vector3 direction = aim.forward; + float range = AlfarPowerConfig.GrafRange.Value; + + Vector3 point = origin + direction * range; + foreach (RaycastHit hit in Physics.RaycastAll(origin, direction, range, ~0, QueryTriggerInteraction.Ignore)) + { + if (hit.collider.GetComponentInParent() == player) continue; + if (Vector3.Distance(origin, hit.point) < Vector3.Distance(origin, point)) point = hit.point; + } + + // The price: a little eitr, a little stone, a little flint. + string stone = SharedName("Stone"); + string flint = SharedName("Flint"); + int needStone = AlfarPowerConfig.GrafStone.Value; + int needFlint = AlfarPowerConfig.GrafFlint.Value; + float eitr = AlfarPowerConfig.GrafEitr.Value; + + Inventory inventory = player.GetInventory(); + if (inventory.CountItems(stone, -1, false) < needStone || inventory.CountItems(flint, -1, false) < needFlint) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_graf_materials", needStone, needFlint)); + return; + } + if (player.GetEitr() < eitr) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_no_eitr")); + return; + } + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(AlfarDrones.MinerName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{AlfarDrones.MinerName}' in ZNetScene: the mining drones cannot be thrown."); + return; + } + + inventory.RemoveItem(stone, needStone, -1, false); + inventory.RemoveItem(flint, needFlint, -1, false); + AlfarEitr.Spend(player, eitr); + readyAt = Time.time + AlfarPowerConfig.GrafCooldown.Value; + AlfarStatusEffects.ShowTimer("graf", AlfarPowerConfig.GrafCooldown.Value); + + int count = AlfarPowerConfig.GrafCount.Value; + for (int i = 0; i < count; i++) + { + Vector2 offset = Random.insideUnitCircle * 1.5f; + Vector3 where = point + new Vector3(offset.x, 1.5f + i * 0.2f, offset.y); + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity); + + AlfarMiner miner = spawned.GetComponent(); + if (miner != null) + { + miner.Centre = point; + miner.Radius = AlfarPowerConfig.GrafRadius.Value; + miner.LiveSeconds = AlfarPowerConfig.GrafSeconds.Value; + } + + // Tame at once so nothing flees them and they flee nothing; no anchor, no leash. + MonsterAI ai = spawned.GetComponent(); + Character character = spawned.GetComponent(); + if (ai != null) ai.MakeTame(); + if (character != null) character.SetTamed(true); + } + + AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", point); + Jotunn.Logger.LogInfo($"[Alfar] Grafvaettir thrown: {count} at {point}."); + } + + private static string SharedName(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + return drop != null ? drop.m_itemData.m_shared.m_name : prefabName; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexus.cs b/JotunnModStub/Alfar/AlfarNexus.cs new file mode 100644 index 0000000..8ba5ac9 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexus.cs @@ -0,0 +1,576 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSKJARNE, the Alfar's Nexus (Alfar_Progettazione.txt sec. 8): the one piece the whole + /// base hangs from. It makes the drones and the constructs, it keeps the crystals, and the towers + /// and the drones only work inside its radius. One per 1.6 km2 like the other races' stations. + /// + /// ONE INTERACTION POINT (guide 4.7): E opens the vanilla merchant window with a row per product + /// (AlfarNexusStore), the way the Trol's war totem and the Dvergar's contract bank do. The first + /// version stepped through the products with Shift+E, which gave trouble in other races' tests, and + /// the player asked for the store. The prices are not coins: they come out of the pack, and the + /// row's tooltip lists them with how many exist and how many are allowed. + /// + /// Everything is paid from the player's inventory. The crystals the Nexus makes (after the + /// Kristallvigsla) pile up inside it, a beehive's way - slowly, to a cap, and it stops when full + /// until somebody collects - and "collect" moves them to the pack. + /// + public static class AlfarNexus + { + public const string PieceName = "AlfarNexus"; + public const string PieceDisplay = "$rov_piece_alfar_nexus_name"; + + public static void Register() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_cartographytable"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Alfar] Could not clone piece_cartographytable; the Ljoskjarne is not registered."); + return; + } + + // The MapTable trap (Butler 4.1): MapTable is Interactable AND Hoverable and takes the E + // key before our Switch sees it. Everything goes except what makes it a building. + foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren(true)) + { + if (behaviour == null) continue; + if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue; + Object.DestroyImmediate(behaviour); + } + + AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f)); + + AlfarNexusBehaviour nexus = prefab.AddComponent(); + nexus.m_switch = prefab.AddComponent(); + nexus.m_switch.m_name = PieceDisplay; + + // A Trader with an empty catalogue: StoreGui needs one to open at all, and the rows are drawn + // by AlfarNexusStore. Disabled and with every list filled, for the reasons the Trol's totem + // spells out (Trader.Update and Start assume an animator and a look-at rig that a nucleus + // does not have, and an unfilled list sends Trader.Interact into a null Say). + Trader trader = prefab.GetComponent() ?? prefab.AddComponent(); + trader.m_name = PieceDisplay; + trader.enabled = false; + trader.m_items = new List(); + trader.m_useItems = new List(); + trader.m_randomTalk = new List(); + trader.m_randomGreets = new List(); + trader.m_randomGoodbye = new List(); + trader.m_randomStartTrade = new List(); + trader.m_randomBuy = new List(); + trader.m_randomSell = new List(); + trader.m_randomGiveItemNo = new List(); + trader.m_randomUseItemAlreadyRecieved = new List(); + trader.m_randomTalkConditionals = new List(); + + Sprite icon = BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore"); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = PieceDisplay; + piece.m_canBeRemoved = true; + piece.m_groundPiece = false; + piece.m_groundOnly = false; + piece.m_icon = icon; + + Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); + if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = PieceDisplay, + Description = "$rov_piece_alfar_nexus_desc", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = icon, + Requirements = new[] + { + new RequirementConfig("Bronze", AlfarNexusConfig.NexusBronze.Value, 0, true), + new RequirementConfig("Stone", AlfarNexusConfig.NexusStone.Value, 0, true), + }, + })); + + PieceDensityLimit.Register(PieceName, PieceDensityLimit.RadiusForArea(AlfarNexusConfig.NexusDensityKm2.Value), + 1, "rov_msg_build_limit_alfar_nexus"); + PieceDensityLimit.RegisterGate(PieceName, (player, position) => + { + if (AlfarRace.IsLocalAlfar()) return true; + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + }); + } + + public static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null + ? drop.m_itemData.m_shared.m_icons + : null; + return icons != null && icons.Length > 0 ? icons[0] : null; + } + + /// Teaches the player the Alfar's pieces: a piece registered after the learning pass does not reach its table alone (guide 4.4). + public static void EnsureKnown(Player player) + { + if (player == null || !AlfarVisuals.IsAlfarPlayer(player)) return; + + Traverse traverse = Traverse.Create(player); + foreach (string name in AlfarPieces.AllNames()) + { + GameObject prefab = PrefabManager.Instance.GetPrefab(name); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece != null) traverse.Method("AddKnownPiece", piece).GetValue(); + } + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + } + + /// The names of every piece the Alfar can build, in one place for the lock and for learning. + public static class AlfarPieces + { + public static readonly List Extra = new List(); + + public static IEnumerable AllNames() + { + yield return AlfarNexus.PieceName; + foreach (string name in Extra) yield return name; + } + } + + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class AlfarKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + AlfarNexus.EnsureKnown(__instance); + } + } + + public class AlfarNexusBehaviour : MonoBehaviour + { + public Switch m_switch; + + public static readonly List All = new List(); + + private const string KeySelected = "RoV_alfarSel"; + private const string KeyUpgrade = "RoV_alfarUp"; + private const string KeyCrystals = "RoV_alfarCr"; + private const string KeyCrystalAt = "RoV_alfarCrAt"; + + public enum Product { Drone = 0, Neistvordr = 1, Eldingvordr = 2, Steinvordr = 3, Upgrade = 4, Collect = 5 } + private static readonly int ProductCount = System.Enum.GetValues(typeof(Product)).Length; + + private ZNetView m_nview; + + private void Awake() + { + m_nview = GetComponent(); + All.Add(this); + RaisedThrall.RegisterStation(transform); + + if (m_switch != null) + { + m_switch.m_onUse = OnUse; + m_switch.m_onHover = Hover; + } + } + + private void OnDestroy() + { + All.Remove(this); + RaisedThrall.UnregisterStation(transform); + } + + /// The nearest Ljoskjarne whose radius covers the point, or null. + public static AlfarNexusBehaviour Covering(Vector3 point) + { + AlfarNexusBehaviour best = null; + float bestDistance = float.MaxValue; + foreach (AlfarNexusBehaviour nexus in All) + { + if (nexus == null) continue; + float distance = Vector3.Distance(nexus.transform.position, point); + if (distance <= AlfarNexusConfig.NexusRadius.Value && distance < bestDistance) + { + best = nexus; + bestDistance = distance; + } + } + return best; + } + + // ─── State ─────────────────────────────────────────────────────────── + + private bool Upgraded => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetInt(KeyUpgrade, 0) == 1; + public int Crystals => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyCrystals, 0) : 0; + + private Product Selected + { + get + { + int value = m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeySelected, 0) : 0; + return (Product)Mathf.Clamp(value, 0, ProductCount - 1); + } + } + + private bool Available(Product product) + { + bool constructsOpen = Upgraded && BossProgressionManager.GetCurrentProgressionState() >= AlfarNexusConfig.ConstructState; + switch (product) + { + case Product.Drone: return true; + case Product.Neistvordr: + case Product.Eldingvordr: + case Product.Steinvordr: return constructsOpen; + case Product.Upgrade: return !Upgraded; + case Product.Collect: return Upgraded; + } + return false; + } + + // ─── Crystals: a beehive's way ─────────────────────────────────────── + + /// + /// One crystal per Time Factor beehive-intervals of WORLD time, up to the cap, and nothing while + /// full: the clock restarts when somebody collects, like the honey. Only the owner counts. + /// The beehive's own interval is read, not copied (guide 3.2) - and only the INTERVAL, not its + /// daylight rule: the Alfar have no light mechanic (doc sec. 8.6). + /// + private void Update() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner() || !Upgraded || ZNet.instance == null) return; + + ZDO zdo = m_nview.GetZDO(); + int cap = AlfarNexusConfig.CrystalCap.Value; + int stored = zdo.GetInt(KeyCrystals, 0); + double now = ZNet.instance.GetTimeSeconds(); + + if (stored >= cap) { zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); return; } + + string stamp = zdo.GetString(KeyCrystalAt, ""); + if (!double.TryParse(stamp, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double at)) + { + zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + return; + } + + float interval = CrystalInterval(); + int made = Mathf.FloorToInt((float)((now - at) / interval)); + if (made <= 0) return; + + stored = Mathf.Min(cap, stored + made); + zdo.Set(KeyCrystals, stored); + zdo.Set(KeyCrystalAt, (at + made * interval).ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + } + + /// Seconds per crystal: Time Factor times a vanilla beehive's seconds per honey. + public static float CrystalInterval() + { + Beehive hive = TrentaConfig.FindVanillaBeehive(); + float honey = hive != null && hive.m_secPerUnit > 0f ? hive.m_secPerUnit : 1200f; + return honey * AlfarNexusConfig.CrystalTimeFactor.Value; + } + + // ─── Costs ─────────────────────────────────────────────────────────── + + private struct Cost + { + public string Item; + public int Amount; + public Cost(string item, int amount) { Item = item; Amount = amount; } + } + + private static List CostOf(Product product) + { + switch (product) + { + case Product.Drone: + return new List { new Cost("Bronze", AlfarNexusConfig.DroneBronze.Value) }; + case Product.Neistvordr: + return new List + { + new Cost("Bronze", AlfarNexusConfig.NeistMetal.Value), + new Cost("Crystal", AlfarNexusConfig.NeistCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.NeistEitr.Value), + }; + case Product.Eldingvordr: + return new List + { + new Cost("Iron", AlfarNexusConfig.EldingMetal.Value), + new Cost("Crystal", AlfarNexusConfig.EldingCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.EldingEitr.Value), + }; + case Product.Steinvordr: + return new List + { + new Cost("BlackMetal", AlfarNexusConfig.SteinMetal.Value), + new Cost("Crystal", AlfarNexusConfig.SteinCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.SteinEitr.Value), + }; + case Product.Upgrade: + return new List { new Cost("Crystal", AlfarNexusConfig.UpgradeCrystals.Value) }; + } + return new List(); + } + + private static string SharedName(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + return drop != null ? drop.m_itemData.m_shared.m_name : prefabName; + } + + private static bool CanPay(Player player, List costs) + { + foreach (Cost cost in costs) + { + if (cost.Amount <= 0) continue; + if (player.GetInventory().CountItems(SharedName(cost.Item), -1, false) < cost.Amount) return false; + } + return true; + } + + private static void Pay(Player player, List costs) + { + foreach (Cost cost in costs) + { + if (cost.Amount > 0) player.GetInventory().RemoveItem(SharedName(cost.Item), cost.Amount, -1, false); + } + } + + private static string CostText(List costs) + { + var parts = new List(); + foreach (Cost cost in costs) + { + if (cost.Amount > 0) parts.Add($"{cost.Amount} {Localization.instance.Localize(SharedName(cost.Item))}"); + } + return parts.Count == 0 ? "-" : string.Join(", ", parts); + } + + // ─── Counts and caps ───────────────────────────────────────────────── + + private int AliveOf(Product product) + { + Vector3 anchor = transform.position; + switch (product) + { + case Product.Drone: return AlfarDrones.CountAlive(anchor); + case Product.Neistvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Neistvordr); + case Product.Eldingvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Eldingvordr); + case Product.Steinvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Steinvordr); + } + return 0; + } + + private static int CapOf(Product product) + { + switch (product) + { + case Product.Drone: return AlfarNexusConfig.DroneCap.Value; + case Product.Neistvordr: return AlfarNexusConfig.NeistCap.Value; + case Product.Eldingvordr: return AlfarNexusConfig.EldingCap.Value; + case Product.Steinvordr: return AlfarNexusConfig.SteinCap.Value; + } + return int.MaxValue; + } + + private static string NameOf(Product product) => ModText.Get("rov_alfar_product_" + product.ToString().ToLowerInvariant()); + + // ─── Interaction ───────────────────────────────────────────────────── + + private string Hover() + { + var sb = new StringBuilder(); + sb.AppendLine(Localization.instance.Localize(AlfarNexus.PieceDisplay)); + sb.AppendLine($"[$KEY_Use] {ModText.Get("rov_alfar_nexus_open")}"); + + if (Upgraded) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value)); + else sb.AppendLine(ModText.Get("rov_alfar_nexus_no_upgrade")); + + return Localization.instance.Localize(sb.ToString()); + } + + private bool OnUse(Switch sw, Humanoid user, ItemDrop.ItemData item) + { + Player player = user as Player; + if (player == null || m_nview == null || !m_nview.IsValid()) return false; + + if (!AlfarVisuals.IsAlfarPlayer(player)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return item != null; + } + + // Holding something is not a way to use the nucleus: it only opens the store. + if (item != null) + { + player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return true; + } + + Trader trader = GetComponent(); + if (trader == null || StoreGui.instance == null) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_store")); + return false; + } + + // The store reads the nucleus back out of StoreGui's own m_trader when it repaints. + StoreGui.instance.Show(trader); + return true; + } + + // ─── What the store window uses ────────────────────────────────────── + + /// The products on offer right now, in the order the rows are drawn. + public List OnOffer() + { + var list = new List(); + foreach (Product product in System.Enum.GetValues(typeof(Product))) + { + if (Available(product)) list.Add(product); + } + return list; + } + + /// Builds a product from the row the player clicked. Every check Build makes still applies. + public void BuildFromStore(Product product) + { + Player player = Player.m_localPlayer; + if (player == null || m_nview == null || !m_nview.IsValid() || !Available(product)) return; + + m_nview.ClaimOwnership(); + Build(player, product); + } + + /// The short number on a row: the metal (or the crystals of the upgrade) it costs. + public static string PriceShort(Product product) + { + foreach (Cost cost in CostOf(product)) + { + if (cost.Amount > 0) return cost.Amount.ToString(); + } + return "-"; + } + + /// The full terms for the row's tooltip: the price, how many exist, how many are allowed. + public string Terms(Product product) + { + var sb = new StringBuilder(); + sb.AppendLine(CostText(CostOf(product))); + + int cap = CapOf(product); + if (cap != int.MaxValue) sb.AppendLine(ModText.Get("rov_alfar_store_count", AliveOf(product), cap)); + if (product == Product.Collect) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value)); + + sb.Append(ModText.Get("rov_alfar_store_terms")); + return sb.ToString(); + } + + public static string ProductName(Product product) => NameOf(product); + + private void Build(Player player, Product product) + { + List costs = CostOf(product); + + if (product == Product.Collect) + { + Collect(player); + return; + } + + if (AliveOf(product) >= CapOf(product)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cap")); + return; + } + + if (!CanPay(player, costs)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cannot_pay", CostText(costs))); + return; + } + + bool done; + switch (product) + { + case Product.Drone: done = AlfarDrones.Spawn(transform.position); break; + case Product.Neistvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Neistvordr); break; + case Product.Eldingvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Eldingvordr); break; + case Product.Steinvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Steinvordr); break; + case Product.Upgrade: done = true; break; + default: done = false; break; + } + if (!done) return; + + Pay(player, costs); + + if (product == Product.Upgrade) + { + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyUpgrade, 1); + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_upgraded")); + } + else + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_built", NameOf(product))); + } + } + + private void Collect(Player player) + { + int stored = Crystals; + if (stored <= 0) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_crystals")); + return; + } + + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab("Crystal") : null; + if (prefab == null) return; + + // Whatever fits goes in the pack; the rest stays in the Nexus. + int taken = 0; + for (int i = 0; i < stored; i++) + { + if (!player.GetInventory().CanAddItem(prefab, 1)) break; + if (!player.GetInventory().AddItem(prefab, 1)) break; + taken++; + } + + if (taken > 0) + { + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyCrystals, stored - taken); + // Collecting restarts the clock, like emptying a hive. + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + } + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_collected", taken)); + } + + /// Crystals a drone may carry away from the Nexus, and the call that does it (used by the drone's work). + public int TakeCrystals(int wanted) + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return 0; + int stored = Crystals; + int taken = Mathf.Min(stored, wanted); + if (taken <= 0) return 0; + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyCrystals, stored - taken); + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + return taken; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexusConfig.cs b/JotunnModStub/Alfar/AlfarNexusConfig.cs new file mode 100644 index 0000000..59c4020 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexusConfig.cs @@ -0,0 +1,144 @@ +using BepInEx.Configuration; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The numbers of the Alfar's base: the Nexus, its drones, the constructs, the towers and the + /// crystals (Alfar_Progettazione.txt sec. 8, 9 and 19). All starting values, all to be corrected + /// in play, none in the logic files. + /// + public static class AlfarNexusConfig + { + // The progression state the constructs open at (BossProgressionManager: 6 = Yagluth down). + public const int ConstructState = 6; + + // ─── The Nexus ─────────────────────────────────────────────────────── + public static ConfigEntry NexusRadius; + public static ConfigEntry NexusDensityKm2; + public static ConfigEntry NexusBronze; + public static ConfigEntry NexusStone; + + // ─── Drones ────────────────────────────────────────────────────────── + public static ConfigEntry DroneBronze; + public static ConfigEntry DroneCap; + public static ConfigEntry DroneHealth; + public static ConfigEntry DroneZapDamage; + public static ConfigEntry DroneZapInterval; + + // ─── Mining drones ─────────────────────────────────────────────────── + public static ConfigEntry MinerDeposits; + public static ConfigEntry MinerDamage; + public static ConfigEntry WildPickables; + + // ─── Constructs ────────────────────────────────────────────────────── + public static ConfigEntry NeistMetal; + public static ConfigEntry NeistCrystal; + public static ConfigEntry NeistEitr; + public static ConfigEntry NeistCap; + + public static ConfigEntry EldingMetal; + public static ConfigEntry EldingCrystal; + public static ConfigEntry EldingEitr; + public static ConfigEntry EldingCap; + + public static ConfigEntry SteinMetal; + public static ConfigEntry SteinCrystal; + public static ConfigEntry SteinEitr; + public static ConfigEntry SteinCap; + + public static ConfigEntry ConstructLeash; + public static ConfigEntry ConstructAlertRange; + public static ConfigEntry WitherSeconds; + + public static ConfigEntry SphereDamage; + public static ConfigEntry SphereIntervalSeconds; + public static ConfigEntry SphereRange; + + // ─── Crystals ──────────────────────────────────────────────────────── + public static ConfigEntry UpgradeCrystals; + public static ConfigEntry CrystalCap; + public static ConfigEntry CrystalTimeFactor; + + // ─── Towers ────────────────────────────────────────────────────────── + public static ConfigEntry TowerBronze; + public static ConfigEntry TowerCrystal; + public static ConfigEntry TowerHealthFactor; + public static ConfigEntry TowerDamage; + public static ConfigEntry TowerScale; + + // ─── Ljosgard (sap) and chests ─────────────────────────────────────── + public static ConfigEntry GardBronze; + public static ConfigEntry GardMushrooms; + public static ConfigEntry GardSecondsPerSap; + public static ConfigEntry GardCapacity; + public static ConfigEntry ChestEyes; + + public static void Bind(ConfigFile config) + { + const string nexus = "Alfar - Nexus"; + NexusRadius = config.Bind(nexus, "Radius", 40f, new ConfigDescription("Metres around a Ljoskjarne where its drones work and its towers run.", new AcceptableValueRange(10f, 150f))); + NexusDensityKm2 = config.Bind(nexus, "Density Km2", 1.6f, new ConfigDescription("At most one Ljoskjarne per this many square kilometres.", new AcceptableValueRange(0.1f, 20f))); + NexusBronze = config.Bind(nexus, "Bronze Cost", 40, new ConfigDescription("Bronze to build a Ljoskjarne.", new AcceptableValueRange(0, 500))); + NexusStone = config.Bind(nexus, "Stone Cost", 30, new ConfigDescription("Stone to build a Ljoskjarne.", new AcceptableValueRange(0, 500))); + + const string drone = "Alfar - Drones"; + DroneBronze = config.Bind(drone, "Bronze Cost", 8, new ConfigDescription("Bronze for each Ljosvaettir.", new AcceptableValueRange(0, 200))); + DroneCap = config.Bind(drone, "Cap Per Nexus", 6, new ConfigDescription("Most drones one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + DroneHealth = config.Bind(drone, "Health", 25f, new ConfigDescription("A drone's health and shield (a Deathsquito has 10).", new AcceptableValueRange(1f, 1000f))); + DroneZapDamage = config.Bind(drone, "Zap Damage", 1f, new ConfigDescription("Lightning damage of a drone's defensive zap.", new AcceptableValueRange(0f, 100f))); + DroneZapInterval = config.Bind(drone, "Zap Interval", 2f, new ConfigDescription("Seconds between a drone's zaps.", new AcceptableValueRange(0.2f, 30f))); + + MinerDeposits = config.Bind(drone, "Mining Targets", "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain", + new ConfigDescription("Comma separated parts of prefab names the mining drones dig (case does not matter). Soft tissue comes from giant_brain.")); + MinerDamage = config.Bind(drone, "Mining Damage", 40f, new ConfigDescription("Pickaxe damage each mining drone does per second to a deposit.", new AcceptableValueRange(1f, 1000f))); + + WildPickables = config.Bind(drone, "Wild Plants Harvested", "Pickable_Mushroom,Pickable_Dandelion,Pickable_Thistle,RaspberryBush,BlueberryBush,CloudberryBush", + new ConfigDescription("Comma separated parts of prefab names of WILD plants the drones pick without replanting (mushrooms, berry bushes, flowers). Trees are never touched. Cultivated crops are always replanted.")); + + const string construct = "Alfar - Constructs"; + NeistMetal = config.Bind(construct, "Neistvordr Bronze", 20, new ConfigDescription("Bronze for a Neistvordr.", new AcceptableValueRange(0, 500))); + NeistCrystal = config.Bind(construct, "Neistvordr Crystal", 3, new ConfigDescription("Crystals for a Neistvordr.", new AcceptableValueRange(0, 50))); + NeistEitr = config.Bind(construct, "Neistvordr Refined Eitr", 3, new ConfigDescription("Refined eitr for a Neistvordr.", new AcceptableValueRange(0, 50))); + NeistCap = config.Bind(construct, "Neistvordr Cap", 4, new ConfigDescription("Most Neistvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + EldingMetal = config.Bind(construct, "Eldingvordr Iron", 20, new ConfigDescription("Iron for an Eldingvordr.", new AcceptableValueRange(0, 500))); + EldingCrystal = config.Bind(construct, "Eldingvordr Crystal", 5, new ConfigDescription("Crystals for an Eldingvordr.", new AcceptableValueRange(0, 50))); + EldingEitr = config.Bind(construct, "Eldingvordr Refined Eitr", 4, new ConfigDescription("Refined eitr for an Eldingvordr.", new AcceptableValueRange(0, 50))); + EldingCap = config.Bind(construct, "Eldingvordr Cap", 4, new ConfigDescription("Most Eldingvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + SteinMetal = config.Bind(construct, "Steinvordr Black Metal", 20, new ConfigDescription("Black metal for a Steinvordr.", new AcceptableValueRange(0, 500))); + SteinCrystal = config.Bind(construct, "Steinvordr Crystal", 8, new ConfigDescription("Crystals for a Steinvordr.", new AcceptableValueRange(0, 50))); + SteinEitr = config.Bind(construct, "Steinvordr Refined Eitr", 6, new ConfigDescription("Refined eitr for a Steinvordr.", new AcceptableValueRange(0, 50))); + SteinCap = config.Bind(construct, "Steinvordr Cap", 1, new ConfigDescription("Most Steinvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + ConstructLeash = config.Bind(construct, "Leash Range", 12f, new ConfigDescription("How far a construct wanders from its Ljoskjarne when not following.", new AcceptableValueRange(2f, 80f))); + ConstructAlertRange = config.Bind(construct, "Alert Range", 25f, new ConfigDescription("How far a construct notices and chases enemies.", new AcceptableValueRange(5f, 100f))); + WitherSeconds = config.Bind(construct, "Wither Seconds", 60f, new ConfigDescription("How long creatures last after their Ljoskjarne falls.", new AcceptableValueRange(0f, 600f))); + + SphereDamage = config.Bind(construct, "Sphere Damage", 80f, new ConfigDescription("Lightning damage of the Eldingvordr's sphere.", new AcceptableValueRange(1f, 1000f))); + SphereIntervalSeconds = config.Bind(construct, "Sphere Interval", 8f, new ConfigDescription("Seconds between the Eldingvordr's shots.", new AcceptableValueRange(0.5f, 60f))); + SphereRange = config.Bind(construct, "Sphere Range", 30f, new ConfigDescription("How far the Eldingvordr shoots.", new AcceptableValueRange(5f, 80f))); + + const string crystal = "Alfar - Crystals"; + UpgradeCrystals = config.Bind(crystal, "Upgrade Cost", 20, new ConfigDescription("Crystals the player must find for the Kristallvigsla.", new AcceptableValueRange(0, 200))); + CrystalCap = config.Bind(crystal, "Stored Cap", 20, new ConfigDescription("Most crystals the Ljoskjarne holds before it stops making them.", new AcceptableValueRange(1, 200))); + CrystalTimeFactor = config.Bind(crystal, "Time Factor", 2f, new ConfigDescription("A crystal takes this many times a vanilla beehive's time for one honey.", new AcceptableValueRange(0.1f, 20f))); + + const string tower = "Alfar - Towers"; + TowerBronze = config.Bind(tower, "Bronze Cost", 25, new ConfigDescription("Bronze for a Prismavard.", new AcceptableValueRange(0, 500))); + TowerCrystal = config.Bind(tower, "Crystal Cost", 2, new ConfigDescription("Crystals for a Prismavard.", new AcceptableValueRange(0, 50))); + TowerHealthFactor = config.Bind(tower, "Health Factor", 0.5f, new ConfigDescription("A Prismavard's health against the charred ballista's 400.", new AcceptableValueRange(0.05f, 3f))); + TowerDamage = config.Bind(tower, "Bolt Damage", 40f, new ConfigDescription("Lightning damage of a Prismavard's bolt.", new AcceptableValueRange(1f, 1000f))); + TowerScale = config.Bind(tower, "Scale", 0.6f, new ConfigDescription("Size of a Prismavard against the charred ballista.", new AcceptableValueRange(0.2f, 2f))); + + const string gard = "Alfar - Ljosgard"; + GardBronze = config.Bind(gard, "Bronze Cost", 40, new ConfigDescription("Bronze for a Ljosgard.", new AcceptableValueRange(0, 500))); + GardMushrooms = config.Bind(gard, "Mushrooms Cost", 10, new ConfigDescription("Jotun Puffs AND Magecap, this many of each, to build a Ljosgard.", new AcceptableValueRange(0, 100))); + GardSecondsPerSap = config.Bind(gard, "Seconds Per Sap", 600f, new ConfigDescription("Seconds to turn one Jotun Puffs and one Magecap into a Sap.", new AcceptableValueRange(10f, 7200f))); + GardCapacity = config.Bind(gard, "Sap Capacity", 10, new ConfigDescription("Sap the Ljosgard holds before it stops.", new AcceptableValueRange(1, 200))); + + ChestEyes = config.Bind(gard, "Chest Greydwarf Eyes", 3, new ConfigDescription("Greydwarf eyes in the price of the entry chest and the wood chest.", new AcceptableValueRange(0, 50))); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexusStore.cs b/JotunnModStub/Alfar/AlfarNexusStore.cs new file mode 100644 index 0000000..4b17cc1 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexusStore.cs @@ -0,0 +1,171 @@ +using System.Collections.Generic; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// The Ljoskjarne's window: the merchant's own store with a column of products in it - the drone, + /// the three constructs, the crystal upgrade, and the crystals to collect. + /// + /// It is the Trol war totem's window (TrolTotemStore) cloned for another trader, and for the same + /// reasons: same three patch points (Awake to build, FillList to repaint, Hide to clear), same trick + /// of instantiating StoreGui.m_listElement for the rows. The empty-catalogue guard that keeps vanilla + /// FillList from throwing is already on every trader with no wares (StoreGuiEmptyCatalogueGuardPatch), + /// so this one needs none of its own. + /// + /// What is different from the totem: a row's price is a number out of the pack and not coins, so the + /// short figure on the row is the metal or the crystals, and the tooltip carries the whole price. + /// + public static class AlfarNexusStore + { + private static RectTransform _list; + private static readonly List _rows = new List(); + + public static AlfarNexusBehaviour ActiveNexus(StoreGui gui) + { + Trader trader = FactionMerchantRuntime.GetActiveTrader(gui); + return trader != null ? trader.GetComponent() : null; + } + + // ─── build ─────────────────────────────────────────────────────────── + + public static void Create(StoreGui gui) + { + if (gui == null || gui.m_listRoot == null || _list != null) return; + + GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent); + clone.name = "AlfarProductList"; + _list = clone.GetComponent(); + _list.anchoredPosition = gui.m_listRoot.anchoredPosition; + + // The clone carries whatever rows the vanilla list held at Awake: it starts empty. + foreach (Transform child in _list) Object.Destroy(child.gameObject); + _list.gameObject.SetActive(false); + } + + public static void Clear() + { + foreach (GameObject row in _rows) if (row != null) Object.Destroy(row); + _rows.Clear(); + if (_list != null) _list.gameObject.SetActive(false); + } + + // ─── fill ──────────────────────────────────────────────────────────── + + public static void Refresh(StoreGui gui) + { + Clear(); + + AlfarNexusBehaviour nexus = ActiveNexus(gui); + if (nexus == null) return; // an ordinary merchant: not ours + + if (_list == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Ljoskjarne's column was never built (did the patch on StoreGui.Awake fail?)."); + return; + } + + _list.gameObject.SetActive(true); + + int row = 0; + foreach (AlfarNexusBehaviour.Product product in nexus.OnOffer()) + { + BuildRow(gui, nexus, product, row++); + } + + float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue(); + _list.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Max(baseSize, row * gui.m_itemSpacing)); + } + + private static string IconOf(AlfarNexusBehaviour.Product product) + { + switch (product) + { + case AlfarNexusBehaviour.Product.Drone: return "TrophyDeathsquito"; + case AlfarNexusBehaviour.Product.Neistvordr: return "TrophySurtling"; + case AlfarNexusBehaviour.Product.Eldingvordr: return "TrophyAbomination"; + case AlfarNexusBehaviour.Product.Steinvordr: return "TrophySGolem"; + default: return "Crystal"; + } + } + + private static void BuildRow(StoreGui gui, AlfarNexusBehaviour nexus, AlfarNexusBehaviour.Product product, int rowIndex) + { + GameObject element = Object.Instantiate(gui.m_listElement, _list); + element.SetActive(true); + + RectTransform rt = (RectTransform)element.transform; + float offset = (_list.rect.width - rt.rect.width) / 2f; + rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset); + + Sprite icon = Icon(IconOf(product)); + Image iconImage = element.transform.Find("icon").GetComponent(); + if (icon != null) iconImage.sprite = icon; + + string name = AlfarNexusBehaviour.ProductName(product); + element.transform.Find("name").GetComponent().text = Localization.instance.Localize(name); + + TMP_Text price = FindDescendant(element.transform, "price"); + if (price != null) price.text = AlfarNexusBehaviour.PriceShort(product); + + // The coin that sits beside the number on a vanilla row is the wrong picture here. + foreach (Image image in element.GetComponentsInChildren(true)) + { + if (image != null && image.gameObject.name.ToLowerInvariant().Contains("coin")) image.gameObject.SetActive(false); + } + + UITooltip tooltip = element.GetComponent(); + if (tooltip != null) tooltip.Set(Localization.instance.Localize(name), nexus.Terms(product), gui.m_tooltipAnchor, default(Vector2)); + + AlfarNexusBehaviour.Product chosen = product; + element.GetComponent