RacesOfValheim/JotunnModStub/Dvergar/DvergarBancoStore.cs
Ferdinando 5c5b8c34d2 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 <noreply@anthropic.com>
2026-08-08 14:58:43 +02:00

211 lines
9.4 KiB
C#

using System.Collections.Generic;
using System.Text;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class DvergarBancoStore
{
private static RectTransform _crewList;
private static readonly List<GameObject> _rows = new List<GameObject>();
/// <summary>
/// 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.
/// </summary>
public static DvergarBancoBehaviour ActiveBank(StoreGui gui)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(gui);
return trader != null ? trader.GetComponent<DvergarBancoBehaviour>() : 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<RectTransform>();
_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<float>();
_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<Image>();
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<TMP_Text>().text = troop.Display;
// The DISCOUNTED price, because that is what will actually leave the player's pocket.
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null) price.text = DvergarBanco.PriceFor(troop).ToString();
UITooltip tooltip = element.GetComponent<UITooltip>();
if (tooltip != null) tooltip.Set(troop.Display, Composition(troop), gui.m_tooltipAnchor, default(Vector2));
string id = troop.Id;
element.GetComponent<Button>().onClick.AddListener(() =>
{
bank.HireFromStore(id);
Traverse.Create(gui).Method("FillList").GetValue(); // repaints the column
});
_rows.Add(element);
}
/// <summary>Who actually turns up, so two thousand coin is not spent blind.</summary>
private static string Composition(DvergarBanco.Troop troop)
{
StringBuilder text = new StringBuilder();
foreach (KeyValuePair<string, int> member in troop.Members)
{
if (text.Length > 0) text.Append('\n');
text.Append(member.Value).Append(" x ").Append(CreatureName(member.Key));
}
int full = troop.Price;
int paid = DvergarBanco.PriceFor(troop);
if (paid < full) text.Append("\n\nList price ").Append(full).Append(" - your seal takes it to ").Append(paid).Append('.');
text.Append("\n\nThey answer the follow command, knit their own wounds shut, keep your truce with " +
"the mountain's dvergr, drop nothing, and do not come back. A dead crew is money spent.");
return text.ToString();
}
private static string CreatureName(string prefabName)
{
Character character = Jotunn.Managers.PrefabManager.Cache.GetPrefab<Character>(prefabName);
if (character == null || string.IsNullOrEmpty(character.m_name)) return prefabName;
return Localization.instance.Localize(character.m_name);
}
// ---------------------------------------------------------------- helpers
private static Sprite TrophyIcon(string prefabName)
{
if (string.IsNullOrEmpty(prefabName)) return null;
ItemDrop drop = Jotunn.Managers.PrefabManager.Cache.GetPrefab<ItemDrop>(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;
}
private static T FindDescendant<T>(Transform root, string childName) where T : Component
{
foreach (T candidate in root.GetComponentsInChildren<T>(true))
{
if (candidate.gameObject.name == childName) return candidate;
}
return null;
}
}
[HarmonyPatch(typeof(StoreGui), "Awake")]
public static class DvergarBancoStoreSetupPatch
{
public static void Postfix(StoreGui __instance) => DvergarBancoStore.Create(__instance);
}
[HarmonyPatch(typeof(StoreGui), "FillList")]
public static class DvergarBancoStoreFillPatch
{
public static void Postfix(StoreGui __instance) => DvergarBancoStore.Refresh(__instance);
}
[HarmonyPatch(typeof(StoreGui), "Hide")]
public static class DvergarBancoStoreHidePatch
{
public static void Postfix() => DvergarBancoStore.Clear();
}
}