RacesOfValheim/JotunnModStub/Fenrir/FenrirMangiatoiaBehaviour.cs
kanym 99a1817eb0 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 <noreply@anthropic.com>
2026-09-28 13:55:14 +02:00

470 lines
19 KiB
C#

using System;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The trough's logic: one rank at a time, one animal at a time, paid for in meat.
///
/// Same shape as DraughSpawnerBehaviour and SkeletonBonePileBehaviour, and deliberately so - all
/// the state in the ZDO, owner-only accounting, and a roster that is COUNTED rather than tallied.
/// Counting fresh on every tick is what makes "when one dies its slot comes back" need no code at
/// all: a death, a despawn, or a player killing his own wolf all correct themselves.
///
/// The ranks fill in order - wolves, then ulv, then fenrir - and whichever rank is short is the
/// one the clock is running for. That is also what "the timer for that one restarts" means: a
/// wolf dying while the trough is working on ulv moves the clock back to the wolf rank, because
/// the lowest short rank always wins.
///
/// HONEST LIMIT, the same one the Skeleton's pile carries: RaisedThrall.BoundTo can only see
/// LOADED creatures. A pack that is off across the map following its owner does not count, and a
/// trough left alone will fill the slots it thinks are empty. The wither is what stops that
/// becoming permanent - a trough only sustains one pack - but a player who ferries animals away
/// and comes back can hold more than the roster says. Closing it properly needs the animals to
/// carry their own bookkeeping, which is the version this replaced and which cost more than it
/// was worth.
/// </summary>
public class FenrirMangiatoiaBehaviour : MonoBehaviour
{
public Switch m_switch;
private const string KeyFeed = "RoV_fenrirFeed";
private const string KeyUpgraded = "RoV_fenrirUpgraded";
private static readonly List<FenrirMangiatoiaBehaviour> Live = new List<FenrirMangiatoiaBehaviour>();
private ZNetView m_nview;
/// <summary>Seconds towards the next animal of whichever rank is currently short.</summary>
private float m_timer;
/// <summary>Which rank the clock is running for, so that a change resets it.</summary>
private string m_waitingFor;
// ---------------------------------------------------------------- life
private void Awake()
{
Live.Add(this);
RaisedThrall.RegisterStation(transform);
m_nview = GetComponent<ZNetView>();
if (m_nview == null || m_nview.GetZDO() == null) return;
if (m_switch != null)
{
m_switch.m_onUse = OnUse;
m_switch.m_onHover = Hover;
}
m_nview.Register<string, int>("RoV_FenrirFeed", RPC_Feed);
m_nview.Register("RoV_FenrirUpgrade", RPC_Upgrade);
WearNTear wear = GetComponent<WearNTear>();
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
InvokeRepeating("Tick", FenrirMangiatoia.TickSeconds, FenrirMangiatoia.TickSeconds);
}
private void OnDestroy()
{
Live.Remove(this);
RaisedThrall.UnregisterStation(transform);
}
/// <summary>The nearest loaded trough, or null if none is in reach.</summary>
public static FenrirMangiatoiaBehaviour NearestTo(Vector3 position)
{
FenrirMangiatoiaBehaviour best = null;
float bestSq = 60f * 60f;
for (int i = Live.Count - 1; i >= 0; i--)
{
FenrirMangiatoiaBehaviour trough = Live[i];
if (trough == null) { Live.RemoveAt(i); continue; }
float sq = Vector3.SqrMagnitude(trough.transform.position - position);
if (sq > bestSq) continue;
bestSq = sq;
best = trough;
}
return best;
}
/// <summary>[DEBUG] Tops up every nearby trough, so a test does not start with a meat run.</summary>
public static void FillNearby(Player player)
{
int filled = 0;
foreach (FenrirMangiatoiaBehaviour trough in Live)
{
if (trough == null || trough.m_nview == null || !trough.m_nview.IsValid()) continue;
if (Vector3.Distance(trough.transform.position, player.transform.position) > 60f) continue;
trough.m_nview.ClaimOwnership();
trough.SetFeed(FenrirMangiatoia.TankCap);
filled++;
}
Console.instance.Print(filled == 0 ? "No troughs within 60m." : $"{filled} filled to the brim.");
}
// ---------------------------------------------------------------- the tick
private void Tick()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (!NextShort(out string kind, out string prefabName, out float wait, out float cost))
{
// Nothing short: the pack is whole. The clock does not run, so a death does not get a
// head start it never earned.
m_timer = 0f;
m_waitingFor = null;
return;
}
// A rank that has just fallen short takes the clock over from the one above it, and it
// starts from zero. This is "the timer for that one restarts", and it is why a death
// costs the full wait rather than whatever happened to be left on another rank's clock.
if (m_waitingFor != kind)
{
m_waitingFor = kind;
m_timer = 0f;
}
if (GetFeed() < cost) return; // no meat, no clock
m_timer += FenrirMangiatoia.TickSeconds;
if (m_timer < wait) return;
m_timer = 0f;
if (Spawn(prefabName)) SetFeed(GetFeed() - cost);
}
/// <summary>
/// The lowest rank that is short, and what raising one of it costs and takes. Ranks fill in
/// order, so this one method is the whole scheduler.
///
/// Extracted so the debug command that forces a spawn goes through EXACTLY this, and cannot
/// quietly fill a rank out of order, past its cap, or before the upgrade opens it. A test
/// tool that skips the rule it is testing proves nothing.
///
/// Returns false when the pack is whole.
/// </summary>
private bool NextShort(out string kind, out string prefabName, out float wait, out float cost)
{
Count(out int wolves, out int ulv, out int fenrir);
if (wolves < WolfCap())
{
kind = FenrirMangiatoia.KindWolf;
prefabName = FenrirMangiatoia.WolfName;
wait = FenrirMangiatoia.WolfSeconds;
cost = FenrirMangiatoia.WolfCost;
return true;
}
if (ulv < UlvCap())
{
kind = FenrirMangiatoia.KindUlv;
prefabName = FenrirMangiatoia.UlvName;
wait = FenrirMangiatoia.UlvSeconds;
cost = FenrirMangiatoia.UlvCost;
return true;
}
if (fenrir < FenrirCap())
{
kind = FenrirMangiatoia.KindFenrir;
prefabName = FenrirMangiatoia.FenrirName;
wait = FenrirMangiatoia.FenrirSeconds;
cost = FenrirMangiatoia.FenrirCost;
return true;
}
kind = null;
prefabName = null;
wait = 0f;
cost = 0f;
return false;
}
/// <summary>
/// [DEBUG] Raises the next <paramref name="count"/> animals at once, skipping only the wait.
///
/// The meat is still charged and the tank is topped up to cover it, because a full roster is
/// far more meat than a tank holds and the point of the command is to skip the CLOCK, not the
/// economy. Everything else - which rank is next, its cap, whether the upgrade has opened the
/// third one - comes from NextShort, the same call the timer uses.
/// </summary>
public static void ForceNearby(Player player, int count)
{
FenrirMangiatoiaBehaviour trough = NearestTo(player.transform.position);
if (trough == null || trough.m_nview == null || !trough.m_nview.IsValid())
{
Console.instance.Print("No trough within 60m.");
return;
}
trough.m_nview.ClaimOwnership();
int raised = 0;
for (int i = 0; i < count; i++)
{
if (!trough.NextShort(out _, out string prefabName, out _, out float cost)) break;
if (trough.GetFeed() < cost) trough.SetFeed(FenrirMangiatoia.TankCap);
if (!trough.Spawn(prefabName)) break;
trough.SetFeed(trough.GetFeed() - cost);
raised++;
}
trough.m_timer = 0f;
Console.instance.Print(raised == 0
? "The pack is already whole."
: $"{raised} raised on the spot. The roster picked them, in its own order.");
}
/// <summary>
/// The roster, counted fresh. Never banked: a tally would have to be corrected on death, on
/// despawn and on a player killing his own, and any one of those going missing leaves a
/// trough that thinks it is full forever.
/// </summary>
private void Count(out int wolves, out int ulv, out int fenrir)
{
wolves = 0;
ulv = 0;
fenrir = 0;
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(transform.position))
{
if (thrall.Kind == FenrirMangiatoia.KindWolf) wolves++;
else if (thrall.Kind == FenrirMangiatoia.KindUlv) ulv++;
else if (thrall.Kind == FenrirMangiatoia.KindFenrir) fenrir++;
}
}
private bool Spawn(string prefabName)
{
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Fenrir] No '{prefabName}' in ZNetScene; the trough cannot raise anything.");
return false;
}
Vector3 offset = UnityEngine.Random.insideUnitSphere * 3f;
offset.y = 0f;
Vector3 position = transform.position + offset + Vector3.up * 0.5f;
GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f));
// Bind tames it, marks whose it is, and sends it home - all three.
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(transform.position);
return true;
}
// ---------------------------------------------------------------- interaction
// 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;
Inventory inventory = user.GetInventory();
if (inventory == null) return false;
if (item == null) item = FindAnyInput(inventory);
if (item == null)
{
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_wants_meat_any_meat"));
return false;
}
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (prefabName == null) return false;
if (prefabName == FenrirMangiatoia.GreaterUlvsblodName) return TryUpgrade(user, inventory, item);
if (!FenrirMangiatoia.IsMeat(prefabName))
{
user.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
if (GetFeed() >= FenrirMangiatoia.TankCap)
{
user.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
// A whole stack per click. A full tank is a lot of neck tails and clicking them out one
// at a time is not a mechanic.
int stack = Mathf.Max(1, item.m_stack);
user.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{stack}");
inventory.RemoveItem(item, stack);
m_nview.InvokeRPC("RoV_FenrirFeed", prefabName, stack);
return true;
}
private ItemDrop.ItemData FindAnyInput(Inventory inventory)
{
foreach (ItemDrop.ItemData candidate in inventory.GetAllItems())
{
if (candidate == null || candidate.m_dropPrefab == null) continue;
string name = candidate.m_dropPrefab.name;
if (name == FenrirMangiatoia.GreaterUlvsblodName) return candidate;
if (FenrirMangiatoia.IsMeat(name)) return candidate;
}
return null;
}
/// <summary>
/// The 1500-coin upgrade, and the second boss gate. Nothing about the trough changes to look
/// at - which is exactly why the hover text has to say it, or the next thing that happens is
/// somebody buys a second one.
/// </summary>
private bool TryUpgrade(Humanoid user, Inventory inventory, ItemDrop.ItemData item)
{
if (IsUpgraded())
{
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, ModText.Get("rov_msg_fenrir_blood_will_not_take_something"));
return false;
}
if (inventory.CountItems(YagluthDropName()) < 1)
{
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_wants_what_yagluth_left_behind"));
return false;
}
inventory.RemoveItem(YagluthDropName(), 1);
inventory.RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_FenrirUpgrade");
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_trough_takes_line_runs_deeper"));
return true;
}
/// <summary>Inventory.RemoveItem and CountItems work on the DISPLAYED name, not the prefab.</summary>
private static string YagluthDropName()
{
ItemDrop drop = Jotunn.Managers.PrefabManager.Cache.GetPrefab<ItemDrop>(FenrirMangiatoia.YagluthDrop);
return drop != null ? drop.m_itemData.m_shared.m_name : FenrirMangiatoia.YagluthDrop;
}
// ---------------------------------------------------------------- accounting
private void RPC_Feed(long sender, string prefabName, int count)
{
if (!m_nview.IsOwner()) return;
if (count < 1) count = 1;
SetFeed(GetFeed() + FenrirMangiatoia.FeedValue(prefabName) * count);
}
private void RPC_Upgrade(long sender)
{
if (!m_nview.IsOwner()) return;
m_nview.GetZDO().Set(KeyUpgraded, true);
}
/// <summary>
/// The trough sustains the pack, so it takes the pack with it - on the wither's delay rather
/// than on the spot. Without some form of this, a trough is a duplication exploit: fill it,
/// dismantle it, rebuild it elsewhere, and keep every animal from every round.
/// </summary>
private void OnDestroyed()
{
if (m_nview == null || !m_nview.IsOwner()) return;
List<RaisedThrall> bound = RaisedThrall.BoundTo(transform.position);
foreach (RaisedThrall thrall in bound) thrall.MarkOrphaned();
if (bound.Count > 0 && Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_fenrir_trough_broken_will_not_outlast", bound.Count));
}
SetFeed(0f);
}
// ---------------------------------------------------------------- state and display
public bool IsUpgraded() =>
m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false);
private int WolfCap() => IsUpgraded() ? FenrirMangiatoia.WolfSlotsUpgraded : FenrirMangiatoia.WolfSlots;
private int UlvCap() => IsUpgraded() ? FenrirMangiatoia.UlvSlotsUpgraded : FenrirMangiatoia.UlvSlots;
private int FenrirCap() => IsUpgraded() ? FenrirMangiatoia.FenrirSlotsUpgraded : FenrirMangiatoia.FenrirSlots;
private float GetFeed() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyFeed) : 0f;
private void SetFeed(float value)
{
if (m_nview != null && m_nview.IsValid())
{
m_nview.GetZDO().Set(KeyFeed, Mathf.Clamp(value, 0f, FenrirMangiatoia.TankCap));
}
}
/// <summary>
/// Everything a player needs without opening a log, which is the standard this project
/// arrived at the hard way: a mechanic that cannot say whether it is working looks exactly
/// like one that is broken.
/// </summary>
private string Hover()
{
Count(out int wolves, out int ulv, out int fenrir);
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() ? ModText.Get("rov_hover_fenrir_fenrir", fenrir, FenrirCap()) : ModText.Get("rov_hover_fenrir_blood_thin_here_raises_no"));
if (m_waitingFor != null)
{
float wait = m_waitingFor == FenrirMangiatoia.KindWolf ? FenrirMangiatoia.WolfSeconds
: m_waitingFor == FenrirMangiatoia.KindUlv ? FenrirMangiatoia.UlvSeconds
: FenrirMangiatoia.FenrirSeconds;
float cost = m_waitingFor == FenrirMangiatoia.KindWolf ? FenrirMangiatoia.WolfCost
: m_waitingFor == FenrirMangiatoia.KindUlv ? FenrirMangiatoia.UlvCost
: FenrirMangiatoia.FenrirCost;
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 += ModText.Get("rov_hover_fenrir_pack_whole");
}
body += ModText.Get("rov_hover_fenrir_fill_with_meat");
return Localization.instance.Localize($"{FenrirMangiatoia.PieceDisplayName} ({body})");
}
}
}