RacesOfValheim/JotunnModStub/Trenta/ComposterBehaviour.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

284 lines
11 KiB
C#

using System;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Composter's logic. Modelled on <see cref="Fermenter"/> - same one-second tick, same
/// owner-only accounting with all state in the ZDO - but with a numeric tank filled by many
/// different meats in place of the barrel's single stored item.
///
/// Three states, and the barrel already has a visual for each of them: filling, composting,
/// ready. Raw flesh is destroyed on the spot and becomes mass; at capacity the lid closes and
/// the clock starts; when it runs out the tap gives a batch of Fertilizer and the cycle resets.
///
/// One simplification over <see cref="BloodRefineryBehaviour"/> worth pointing out: the refinery
/// has to carry a time accumulator because it produces continuously and must catch up on every
/// second it spent unloaded. This works in batches, so the whole timer is one stored timestamp
/// compared against ZNet's world clock - which gets "keeps composting while the zone is
/// unloaded and the game is shut" for free rather than by bookkeeping.
/// </summary>
public class ComposterBehaviour : MonoBehaviour
{
// Handed over from the vanilla Fermenter before it is destroyed, which is what keeps the
// three visual states, the sounds and the tap effects identical to the real barrel's. The
// Switch is ours - see the comment in TrentaComposter.RegisterPiece for why.
public Switch m_switch;
public GameObject m_topObject;
public GameObject m_fermentingObject;
public GameObject m_readyObject;
public Transform m_outputPoint;
public EffectList m_addedEffects;
public EffectList m_tapEffects;
public EffectList m_spawnEffects;
public float m_capacity = 100f;
public float m_compostSeconds = 2400f;
public int m_yield = 20;
private const string KeyFlesh = "RoV_compostFlesh";
private const string KeySealed = "RoV_compostSealed";
private ZNetView m_nview;
public enum State
{
Filling,
Composting,
Ready,
}
private void Awake()
{
m_nview = GetComponent<ZNetView>();
if (m_nview == null) m_nview = GetComponentInParent<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>("RoV_CompostAdd", RPC_Add);
m_nview.Register("RoV_CompostTap", RPC_Tap);
WearNTear wear = GetComponent<WearNTear>();
if (wear == null) wear = GetComponentInParent<WearNTear>();
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
InvokeRepeating("UpdateComposter", 1f, 1f);
}
// ---------------------------------------------------------------- interaction
/// <summary>
/// One interaction point, exactly like the vanilla barrel: the item in hand decides what the
/// click means. Holding flesh feeds it; empty hands tap it when it is ready and otherwise
/// just report what it is doing.
/// </summary>
// 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;
State state = GetState();
if (state == State.Ready)
{
m_nview.InvokeRPC("RoV_CompostTap");
return true;
}
if (state == State.Composting)
{
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_still_rotting_minutes", MinutesLeft()));
return false;
}
Inventory inventory = user.GetInventory();
if (inventory == null) return false;
if (item == null) item = FindFlesh(inventory);
if (item == null)
{
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_no_raw_flesh_rot"));
return false;
}
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (AswidBloodRefinery.FleshValue(prefabName) <= 0)
{
user.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
user.Message(MessageHud.MessageType.Center, "$msg_added " + item.m_shared.m_name);
inventory.RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_CompostAdd", prefabName);
return true;
}
private ItemDrop.ItemData FindFlesh(Inventory inventory)
{
foreach (ItemDrop.ItemData candidate in inventory.GetAllItems())
{
if (candidate == null || candidate.m_dropPrefab == null) continue;
if (AswidBloodRefinery.FleshValue(candidate.m_dropPrefab.name) > 0) return candidate;
}
return null;
}
private void RPC_Add(long sender, string prefabName)
{
if (!m_nview.IsOwner()) return;
if (GetState() != State.Filling) return;
int value = AswidBloodRefinery.FleshValue(prefabName);
if (value <= 0) return;
float flesh = Mathf.Min(m_capacity, GetFlesh() + value);
SetFlesh(flesh);
// Reaching capacity is what starts the clock. Stamped once, here, so a barrel that fills
// up while nobody is watching still seals at the right moment.
if (flesh >= m_capacity) m_nview.GetZDO().Set(KeySealed, ZNet.instance.GetTime().Ticks);
if (m_addedEffects != null) m_addedEffects.Create(transform.position, transform.rotation);
}
private void RPC_Tap(long sender)
{
if (!m_nview.IsOwner()) return;
if (GetState() != State.Ready) return;
SetFlesh(0f);
m_nview.GetZDO().Set(KeySealed, 0L);
Produce();
}
private void Produce()
{
GameObject prefab = ObjectDB.instance != null
? ObjectDB.instance.GetItemPrefab(TrentaConfig.FertilizerName)
: null;
if (prefab == null || m_outputPoint == null) return;
if (m_tapEffects != null) m_tapEffects.Create(transform.position, transform.rotation);
if (m_spawnEffects != null) m_spawnEffects.Create(m_outputPoint.position, m_outputPoint.rotation);
// One stack rather than twenty objects on the ground: Fertilizer stacks to 50, so the
// whole batch fits, the same way Smelter.m_spawnStack gathers its output.
GameObject spawned = Instantiate(prefab, m_outputPoint.position, m_outputPoint.rotation);
ItemDrop drop = spawned.GetComponent<ItemDrop>();
if (drop != null)
{
drop.m_itemData.m_stack = m_yield;
ItemDrop.OnCreateNew(drop);
}
}
/// <summary>
/// A finished batch is given back; flesh that has already rotted is not. Same rule the Blood
/// Refinery follows for blood, and for the same reason - what the machine has absorbed is
/// gone by design, and the hover text says so before anyone swings a hammer at it.
/// </summary>
private void OnDestroyed()
{
if (m_nview == null || !m_nview.IsOwner()) return;
bool ready = GetState() == State.Ready;
SetFlesh(0f);
m_nview.GetZDO().Set(KeySealed, 0L);
if (!ready) return;
GameObject prefab = ObjectDB.instance != null
? ObjectDB.instance.GetItemPrefab(TrentaConfig.FertilizerName)
: null;
if (prefab == null) return;
Vector3 position = transform.position + Vector3.up * 0.5f;
GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f));
ItemDrop drop = spawned.GetComponent<ItemDrop>();
if (drop != null)
{
drop.m_itemData.m_stack = m_yield;
ItemDrop.OnCreateNew(drop);
}
}
// ---------------------------------------------------------------- state and display
public State GetState()
{
if (GetFlesh() < m_capacity) return State.Filling;
return SecondsSealed() >= m_compostSeconds ? State.Ready : State.Composting;
}
private void UpdateComposter()
{
if (m_nview == null || !m_nview.IsValid()) return;
State state = GetState();
if (m_topObject != null) m_topObject.SetActive(state == State.Filling);
if (m_fermentingObject != null) m_fermentingObject.SetActive(state == State.Composting);
if (m_readyObject != null) m_readyObject.SetActive(state == State.Ready);
}
private int MinutesLeft()
{
double left = m_compostSeconds - SecondsSealed();
return Mathf.Max(1, Mathf.CeilToInt((float)left / 60f));
}
private string Hover()
{
string body;
switch (GetState())
{
case State.Ready:
body = ModText.Get("rov_hover_trenta_ready_empty", m_yield, TrentaConfig.FertilizerDisplayName);
break;
case State.Composting:
body = ModText.Get("rov_hover_trenta_rotting_minutes_left", MinutesLeft());
break;
default:
body = ModText.Get("rov_hover_trenta_flesh_feed_raw_flesh", Mathf.Floor(GetFlesh()), m_capacity);
break;
}
return Localization.instance.Localize($"{TrentaConfig.ComposterDisplayName} ({body})");
}
// ---------------------------------------------------------------- ZDO accessors
/// <summary>
/// Seconds since the barrel sealed itself, on ZNet's world clock rather than on frames - so
/// it keeps counting while the zone is unloaded and across a restart. 0 while still filling.
/// </summary>
private double SecondsSealed()
{
if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return 0.0;
long ticks = m_nview.GetZDO().GetLong(KeySealed, 0L);
if (ticks == 0L) return 0.0;
return (ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds;
}
private float GetFlesh() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyFlesh) : 0f;
private void SetFlesh(float value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyFlesh, Mathf.Max(0f, value));
}
}
}