From 5c5b8c34d2c9ef1707963fd5232dad3c402f7b07 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Sat, 8 Aug 2026 14:58:43 +0200 Subject: [PATCH] feat(races): Skadi hollow chain, plus the pending Dvergar and Fenrir ones Three per-race item chains had accumulated uncommitted. They land together because FactionMerchantCatalog.cs carries hunks from all three and cannot be split without interactive staging. Skadi (new this session): - SkadiNokkel - "Skadis Nokkel", a StaffSkeleton clone recoloured to ice, stripped of its eitr and health costs and of the skeleton summon, opening an ice-blue portal to a troll cave the player claims as their own. Crafted at the forge after Moder from a 1500-coin Greater Frost Heart, a DragonTear and a TrophySkeleton. - SkadiFrostHeart - the bought leg of that recipe, sold by the Cultist bench. - SkadiHollow / SkadiHollowPortal - claims one existing TrollCave02 in the Black Forest, half a world radius out and south of the equator, and opens a linked local portal pair to it. - RaceCaveBuilding - Skadi and Trol may build inside any troll cave. Two facts worth keeping, both paid for the hard way: - a troll cave counts as a DUNGEON, so the flag that refuses a piece there is the per-piece Piece.m_allowedInDungeons, not the per-location Location.m_noBuild. Player.m_placementStatus names the exact refusal reason and is now logged. - Object.DestroyImmediate is forbidden inside an animation event callback, and a staff cast runs in one - it fails silently there. Also carried in, from earlier sessions and unverified in game: - Dvergar contract bank and barrel (DvergarBanco*, DvergarBotte*) - Fenrir Ulvsblod trough (FenrirMangiatoia*) - the Wolf -> Ulv merchant bench move, so tameable wolves stop answering the E key with a shop window Status: compiles clean with no new warnings. The Skadi chain has NOT been confirmed working in game - the most recent fix to the troll cave detection is still untested. Co-Authored-By: Claude Opus 5 --- JotunnModStub/Dvergar/DvergarBanco.cs | 455 +++++++++++++++ .../Dvergar/DvergarBancoBehaviour.cs | 290 ++++++++++ JotunnModStub/Dvergar/DvergarBancoStore.cs | 211 +++++++ JotunnModStub/Dvergar/DvergarBotte.cs | 309 +++++++++++ .../Dvergar/DvergarBotteBehaviour.cs | 267 +++++++++ JotunnModStub/Dvergar/DvergarRace.cs | 8 + .../Factions/FactionMerchantCatalog.cs | 39 +- JotunnModStub/Fenrir/FenrirMangiatoia.cs | 516 ++++++++++++++++++ .../Fenrir/FenrirMangiatoiaBehaviour.cs | 468 ++++++++++++++++ JotunnModStub/Fenrir/FenrirRace.cs | 5 + JotunnModStub/PieceDensityLimit.cs | 21 + JotunnModStub/RaceCaveBuilding.cs | 212 +++++++ JotunnModStub/RacesOfValheim.cs | 5 + JotunnModStub/RacesOfValheim.csproj | 6 + JotunnModStub/Skadi/SkadiConfig.cs | 16 + JotunnModStub/Skadi/SkadiFrostHeart.cs | 57 ++ JotunnModStub/Skadi/SkadiHollow.cs | 256 +++++++++ JotunnModStub/Skadi/SkadiHollowPortal.cs | 234 ++++++++ JotunnModStub/Skadi/SkadiNokkel.cs | 396 ++++++++++++++ JotunnModStub/Skadi/SkadiRace.cs | 30 +- 20 files changed, 3784 insertions(+), 17 deletions(-) create mode 100644 JotunnModStub/Dvergar/DvergarBanco.cs create mode 100644 JotunnModStub/Dvergar/DvergarBancoBehaviour.cs create mode 100644 JotunnModStub/Dvergar/DvergarBancoStore.cs create mode 100644 JotunnModStub/Dvergar/DvergarBotte.cs create mode 100644 JotunnModStub/Dvergar/DvergarBotteBehaviour.cs create mode 100644 JotunnModStub/Fenrir/FenrirMangiatoia.cs create mode 100644 JotunnModStub/Fenrir/FenrirMangiatoiaBehaviour.cs create mode 100644 JotunnModStub/RaceCaveBuilding.cs create mode 100644 JotunnModStub/Skadi/SkadiFrostHeart.cs create mode 100644 JotunnModStub/Skadi/SkadiHollow.cs create mode 100644 JotunnModStub/Skadi/SkadiHollowPortal.cs create mode 100644 JotunnModStub/Skadi/SkadiNokkel.cs diff --git a/JotunnModStub/Dvergar/DvergarBanco.cs b/JotunnModStub/Dvergar/DvergarBanco.cs new file mode 100644 index 0000000..2b519aa --- /dev/null +++ b/JotunnModStub/Dvergar/DvergarBanco.cs @@ -0,0 +1,455 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Dvergar's station: a contract bank. Coin goes on the table, a crew signs on. + /// + /// The Trol's war totem is the twin of this file and the two should be read together - same five + /// group slots, same empty Trader driving vanilla's store window, same "a dead band is money spent". + /// What is NOT shared is deliberate: the dvergr are hired professionals rather than a shouted-for + /// warband, and everything different here follows from that one sentence. + /// + /// - they are TAMED and answer the follow command, like every servant in this mod (RaisedThrall); + /// - they knit their own wounds shut, the sentry's regeneration reused whole; + /// - they are NOT merchants, which costs no code at all: FactionMerchantSetupPatch matches the + /// exact prefab name and these clones are DvergarMerc_*. This is the same mechanism that made + /// every tameable wolf in the world a shop window until the catalogue stopped listing "Wolf", + /// read from the other side; + /// - they keep their race's truce. A hired crew walking into a dvergr outpost does not start a + /// war with the shopkeeper - see DvergarMercenaryTrucePatch at the bottom, which is the one + /// rule in this file that has no counterpart on the totem; + /// - they can be given drink, later. Nothing here is needed for that: a rune barrel will buff + /// whatever RaisedThrall is bound to this bank's anchor, so the mercenaries need no hook of + /// their own and this file does not have to be reopened to add one. + /// + /// The seekers in the low bands are not allies, they are LEASHED. A dvergr contract sends you two + /// workers and their beasts, which is also why the truce has to cover them: wild dvergr shoot + /// seekers on sight, and a firefight started by a brood at your heel would be retaliation damage, + /// which IsEnemy has no say over once it has begun. + /// + public static class DvergarBanco + { + public const string PieceName = "DvergarContractBank"; + public const string PieceDisplayName = "Contract Bank"; + public const string RaceId = DvergarConfig.RaceId; + + /// The Queen's drop, mapped to state 7 in BossProgressionManager. Mistlands money for + /// a mistlands station: the dvergr do not take Yagluth's leavings seriously. + public const string UpgradeItem = "QueenDrop"; + public const int UpgradeProgressionState = 7; // The Queen + + public const int MaxTroops = 5; + + /// Written into each hired creature's ZDO so the bank can tell its crews apart - + /// five slots means counting contracts, not bodies. + public const string KeyGroup = "RoV_dvergarGroup"; + + public const float LeashRange = 12f; + public const float WitherSeconds = 60f; + public const float HomeCheckRange = 25f; + + /// No cap: a signed contract walks out as a contract. + public const int MaxFollowers = -1; + + // One per square kilometre. Looser than the Fenrir's pen (2.59 km2) because a bank does not + // grow anything on its own, stricter than the Trol's totem, which has no limit at all and + // should probably get one once it is out of test. + public const int MaxBanksInRange = 1; + public const float DensityAreaKm2 = 1f; + + // ---------------------------------------------------------------- the look, in metres + /// A cartography table, slightly cut down. The dvergr write smaller than we do. + private const float TableScale = 0.8f; + + /// + /// How high the coin pile sits, in the piece's own space and BEFORE TableScale is applied. + /// Unlike the totem's head this is not measured: the table keeps its own vanilla mesh, so + /// there is no borrowed holder to call ModelBorrow.HeightOf on. If the pile floats or sinks, + /// this is the ONE number to touch. + /// + private const float PileHeight = 1.05f; + private const float PileSize = 0.45f; + + public class Troop + { + public string Id; + public string Display; + public int Price; + public bool NeedsUpgrade; + /// Trophy of whoever leads the crew - the face it wears in the rack. + public string Icon; + /// Vanilla creature prefab -> how many of it. + public KeyValuePair[] Members; + } + + // Anchored at the same 400-2000 as the Trol's totem, and laddered against ITS bands rather + // than against head count: one Dverger is worth rather more than six greydwarves, so the + // bodies come down as the coin goes up and the seekers make up the difference at the bottom. + // + // The top band is knowingly stronger than the totem's two thousand coin fuling war band. It + // sits behind the Queen and it dies for good; if it proves too much in play, the lever is to + // drop the support mage out of it before touching the price. + public static readonly Troop[] Troops = + { + new Troop + { + Id = "escort", Display = "Escort", Price = 400, NeedsUpgrade = false, Icon = "TrophyDvergr", + Members = new[] + { + new KeyValuePair("Dverger", 1), + new KeyValuePair("SeekerBrood", 2), + } + }, + new Troop + { + Id = "yard_patrol", Display = "Yard Patrol", Price = 700, NeedsUpgrade = false, Icon = "TrophyDvergr", + Members = new[] + { + new KeyValuePair("Dverger", 2), + new KeyValuePair("SeekerBrood", 2), + } + }, + new Troop + { + Id = "fire_crew", Display = "Fire Crew", Price = 1000, NeedsUpgrade = false, Icon = "TrophyDvergr", + Members = new[] + { + new KeyValuePair("Dverger", 1), + new KeyValuePair("DvergerMageFire", 1), + new KeyValuePair("SeekerBrood", 3), + } + }, + new Troop + { + Id = "runic_crew", Display = "Runic Crew", Price = 1500, NeedsUpgrade = true, Icon = "TrophyDvergr", + Members = new[] + { + new KeyValuePair("Dverger", 2), + new KeyValuePair("DvergerMageIce", 1), + new KeyValuePair("DvergerMageSupport", 1), + } + }, + new Troop + { + Id = "ash_guard", Display = "Ash Guard", Price = 2000, NeedsUpgrade = true, Icon = "TrophySeekerBrute", + Members = new[] + { + new KeyValuePair("DvergerAshlands", 2), + new KeyValuePair("DvergerMageSupport", 1), + new KeyValuePair("SeekerBrute", 1), + } + }, + }; + + public static Troop Find(string id) + { + foreach (Troop troop in Troops) if (troop.Id == id) return troop; + return null; + } + + /// + /// What this player actually pays, after the Dvergar's own trader discount. + /// + /// It reads the LOCAL player's tier, which is correct rather than convenient: the coin comes + /// out of that player's own inventory, on that player's own client, and a contract bank is not + /// a shared till. The discount table stops at 25% at state 7 (DvergarConfig.cs), which is the + /// same state that unlocks the two upgraded bands - so the top of the list can never be + /// discounted before it can be bought, and no separate ceiling is needed. + /// + public static int PriceFor(Troop troop) + { + if (troop == null) return 0; + + float discount = Mathf.Clamp01(DvergarProgression.Current.TraderBuyDiscount); + return Mathf.Max(1, Mathf.RoundToInt(troop.Price * (1f - discount))); + } + + /// Every distinct creature the bank can hire, so their clones exist before anyone signs. + private static readonly Dictionary HiredPrefabs = new Dictionary(); + + public static string HiredNameFor(string vanillaPrefab) => + HiredPrefabs.TryGetValue(vanillaPrefab, out string name) ? name : null; + + /// The mercenary prefabs, by name, so the truce can recognise its own cheaply. + private static readonly HashSet HiredNames = new HashSet(); + + public static bool IsHiredName(string prefabName) => + !string.IsNullOrEmpty(prefabName) && HiredNames.Contains(prefabName); + + 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(); + + PieceDensityLimit.Register(PieceName, + PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxBanksInRange, + "There is already {0} contract bank within a day's walk. One ledger per valley."); + } + + // ---------------------------------------------------------------- the hired + + /// + /// One signed mercenary: the vanilla creature, tamed, leashed, healing, and worth nothing dead. + /// + /// CharacterDrop is destroyed for the reason it always is here, and it matters more on this + /// chain than on any other: dvergr and seekers both carry loot that SELLS. A mercenary that + /// dropped its own parts would make the bank a way of turning coin into more coin. + /// + private static void RegisterHired(string source) + { + string prefabName = "DvergarMerc_" + source; + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Dvergar] Could not clone {source}; that crew member cannot be hired. " + + "The rest of its band still signs on without it."); + 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 = "Your name is not on the contract."; + + // Ten seconds unhurt, then two percent a second - the sentry's regeneration, shared with + // the Trol's troops and the Fenrir's pack. A dead mercenary still stays dead. + prefab.AddComponent(); + + PrefabManager.Instance.AddPrefab(prefab); + HiredPrefabs[source] = prefabName; + HiredNames.Add(prefabName); + } + + // ---------------------------------------------------------------- the bank + + private static void RegisterPiece() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_cartographytable"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Dvergar] Could not clone piece_cartographytable; the contract bank " + + "is not registered."); + return; + } + + // EVERY behaviour goes except the three that make it a building, and the blanket sweep is + // the point rather than laziness: the cartography table's MapTable is Interactable AND + // Hoverable, so it takes the E key before our own Switch ever sees it and opens the shared + // map instead of the ledger. That is the same bug as the barrel's Container on the Fenrir + // trough and the Trader on the vanilla wolf, and stripping by capability instead of by + // type name means it cannot come back if a future patch renames or adds a component. + // + // Unlike the Trol's totem the renderers are KEPT: the table is the look, there is nothing + // borrowed underneath it. + 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); + } + + AswidBloodRefinery.StripOffensive(prefab, PieceName); + + prefab.transform.localScale = Vector3.one * TableScale; + + DvergarBancoBehaviour bank = prefab.AddComponent(); + + foreach (Switch existing in prefab.GetComponentsInChildren(true)) + { + if (existing != null) Object.DestroyImmediate(existing); + } + bank.m_switch = prefab.AddComponent(); + bank.m_switch.m_name = PieceDisplayName; + + // An empty catalogue IS the design: the bank sells crews and buys nothing. Every list is + // filled in even though this trader never talks, because a Trader added with AddComponent + // comes up with all of them null and Trader.Interact walks into Say(m_randomStartTrade) + // if the player's E happens to reach it instead of our Switch. + // + // The empty list would also throw out of StoreGui.FillList on its last instruction - that + // is fixed once and for everyone by StoreGuiEmptyCatalogueGuardPatch over in + // Trol/TrolTotemStore.cs, which is generic and is deliberately NOT copied here. + 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(); + + // The mark of a bank that has been paid: a heap of coin on the table, hidden until the + // Queen has fallen and the ledger has been rewritten. + // + // 'treasure_pile' is the player's own choice of prop and is NOT verified against this + // build - nothing else in the project references it. ModelBorrow is null-safe by + // construction, so a wrong name costs exactly one warning in the log and an empty holder; + // if that warning appears, 'Coins' is the fallback and this is a one-string change. + bank.m_coinPile = ModelBorrow.Attach(prefab.transform, "BankCoinPile", "treasure_pile", + new Vector3(0f, PileHeight, 0f), Quaternion.identity, + PileSize, "Dvergar"); + bank.m_coinPile.SetActive(false); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_craftingStation = null; // a bank is built where the work is, not at a bench + 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("TrophyDvergr"); + + Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); + if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect; + + // Coin in the RECIPE, and that is the whole reason this chain needs no gate item bought + // from a merchant the way the other three do: the Dvergar pay for everything, so the + // station opens by being paid for rather than by being unlocked. + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = PieceDisplayName, + Description = "A ledger, a seal and a heap of coin. Sign here and someone else does the dying.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = BorrowIcon("TrophyDvergr"), + Requirements = new[] + { + new RequirementConfig("BlackMarble", 10, 0, true), + new RequirementConfig("YggdrasilWood", 5, 0, true), + new RequirementConfig("Sap", 2, 0, true), + new RequirementConfig("Coins", 100, 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 DvergarBancoKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + DvergarBanco.EnsureKnown(__instance); + } + } + + /// + /// The race lock, caught at placement so the marble and the coin are not spent before the refusal. + /// The same shape as TrolTotemRaceLockPatch - the second station in the mod that refuses the hammer + /// outright, because hiring dvergr with dvergr money is the race's identity and not a tool it owns. + /// + [HarmonyPatch(typeof(Player), "PlacePiece", + new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })] + public static class DvergarBancoRaceLockPatch + { + public static bool Prefix(Player __instance, Piece __0) + { + if (__instance != Player.m_localPlayer || __0 == null) return true; + if (Utils.GetPrefabName(__0.gameObject) != DvergarBanco.PieceName) return true; + if (DvergarRace.IsDvergar()) return true; + + __instance.Message(MessageHud.MessageType.Center, "The contract is in runic. You do not sign it."); + return false; + } + } + + /// + /// A hired crew keeps its employer's truce. + /// + /// Without this the station fights itself: a Dvergar player is at peace with the mountain's dvergr + /// (FactionHostilityPatch), and those dvergr are where the player BUYS - so walking into an outpost + /// with an escort would mean the escort killing the shopkeeper. Taming a creature puts it in the + /// player faction, which makes it an enemy of everything the player is merely not fighting. + /// + /// One condition covers the whole band, seekers included, because every hired body is a RaisedThrall + /// carrying the same commanding race - so the leashed brood at your heel is as welcome in an outpost + /// as the dvergr holding its chain, even though wild dvergr shoot seekers on sight. That was the + /// player's call and it is the only reason a bank is usable in the mistlands at all: retaliation + /// damage does not go through IsEnemy, so one shot fired by an outpost would have escalated into a + /// war this patch could no longer stop. + /// + /// A postfix that only ever says "not enemies", layered on top of the older hostility patch on the + /// same method exactly as that one layers on RaceHostilityManager. It cannot make anything hostile + /// that was not already. + /// + [HarmonyPatch(typeof(BaseAI), nameof(BaseAI.IsEnemy), new System.Type[] { typeof(Character), typeof(Character) })] + public static class DvergarMercenaryTrucePatch + { + /// The mountain's dvergr, by prefab name. The same roster FactionHostilityPatch uses + /// for the player's own truce - kept as its own copy so a change to one is a deliberate change + /// to that one, since these two lists answer different questions. + private static readonly HashSet WildDvergr = new HashSet + { + "Dverger", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands", + }; + + public static void Postfix(Character a, Character b, ref bool __result) + { + if (!__result) return; // already not enemies, nothing to add + if (a == null || b == null) return; + + if (IsTruce(a, b) || IsTruce(b, a)) __result = false; + } + + /// True if is one of ours and is + /// a wild dvergr. + private static bool IsTruce(Character mercenary, Character other) + { + RaisedThrall thrall = mercenary.GetComponent(); + if (thrall == null || thrall.m_commandingRace != DvergarBanco.RaceId) return false; + + return WildDvergr.Contains(Utils.GetPrefabName(other.gameObject)); + } + } +} diff --git a/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs b/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs new file mode 100644 index 0000000..dbbfa6e --- /dev/null +++ b/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs @@ -0,0 +1,290 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The bank's logic: five contracts, bought with coin, and no way to cancel one. + /// + /// Slots count CREWS, not bodies - a fire crew of five is one slot, and it stays one slot as its + /// members die. Each hired body carries its crew's id in its own ZDO, so the count survives a reload + /// and corrects itself when a whole crew is wiped, with nothing tallied anywhere. + /// + /// This is TrolTotemBehaviour's twin and was written from it. The differences are all consequences + /// of one thing - these are paid professionals rather than a shouted-for warband: + /// - the price a player pays is discounted by their own Dvergar tier (DvergarBanco.PriceFor); + /// - the upgrade is the Queen's drop rather than Yagluth's, and it puts coin on the table + /// instead of a head on a post. + /// If a bug is found in one of the two files, look for it in the other before assuming it is local. + /// + public class DvergarBancoBehaviour : MonoBehaviour + { + public Switch m_switch; + public GameObject m_coinPile; + + private const string KeyUpgraded = "RoV_dvergarBankUpgraded"; + private const string KeyNextGroup = "RoV_dvergarBankNextGroup"; + + 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_DvergarHire", RPC_Hire); + m_nview.Register("RoV_DvergarUpgrade", RPC_Upgrade); + + InvokeRepeating("UpdatePile", 0.5f, 2f); + } + + private void OnDestroy() + { + RaisedThrall.UnregisterStation(transform); + } + + /// The coin is mounted from the start; the tier decides whether it is there to see. + private void UpdatePile() + { + if (m_coinPile != null) m_coinPile.SetActive(IsUpgraded()); + } + + // ---------------------------------------------------------------- interaction + + private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + Player player = user as Player; + if (player == null) return false; + + if (!DvergarRace.IsDvergar()) + { + player.Message(MessageHud.MessageType.Center, "The ledger is not written for you."); + return false; + } + + // The Queen's drop in hand rewrites the ledger: coin on the table, and two more crews. + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == DvergarBanco.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() < DvergarBanco.UpgradeProgressionState) + { + player.Message(MessageHud.MessageType.Center, "Not while she still sits under the mist."); + return false; + } + + player.GetInventory().RemoveItem(item, 1); + m_nview.InvokeRPC("RoV_DvergarUpgrade"); + player.Message(MessageHud.MessageType.Center, "The ledger is rewritten. Better names sign it now."); + return true; + } + + /// + /// Opens the vanilla store window, with the crew column hung off it by DvergarBancoStore. A + /// Trader has to be present for StoreGui.Show to have anything to show; this one's catalogue is + /// empty, which is how "hires crews, buys nothing" is expressed. + /// + private bool OpenStore(Player player) + { + Trader trader = GetComponent(); + if (trader == null || StoreGui.instance == null) + { + player.Message(MessageHud.MessageType.Center, "The ledger is shut."); + return false; + } + + // Nothing is handed to the panel: DvergarBancoStore reads the bank back out of StoreGui's + // own m_trader when it repaints, so the window cannot draw one bank's crews while showing + // another's, and there is no static left over to go stale. + StoreGui.instance.Show(trader); + return true; + } + + // ---------------------------------------------------------------- what the store calls + + /// Sign a crew by id, from a row the player clicked. Every check TryHire made applies. + public void HireFromStore(string troopId) + { + Player player = Player.m_localPlayer; + if (player == null) return; + + DvergarBanco.Troop troop = DvergarBanco.Find(troopId); + if (troop == null) return; + if (troop.NeedsUpgrade && !IsUpgraded()) return; + + if (CountGroups() >= DvergarBanco.MaxTroops) + { + player.Message(MessageHud.MessageType.Center, "Five contracts is all the ledger holds."); + return; + } + + Inventory inventory = player.GetInventory(); + if (inventory == null) return; + + // Priced here and NOT on the way in from the row: the button only draws a number, and the + // player's tier could have changed since the window was opened. + int price = DvergarBanco.PriceFor(troop); + + if (CountCoins(inventory) < price) + { + player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney"); + return; + } + + TakeCoins(inventory, price); + m_nview.InvokeRPC("RoV_DvergarHire", troop.Id); + player.Message(MessageHud.MessageType.Center, $"{troop.Display} signs on."); + } + + 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; + + DvergarBanco.Troop troop = DvergarBanco.Find(troopId); + if (troop == null || CountGroups() >= DvergarBanco.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 = DvergarBanco.HiredNameFor(member.Key); + if (hired == null) continue; + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(hired) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Dvergar] No '{hired}' in ZNetScene; part of {troop.Display} " + + "did not turn up for work."); + continue; + } + + for (int i = 0; i < member.Value; i++) SpawnOne(prefab, group); + } + } + + private void SpawnOne(GameObject prefab, string group) + { + Vector3 offset = Random.insideUnitSphere * 3f; + offset.y = 0f; + Vector3 position = transform.position + offset + Vector3.up * 0.5f; + + GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, Random.Range(0, 360), 0f)); + + ZNetView nview = spawned.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(DvergarBanco.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(DvergarBanco.KeyGroup, ""); + return string.IsNullOrEmpty(group) ? null : group; + } + + /// + /// Live crews, counted as distinct groups rather than as bodies. Nothing is stored: the count + /// is the truth, and it corrects itself the moment a crew 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 = $"contracts {CountGroups()}/{DvergarBanco.MaxTroops}"; + + // Said in as many words: a player who cannot see their own discount will read the lower + // number in the window as a mistake. + float discount = Mathf.Clamp01(DvergarProgression.Current.TraderBuyDiscount); + if (discount > 0f) body += $"\nyour seal is worth {Mathf.RoundToInt(discount * 100f)}% off"; + + if (!IsUpgraded()) body += "\n(what the Queen left behind buys two more crews)"; + + body += "\n[$KEY_Use] Read the ledger"; + + return Localization.instance.Localize($"{DvergarBanco.PieceDisplayName} ({body})"); + } + } +} diff --git a/JotunnModStub/Dvergar/DvergarBancoStore.cs b/JotunnModStub/Dvergar/DvergarBancoStore.cs new file mode 100644 index 0000000..e225ae0 --- /dev/null +++ b/JotunnModStub/Dvergar/DvergarBancoStore.cs @@ -0,0 +1,211 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// The contract bank's window: the merchant's own store, with a column of hireable crews in it. + /// + /// TWINNED WITH Trol/TrolTotemStore.cs. This is a copy of that file, taken deliberately rather than + /// refactored into something shared, so the Trol's totem is not touched while it is in test - the + /// two are the same panel drawn from a different roster. A FIX TO ONE BELONGS IN THE OTHER; when + /// the totem is settled they should collapse into one panel driven by a common station interface. + /// + /// Two things are deliberately NOT copied across: + /// - StoreGuiEmptyCatalogueGuardPatch, which is what stops vanilla FillList throwing on an empty + /// catalogue and taking every postfix down with it. It is generic - it fires for any trader with + /// nothing to sell - so it already covers this bank, and a second copy would just be a second + /// prefix on the same method doing the same work. + /// - the slot rack. There was one on the totem and it was removed at the player's call: a crew + /// that dies is dead, and a butcher knife already dismisses one that has outlived its use. + /// + /// The two columns cannot collide. Each one clears itself at the top of its own Refresh and only + /// switches on when the trader the window belongs to carries ITS behaviour, so at most one is ever + /// drawn - a bank is not a totem. + /// + public static class DvergarBancoStore + { + private static RectTransform _crewList; + private static readonly List _rows = new List(); + + /// + /// The bank the open window belongs to, read back out of StoreGui's own m_trader rather than + /// pushed in before Show(). Same field the factions sell panel and the totem's column read. + /// + public static DvergarBancoBehaviour ActiveBank(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("[Dvergar] StoreGui has no m_listRoot; the contract bank's window " + + "cannot be built."); + return; + } + if (_crewList != null) return; + + GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent); + clone.name = "DvergarCrewList"; + _crewList = clone.GetComponent(); + _crewList.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 _crewList) Object.Destroy(child.gameObject); + + _crewList.gameObject.SetActive(false); + } + + public static void Clear() + { + foreach (GameObject row in _rows) if (row != null) Object.Destroy(row); + _rows.Clear(); + + if (_crewList != null) _crewList.gameObject.SetActive(false); + } + + // ---------------------------------------------------------------- fill + + public static void Refresh(StoreGui gui) + { + Clear(); + + DvergarBancoBehaviour bank = ActiveBank(gui); + if (bank == null) return; // an ordinary merchant, or the Trol's totem. Not ours. + + if (_crewList == null) + { + Jotunn.Logger.LogWarning("[Dvergar] The contract bank's column was never built (did the patch " + + "on StoreGui.Awake fail?), so nothing can be drawn into it."); + return; + } + + _crewList.gameObject.SetActive(true); + + int row = 0; + int hidden = 0; + foreach (DvergarBanco.Troop troop in DvergarBanco.Troops) + { + if (troop.NeedsUpgrade && !bank.IsUpgraded()) { hidden++; continue; } + BuildRow(gui, bank, troop, row++); + } + + float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue(); + _crewList.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, + Mathf.Max(baseSize, row * gui.m_itemSpacing)); + + Jotunn.Logger.LogInfo($"[Dvergar] Contract bank window: {row} crews on offer, {hidden} still behind " + + $"the Queen, {bank.CountGroups()}/{DvergarBanco.MaxTroops} contracts live."); + } + + private static void BuildRow(StoreGui gui, DvergarBancoBehaviour bank, DvergarBanco.Troop troop, int rowIndex) + { + GameObject element = Object.Instantiate(gui.m_listElement, _crewList); + element.SetActive(true); + + RectTransform rt = (RectTransform)element.transform; + float offset = (_crewList.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($"[Dvergar] 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; + + // The DISCOUNTED price, because that is what will actually leave the player's pocket. + TMP_Text price = FindDescendant(element.transform, "price"); + if (price != null) price.text = DvergarBanco.PriceFor(troop).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