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

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

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

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

514 lines
24 KiB
C#

using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Fenrir station: a trough that keeps a standing pack, in three ranks.
///
/// Seventh of the per-race chains, and the same family as the Draugh's body pile and the
/// Skeleton's bone pile - meat goes in, a roster fills up, and a death is a slot that refills
/// itself. The ranks fill in order and each one waits for the one below it to be full:
///
/// 10 wolves, one every two minutes
/// then 6 ulv, one every three
/// upgraded: 15 wolves, 10 ulv, and 5 fenrir on top
///
/// CORRECTION, and the reason this file was rewritten: the first two versions bred the pack
/// instead of raising it - the trough rewrote what the animals in its circle gave birth to, and
/// the ranks were meant to fill through vanilla's own Procreation. It cannot work. Cubs are a
/// different prefab from adults, so they either count towards the cap - and then the pen jams at
/// its first litter, because vanilla stops breeding at four head - or they do not, and then
/// nothing stops the pen breeding until it is shoulder to shoulder. There is no third option,
/// and the whole ladder of chances and forced rungs went with it. What is left is smaller, has
/// no cache to prime, no private fields to reach into, and cannot overshoot.
///
/// It is still not a spawner of the kind the guide warns against (4.9b), and the difference is
/// the same one the Skeleton's pile has: nothing here is free or immediate. The pack is paid for
/// in meat, arrives one animal at a time over the better part of an hour, and dies for good if
/// the trough does - so it is a herd you keep, not a button you press before a fight.
/// </summary>
public static class FenrirMangiatoia
{
// ─── Names ───────────────────────────────────────────────────────────
public const string PieceName = "FenrirPackTrough";
public const string PieceDisplayName = "$rov_piece_fenrir_packtrough_name";
public const string UlvsblodName = "Ulvsblod";
public const string UlvsblodDisplayName = "$rov_item_fenrir_ulvsblod_name";
public const string GreaterUlvsblodName = "GreaterUlvsblod";
public const string GreaterUlvsblodDisplayName = "$rov_item_fenrir_greaterulvsblod_name";
public const int UlvsblodPrice = 500;
public const int GreaterUlvsblodPrice = 1500;
public const string WolfName = "FenrirPack_Wolf";
public const string UlvName = "FenrirPack_Ulv";
public const string FenrirName = "FenrirPack_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";
public const string KindFenrir = "FenrirPackFenrir";
public const string RaceId = "Fenrir";
// Moder needs no state check of her own: her drop is IN the recipe, so a trough cannot be
// built without her having fallen. Yagluth's is checked as well as spent, because the
// upgrade is bought with coin and a drop rather than built.
public const string ModerDrop = "DragonTear";
public const string YagluthDrop = "YagluthDrop";
public const int UpgradeProgressionState = 6; // Yagluth
// ─── The roster ──────────────────────────────────────────────────────
public const int WolfSlots = 10;
public const int UlvSlots = 6;
public const int FenrirSlots = 0; // none at all until upgraded
public const int WolfSlotsUpgraded = 15;
public const int UlvSlotsUpgraded = 10;
public const int FenrirSlotsUpgraded = 5;
/// <summary>
/// How long each rank takes to put one more up. Local seconds, and only while the zone is
/// loaded: a pack that rebuilt itself in an unloaded zone would mean walking away was the
/// fastest way to raise one.
///
/// The fenrir's five minutes is the one number here nobody specified. It is set longest
/// because it is the rank worth waiting for; it is one constant.
/// </summary>
public const float WolfSeconds = 120f;
public const float UlvSeconds = 180f;
public const float FenrirSeconds = 300f;
/// <summary>
/// What one of each costs out of the tank, on AswidBloodRefinery.FleshValue's scale - the
/// same one three other chains use, so a lox steak already counts for more than a neck tail
/// without a second table.
///
/// Anchored to the Draugh's hundred-per-thrall rather than picked: a fenrir is worth one of
/// those, and the ranks below it step down from there.
/// </summary>
public const float WolfCost = 25f;
public const float UlvCost = 50f;
public const float FenrirCost = 100f;
/// <summary>The tank. Four fenrir deep, so a full pack is several trips and not one.</summary>
public const float TankCap = 400f;
public const float TickSeconds = 5f;
// ─── Behaviour ───────────────────────────────────────────────────────
// Five minutes. Long enough to notice the mistake and rebuild, short enough that the wither
// is really doing its job. The trough cannot be broken by accident anyway - it is immune to
// pickaxes - so losing a pack is always a deliberate act.
public const float OrphanWitherSeconds = 300f;
public const float HomeCheckRange = 45f;
public const float LeashRange = 15f;
// No cap, and that is a balance decision rather than an oversight: this chain sits AFTER the
// mountain - Moder to build it, Yagluth for the fenrir at all - and five fenrir is a small
// number next to what the other races field by then.
public const int MaxFollowers = -1;
// One per square mile. 2.59 km2, and stricter than every other station in the mod because of
// what stands around this one.
public const int MaxTroughsInRange = 1;
public const float DensityAreaKm2 = 2.59f;
// ─── Looks ───────────────────────────────────────────────────────────
private const float TroughScale = 1.1f;
/// <summary>
/// A fenrir is a Fenring, and the player's own race turns INTO a Fenring at tier 4. If the
/// two are the same size they are the same silhouette in a melee. This is the only number
/// written over a vanilla creature's own, and it is a legibility fix, not a stat.
/// </summary>
private const float FenrirScale = 1.6f;
private static readonly Color TroughTint = new Color(0.42f, 0.36f, 0.30f, 1f);
private static readonly Color UlvsblodTint = new Color(0.55f, 0.10f, 0.12f, 1f);
private static readonly Color GreaterUlvsblodTint = new Color(0.30f, 0.16f, 0.42f, 1f);
public static void Register()
{
RegisterUlvsblod(UlvsblodName, UlvsblodDisplayName, UlvsblodTint,
"$rov_item_fenrir_ulvsblod_desc");
RegisterUlvsblod(GreaterUlvsblodName, GreaterUlvsblodDisplayName, GreaterUlvsblodTint,
"$rov_item_fenrir_greaterulvsblod_desc");
RegisterPackAnimal(WolfName, "Wolf", WolfDisplayName, KindWolf,
"$rov_creature_fenrir_pack_desc", 1f);
RegisterPackAnimal(UlvName, "Ulv", UlvDisplayName, KindUlv,
"$rov_creature_fenrir_pack_desc", 1f);
RegisterPackAnimal(FenrirName, "Fenring", FenrirDisplayName, KindFenrir,
"$rov_creature_fenrir_packfenrir_desc", FenrirScale);
RegisterPiece();
PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxTroughsInRange,
"rov_msg_build_limit_fenrir_packtrough");
}
// ---------------------------------------------------------------- items
private static void RegisterUlvsblod(string prefabName, string displayName, Color tint, string description)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "Bloodbag");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Fenrir] Could not clone Bloodbag; {displayName} not registered.");
return;
}
Recolour(prefab, tint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = displayName;
shared.m_description = description;
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_weight = 1f;
shared.m_maxStackSize = 10;
// A Bloodbag is food in vanilla. Left alone, someone eats the gate item.
shared.m_food = 0f;
shared.m_foodStamina = 0f;
shared.m_foodRegen = 0f;
shared.m_foodBurnTime = 0f;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
}
// ---------------------------------------------------------------- the pack
/// <summary>
/// One rank of the pack: a vanilla creature, born tame, leashed to the trough that raised it,
/// and carrying nothing on death.
///
/// Everything it is - health, damage, resistances, speed - stays exactly as vanilla has it.
/// The only number written over is the fenrir's scale, and only so it cannot be mistaken for
/// a transformed player at a glance.
///
/// No Procreation on any of them, deliberately: the trough raises the pack, the pack does not
/// raise itself. That is the whole correction this file was rewritten for.
///
/// The CharacterDrop goes for the usual reason and one of this chain's own: a slot refills
/// itself forever, so an animal that dropped its pelt would not be a farm but a mint.
/// </summary>
private static void RegisterPackAnimal(string prefabName, string source, string displayName,
string kind, string refusal, float scale)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Fenrir] Could not clone {source}; {displayName} not registered.");
return;
}
Character character = prefab.GetComponent<Character>();
if (character != null) character.m_name = displayName;
if (scale != 1f) prefab.transform.localScale = Vector3.one * scale;
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = LeashRange;
// A raised pack does not breed. Vanilla gives the Ulv and the Fenring none anyway; the
// wolf comes with one, and it goes.
foreach (Procreation breeding in prefab.GetComponentsInChildren<Procreation>(true))
{
if (breeding != null) Object.DestroyImmediate(breeding);
}
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
// Vanilla gives the Ulv and the Fenring no Tameable at all. Without one they are tamed
// animals that cannot be named or handled like one, so the wolf's is copied across.
if (prefab.GetComponent<Tameable>() == null)
{
GameObject wolf = PrefabManager.Cache.GetPrefab<GameObject>("Wolf");
Tameable source_tame = wolf != null ? wolf.GetComponent<Tameable>() : null;
if (source_tame != null) CopyPublicFields(source_tame, prefab.AddComponent<Tameable>(), prefabName);
}
// "Ten seconds unhurt, then 2% a second" - the same one the Trol's troops already use.
// The postfix that resets its clock on a hit looks for the component, not for a skeleton.
prefab.AddComponent<SkeletonSentryBehaviour>();
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = kind;
thrall.m_commandingRace = RaceId;
thrall.m_maxFollowers = MaxFollowers;
thrall.m_witherSeconds = OrphanWitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = refusal;
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Fenrir] {prefabName} from '{source}': tamed, leashed, no drops, no breeding.");
}
/// <summary>True if the trough takes this as meat. Any flesh, by the scale three chains share.</summary>
public static bool IsMeat(string prefabName)
{
return !string.IsNullOrEmpty(prefabName) && AswidBloodRefinery.FleshValue(prefabName) > 0;
}
public static float FeedValue(string prefabName)
{
int flesh = AswidBloodRefinery.FleshValue(prefabName);
return flesh > 0 ? flesh : 0f;
}
// ---------------------------------------------------------------- piece
private static void RegisterPiece()
{
// A barrel, because a trough is a barrel that someone left open. piece_chest_barrel is
// free - the taken list names piece_chest_wood, which is the Trenta's.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_chest_barrel");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Fenrir] Could not clone piece_chest_barrel; the trough is not registered.");
return;
}
// The barrel's Container is itself the Hoverable AND the Interactable, so a chest would
// swallow both the click that feeds the trough and the hover text that carries the
// roster. The model stays; the chest goes.
foreach (Container container in prefab.GetComponentsInChildren<Container>(true))
{
if (container != null) Object.DestroyImmediate(container);
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
FenrirMangiatoiaBehaviour behaviour = prefab.AddComponent<FenrirMangiatoiaBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
{
if (existing != null) Object.DestroyImmediate(existing);
}
behaviour.m_switch = prefab.AddComponent<Switch>();
behaviour.m_switch.m_name = PieceDisplayName;
prefab.transform.localScale = Vector3.one * TroughScale;
Recolour(prefab, TroughTint);
// Ten silver ingots in the recipe, and a pickaxe that does literally nothing to it.
// "Silver hit points" is not a thing - WearNTear.MaterialType has no silver - but an
// immunity is more precise than a big number anyway: a stray swing while mining out a pen
// cannot cost a pack, and the hammer still takes it down deliberately, because removing a
// piece in Valheim does not go through damage at all.
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear != null)
{
wear.m_damages.m_pickaxe = HitData.DamageModifier.Immune;
wear.m_materialType = WearNTear.MaterialType.Iron;
Jotunn.Logger.LogInfo($"[Fenrir] Trough health {wear.m_health} (inherited), pickaxe immune.");
}
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = BorrowIcon("TrophyFenring");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("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 = PieceDisplayName,
Description = "$rov_piece_fenrir_packtrough_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("TrophyFenring"),
Requirements = new[]
{
new RequirementConfig(UlvsblodName, 1, 0, true),
new RequirementConfig("Silver", 10, 0, true),
new RequirementConfig(ModerDrop, 1, 0, true),
new RequirementConfig("FineWood", 20, 0, true),
}
}));
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
GameObject prefab = PrefabManager.Instance.GetPrefab(PieceName);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) return;
Traverse traverse = Traverse.Create(player);
traverse.Method("AddKnownPiece", piece).GetValue();
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
// ---------------------------------------------------------------- helpers
/// <summary>
/// Copies every public instance field from one component to another of the same type. Private
/// ones are left alone - they are the caches Awake fills in.
/// </summary>
private static void CopyPublicFields<T>(T source, T target, string label) where T : Component
{
if (source == null || target == null) return;
int copied = 0;
foreach (System.Reflection.FieldInfo field in typeof(T).GetFields(
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
field.SetValue(target, field.GetValue(source));
copied++;
}
Jotunn.Logger.LogInfo($"[Fenrir] {label}: {copied} {typeof(T).Name} values taken from the vanilla Wolf.");
}
private static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(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($"[Fenrir] Could not borrow the icon from '{prefabName}'.");
return null;
}
private static void Recolour(GameObject root, Color tint)
{
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
foreach (Material material in renderer.materials)
{
if (material == null) continue;
material.color = tint;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
}
}
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class FenrirMangiatoiaKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
FenrirMangiatoia.EnsureKnown(__instance);
}
}
/// <summary>
/// [DEBUG] The pack, without the hour it takes to raise one.
///
/// A full roster is 30 animals at two to five minutes each, which is most of an afternoon, and
/// the things worth looking at - what a rank looks like, whether a slot refills after a death,
/// whether the upgrade opens the third rank - are all at the far end of it.
/// </summary>
public class FenrirPackSpawnCommand : ConsoleCommand
{
public override string Name => "fenrirpack";
public override string Help =>
"[DEBUG] fenrirpack now [count] - the nearest trough raises its next animals immediately. " +
"'fenrirpack fill' tops up its meat; 'fenrirpack [wolf|ulv|fenrir] [count]' puts animals " +
"in front of you directly, roster or no roster.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null)
{
Console.instance.Print("You must be in-game.");
return;
}
string what = args.Length > 0 ? args[0].ToLowerInvariant() : "wolf";
if (what == "fill") { FenrirMangiatoiaBehaviour.FillNearby(player); return; }
if (what == "now")
{
// No number given means "as many as the roster still wants" - 30 is past the biggest
// possible roster, so the loop stops when NextShort says the pack is whole.
int wanted = 30;
if (args.Length > 1 && !int.TryParse(args[1], out wanted)) wanted = 30;
FenrirMangiatoiaBehaviour.ForceNearby(player, Mathf.Clamp(wanted, 1, 30));
return;
}
string prefabName;
switch (what)
{
case "wolf": prefabName = FenrirMangiatoia.WolfName; break;
case "ulv": prefabName = FenrirMangiatoia.UlvName; break;
case "fenrir": prefabName = FenrirMangiatoia.FenrirName; break;
default:
Console.instance.Print($"'{what}'? wolf, ulv, fenrir - or now / fill.");
return;
}
int count = 2;
if (args.Length > 1 && !int.TryParse(args[1], out count)) count = 2;
count = Mathf.Clamp(count, 1, 30);
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Console.instance.Print($"No '{prefabName}' in ZNetScene - the chain did not register.");
return;
}
// Bound to a trough if there is one in reach, so they count against its roster exactly as
// if it had raised them. Loose otherwise, which is its own useful test.
FenrirMangiatoiaBehaviour trough = FenrirMangiatoiaBehaviour.NearestTo(player.transform.position);
for (int i = 0; i < count; i++)
{
float angle = i * Mathf.PI * 2f / count;
Vector3 ring = new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * 3f;
Vector3 position = player.transform.position + player.transform.forward * 3f + ring + Vector3.up * 0.5f;
GameObject spawned = Object.Instantiate(prefab, position, Quaternion.identity);
Character character = spawned.GetComponent<Character>();
if (character != null) character.SetTamed(true);
MonsterAI ai = spawned.GetComponent<MonsterAI>();
if (ai != null) ai.MakeTame();
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null && trough != null) thrall.Bind(trough.transform.position);
}
Console.instance.Print(trough != null
? $"{count} {prefabName}, bound to the trough {Mathf.RoundToInt(Vector3.Distance(player.transform.position, trough.transform.position))}m away."
: $"{count} {prefabName}, bound to nothing - no trough within range.");
}
}
}