diff --git a/JotunnModStub/Draugh/DraughRace.cs b/JotunnModStub/Draugh/DraughRace.cs index 0293ec8..0fa6662 100644 --- a/JotunnModStub/Draugh/DraughRace.cs +++ b/JotunnModStub/Draugh/DraughRace.cs @@ -18,6 +18,11 @@ namespace RacesOfValheim public void CreateModAssets() { + // The body pile and its thralls. Registered here because the faction merchant catalogue + // resolves its entries by prefab name, so the two cursed bones have to exist before a + // Draugr is ever set up as a bench. + DraughSpawner.Register(); + // Generate EdibleUncooked prefabs for Draugh raw food logic foreach (var mapping in DraughFoodPatches.rawToCookedMapping) { diff --git a/JotunnModStub/Draugh/DraughSpawner.cs b/JotunnModStub/Draugh/DraughSpawner.cs new file mode 100644 index 0000000..b921be7 --- /dev/null +++ b/JotunnModStub/Draugh/DraughSpawner.cs @@ -0,0 +1,335 @@ +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Draugh station: a smaller, green body pile that eats raw flesh and answers with tamed + /// draugr. Third of the per-race station chains, after the Aswid's Blood Refinery and the + /// Trenta's Composter, and it takes its input rules straight from the second one - 100 units of + /// flesh valued by , one batch, one draugr. + /// + /// What makes it a Draugh thing rather than a piece of furniture anyone can use: the pile itself + /// works for whoever built it, but the draugr only take ORDERS from a Draugh. Anyone else gets a + /// grave that defends its own ten metres; a Draugh gets an escort. That asymmetry is the design, + /// not a limitation. + /// + /// Two special inputs, both of them draugr remains, because the pile is not fussy about where the + /// meat comes from: a Draugr trophy is worth a whole batch, and an Elite trophy is worth an elite + /// outright once the pile has been upgraded to hold any. + /// + public static class DraughSpawner + { + // ─── Names ─────────────────────────────────────────────────────────── + public const string PieceName = "DraughBodyPile"; + public const string PieceDisplayName = "Cursed Body Pile"; + + public const string BoneName = "CursedBone"; + public const string BoneDisplayName = "Cursed Bone"; + public const string GreaterBoneName = "GreaterCursedBone"; + public const string GreaterBoneDisplayName = "Greater Cursed Bone"; + + 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"; + + // 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. + public const string KindNormal = "DraughDraugr"; + public const string KindElite = "DraughDraugrElite"; + + public const string RaceId = "Draugh"; + + // The two trophies the pile accepts in place of meat. + public const string TrophyDraugr = "TrophyDraugr"; + public const string TrophyDraugrElite = "TrophyDraugrElite"; + + // ─── Balance ───────────────────────────────────────────────────────── + // 100 units is one full Composter batch on the same FleshValue scale, which is deliberate: + // it makes a Draugr trophy (worth exactly one batch) the real currency and raw meat the + // fallback. A trophy drops from roughly one draugr in ten, so the pile is fed mostly by + // doing the thing it is thematically about. + public const float FleshPerThrall = 100f; + + public const int AliveCap = 5; + public const int AliveCapUpgraded = 7; // +2 normals, as designed + public const int EliteCap = 0; // none at all until upgraded + public const int EliteCapUpgraded = 3; + + public const int ReserveCap = 5; + public const int ReserveCapElite = 3; + + // Local seconds, and only while the zone is loaded - see DraughSpawnerBehaviour. + public const float RespawnSeconds = 60f; + + // How long a thrall outlives the pile that made it. The same minute as the respawn on + // purpose: the player learns one number and it reads as "this pile thinks in minutes". + // + // Not zero, which is what it used to be. Killing them on the spot closed the duplication + // exploit but read terribly - dismantle your own pile and ten bodies drop with no + // explanation - and it disarmed you mid-fight if a raid took the pile down while your + // escort was out with you. A minute is short enough that rebuilding elsewhere to keep the + // old thralls is not worth the walk, and the anchor check in RaisedThrall is what actually + // closes that door rather than the length of this timer. + // + // World time, not local: an orphan has to keep withering while its zone is unloaded, or + // walking away would be a way to keep a dead pile's army alive indefinitely. + public const float OrphanWitherSeconds = 60f; + + // A thrall only asks "is my pile still standing?" when it is this close to home, because the + // answer can only be trusted where the pile would be loaded if it existed. Further out - out + // following its master, most of the time - the question is unanswerable and gets skipped. + // The leash is 10 m; this leaves room for one that has been knocked about. + public const float HomeCheckRange = 20f; + + // How far a thrall strays from the pile when it is not following anybody. Written onto the + // clone's BaseAI.m_randomMoveRange, which is the radius vanilla's own patrol wandering uses. + public const float LeashRange = 10f; + + // An escort, not a doomstack. The pile can hold ten; it can lend you four. + public const int MaxFollowers = 3; + public const int MaxEliteFollowers = 1; + + // Upgrading is gated on the lord of the swamp dead rather than on money alone. + public const int UpgradeProgressionState = 4; // Bonemass + + // ─── Density ───────────────────────────────────────────────────────── + // Five piles per 1.6 square kilometres, enforced by PieceDensityLimit. For scale, a Valheim + // zone is 64 m square, so 1.6 km2 is a disc about 22 zones across - big enough that five + // piles is a regional army rather than base decoration. + public const int MaxPilesInRange = 5; + public const float DensityAreaKm2 = 1.6f; + + // ─── Looks ─────────────────────────────────────────────────────────── + // Bigger than the vanilla pile, not smaller. The first pass went to 0.8 on the assumption that + // a buildable wants to be unobtrusive; in game it read as a scrap heap rather than as something + // that raises the dead. 1.2 gives it the presence the feature deserves. + private const float ModelScale = 1.2f; + + // Green, and far enough from the vanilla pile's brown-grey to be told apart across a swamp. + private static readonly Color PileTint = new Color(0.22f, 0.52f, 0.24f, 1f); + private static readonly Color BoneTint = new Color(0.35f, 0.45f, 0.30f, 1f); + private static readonly Color GreaterBoneTint = new Color(0.20f, 0.55f, 0.25f, 1f); + + 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."); + RegisterBone(GreaterBoneName, GreaterBoneDisplayName, GreaterBoneTint, + "The same bone, older, and louder. A pile fed one of these starts keeping officers."); + + RegisterThrall(ThrallName, "Draugr", ThrallDisplayName, KindNormal, MaxFollowers); + RegisterThrall(ThrallEliteName, "Draugr_Elite", ThrallEliteDisplayName, KindElite, MaxEliteFollowers); + + RegisterPiece(); + + PieceDensityLimit.Register(PieceName, + PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange, + "The ground here already carries {0} of these. Find another country."); + } + + // ---------------------------------------------------------------- items + + private static void RegisterBone(string prefabName, string displayName, Color tint, string description) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "BoneFragments"); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Draugh] Could not clone BoneFragments; {displayName} not registered."); + return; + } + + Recolour(prefab, tint); + + ItemDrop drop = prefab.GetComponent(); + 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; + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + } + + // ---------------------------------------------------------------- thralls + + /// + /// A draugr that is born tame and on a leash. + /// + /// Cloned rather than tamed in place so the leash range, the name and the loot table are the + /// prefab's own business and no vanilla draugr is touched. Its CharacterDrop is destroyed + /// outright: a conjured corpse leaves nothing behind. Without that, killing your own thralls + /// would farm the entrails and bone fragments this whole chain is built out of - and, at a one + /// in ten trophy rate, hand back a slice of the flesh that paid for it. + /// + private static void RegisterThrall(string prefabName, string source, string displayName, + string kind, int maxFollowers) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Draugh] Could not clone {source}; {displayName} not registered."); + return; + } + + Character character = prefab.GetComponent(); + if (character != null) character.m_name = displayName; + + BaseAI ai = prefab.GetComponent(); + if (ai != null) + { + // The radius vanilla's own patrol wandering keeps to around m_patrolPoint, which + // RaisedThrall pins to the pile. + ai.m_randomMoveRange = LeashRange; + } + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = kind; + thrall.m_commandingRace = RaceId; // only a Draugh may give these orders + thrall.m_maxFollowers = maxFollowers; + thrall.m_witherSeconds = OrphanWitherSeconds; + thrall.m_homeCheckRange = HomeCheckRange; + thrall.m_refusalMessage = "The dead do not take orders from the living."; + + PrefabManager.Instance.AddPrefab(prefab); + } + + // ---------------------------------------------------------------- piece + + private static void RegisterPiece() + { + // Spawner_DraugrPile is the visible, destructible body pile of the swamps - the only one + // of the seven Spawner_Draugr* prefabs with hit and destruction effects of its own, which + // is what says it has a model rather than being a world-generation spawn point. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "Spawner_DraugrPile"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Draugh] Could not clone Spawner_DraugrPile; the body pile is not registered."); + return; + } + + // The vanilla pile's whole job is spawning hostile draugr on a timer at anyone who walks + // past. Every bit of that goes: what it produces, when, and for whom is ours now. + foreach (SpawnArea area in prefab.GetComponentsInChildren(true)) + { + if (area != null) Object.DestroyImmediate(area); + } + + // Same belt as the Composter: a bone pile carries nothing that shoots, but the eitr + // refinery taught this codebase not to assume. A silent log is the proof. + AswidBloodRefinery.StripOffensive(prefab, PieceName); + + DraughSpawnerBehaviour behaviour = prefab.AddComponent(); + + // One interaction point, as on the Composter: what is in your hand decides what the click + // means. Any Switch the prefab happened to carry goes first so it cannot win the hover + // from a child collider - the components only, never their colliders. + foreach (Switch existing in prefab.GetComponentsInChildren(true)) + { + if (existing != null) Object.DestroyImmediate(existing); + } + behaviour.m_switch = prefab.AddComponent(); + behaviour.m_switch.m_name = PieceDisplayName; + + prefab.transform.localScale = Vector3.one * ModelScale; + Recolour(prefab, PileTint); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + 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(TrophyDraugr); + + // Learned on the Furling's bushes: a Piece added to world scenery is born with no icon + // and no place effect, and a null icon is a blank, unclickable square in the build menu. + 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 = PieceDisplayName, + Description = "Feed it and it answers. The dead here are yours, if you are dead enough to ask.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = BorrowIcon(TrophyDraugr), + Requirements = new[] + { + new RequirementConfig(BoneName, 1, 0, true), + new RequirementConfig("Entrails", 10, 0, true), + new RequirementConfig("BoneFragments", 20, 0, true), + } + })); + } + + /// + /// Same reason as the Composter's and the Furling's: a piece registered after the vanilla + /// learning pass never reaches the hammer on its own. The purchased Cursed Bone is the gate. + /// + public static void EnsureKnown(Player player) + { + if (player == null) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(PieceName); + 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(); + } + + // ---------------------------------------------------------------- helpers + + 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($"[Draugh] Could not borrow the icon from '{prefabName}'."); + return null; + } + + private static void Recolour(GameObject root, Color tint) + { + foreach (Renderer renderer in root.GetComponentsInChildren(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 DraughSpawnerKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + DraughSpawner.EnsureKnown(__instance); + } + } +} diff --git a/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs b/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs new file mode 100644 index 0000000..98c760d --- /dev/null +++ b/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs @@ -0,0 +1,366 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The body pile's logic. Same skeleton as ComposterBehaviour - one Switch, one numeric tank fed + /// by many different meats, all state in the ZDO, owner-only accounting - with a roster on top. + /// + /// Two deliberate differences from the Composter's timing, both of them about not punishing the + /// player for walking away: + /// - the respawn timer runs on LOCAL time and only while the zone is loaded. The Composter's + /// seal time is world time, because rotting happens whether anyone watches; a grave refilling + /// itself while unloaded would instead let a wandering troll drain the whole reserve into a + /// field of corpses nobody was there to use. + /// - the roster is counted, never tallied. Alive thralls are found by asking the world which + /// creatures are bound to this pile, so a death, a despawn or a player killing his own thrall + /// all correct themselves with no bookkeeping to drift. + /// + public class DraughSpawnerBehaviour : MonoBehaviour + { + public Switch m_switch; + + private const string KeyFlesh = "RoV_draughFlesh"; + private const string KeyReserve = "RoV_draughReserve"; + private const string KeyReserveElite = "RoV_draughReserveElite"; + private const string KeyUpgraded = "RoV_draughUpgraded"; + + private ZNetView m_nview; + private float m_respawnTimer; + + private void OnDestroy() + { + RaisedThrall.UnregisterStation(transform); + } + + private void Awake() + { + // The shared registry RaisedThrall consults to answer "is my pile still standing?". + RaisedThrall.RegisterStation(transform); + + m_nview = GetComponent(); + 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_DraughFeed", RPC_Feed); + m_nview.Register("RoV_DraughUpgrade", RPC_Upgrade); + + WearNTear wear = GetComponent(); + if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed)); + + InvokeRepeating("UpdatePile", 2f, 2f); + } + + // ---------------------------------------------------------------- interaction + + /// + /// One interaction point, like the Composter's: what is in hand decides what the click means. + /// Raw flesh feeds it, a Draugr trophy is a whole batch, an Elite trophy is an officer, and a + /// Greater Cursed Bone upgrades it. Empty hands just report. + /// + 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 = FindAnyInput(inventory); + if (item == null) + { + user.Message(MessageHud.MessageType.Center, "It wants flesh, or the head of one of its own."); + return false; + } + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; + if (prefabName == null) return false; + + if (prefabName == DraughSpawner.GreaterBoneName) return TryUpgrade(user, inventory, item); + + if (prefabName == DraughSpawner.TrophyDraugrElite && !IsUpgraded()) + { + user.Message(MessageHud.MessageType.Center, "This pile keeps no officers yet."); + return false; + } + + if (prefabName != DraughSpawner.TrophyDraugr && + prefabName != DraughSpawner.TrophyDraugrElite && + AswidBloodRefinery.FleshValue(prefabName) <= 0) + { + user.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return false; + } + + // Fullness depends on which shelf the input goes on. Asking the wrong one is not cosmetic: + // an Elite trophy accepted here and then dropped by RPC_Feed for want of an officer slot + // would be an item destroyed for nothing. + bool elite = prefabName == DraughSpawner.TrophyDraugrElite; + if (elite ? GetReserveElite() >= DraughSpawner.ReserveCapElite : IsFull()) + { + user.Message(MessageHud.MessageType.Center, "$msg_itsfull"); + return false; + } + + // An Elite trophy banks an officer each, and the shelf holds three - so a stack of ten + // would have had seven of them clamped away by RPC_Feed and destroyed. Found on the + // Skeleton's pile, which has the identical shape, and fixed here before it could bite. + // Flesh needs no equivalent because its remainder stays in the tank rather than vanishing. + if (elite) + { + int room = DraughSpawner.ReserveCapElite - GetReserveElite(); + int takenElite = Mathf.Min(Mathf.Max(1, item.m_stack), room); + + user.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{takenElite}"); + inventory.RemoveItem(item, takenElite); + m_nview.InvokeRPC("RoV_DraughFeed", prefabName, takenElite); + return true; + } + + // A whole stack per click. The Composter asks for a hundred units one item at a time and + // gets away with it because a batch is the end of the story; a full complement here is ten + // batches, and clicking that out one neck tail at a time is not a mechanic. + // + // The count goes over as an argument rather than as one RPC per item - a stack of fifty + // neck tails would otherwise be fifty round trips to say the same thing. + 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_DraughFeed", 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 == DraughSpawner.TrophyDraugr) return candidate; + if (name == DraughSpawner.TrophyDraugrElite && IsUpgraded()) return candidate; + if (AswidBloodRefinery.FleshValue(name) > 0) return candidate; + } + return null; + } + + private bool TryUpgrade(Humanoid user, Inventory inventory, ItemDrop.ItemData item) + { + if (IsUpgraded()) + { + user.Message(MessageHud.MessageType.Center, "It 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."); + return false; + } + + inventory.RemoveItem(item, 1); + m_nview.InvokeRPC("RoV_DraughUpgrade"); + user.Message(MessageHud.MessageType.Center, "The pile stirs. It will keep officers now."); + return true; + } + + // ---------------------------------------------------------------- accounting + + private void RPC_Feed(long sender, string prefabName, int count) + { + if (!m_nview.IsOwner()) return; + if (count < 1) count = 1; + + // An Elite trophy is not flesh - it banks an officer outright. + if (prefabName == DraughSpawner.TrophyDraugrElite) + { + if (!IsUpgraded()) return; + SetReserveElite(GetReserveElite() + count); // the setter clamps to the shelf + return; + } + + float value = prefabName == DraughSpawner.TrophyDraugr + ? DraughSpawner.FleshPerThrall // a head is worth a whole batch + : AswidBloodRefinery.FleshValue(prefabName); + if (value <= 0f) return; + + float flesh = GetFlesh() + value * count; + + // Every complete batch becomes a banked thrall. A loop rather than a single test so a + // trophy - or a stack of them - cannot overflow into flesh that never gets counted. + while (flesh >= DraughSpawner.FleshPerThrall && GetReserve() < DraughSpawner.ReserveCap) + { + flesh -= DraughSpawner.FleshPerThrall; + SetReserve(GetReserve() + 1); + } + + SetFlesh(flesh); + } + + private void RPC_Upgrade(long sender) + { + if (!m_nview.IsOwner()) return; + m_nview.GetZDO().Set(KeyUpgraded, true); + } + + private void UpdatePile() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + + List bound = RaisedThrall.BoundTo(transform.position); + int aliveNormal = 0; + int aliveElite = 0; + foreach (RaisedThrall thrall in bound) + { + if (thrall.Kind == DraughSpawner.KindElite) aliveElite++; else aliveNormal++; + } + + bool wantsNormal = aliveNormal < AliveCap() && GetReserve() > 0; + bool wantsElite = aliveElite < EliteCap() && GetReserveElite() > 0; + + if (!wantsNormal && !wantsElite) + { + m_respawnTimer = 0f; + return; + } + + m_respawnTimer += 2f; // the tick interval + if (m_respawnTimer < DraughSpawner.RespawnSeconds) return; + m_respawnTimer = 0f; + + // Officers first: they are the scarcer resource and the reason to upgrade at all. + if (wantsElite) + { + if (Spawn(DraughSpawner.ThrallEliteName)) SetReserveElite(GetReserveElite() - 1); + } + else if (wantsNormal) + { + if (Spawn(DraughSpawner.ThrallName)) SetReserve(GetReserve() - 1); + } + } + + private bool Spawn(string prefabName) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Draugh] No '{prefabName}' in ZNetScene; the pile cannot raise anything."); + return false; + } + + Vector3 offset = UnityEngine.Random.insideUnitSphere * 2f; + 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)); + RaisedThrall thrall = spawned.GetComponent(); + if (thrall != null) thrall.Bind(transform.position); + + return true; + } + + /// + /// The pile sustains them, so it takes them with it - but on a minute's delay rather than on + /// the spot. Without some form of this a pile is a duplication exploit: fill it, dismantle it, + /// rebuild it elsewhere, fill it again, and keep every thrall from every round. + /// + /// This marks the ones it can reach. It cannot reach thralls whose zone is unloaded right now, + /// which is why RaisedThrall also checks for itself once it is home again - between the two, + /// nothing outlives its pile. + /// + private void OnDestroyed() + { + if (m_nview == null || !m_nview.IsOwner()) return; + + List bound = RaisedThrall.BoundTo(transform.position); + foreach (RaisedThrall thrall in bound) thrall.MarkOrphaned(); + + // Said once, by the client that just knocked it down, because the hover text that would + // otherwise explain this is going away with the pile. + 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."); + } + + SetFlesh(0f); + SetReserve(0); + SetReserveElite(0); + } + + // ---------------------------------------------------------------- state and display + + public bool IsUpgraded() => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false); + + private int AliveCap() => IsUpgraded() ? DraughSpawner.AliveCapUpgraded : DraughSpawner.AliveCap; + + private int EliteCap() => IsUpgraded() ? DraughSpawner.EliteCapUpgraded : DraughSpawner.EliteCap; + + /// Full when there is nowhere left to put a finished thrall. + private bool IsFull() => GetReserve() >= DraughSpawner.ReserveCap; + + /// + /// Everything a player needs to know 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. + /// + private string Hover() + { + List bound = RaisedThrall.BoundTo(transform.position); + int aliveNormal = 0; + int aliveElite = 0; + foreach (RaisedThrall thrall in bound) + { + if (thrall.Kind == DraughSpawner.KindElite) aliveElite++; else aliveNormal++; + } + + string body = $"flesh {Mathf.Floor(GetFlesh())}/{DraughSpawner.FleshPerThrall}, " + + $"risen {aliveNormal}/{AliveCap()}, waiting {GetReserve()}/{DraughSpawner.ReserveCap}"; + + if (IsUpgraded()) + { + body += $"\nofficers {aliveElite}/{EliteCap()}, waiting {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 += "\n[$KEY_Use] Feed it flesh, or a draugr's head"; + + return Localization.instance.Localize($"{DraughSpawner.PieceDisplayName} ({body})"); + } + + // ---------------------------------------------------------------- ZDO accessors + + 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)); + } + + private int GetReserve() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyReserve) : 0; + + private void SetReserve(int value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyReserve, Mathf.Clamp(value, 0, DraughSpawner.ReserveCap)); + } + + private int GetReserveElite() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyReserveElite) : 0; + + private void SetReserveElite(int value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyReserveElite, Mathf.Clamp(value, 0, DraughSpawner.ReserveCapElite)); + } + } +}