feat(trenta): composter and heartwood grove
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
b67a324cb8
commit
1a741978bf
7 changed files with 1659 additions and 19 deletions
373
JotunnModStub/Trenta/GroveBehaviour.cs
Normal file
373
JotunnModStub/Trenta/GroveBehaviour.cs
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
using System;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The Heartwood Grove's logic: three independent jobs on one timer.
|
||||
///
|
||||
/// GROWING UP one timestamp on ZNet's world clock, exactly like the Composter's seal time, so
|
||||
/// a planted grove keeps ageing with the zone unloaded and the game shut. The only
|
||||
/// visible effect is which of the two models is showing.
|
||||
/// FERTILISING once grown, one plant per minute inside the radius, one Fertilizer each, drawn
|
||||
/// from a tank the player fills through the Switch on the trunk. Deliberately one
|
||||
/// plant per tick and not the whole radius: a full tank is then twenty minutes of
|
||||
/// autonomy instead of one tick's worth.
|
||||
/// HONEY accrues into the Container on the root at the vanilla Beehive's own rate, read
|
||||
/// off that prefab rather than invented.
|
||||
///
|
||||
/// A tank that is empty stops the fertilising and nothing else. The bees do not care, and neither
|
||||
/// does the honey - they are three jobs, not three stages.
|
||||
///
|
||||
/// Everything that changes state runs on the ZNetView owner only, which is also why the swarm is
|
||||
/// spawned there: bees on every client would mean every client's copy landing its own sting.
|
||||
/// </summary>
|
||||
public class GroveBehaviour : MonoBehaviour
|
||||
{
|
||||
public Switch m_switch;
|
||||
public Container m_container;
|
||||
public GameObject m_youngModel;
|
||||
public GameObject m_grownModel;
|
||||
|
||||
private const string KeyPlanted = "RoV_grovePlanted";
|
||||
private const string KeyFertilizer = "RoV_groveFert";
|
||||
private const string KeyHoneyTime = "RoV_groveHoneyTime";
|
||||
|
||||
// Container.Save is private, so it is reached the same way AswidBloodPotions reaches
|
||||
// Fermenter.GetContent. Honey added by us has to be written to the ZDO explicitly: a player
|
||||
// dropping items in goes through the inventory's own change callback, and nothing guarantees
|
||||
// that callback covers a write made from outside the container's own UI.
|
||||
private static readonly System.Reflection.MethodInfo ContainerSaveMethod =
|
||||
HarmonyLib.AccessTools.Method(typeof(Container), "Save");
|
||||
|
||||
private ZNetView m_nview;
|
||||
private GameObject m_bees;
|
||||
|
||||
// Read off the vanilla Beehive at Awake, so the grove uses the game's own honey rate. Only
|
||||
// the capacity is scaled - a tree of bees has to last while the player is away.
|
||||
private float m_secPerHoney = 1200f;
|
||||
private int m_honeyCapacity = 20;
|
||||
private GameObject m_honeyPrefab;
|
||||
|
||||
// The fertilise tick is local time, not world time, and that is correct rather than lazy: an
|
||||
// unloaded grove cannot grow plants in a zone that is not there, so banking the time it spent
|
||||
// unloaded would hand back growth that never could have happened. Honey banks; growth does not.
|
||||
private float m_fertilizeTimer;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
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("RoV_GroveFeed", RPC_Feed);
|
||||
|
||||
ReadHoneyRates();
|
||||
|
||||
if (m_nview.IsOwner())
|
||||
{
|
||||
// Stamped once, on the first client to own it, which is the moment it was planted.
|
||||
if (m_nview.GetZDO().GetLong(KeyPlanted, 0L) == 0L)
|
||||
{
|
||||
m_nview.GetZDO().Set(KeyPlanted, ZNet.instance.GetTime().Ticks);
|
||||
}
|
||||
if (m_nview.GetZDO().GetLong(KeyHoneyTime, 0L) == 0L)
|
||||
{
|
||||
m_nview.GetZDO().Set(KeyHoneyTime, ZNet.instance.GetTime().Ticks);
|
||||
}
|
||||
}
|
||||
|
||||
InvokeRepeating("UpdateGrove", 1f, 1f);
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (m_bees != null) Destroy(m_bees);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Borrows m_secPerUnit, m_maxHoney and the honey item off the vanilla Beehive. The rate is
|
||||
/// not a design decision this mod gets to make - a hive's is already tuned - so only the
|
||||
/// capacity is multiplied.
|
||||
/// </summary>
|
||||
private void ReadHoneyRates()
|
||||
{
|
||||
Beehive hive = TrentaConfig.FindVanillaBeehive();
|
||||
|
||||
if (hive != null)
|
||||
{
|
||||
if (hive.m_secPerUnit > 0f) m_secPerHoney = hive.m_secPerUnit;
|
||||
if (hive.m_maxHoney > 0) m_honeyCapacity = hive.m_maxHoney * TrentaConfig.GroveHoneyCapacityFactor;
|
||||
if (hive.m_honeyItem != null) m_honeyPrefab = hive.m_honeyItem.gameObject;
|
||||
}
|
||||
else
|
||||
{
|
||||
Jotunn.Logger.LogWarning("[Trenta] Heartwood Grove: no vanilla beehive; falling back to default honey rates.");
|
||||
}
|
||||
|
||||
if (m_honeyPrefab == null && ObjectDB.instance != null)
|
||||
{
|
||||
m_honeyPrefab = ObjectDB.instance.GetItemPrefab("Honey");
|
||||
}
|
||||
|
||||
// Without this the honey half fails silently, which is exactly how the night-gate bug
|
||||
// managed to hide: nothing appeared and nothing said why. The log line also settles a
|
||||
// question the design doc left open - whether the tuned Beehive component lives on
|
||||
// "Beehive" or on "piece_beehive" - by printing what was actually read.
|
||||
if (m_honeyPrefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning("[Trenta] Heartwood Grove: no honey prefab found; this grove will never produce honey.");
|
||||
return;
|
||||
}
|
||||
|
||||
Jotunn.Logger.LogInfo($"[Trenta] Heartwood Grove: honey every {m_secPerHoney:0}s, capacity {m_honeyCapacity} " +
|
||||
$"(rates {(hive != null ? "read from the vanilla beehive" : "defaulted")}).");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the loop
|
||||
|
||||
private void UpdateGrove()
|
||||
{
|
||||
if (m_nview == null || !m_nview.IsValid()) return;
|
||||
|
||||
bool grown = IsGrown();
|
||||
if (m_youngModel != null) m_youngModel.SetActive(!grown);
|
||||
if (m_grownModel != null) m_grownModel.SetActive(grown);
|
||||
|
||||
if (!m_nview.IsOwner()) return;
|
||||
|
||||
if (!grown) return;
|
||||
|
||||
EnsureBees();
|
||||
TickHoney();
|
||||
|
||||
m_fertilizeTimer += 1f;
|
||||
if (m_fertilizeTimer >= TrentaConfig.GroveFertilizeInterval)
|
||||
{
|
||||
m_fertilizeTimer = 0f;
|
||||
TickFertilize();
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureBees()
|
||||
{
|
||||
if (m_bees != null) return;
|
||||
m_bees = TrentaHornetSwarm.SpawnAtAnchor(transform, TrentaConfig.GroveStingRadius);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Grows exactly one thing per tick, through the very same method a player's Fertilizer click
|
||||
/// goes through. That sharing is the point: two tiers growing plants by two slightly
|
||||
/// different sets of rules is the failure this is written to prevent.
|
||||
/// </summary>
|
||||
private void TickFertilize()
|
||||
{
|
||||
if (GetFertilizer() <= 0) return;
|
||||
|
||||
foreach (Collider collider in Physics.OverlapSphere(transform.position, TrentaConfig.GroveRadius))
|
||||
{
|
||||
if (collider == null) continue;
|
||||
|
||||
if (TrentaComposter.TryGrow(collider.gameObject) != TrentaComposter.GrowOutcome.Grown) continue;
|
||||
|
||||
SetFertilizer(GetFertilizer() - 1);
|
||||
return; // One per tick, by design
|
||||
}
|
||||
}
|
||||
|
||||
private void TickHoney()
|
||||
{
|
||||
if (m_honeyPrefab == null || m_container == null) return;
|
||||
|
||||
long stamp = m_nview.GetZDO().GetLong(KeyHoneyTime, 0L);
|
||||
if (stamp == 0L) return;
|
||||
|
||||
DateTime now = ZNet.instance.GetTime();
|
||||
|
||||
// No night gate. There used to be one, and it was what stopped the honey ever appearing -
|
||||
// see the long note in TrentaConfig where GroveHoneyAtNight used to live.
|
||||
double elapsed = (now - new DateTime(stamp)).TotalSeconds;
|
||||
if (elapsed < m_secPerHoney) return;
|
||||
|
||||
Inventory inventory = m_container.GetInventory();
|
||||
if (inventory == null) return;
|
||||
|
||||
int produced = 0;
|
||||
bool blocked = false;
|
||||
while (elapsed >= m_secPerHoney)
|
||||
{
|
||||
if (CountHoney(inventory) >= m_honeyCapacity || !inventory.AddItem(m_honeyPrefab, 1))
|
||||
{
|
||||
blocked = true;
|
||||
break;
|
||||
}
|
||||
|
||||
elapsed -= m_secPerHoney;
|
||||
produced++;
|
||||
}
|
||||
|
||||
if (blocked)
|
||||
{
|
||||
// Full chest: the clock is reset to now and the surplus is thrown away, so an
|
||||
// untouched grove cannot bank an unbounded debt that dumps all at once the moment
|
||||
// the player finally empties it. This is also what a vanilla hive does when it caps.
|
||||
m_nview.GetZDO().Set(KeyHoneyTime, now.Ticks);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Only the time actually spent on the honey produced is consumed. Resetting to now
|
||||
// here instead would silently throw away the remainder on every single unit and
|
||||
// leave the grove producing slower than the hive whose rate it borrowed.
|
||||
m_nview.GetZDO().Set(KeyHoneyTime, now.AddSeconds(-elapsed).Ticks);
|
||||
}
|
||||
|
||||
if (produced > 0 && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(m_container, null);
|
||||
}
|
||||
|
||||
private int CountHoney(Inventory inventory)
|
||||
{
|
||||
if (m_honeyPrefab == null) return 0;
|
||||
|
||||
ItemDrop drop = m_honeyPrefab.GetComponent<ItemDrop>();
|
||||
string name = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
|
||||
? drop.m_itemData.m_shared.m_name
|
||||
: null;
|
||||
if (name == null) return 0;
|
||||
|
||||
// Counted by hand rather than through Inventory.CountItems so no overload's quality and
|
||||
// world-level arguments have to be guessed at.
|
||||
int total = 0;
|
||||
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
|
||||
{
|
||||
if (item != null && item.m_shared != null && item.m_shared.m_name == name) total += item.m_stack;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- interaction
|
||||
|
||||
/// <summary>
|
||||
/// E on the tree. Holding Fertilizer fills the tank; empty-handed it reports what the grove is
|
||||
/// doing. Loading a tank before the tree has grown is allowed on purpose - there is no reason
|
||||
/// to make the player come back twice.
|
||||
/// </summary>
|
||||
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
|
||||
{
|
||||
if (user == null) return false;
|
||||
|
||||
Inventory inventory = user.GetInventory();
|
||||
if (inventory == null) return false;
|
||||
|
||||
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.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!TrentaComposter.IsFertilizer(item))
|
||||
{
|
||||
user.Message(MessageHud.MessageType.Center, "$msg_wontwork");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (GetFertilizer() >= TrentaConfig.GroveFertilizerCapacity)
|
||||
{
|
||||
user.Message(MessageHud.MessageType.Center, "$msg_itsfull");
|
||||
return false;
|
||||
}
|
||||
|
||||
user.Message(MessageHud.MessageType.Center, "$msg_added " + item.m_shared.m_name);
|
||||
inventory.RemoveItem(item, 1);
|
||||
m_nview.InvokeRPC("RoV_GroveFeed");
|
||||
return true;
|
||||
}
|
||||
|
||||
private ItemDrop.ItemData FindFertilizer(Inventory inventory)
|
||||
{
|
||||
foreach (ItemDrop.ItemData candidate in inventory.GetAllItems())
|
||||
{
|
||||
if (TrentaComposter.IsFertilizer(candidate)) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void RPC_Feed(long sender)
|
||||
{
|
||||
if (!m_nview.IsOwner()) return;
|
||||
|
||||
int stored = GetFertilizer();
|
||||
if (stored >= TrentaConfig.GroveFertilizerCapacity) return;
|
||||
SetFertilizer(stored + 1);
|
||||
}
|
||||
|
||||
private string Hover()
|
||||
{
|
||||
if (!IsGrown())
|
||||
{
|
||||
return Localization.instance.Localize(
|
||||
$"{TrentaConfig.GroveDisplayName} (growing, {MinutesLeft()} minutes left)");
|
||||
}
|
||||
|
||||
// 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" +
|
||||
"[<color=yellow><b>$KEY_Use</b></color>] Feed it Fertilizer");
|
||||
}
|
||||
|
||||
/// <summary>How much honey is in the crate and how long until the next drop of it.</summary>
|
||||
private string HoneyStatus()
|
||||
{
|
||||
if (m_honeyPrefab == null) return "none (no honey item found)";
|
||||
|
||||
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";
|
||||
|
||||
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";
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
|
||||
public bool IsGrown() => SecondsSincePlanted() >= TrentaConfig.GroveGrowSeconds;
|
||||
|
||||
private double SecondsSincePlanted()
|
||||
{
|
||||
if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return 0.0;
|
||||
|
||||
long ticks = m_nview.GetZDO().GetLong(KeyPlanted, 0L);
|
||||
if (ticks == 0L) return 0.0;
|
||||
|
||||
return (ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds;
|
||||
}
|
||||
|
||||
private int MinutesLeft()
|
||||
{
|
||||
double left = TrentaConfig.GroveGrowSeconds - SecondsSincePlanted();
|
||||
return Mathf.Max(1, Mathf.CeilToInt((float)left / 60f));
|
||||
}
|
||||
|
||||
private int GetFertilizer() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyFertilizer) : 0;
|
||||
|
||||
private void SetFertilizer(int value)
|
||||
{
|
||||
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyFertilizer, Mathf.Max(0, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue