From df7ce7c893cf77f0ba640a62512f885ec6a7c7cc Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Fri, 7 Aug 2026 17:02:48 +0200 Subject: [PATCH] feat(trol): war totem and its mercenary store Co-Authored-By: Claude Opus 5 --- JotunnModStub/Trol/TrolRace.cs | 4 + JotunnModStub/Trol/TrolTotem.cs | 368 +++++++++++++++++++++++ JotunnModStub/Trol/TrolTotemBehaviour.cs | 288 ++++++++++++++++++ JotunnModStub/Trol/TrolTotemStore.cs | 257 ++++++++++++++++ 4 files changed, 917 insertions(+) create mode 100644 JotunnModStub/Trol/TrolTotem.cs create mode 100644 JotunnModStub/Trol/TrolTotemBehaviour.cs create mode 100644 JotunnModStub/Trol/TrolTotemStore.cs diff --git a/JotunnModStub/Trol/TrolRace.cs b/JotunnModStub/Trol/TrolRace.cs index 5b7eb15..9867b73 100644 --- a/JotunnModStub/Trol/TrolRace.cs +++ b/JotunnModStub/Trol/TrolRace.cs @@ -38,6 +38,10 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo("Initializing Trol Race..."); TrolStatusEffects.RegisterStatusEffects(); + // The war totem and every creature it can hire. Race-locked at placement, unlike every + // other station in the mod. + TrolTotem.Register(); + // No custom projectile needed anymore string[] logNames = new string[] { diff --git a/JotunnModStub/Trol/TrolTotem.cs b/JotunnModStub/Trol/TrolTotem.cs new file mode 100644 index 0000000..945433f --- /dev/null +++ b/JotunnModStub/Trol/TrolTotem.cs @@ -0,0 +1,368 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Trol's totem: a troll's head on a core-wood post that hires warbands for coin. + /// + /// The first station in the mod that is RACE LOCKED. Every other chain can be built by anyone and + /// only its output is restricted; this one refuses the hammer outright to anyone who is not a Trol, + /// because a warband of trolls and greydwarves for money is the Trol's whole identity rather than a + /// tool it happens to own. + /// + /// The troops are the real creatures, unaltered - a Troll is a Troll - with three differences: + /// - they answer to the follow command, because they carry RaisedThrall like every other servant + /// in this mod, so the taunt and the click already work on them with no new code; + /// - they knit their wounds back up when left alone, the sentry's regeneration reused whole; + /// - they drop NOTHING and never come back. A dead warband is money spent. That is the balance + /// against troops that cost coin instead of materials, and it is why they are worth what they + /// are worth. + /// + public static class TrolTotem + { + public const string PieceName = "TrolWarTotem"; + public const string PieceDisplayName = "War Totem"; + public const string RaceId = "Trol"; + + /// Core wood. The item is RoundLog - another display name that does not predict the id. + public const string CoreWood = "RoundLog"; + public const string TrollHead = "TrophyForestTroll"; + + /// Yagluth's secondary drop, already mapped to state 6 in BossProgressionManager. + /// Distinct from TrophyGoblinKing, which is the head that replaces the troll's on upgrade. + public const string UpgradeItem = "YagluthDrop"; + public const string YagluthHead = "TrophyGoblinKing"; + + public const int UpgradeProgressionState = 6; // Yagluth + public const int MaxTroops = 5; + + // ---------------------------------------------------------------- the look, in metres + // These used to be bare multipliers (3f for the totem, 1.5f for the head) guessed against meshes + // nobody had measured, and the head came out with a circumference three times the height of the + // post under it. ModelBorrow now measures the mesh and scales it to fit, so a number here is a + // SIZE and not a factor: 2.2 m is a totem you can stand next to, 0.55 m is a head on top of it. + private const float TotemHeight = 2.2f; + private const float HeadSize = 0.9f; + + /// + /// How far the head sinks into the totem's crown, as a fraction of its own size. Mounting it exactly + /// ON the measured top left it hovering with daylight under it - a trophy sitting on a post shares + /// some of the post, so the two models are made to overlap instead of merely touching. + /// + private const float HeadSink = 0.35f; + + /// + /// A trophy is authored lying down, and the first correction (Euler(90,0,0)) stood it up but left it + /// upside down and facing away - seen in game, not reasoned about. Another half turn on each of the + /// two axes that were wrong puts it the right way up and looking out. + /// If it is still off, this is the ONE line to touch: the two 180s are what was added. + /// + private static readonly Quaternion HeadTilt = Quaternion.Euler(90f + 180f, 180f, 0f); + + /// Written into each hired creature's ZDO so the totem can tell its warbands apart - + /// five slots means counting groups, not bodies. + public const string KeyGroup = "RoV_trolGroup"; + + public const float LeashRange = 12f; + public const float WitherSeconds = 60f; + public const float HomeCheckRange = 25f; + + /// No cap: a hired warband follows as a warband. + public const int MaxFollowers = -1; + + public class Troop + { + public string Id; + public string Display; + public int Price; + public bool NeedsUpgrade; + /// Trophy of the strongest thing in the band - the face it wears in the rack. + public string Icon; + /// Vanilla creature prefab -> how many of it. + public KeyValuePair[] Members; + } + + // Anchored at 2000 for the strongest, as specified, and laddered by what each band can actually + // do rather than by head count. + public static readonly Troop[] Troops = + { + new Troop + { + Id = "greydwarf_patrol", Display = "Greydwarf Patrol", Price = 400, NeedsUpgrade = false, Icon = "TrophyGreydwarfBrute", + Members = new[] + { + new KeyValuePair("Greydwarf", 4), + new KeyValuePair("Greydwarf_Shaman", 1), + new KeyValuePair("Greydwarf_Elite", 1), + } + }, + new Troop + { + Id = "troll", Display = "Troll", Price = 700, NeedsUpgrade = false, Icon = "TrophyForestTroll", + Members = new[] { new KeyValuePair("Troll", 1) } + }, + new Troop + { + Id = "troll_summoned", Display = "Staff Troll", Price = 900, NeedsUpgrade = false, Icon = "TrophyForestTroll", + Members = new[] { new KeyValuePair("Troll_Summoned", 1) } + }, + new Troop + { + Id = "goblin_patrol", Display = "Fuling Patrol", Price = 1400, NeedsUpgrade = true, Icon = "TrophyGoblinBrute", + Members = new[] + { + new KeyValuePair("Goblin", 4), + new KeyValuePair("GoblinShaman", 1), + new KeyValuePair("GoblinBrute", 1), + } + }, + new Troop + { + Id = "goblin_band", Display = "Fuling War Band", Price = 2000, NeedsUpgrade = true, Icon = "TrophyGoblin", + Members = new[] + { + new KeyValuePair("Goblin", 4), + new KeyValuePair("GoblinArcher", 4), + } + }, + }; + + public static Troop Find(string id) + { + foreach (Troop troop in Troops) if (troop.Id == id) return troop; + return null; + } + + /// Every distinct creature the totem can hire, so their clones exist before anyone buys. + private static readonly Dictionary HiredPrefabs = new Dictionary(); + + public static string HiredNameFor(string vanillaPrefab) => + HiredPrefabs.TryGetValue(vanillaPrefab, out string name) ? name : null; + + public static void Register() + { + HashSet sources = new HashSet(); + foreach (Troop troop in Troops) + { + foreach (KeyValuePair member in troop.Members) sources.Add(member.Key); + } + foreach (string source in sources) RegisterHired(source); + + RegisterPiece(); + } + + // ---------------------------------------------------------------- the hired + + /// + /// One hired creature: the vanilla thing, tamed, leashed, healing, and worth nothing dead. + /// + /// CharacterDrop is destroyed for the reason it always is here - a mercenary that dropped a troll + /// hide would make the totem a farm - and this time it is also what "leaves nothing when it dies" + /// literally means. + /// + private static void RegisterHired(string source) + { + string prefabName = "TrolHired_" + source; + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Trol] Could not clone {source}; that troop cannot be hired."); + return; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = LeashRange; + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = prefabName; + thrall.m_commandingRace = RaceId; + thrall.m_maxFollowers = MaxFollowers; + thrall.m_witherSeconds = WitherSeconds; + thrall.m_homeCheckRange = HomeCheckRange; + thrall.m_refusalMessage = "They were not paid by you."; + + // The sentry's regeneration, reused whole: untouched for ten seconds, then two percent a + // second. "Rigenerarsi come i nostri scheletri" is the healing, not a respawn - a dead + // mercenary stays dead and has to be hired again. + prefab.AddComponent(); + + PrefabManager.Instance.AddPrefab(prefab); + HiredPrefabs[source] = prefabName; + } + + // ---------------------------------------------------------------- the totem + + private static void RegisterPiece() + { + // A REAL PIECE as the base, and this is the whole bug fix. The first version cloned + // "GoblinTotem", which lives in Assets/GameElements/Items/misc - it is the ITEM offered at + // Yagluth's altar, not a building. An ItemDrop wearing a Piece destroyed itself the moment it + // was placed and left the item lying on the ground. Verified in this very project when the + // merchant catalogue's "FulingTotem" was corrected to "GoblinTotem" as an ITEM, and then + // contradicted here. + // + // piece_workbench is a genuine piece and is already the stripped base of the Skeleton + // sentry's seed, so the pattern is proven. goblin_totempole was the other candidate and is + // not a piece either - it is dungeon scenery under Assets/world. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_workbench"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Trol] Could not clone piece_workbench; the war totem is not registered."); + return; + } + + // Strip the workbench down to a placeable shell: no station, no crafting, no furniture. The + // look comes from the borrowed totem below. + 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); + } + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + if (renderer != null) renderer.enabled = false; // the bench's own mesh, hidden + } + + AswidBloodRefinery.StripOffensive(prefab, PieceName); + + // The look the player asked for: the totem itself, not a log with a head on it. Grounded on + // its own base, so Vector3.zero really is "standing on the spot the hammer picked". + GameObject totemModel = ModelBorrow.Attach(prefab.transform, "TotemModel", "GoblinTotem", + Vector3.zero, Quaternion.identity, TotemHeight, "Trol"); + + TrolTotemBehaviour totem = prefab.AddComponent(); + + foreach (Switch existing in prefab.GetComponentsInChildren(true)) + { + if (existing != null) Object.DestroyImmediate(existing); + } + totem.m_switch = prefab.AddComponent(); + totem.m_switch.m_name = PieceDisplayName; + + // A Trader with an empty catalogue: StoreGui needs one to open at all, and an empty list is + // exactly "sells troops, buys nothing". An empty catalogue is also what used to kill the whole + // window - see StoreGuiEmptyCatalogueGuardPatch in TrolTotemStore.cs, which is the fix. + // + // Every list is filled in even though this trader never talks: a Trader added with + // AddComponent comes up with all of them null, and Trader.Interact - which fires if the + // player's E happens to reach the Trader instead of our Switch, both being on this same + // GameObject - walks straight into Say(m_randomStartTrade, ...) right after opening the store. + Trader trader = prefab.GetComponent() ?? prefab.AddComponent(); + trader.m_name = PieceDisplayName; + trader.m_items = new List(); + trader.m_useItems = new List(); + trader.m_randomTalk = new List(); + trader.m_randomGreets = new List(); + trader.m_randomGoodbye = new List(); + trader.m_randomStartTrade = new List(); + trader.m_randomBuy = new List(); + trader.m_randomSell = new List(); + trader.m_randomGiveItemNo = new List(); + trader.m_randomUseItemAlreadyRecieved = new List(); + trader.m_randomTalkConditionals = new List(); + + // Only ONE head now, and only for the upgraded tier. At tier one the totem is just a totem, + // which is what was asked for - the troll head on a post was the thing being replaced, and + // mounting trophies is also what dropped a giant Yagluth head out of the sky. Borrowed + // safely this time, and mounted on the MEASURED top of the totem rather than at a guessed + // 2.2 m up an unmeasured post - sunk into the crown so it sits on it instead of over it. + float crown = ModelBorrow.HeightOf(totemModel); + Jotunn.Logger.LogInfo($"[Trol] Totem crown measured at {crown:0.##} m; the king's head is " + + $"{HeadSize} m across and sunk {HeadSize * HeadSink:0.##} m into it."); + + totem.m_yagluthHead = ModelBorrow.Attach(prefab.transform, "TotemHeadYagluth", YagluthHead, + new Vector3(0f, crown - HeadSize * HeadSink, 0f), + HeadTilt, HeadSize, "Trol"); + totem.m_yagluthHead.SetActive(false); + + 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(TrollHead); + + 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 = "A head that still remembers how to shout. Coin goes in, a warband walks out.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = BorrowIcon(TrollHead), + Requirements = new[] + { + new RequirementConfig(CoreWood, 1, 0, true), + new RequirementConfig(TrollHead, 1, 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(); + } + + 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; + return icons != null && icons.Length > 0 ? icons[0] : null; + } + } + + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class TrolTotemKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + TrolTotem.EnsureKnown(__instance); + } + } + + /// + /// The race lock. Every other station in this mod is buildable by anyone; this one is not, so the + /// refusal is caught at placement - before the core wood and the head are spent. + /// + [HarmonyPatch(typeof(Player), "PlacePiece", + new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })] + public static class TrolTotemRaceLockPatch + { + public static bool Prefix(Player __instance, Piece __0) + { + if (__instance != Player.m_localPlayer || __0 == null) return true; + if (Utils.GetPrefabName(__0.gameObject) != TrolTotem.PieceName) return true; + if (TrolRace.IsTrol()) return true; + + __instance.Message(MessageHud.MessageType.Center, "The head will not shout for you."); + return false; + } + } +} diff --git a/JotunnModStub/Trol/TrolTotemBehaviour.cs b/JotunnModStub/Trol/TrolTotemBehaviour.cs new file mode 100644 index 0000000..c3ab254 --- /dev/null +++ b/JotunnModStub/Trol/TrolTotemBehaviour.cs @@ -0,0 +1,288 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The totem's logic: five warband slots, bought with coin, disbanded on demand. + /// + /// Slots count GROUPS, not bodies - a six-greydwarf patrol is one slot, and it stays one slot as its + /// members die. Each hired creature carries the group's id in its own ZDO, so the count survives a + /// reload and corrects itself when a whole band is wiped, with nothing tallied anywhere. + /// + /// E opens the vanilla store with a warband column in it, built in TrolTotemStore. It replaced a + /// hold-to-cycle gesture on the Switch that fired faster than anyone could read it. + /// Factions/FactionMerchantSellPanel.cs is the blueprint that made it possible without guessing at a + /// single UI field name. + /// + /// There is no disband button and no rack of slots: a warband that dies is dead, and a butcher knife + /// already dismisses one that has outlived its use. The count is the only bookkeeping there is. + /// + public class TrolTotemBehaviour : MonoBehaviour + { + public Switch m_switch; + public GameObject m_yagluthHead; + + private const string KeyUpgraded = "RoV_trolTotemUpgraded"; + private const string KeyNextGroup = "RoV_trolTotemNextGroup"; + + private ZNetView m_nview; + + private void Awake() + { + 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_TrolHire", RPC_Hire); + m_nview.Register("RoV_TrolUpgrade", RPC_Upgrade); + + InvokeRepeating("UpdateHeads", 0.5f, 2f); + } + + private void OnDestroy() + { + RaisedThrall.UnregisterStation(transform); + } + + /// Both heads are mounted; the tier decides which one is looking at you. + private void UpdateHeads() + { + // Tier one is a plain totem; the king's head only appears once it has been earned. + if (m_yagluthHead != null) m_yagluthHead.SetActive(IsUpgraded()); + } + + // ---------------------------------------------------------------- interaction + + private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + Player player = user as Player; + if (player == null) return false; + + if (!TrolRace.IsTrol()) + { + player.Message(MessageHud.MessageType.Center, "The head will not shout for you."); + return false; + } + + // Yagluth's drop in hand upgrades it: a new head, and two more warbands on the list. + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == TrolTotem.UpgradeItem) + { + return TryUpgrade(player, item); + } + + if (item != null) + { + player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return false; + } + + return OpenStore(player); + } + + private bool TryUpgrade(Player player, ItemDrop.ItemData item) + { + if (IsUpgraded()) + { + player.Message(MessageHud.MessageType.Center, "It has already had one."); + return false; + } + + if (BossProgressionManager.GetCurrentProgressionState() < TrolTotem.UpgradeProgressionState) + { + player.Message(MessageHud.MessageType.Center, "Not until the one it belonged to has fallen."); + return false; + } + + player.GetInventory().RemoveItem(item, 1); + m_nview.InvokeRPC("RoV_TrolUpgrade"); + player.Message(MessageHud.MessageType.Center, "The totem wears a king now."); + return true; + } + + /// + /// Opens the vanilla store window, with the warband column hung off it by + /// TrolTotemStore. A Trader has to be present for StoreGui.Show to have anything to show; the + /// totem's own sells nothing, which is how "does not buy from the player" is expressed. + /// + private bool OpenStore(Player player) + { + Trader trader = GetComponent(); + if (trader == null || StoreGui.instance == null) + { + player.Message(MessageHud.MessageType.Center, "The head has nothing to say."); + return false; + } + + // Nothing is handed to the panel here on purpose: TrolTotemStore reads the totem back out of + // StoreGui's own m_trader when it repaints, so the window cannot end up drawing one totem's + // warbands while showing another's - and there is no static left over to go stale. + StoreGui.instance.Show(trader); + return true; + } + + // ---------------------------------------------------------------- what the store calls + + /// Hire by id, from a row the player clicked. Every check TryHire makes still applies. + public void HireFromStore(string troopId) + { + Player player = Player.m_localPlayer; + if (player == null) return; + + TrolTotem.Troop troop = TrolTotem.Find(troopId); + if (troop == null) return; + if (troop.NeedsUpgrade && !IsUpgraded()) return; + + if (CountGroups() >= TrolTotem.MaxTroops) + { + player.Message(MessageHud.MessageType.Center, "Five warbands is all it can shout for."); + return; + } + + Inventory inventory = player.GetInventory(); + if (inventory == null) return; + + if (CountCoins(inventory) < troop.Price) + { + player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney"); + return; + } + + TakeCoins(inventory, troop.Price); + m_nview.InvokeRPC("RoV_TrolHire", troop.Id); + player.Message(MessageHud.MessageType.Center, $"{troop.Display} answers."); + } + + private const string CoinsPrefab = "Coins"; + + private static int CountCoins(Inventory inventory) + { + int total = 0; + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == CoinsPrefab) + { + total += item.m_stack; + } + } + return total; + } + + private static void TakeCoins(Inventory inventory, int amount) + { + foreach (ItemDrop.ItemData item in new List(inventory.GetAllItems())) + { + if (amount <= 0) return; + if (item == null || item.m_dropPrefab == null || item.m_dropPrefab.name != CoinsPrefab) continue; + + int take = Mathf.Min(amount, item.m_stack); + inventory.RemoveItem(item, take); + amount -= take; + } + } + + // ---------------------------------------------------------------- hiring + + private void RPC_Hire(long sender, string troopId) + { + if (!m_nview.IsOwner()) return; + + TrolTotem.Troop troop = TrolTotem.Find(troopId); + if (troop == null || CountGroups() >= TrolTotem.MaxTroops) return; + if (troop.NeedsUpgrade && !IsUpgraded()) return; + + int next = m_nview.GetZDO().GetInt(KeyNextGroup) + 1; + m_nview.GetZDO().Set(KeyNextGroup, next); + string group = troopId + "#" + next; + + foreach (KeyValuePair member in troop.Members) + { + string hired = TrolTotem.HiredNameFor(member.Key); + if (hired == null) continue; + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(hired) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Trol] No '{hired}' in ZNetScene; part of {troop.Display} did not arrive."); + continue; + } + + for (int i = 0; i < member.Value; i++) SpawnOne(prefab, group); + } + } + + private void SpawnOne(GameObject prefab, string group) + { + Vector3 offset = UnityEngine.Random.insideUnitSphere * 3f; + offset.y = 0f; + Vector3 position = transform.position + offset + Vector3.up * 0.5f; + + GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f)); + + ZNetView nview = spawned.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(TrolTotem.KeyGroup, group); + + RaisedThrall thrall = spawned.GetComponent(); + if (thrall != null) thrall.Bind(transform.position); + } + + private void RPC_Upgrade(long sender) + { + if (!m_nview.IsOwner()) return; + m_nview.GetZDO().Set(KeyUpgraded, true); + } + + // ---------------------------------------------------------------- state + + public bool IsUpgraded() => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false); + + private static string GroupOf(RaisedThrall thrall) + { + ZNetView nview = thrall != null ? thrall.GetComponent() : null; + if (nview == null || !nview.IsValid()) return null; + + string group = nview.GetZDO().GetString(TrolTotem.KeyGroup, ""); + return string.IsNullOrEmpty(group) ? null : group; + } + + /// + /// Live warbands, counted as distinct groups rather than as bodies. This is the whole of the + /// five-slot mechanic now that the rack is gone: nothing is stored, the count is the truth, and it + /// corrects itself the moment a band is wiped out. + /// + public int CountGroups() + { + HashSet groups = new HashSet(); + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(transform.position)) + { + string group = GroupOf(thrall); + if (group != null) groups.Add(group); + } + return groups.Count; + } + + private string Hover() + { + string body = $"warbands {CountGroups()}/{TrolTotem.MaxTroops}"; + + if (!IsUpgraded()) body += "\n(a Yagluth drop in hand buys a king's head, and two more bands)"; + + // The roster lives in the window now, not in the hover - so this only has to get the player + // to open it. The hold gesture it used to advertise was unreadable: it cycled faster than + // anyone could see what was selected. + body += "\n[$KEY_Use] Call the warbands"; + + return Localization.instance.Localize($"{TrolTotem.PieceDisplayName} ({body})"); + } + } + +} diff --git a/JotunnModStub/Trol/TrolTotemStore.cs b/JotunnModStub/Trol/TrolTotemStore.cs new file mode 100644 index 0000000..2bb61f1 --- /dev/null +++ b/JotunnModStub/Trol/TrolTotemStore.cs @@ -0,0 +1,257 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// The war totem's window: the merchant's own store, with a column of hireable warbands in it. + /// + /// Built by cloning the vanilla store's list the way Factions/FactionMerchantSellPanel.cs already + /// does - same three patch points (Awake to build, FillList to repaint, Hide to clear), same trick of + /// instantiating StoreGui.m_listElement for rows. That file is the reason this one could be written + /// without guessing at a single UI field name. + /// + /// It replaces a hold-to-cycle gesture on the Switch, which was unreadable: the hold fired faster + /// than anyone could see what was selected. + /// + /// NO SLOT RACK. There was one, with five squares wearing the trophies of the bands standing in them + /// and a yes/no box to disband one. It is gone at the player's call: a warband that dies is simply + /// dead, and a butcher knife already dismisses one that has outlived its use - tested in game. The + /// five-band CEILING stays, counted in TrolTotemBehaviour and reported by the totem's hover text; it + /// was only ever the rack that was UI, not the limit. + /// + /// WHY THIS FILE ONCE DREW NOTHING AT ALL - see StoreGuiEmptyCatalogueGuardPatch at the bottom. It + /// was not this panel failing; it was vanilla FillList throwing on its last instruction, and a + /// Postfix never runs when the original throws. + /// + public static class TrolTotemStore + { + private static RectTransform _troopList; + private static readonly List _rows = new List(); + + /// + /// The totem the open window belongs to, read back out of StoreGui's own m_trader instead of being + /// pushed in by the totem before Show(). + /// + /// It used to be a static the totem set on its way in, which meant the panel's correctness depended + /// on the order Show/Hide/FillList happen to run in. Reading it back makes the question local: this + /// window belongs to whatever trader vanilla says it belongs to, and if that trader has a + /// TrolTotemBehaviour on it, it is a totem. Same field the factions sell panel reads. + /// + public static TrolTotemBehaviour ActiveTotem(StoreGui gui) + { + Trader trader = FactionMerchantRuntime.GetActiveTrader(gui); + return trader != null ? trader.GetComponent() : null; + } + + // ---------------------------------------------------------------- build + + public static void Create(StoreGui gui) + { + if (gui == null || gui.m_listRoot == null) + { + Jotunn.Logger.LogWarning("[Trol] StoreGui has no m_listRoot; the war totem's window cannot be built."); + return; + } + if (_troopList != null) return; + + GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent); + clone.name = "TrolTroopList"; + _troopList = clone.GetComponent(); + _troopList.anchoredPosition = gui.m_listRoot.anchoredPosition; + + // The clone carries whatever rows the vanilla list held at Awake. Usually none, but a leftover + // would sit under ours forever, so it starts empty by construction. + foreach (Transform child in _troopList) Object.Destroy(child.gameObject); + + _troopList.gameObject.SetActive(false); + } + + public static void Clear() + { + foreach (GameObject row in _rows) if (row != null) Object.Destroy(row); + _rows.Clear(); + + if (_troopList != null) _troopList.gameObject.SetActive(false); + } + + // ---------------------------------------------------------------- fill + + public static void Refresh(StoreGui gui) + { + Clear(); + + TrolTotemBehaviour totem = ActiveTotem(gui); + if (totem == null) return; // an ordinary merchant. Not ours, and not worth a line in the log. + + if (_troopList == null) + { + Jotunn.Logger.LogWarning("[Trol] The war totem's column was never built (did the patch on " + + "StoreGui.Awake fail?), so nothing can be drawn into it."); + return; + } + + _troopList.gameObject.SetActive(true); + + int row = 0; + int hidden = 0; + foreach (TrolTotem.Troop troop in TrolTotem.Troops) + { + if (troop.NeedsUpgrade && !totem.IsUpgraded()) { hidden++; continue; } + BuildRow(gui, totem, troop, row++); + } + + float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue(); + _troopList.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, + Mathf.Max(baseSize, row * gui.m_itemSpacing)); + + Jotunn.Logger.LogInfo($"[Trol] War totem window: {row} warbands on offer, {hidden} still behind " + + $"the king's head, {totem.CountGroups()}/{TrolTotem.MaxTroops} bands alive."); + } + + private static void BuildRow(StoreGui gui, TrolTotemBehaviour totem, TrolTotem.Troop troop, int rowIndex) + { + GameObject element = Object.Instantiate(gui.m_listElement, _troopList); + element.SetActive(true); + + RectTransform rt = (RectTransform)element.transform; + float offset = (_troopList.rect.width - rt.rect.width) / 2f; + rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset); + + Sprite icon = TrophyIcon(troop.Icon); + Image iconImage = element.transform.Find("icon").GetComponent(); + if (icon != null) iconImage.sprite = icon; + else Jotunn.Logger.LogWarning($"[Trol] No icon on '{troop.Icon}' for {troop.Display}; the row keeps " + + "whatever the cloned element was showing."); + + element.transform.Find("name").GetComponent().text = troop.Display; + + TMP_Text price = FindDescendant(element.transform, "price"); + if (price != null) price.text = troop.Price.ToString(); + + UITooltip tooltip = element.GetComponent(); + if (tooltip != null) tooltip.Set(troop.Display, Composition(troop), gui.m_tooltipAnchor, default(Vector2)); + + string id = troop.Id; + element.GetComponent