From b67a324cb8ce9b94347a196ee7aca034772ae53f Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Fri, 7 Aug 2026 17:02:35 +0200 Subject: [PATCH] feat(skeleton): bound bone pile and bound sentry Co-Authored-By: Claude Opus 5 --- JotunnModStub/Skeleton/SkeletonBonePile.cs | 383 +++++++++++++++++ .../Skeleton/SkeletonBonePileBehaviour.cs | 403 ++++++++++++++++++ JotunnModStub/Skeleton/SkeletonPatches.cs | 4 +- JotunnModStub/Skeleton/SkeletonRace.cs | 5 + JotunnModStub/Skeleton/SkeletonSentry.cs | 283 ++++++++++++ 5 files changed, 1077 insertions(+), 1 deletion(-) create mode 100644 JotunnModStub/Skeleton/SkeletonBonePile.cs create mode 100644 JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs create mode 100644 JotunnModStub/Skeleton/SkeletonSentry.cs diff --git a/JotunnModStub/Skeleton/SkeletonBonePile.cs b/JotunnModStub/Skeleton/SkeletonBonePile.cs new file mode 100644 index 0000000..19f22f7 --- /dev/null +++ b/JotunnModStub/Skeleton/SkeletonBonePile.cs @@ -0,0 +1,383 @@ +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Skeleton station: a bone pile from the crypts that raises a standing garrison. + /// + /// Same family as the Draugh's body pile and it shares that feature's whole thrall layer + /// (), but the economy is the opposite way round on purpose. The Draugh + /// pays per draugr out of a reserve that empties; the Skeleton pays ONCE PER SLOT and that slot + /// then refills itself forever. Skeletons are fragile - a troll or a drake clears the whole line + /// in one swing - so an army you have to re-buy after every fight is an army nobody would take + /// out of the house. + /// + /// That permanent slot is also, by itself, the "skeletons leave exactly the materials that made + /// them" idea: the bones are not dropped and re-fed, they simply get up again. Nothing is + /// generated, nothing is consumed, and the same twenty fragments stand back up as many times as + /// they are knocked down. It needs no death hook and no drop table - which is why the thralls have + /// their CharacterDrop stripped like the Draugh's, rather than filled in. + /// + /// Two differences from the Draugh worth stating because they are deliberate, not oversights: + /// - a destroyed pile kills its garrison INSTANTLY, where a body pile gives its draugr a minute. + /// Free perpetual regeneration is the trade for a hard off switch. + /// - melee and ranged are the same vanilla creature with different hands. There is no ranged + /// skeleton prefab: Skeleton_NoArcher is vanilla's own guaranteed-melee variant, and the + /// archer is a plain Skeleton whose loadout is forced to the bow. + /// + public static class SkeletonBonePile + { + // ─── Names ─────────────────────────────────────────────────────────── + public const string PieceName = "SkeletonBonePile"; + public const string PieceDisplayName = "Bound Bone Pile"; + + // The Soul Stone: a green ruby, sold by the Skeleton bench, and the thing that binds a skull and + // ten fragments into a sentry that cannot walk. Cheap on purpose - 50 coins - because the real + // cost of a sentry is the skull, which has to be taken off a skeleton rather than bought. + public const string SoulStoneName = "SoulStone"; + public const string SoulStoneDisplayName = "Soul Stone"; + public const int SoulStonePrice = 50; + + private static readonly Color SoulStoneTint = new Color(0.15f, 0.85f, 0.35f, 1f); + + public const string SkullName = "CursedSkull"; + public const string SkullDisplayName = "Cursed Skull"; + public const string GreaterSkullName = "GreaterCursedSkull"; + public const string GreaterSkullDisplayName = "Greater Cursed Skull"; + + public const string ThrallMeleeName = "SkeletonThrall_Melee"; + public const string ThrallRangedName = "SkeletonThrall_Ranged"; + public const string ThrallRancidName = "SkeletonThrall_Rancid"; + + public const string ThrallMeleeDisplay = "Bound Skeleton"; + public const string ThrallRangedDisplay = "Bound Archer"; + public const string ThrallRancidDisplay = "Bound Rancid Remains"; + + public const string KindMelee = "SkeletonMelee"; + public const string KindRanged = "SkeletonRanged"; + public const string KindRancid = "SkeletonRancid"; + + public const string RaceId = "Skeleton"; + + /// The one material a slot is bought with. Fixed, not a fungible bone tank - see the + /// class comment on why "exactly the materials that made them" needs a recipe. + public const string BonePrefab = "BoneFragments"; + public const int BonesPerSlot = 20; + + /// Buys a Rancid slot outright, the way an Elite trophy buys the Draugh an officer. + public const string RancidTrophy = "TrophySkeletonPoison"; + + // ─── Balance ───────────────────────────────────────────────────────── + public const int MeleeSlots = 4; + public const int RangedSlots = 4; + public const int MeleeSlotsUpgraded = 5; + public const int RangedSlotsUpgraded = 5; + public const int RancidSlots = 0; // none at all until upgraded + public const int RancidSlotsUpgraded = 2; + + // Local seconds, and only while the zone is loaded - a garrison should not quietly rebuild + // itself in an unloaded zone. Faster once upgraded: the pile gets better at it. + public const float RespawnSeconds = 20f; + public const float RespawnSecondsUpgraded = 15f; + + // NOT the "instant" from the design conversation - that lives in the pile's OnDestroyed, which + // calls Kill() on the spot. This number only governs the FALLBACK: a skeleton that was in an + // unloaded zone when the pile fell and finds nothing at home when it loads again. + // + // It was 0, and zero has no tolerance for a hiccup: a pile whose zone unloads for a moment + // while a skeleton at the boundary stays loaded reads as "no pile" and wipes the garrison with + // no appeal. Five seconds costs nothing anyone can perceive - the deliberate destruction path + // is still immediate - and it means one bad frame is not a wipe. + public const float OrphanWitherSeconds = 5f; + public const float HomeCheckRange = 20f; + public const float LeashRange = 10f; + + // No cap: the whole point of the new command is that the garrison moves as one. + public const int MaxFollowers = -1; + + // A Rancid Remains clicked directly takes five of the rank and file with it, instead of the + // whole line the pile would send. Its own squad, and small enough that it stays a squad. + public const int RancidEscort = 5; + + public const int UpgradeProgressionState = 4; // Bonemass, same gate as the Draugh's officers + + public const int MaxPilesInRange = 5; + public const float DensityAreaKm2 = 1.6f; + + // ─── Looks ─────────────────────────────────────────────────────────── + private const float ModelScale = 1.2f; + + // Cold bone-white, so it never reads as the Draugh's green pile at a glance. + private static readonly Color PileTint = new Color(0.82f, 0.84f, 0.78f, 1f); + private static readonly Color SkullTint = new Color(0.78f, 0.80f, 0.74f, 1f); + private static readonly Color GreaterSkullTint = new Color(0.62f, 0.72f, 0.80f, 1f); + + public static void Register() + { + RegisterSkull(SkullName, SkullDisplayName, SkullTint, + "A skull that keeps counting. Set it down and the ground starts answering."); + RegisterSkull(GreaterSkullName, GreaterSkullDisplayName, GreaterSkullTint, + "Older, and it counts higher. A pile given one of these raises the rotten too."); + + RegisterSoulStone(); + + RegisterThrall(ThrallMeleeName, "Skeleton_NoArcher", ThrallMeleeDisplay, KindMelee, null); + RegisterThrall(ThrallRangedName, "Skeleton", ThrallRangedDisplay, KindRanged, "skeleton_bow"); + RegisterThrall(ThrallRancidName, "Skeleton_Poison", ThrallRancidDisplay, KindRancid, null, RancidEscort); + + RegisterPiece(); + + // The standing sentry. Registered after the archer it clones, so that prefab exists first. + SkeletonSentry.Register(); + + PieceDensityLimit.Register(PieceName, + PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange, + "There are already {0} of these listening nearby. Take it further out."); + } + + // ---------------------------------------------------------------- items + + private static void RegisterSkull(string prefabName, string displayName, Color tint, string description) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "TrophySkeleton"); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] Could not clone TrophySkeleton; {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)); + } + + /// + /// A ruby, turned green. Cloned rather than tinted in place so real rubies keep being red, the + /// same discipline every other borrowed prefab in this project follows. + /// + /// One caveat that always applies and is worth repeating on a gemstone: the tint reaches the + /// world and held models but NOT the inventory icon, because icons are atlas sprites and + /// repainting one produces an empty slot. In the inventory this reads as a ruby; the name and + /// the tooltip are what tell it apart. If that matters, borrow the icon of a green vanilla item + /// instead - it is one line. + /// + private static void RegisterSoulStone() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SoulStoneName, "Ruby"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Skeleton] Could not clone Ruby; Soul Stone not registered."); + return; + } + + Recolour(prefab, SoulStoneTint); + + ItemDrop drop = prefab.GetComponent(); + if (drop == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = SoulStoneDisplayName; + shared.m_description = "Something is still in there, and it is still angry. Bind it to a skull " + + "and it will stand watch as long as the bones hold."; + shared.m_itemType = ItemDrop.ItemData.ItemType.Material; + shared.m_weight = 0.5f; + shared.m_maxStackSize = 20; + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + } + + // ---------------------------------------------------------------- thralls + + /// + /// One kind of bound skeleton, born tame and leashed to its pile. + /// + /// The weapon argument is what separates melee from ranged, because the distinction does not + /// exist at the prefab level: Skeleton_NoArcher is vanilla's guaranteed-melee variant, and a + /// plain Skeleton rolls its own weapon. Forcing m_defaultItems and clearing the random lists is + /// what makes an archer an archer every time instead of four times in eight. + /// + /// CharacterDrop is destroyed for the same reason as the Draugh's, plus one of its own: a + /// garrison that regenerates for free and drops its bones on death would be a bone mill. + /// + private static void RegisterThrall(string prefabName, string source, string displayName, + string kind, string forcedWeapon, int escortCount = 0) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] 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) ai.m_randomMoveRange = LeashRange; + + if (forcedWeapon != null) + { + Humanoid humanoid = prefab.GetComponent(); + GameObject weapon = PrefabManager.Cache.GetPrefab(forcedWeapon); + if (humanoid != null && weapon != null) + { + humanoid.m_defaultItems = new[] { weapon }; + humanoid.m_randomWeapon = new GameObject[0]; + humanoid.m_randomSets = new Humanoid.ItemSet[0]; + Jotunn.Logger.LogInfo($"[Skeleton] {prefabName}: loadout forced to '{forcedWeapon}'."); + } + else + { + Jotunn.Logger.LogWarning($"[Skeleton] {prefabName}: could not force '{forcedWeapon}'; " + + "it will roll a random weapon like a wild one."); + } + } + + 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; + thrall.m_maxFollowers = MaxFollowers; + thrall.m_witherSeconds = OrphanWitherSeconds; + thrall.m_homeCheckRange = HomeCheckRange; + thrall.m_refusalMessage = "These bones answer only to their own kind."; + thrall.m_escortCount = escortCount; + + PrefabManager.Instance.AddPrefab(prefab); + } + + // ---------------------------------------------------------------- piece + + private static void RegisterPiece() + { + // BonePileSpawner is the skeleton's own crypt spawner - the right base rather than a + // repainted body pile, and it already has hit and destruction effects of its own. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "BonePileSpawner"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Skeleton] Could not clone BonePileSpawner; the bone pile is not registered."); + return; + } + + // Its whole vanilla job is throwing hostile skeletons at whoever walks past. All of it goes. + foreach (SpawnArea area in prefab.GetComponentsInChildren(true)) + { + if (area != null) Object.DestroyImmediate(area); + } + + AswidBloodRefinery.StripOffensive(prefab, PieceName); + + SkeletonBonePileBehaviour behaviour = prefab.AddComponent(); + + 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("TrophySkeleton"); + + // A Piece added to world scenery is born with no icon and no place effect - the Furling's + // bushes taught this the hard way, where the entry existed as a blank unclickable square. + 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 = "Twenty fragments buy a place in the line. The one who fills it will keep standing up.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = BorrowIcon("TrophySkeleton"), + Requirements = new[] + { + new RequirementConfig(SkullName, 1, 0, true), + new RequirementConfig("BoneFragments", 30, 0, true), + new RequirementConfig("Ooze", 10, 0, true), + } + })); + } + + 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($"[Skeleton] 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 SkeletonBonePileKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + SkeletonBonePile.EnsureKnown(__instance); + SkeletonSentry.EnsureKnown(__instance); + } + } +} diff --git a/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs b/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs new file mode 100644 index 0000000..83c6046 --- /dev/null +++ b/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs @@ -0,0 +1,403 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The bone pile's logic. Simpler than the body pile's, because there is no reserve to keep books + /// on: the ZDO holds how many SLOTS have been paid for per kind, and a slot with nobody standing + /// in it refills itself on a timer, forever. + /// + /// That is the whole "skeletons are immortal" mechanic, and it is why nothing here drops or + /// consumes bones on death. Twenty fragments buy a place in the line once; whoever is standing in + /// that place gets back up as often as they are knocked down. No death hook, no drop table, no + /// resource created or destroyed. + /// + /// The roster is counted from the world rather than tallied, exactly like the body pile's, so a + /// death, a despawn or a player killing his own skeleton all correct themselves. + /// + public class SkeletonBonePileBehaviour : MonoBehaviour + { + public Switch m_switch; + + private const string KeyBones = "RoV_skelBones"; + private const string KeySlotsMelee = "RoV_skelSlotsMelee"; + private const string KeySlotsRanged = "RoV_skelSlotsRanged"; + private const string KeySlotsRancid = "RoV_skelSlotsRancid"; + private const string KeyUpgraded = "RoV_skelUpgraded"; + + private ZNetView m_nview; + private float m_respawnTimer; + + private void Awake() + { + // The 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_SkelFeed", RPC_Feed); + m_nview.Register("RoV_SkelUpgrade", RPC_Upgrade); + + WearNTear wear = GetComponent(); + if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed)); + + InvokeRepeating("UpdatePile", 2f, 2f); + } + + private void OnDestroy() + { + RaisedThrall.UnregisterStation(transform); + } + + // ---------------------------------------------------------------- interaction + + /// + /// Bones in hand feed it, a Greater Cursed Skull upgrades it, a Rancid trophy buys an officer - + /// and EMPTY HANDS move the whole garrison. That last one is the mechanic the Draugh does not + /// have: a body pile is commanded draugr by draugr, a bone pile is commanded as a line. + /// + /// Empty hands were free to use for this because the pile's own hover already carries the + /// status the Draugh needs an empty-handed click to report. + /// + private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + Player player = user as Player; + if (player == null) return false; + + Inventory inventory = player.GetInventory(); + if (inventory == null) return false; + + // EMPTY HANDS MEAN THE COMMAND, always, and nothing else is consulted. + // + // This used to scan the pack for something to feed first, copied from the body pile where + // empty hands mean nothing else. Two bugs came out of it: a Rancid trophy in the pack was + // skipped in SILENCE when the pile was not upgraded yet - the refusal that explains why was + // only reachable by holding the item - and, worse, anyone carrying bone fragments (which is + // everyone) would feed the pile when they meant to move the line. The hover has always said + // "bone in hand to buy a place, empty hands to move the line"; now the code agrees with it. + if (item == null) return ToggleGarrison(player); + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; + if (prefabName == null) return false; + + if (prefabName == SkeletonBonePile.GreaterSkullName) return TryUpgrade(player, inventory, item); + + // How many of this the pile can still take. Not "is there room for one" - that was the bug: + // the old check only asked whether a single trophy would fit and then handed over the WHOLE + // stack, so ten Rancid trophies went in, RPC_Feed clamped the slots to two, and eight were + // destroyed for nothing. Anything taken from the player has to be something the pile will + // actually keep. + int room; + if (prefabName == SkeletonBonePile.RancidTrophy) + { + if (!IsUpgraded()) + { + player.Message(MessageHud.MessageType.Center, "This pile cannot hold the rotten yet."); + return false; + } + room = RancidCap() - GetSlots(SkeletonBonePile.KindRancid); + } + else if (prefabName == SkeletonBonePile.BonePrefab) + { + // Bone is measured in fragments, not places: what is left to buy, minus what is already + // part-paid towards the next place. + room = (TotalCap() - PaidSlots()) * SkeletonBonePile.BonesPerSlot + - m_nview.GetZDO().GetInt(KeyBones); + } + else + { + player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return false; + } + + if (room <= 0) + { + player.Message(MessageHud.MessageType.Center, "$msg_itsfull"); + return false; + } + + int taken = Mathf.Min(Mathf.Max(1, item.m_stack), room); + player.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{taken}"); + inventory.RemoveItem(item, taken); + + m_nview.InvokeRPC("RoV_SkelFeed", prefabName, taken); + return true; + } + + /// + /// The new command: every skeleton of this pile follows, or every one of them comes home. One + /// click for the line, decided by whether any of them is already out. + /// + private bool ToggleGarrison(Player player) + { + List bound = RaisedThrall.BoundTo(transform.position); + if (bound.Count == 0) + { + player.Message(MessageHud.MessageType.Center, "Nothing is standing yet. It wants bone."); + return false; + } + + bool anyFollowing = false; + foreach (RaisedThrall thrall in bound) + { + if (thrall.IsFollowing(player)) { anyFollowing = true; break; } + } + + int moved = 0; + foreach (RaisedThrall thrall in bound) + { + // announce: false - one message for the line, not one per skeleton. + if (thrall.SetFollowing(player, !anyFollowing, announce: false)) moved++; + } + + if (moved == 0) + { + // Every one of them refused, which for these means the player is not a Skeleton. + player.Message(MessageHud.MessageType.Center, "These bones answer only to their own kind."); + return false; + } + + player.Message(MessageHud.MessageType.Center, anyFollowing + ? $"{moved} return to the pile." + : $"{moved} rise and follow."); + return true; + } + + private bool TryUpgrade(Player player, Inventory inventory, ItemDrop.ItemData item) + { + if (IsUpgraded()) + { + player.Message(MessageHud.MessageType.Center, "It has already had one."); + return false; + } + + if (BossProgressionManager.GetCurrentProgressionState() < SkeletonBonePile.UpgradeProgressionState) + { + player.Message(MessageHud.MessageType.Center, "The skull will not wake. Something older has to fall first."); + return false; + } + + inventory.RemoveItem(item, 1); + m_nview.InvokeRPC("RoV_SkelUpgrade"); + player.Message(MessageHud.MessageType.Center, "The pile deepens. The rotten will stand here too."); + return true; + } + + // ---------------------------------------------------------------- accounting + + private void RPC_Feed(long sender, string prefabName, int count) + { + if (!m_nview.IsOwner()) return; + if (count < 1) count = 1; + + if (prefabName == SkeletonBonePile.RancidTrophy) + { + if (!IsUpgraded()) return; + SetSlots(SkeletonBonePile.KindRancid, + Mathf.Min(RancidCap(), GetSlots(SkeletonBonePile.KindRancid) + count)); + return; + } + + if (prefabName != SkeletonBonePile.BonePrefab) return; + + int bones = m_nview.GetZDO().GetInt(KeyBones) + count; + + // Melee places fill first, then the archers'. A loop rather than a single test so a whole + // stack cannot overflow into bones that are never counted. + while (bones >= SkeletonBonePile.BonesPerSlot && PaidSlots() < TotalCap()) + { + bones -= SkeletonBonePile.BonesPerSlot; + + if (GetSlots(SkeletonBonePile.KindMelee) < MeleeCap()) + { + SetSlots(SkeletonBonePile.KindMelee, GetSlots(SkeletonBonePile.KindMelee) + 1); + } + else + { + SetSlots(SkeletonBonePile.KindRanged, GetSlots(SkeletonBonePile.KindRanged) + 1); + } + } + + m_nview.GetZDO().Set(KeyBones, bones); + } + + 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; + + string empty = FirstEmptyKind(); + if (empty == null) + { + m_respawnTimer = 0f; + return; + } + + m_respawnTimer += 2f; // the tick interval + if (m_respawnTimer < RespawnSeconds()) return; + m_respawnTimer = 0f; + + Spawn(empty); + } + + /// A kind that has a paid slot with nobody standing in it, or null. Rotten first - + /// they are the scarcest and the reason to upgrade. + private string FirstEmptyKind() + { + Dictionary alive = CountAlive(); + + if (alive[SkeletonBonePile.KindRancid] < GetSlots(SkeletonBonePile.KindRancid)) return SkeletonBonePile.KindRancid; + if (alive[SkeletonBonePile.KindMelee] < GetSlots(SkeletonBonePile.KindMelee)) return SkeletonBonePile.KindMelee; + if (alive[SkeletonBonePile.KindRanged] < GetSlots(SkeletonBonePile.KindRanged)) return SkeletonBonePile.KindRanged; + return null; + } + + private Dictionary CountAlive() + { + Dictionary alive = new Dictionary + { + { SkeletonBonePile.KindMelee, 0 }, + { SkeletonBonePile.KindRanged, 0 }, + { SkeletonBonePile.KindRancid, 0 }, + }; + + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(transform.position)) + { + if (thrall.Kind != null && alive.ContainsKey(thrall.Kind)) alive[thrall.Kind]++; + } + return alive; + } + + private void Spawn(string kind) + { + string prefabName = + kind == SkeletonBonePile.KindRancid ? SkeletonBonePile.ThrallRancidName : + kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.ThrallRangedName : + SkeletonBonePile.ThrallMeleeName; + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] No '{prefabName}' in ZNetScene; the pile cannot raise anything."); + return; + } + + 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); + } + + /// + /// Instantly, unlike the body pile's minute. The garrison rebuilds itself for free forever, so + /// the pile being broken has to be an immediate off switch or there is no counterweight at all. + /// MarkOrphaned still covers any that were unloaded when it fell - with a wither of zero they + /// die on their first tick home rather than lingering. + /// + private void OnDestroyed() + { + if (m_nview == null || !m_nview.IsOwner()) return; + + List bound = RaisedThrall.BoundTo(transform.position); + foreach (RaisedThrall thrall in bound) + { + thrall.MarkOrphaned(); + thrall.Kill(); + } + + if (bound.Count > 0 && Player.m_localPlayer != null) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, + $"The pile is broken. {bound.Count} fall where they stand."); + } + } + + // ---------------------------------------------------------------- state and display + + public bool IsUpgraded() => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false); + + private int MeleeCap() => IsUpgraded() ? SkeletonBonePile.MeleeSlotsUpgraded : SkeletonBonePile.MeleeSlots; + + private int RangedCap() => IsUpgraded() ? SkeletonBonePile.RangedSlotsUpgraded : SkeletonBonePile.RangedSlots; + + private int RancidCap() => IsUpgraded() ? SkeletonBonePile.RancidSlotsUpgraded : SkeletonBonePile.RancidSlots; + + private float RespawnSeconds() => + IsUpgraded() ? SkeletonBonePile.RespawnSecondsUpgraded : SkeletonBonePile.RespawnSeconds; + + /// Paid melee and archer places. Rotten ones are bought with trophies, not bone, so + /// they are counted separately and do not compete for the same twenty fragments. + private int PaidSlots() => GetSlots(SkeletonBonePile.KindMelee) + GetSlots(SkeletonBonePile.KindRanged); + + private int TotalCap() => MeleeCap() + RangedCap(); + + private string Hover() + { + Dictionary alive = CountAlive(); + + // A line per kind, each reading "standing / places bought / places possible", because the + // first version told the player none of that: the rotten line was hidden until the pile was + // upgraded, so there was no way to know the cap was two until ten trophies had gone in. + // Every shelf is now visible whether or not it can be used yet, and says why when it cannot. + string body = + $"\nmelee {alive[SkeletonBonePile.KindMelee]}/{GetSlots(SkeletonBonePile.KindMelee)} of {MeleeCap()}" + + $"\narchers {alive[SkeletonBonePile.KindRanged]}/{GetSlots(SkeletonBonePile.KindRanged)} of {RangedCap()}" + + $"\nrotten {alive[SkeletonBonePile.KindRancid]}/{GetSlots(SkeletonBonePile.KindRancid)} of {RancidCap()}"; + + if (!IsUpgraded()) body += " (needs a Greater Cursed Skull)"; + + int bonesToward = m_nview.GetZDO().GetInt(KeyBones); + int placesLeft = TotalCap() - PaidSlots(); + body += placesLeft > 0 + ? $"\nbone {bonesToward}/{SkeletonBonePile.BonesPerSlot} toward the next of {placesLeft} places" + : "\nevery place is bought"; + + if (m_respawnTimer > 0f) + { + int left = Mathf.Max(1, Mathf.CeilToInt(RespawnSeconds() - m_respawnTimer)); + body += $"\nnext rises in {left}s"; + } + + body += "\n[$KEY_Use] Bone in hand to buy a place, empty hands to move the line"; + + return Localization.instance.Localize($"{SkeletonBonePile.PieceDisplayName} ({body})"); + } + + // ---------------------------------------------------------------- ZDO accessors + + private int GetSlots(string kind) + { + if (m_nview == null || !m_nview.IsValid()) return 0; + return m_nview.GetZDO().GetInt(KeyFor(kind)); + } + + private void SetSlots(string kind, int value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyFor(kind), Mathf.Max(0, value)); + } + + private static string KeyFor(string kind) + { + if (kind == SkeletonBonePile.KindRanged) return KeySlotsRanged; + if (kind == SkeletonBonePile.KindRancid) return KeySlotsRancid; + return KeySlotsMelee; + } + } +} diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index 1fee96c..10a6ce5 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -84,7 +84,9 @@ namespace RacesOfValheim __result = false; return false; } - else if (AswidRace.IsAswid() && !AswidRace.BypassAswidFoodCheck && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0)) + // Blood Essence is the one real food an Aswid can still chew, so it has to + // survive this blanket refusal - everything else mortal still bounces. + else if (AswidRace.IsAswid() && !AswidRace.BypassAswidFoodCheck && !AswidBloodRefinery.IsAswidMeal(item) && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0)) { __instance.Message(MessageHud.MessageType.Center, "Mortal food disgusts you."); __result = false; diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index fa1b74f..b894318 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -17,6 +17,11 @@ namespace RacesOfValheim public void CreateModAssets() { + // The bone pile and its garrison. Registered here because the faction merchant catalogue + // resolves its entries by prefab name, so the two cursed skulls have to exist before a + // Skeleton is ever set up as a bench. + SkeletonBonePile.Register(); + var se = ScriptableObject.CreateInstance(); se.name = "SE_SkeletonStats"; se.m_name = "Undead Fortitude"; diff --git a/JotunnModStub/Skeleton/SkeletonSentry.cs b/JotunnModStub/Skeleton/SkeletonSentry.cs new file mode 100644 index 0000000..ef37404 --- /dev/null +++ b/JotunnModStub/Skeleton/SkeletonSentry.cs @@ -0,0 +1,283 @@ +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// A bound archer that cannot walk: built with the hammer, stands where it is put, shoots what comes + /// near, knits itself back together when left alone, and hands its parts back when it falls. + /// + /// TWO PREFABS, and that is forced rather than chosen. The design settled on cloning the tamed + /// archer, so the sentry is a CHARACTER - and a Character cannot sit in the hammer's piece table, + /// because the hammer builds Piece. So a small seed piece goes in the table, spawns the sentry the + /// moment it is placed, and removes itself. The alternative was cloning the Ballista, which would + /// have brought WearNTear's health, repair and component refund for free; cloning the archer instead + /// means those are written here, which is the trade that was made deliberately. + /// + /// The refund is a CharacterDrop at full chance - which makes the sentry the one skeleton in this mod + /// that drops anything. Every other thrall has its drop table stripped precisely so a garrison that + /// regenerates for free cannot be farmed; this one is not free and does not regenerate its slot, so + /// giving the parts back is safe and is what was asked for. + /// + public static class SkeletonSentry + { + public const string SentryName = "SkeletonSentry"; + public const string SeedPieceName = "SkeletonSentrySeed"; + public const string DisplayName = "Bound Sentry"; + + /// Seconds without being hit before it starts closing its wounds. + public const float RegenDelay = 10f; + + /// Fraction of maximum health per second once it starts. + public const float RegenPerSecond = 0.02f; + + // What it costs, and therefore exactly what it gives back. + public const int BoneCost = 10; + + public static void Register() + { + GameObject sentry = BuildSentry(); + if (sentry != null) BuildSeedPiece(); + } + + // ---------------------------------------------------------------- the sentry + + private static GameObject BuildSentry() + { + // The archer we already register for the bone pile, so its forced bow loadout comes along. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SentryName, SkeletonBonePile.ThrallRangedName); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] Could not clone {SkeletonBonePile.ThrallRangedName}; the sentry is not registered."); + return null; + } + + Character character = prefab.GetComponent(); + if (character != null) + { + character.m_name = DisplayName; + + // Rooted. Every way it could move, set to nothing - and m_randomMoveRange so it does not + // even try to wander. If the AI still shuffles or stops shooting because it wants to + // close distance and cannot, the fallback is to pin it from the AI side instead, with + // the patrol trick the thralls and the grove already use. + character.m_speed = 0f; + character.m_walkSpeed = 0f; + character.m_runSpeed = 0f; + character.m_acceleration = 0f; + character.m_jumpForce = 0f; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = 0f; + + // Its parts back, all of them, every time. Replaces the stripped table the archer clone + // inherits rather than adding to it. + foreach (CharacterDrop existing in prefab.GetComponentsInChildren(true)) + { + if (existing != null) Object.DestroyImmediate(existing); + } + + CharacterDrop drops = prefab.AddComponent(); + drops.m_drops = new System.Collections.Generic.List(); + AddDrop(drops, SkeletonBonePile.SoulStoneName, 1); + AddDrop(drops, "TrophySkeleton", 1); + AddDrop(drops, SkeletonBonePile.BonePrefab, BoneCost); + + prefab.AddComponent(); + + PrefabManager.Instance.AddPrefab(prefab); + return prefab; + } + + private static void AddDrop(CharacterDrop drops, string prefabName, int amount) + { + GameObject prefab = PrefabManager.Cache.GetPrefab(prefabName); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] Sentry: no '{prefabName}' to give back; that part is lost on death."); + return; + } + + drops.m_drops.Add(new CharacterDrop.Drop + { + m_prefab = prefab, + m_amountMin = amount, + m_amountMax = amount, + m_chance = 1f, + m_levelMultiplier = false, + m_dontScale = true, // the refund is the cost, not a loot roll + m_onePerPlayer = false, + }); + } + + // ---------------------------------------------------------------- the seed + + /// + /// The hammer entry. Exists only to be placed and immediately replaced by the sentry, which is + /// how a creature gets into a piece table at all. + /// + private static void BuildSeedPiece() + { + // An armour stand, because the seed's real job is its BUILD GHOST: the sentry itself only + // exists a frame later, so what the player aims at while placing is this prefab's silhouette. + // A workbench read as furniture; a standing human frame reads as "someone will be here", which + // is what is about to happen. ArmorStand is the buildable one, so it arrives with the Piece, + // ZNetView and WearNTear the strip below keeps. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SeedPieceName, "ArmorStand"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Skeleton] Could not clone ArmorStand; the sentry cannot be built."); + return; + } + + // Everything the stand actually DOES goes - its armour slots included. All that is wanted is a + // placeable shell with the right outline, alive for one frame. + foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren(true)) + { + if (behaviour == null) continue; + if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue; + Object.DestroyImmediate(behaviour); + } + + prefab.AddComponent(); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = DisplayName; + piece.m_canBeRemoved = true; + piece.m_groundPiece = true; + piece.m_groundOnly = true; + piece.m_icon = BorrowIcon("TrophySkeleton"); + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = DisplayName, + Description = "A skull on a soul stone. It will not walk, and it will not stop watching.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = BorrowIcon("TrophySkeleton"), + Requirements = new[] + { + new RequirementConfig(SkeletonBonePile.SoulStoneName, 1, 0, true), + new RequirementConfig("TrophySkeleton", 1, 0, true), + new RequirementConfig(SkeletonBonePile.BonePrefab, BoneCost, 0, true), + } + })); + } + + public static void EnsureKnown(Player player) + { + if (player == null) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(SeedPieceName); + 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(); + } + + 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]; + return null; + } + } + + /// + /// Lives for one frame: swaps itself for the sentry and goes. Owner only, so in multiplayer exactly + /// one archer stands up rather than one per client. + /// + public class SkeletonSentrySeed : MonoBehaviour + { + private void Start() + { + ZNetView nview = GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + GameObject prefab = ZNetScene.instance != null + ? ZNetScene.instance.GetPrefab(SkeletonSentry.SentryName) + : null; + + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] No '{SkeletonSentry.SentryName}' in ZNetScene; nothing was raised."); + return; + } + + GameObject spawned = Instantiate(prefab, transform.position, transform.rotation); + + // Tamed, so it never turns on the person who built it. The bone pile's thralls get this from + // RaisedThrall.Bind; a sentry has no pile to be bound to, so it is done here. + MonsterAI ai = spawned.GetComponent(); + if (ai != null) ai.MakeTame(); + Character character = spawned.GetComponent(); + if (character != null) character.SetTamed(true); + + ZNetScene.instance.Destroy(gameObject); + } + } + + /// + /// The regeneration: untouched for ten seconds, then two percent of maximum health a second until + /// whole. The clock is local rather than world time on purpose - a sentry nobody is near is a sentry + /// in an unloaded zone, and healing through that would mean coming home to a full-health guard that + /// was left at death's door. + /// + public class SkeletonSentryBehaviour : MonoBehaviour + { + private Character m_character; + private ZNetView m_nview; + private float m_sinceDamage; + + private void Awake() + { + m_character = GetComponent(); + m_nview = GetComponent(); + InvokeRepeating("TickRegen", 1f, 1f); + } + + /// Called from the Character.Damage postfix below. + public void NoteDamage() => m_sinceDamage = 0f; + + private void TickRegen() + { + if (m_character == null || m_character.IsDead()) return; + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + + m_sinceDamage += 1f; + if (m_sinceDamage < SkeletonSentry.RegenDelay) return; + + float max = m_character.GetMaxHealth(); + if (m_character.GetHealth() >= max) return; + + m_character.Heal(max * SkeletonSentry.RegenPerSecond, false); + } + } + + /// + /// Resets a sentry's regeneration clock whenever it is hit. A postfix on the same method the Trenta's + /// Thorns already patches, so the shape is known to work. + /// + [HarmonyPatch(typeof(Character), "Damage")] + public static class SkeletonSentryDamagePatch + { + public static void Postfix(Character __instance) + { + if (__instance == null) return; + + SkeletonSentryBehaviour sentry = __instance.GetComponent(); + if (sentry != null) sentry.NoteDamage(); + } + } +}