RacesOfValheim/JotunnModStub/Trol/TrolTotemStore.cs
kanym 1bd09ed31d feat(text): merchants, troops and the hive's shelf come from translation files
The faction merchants' 90 jokes, their generic lines and their names now
read from merchants.json. Merchant names use the game's own creature
tokens where one matches, so they arrive translated in every language
Valheim ships; the Dverg keeps a key of its own, since vanilla's token
reads "Dvergr Rogue".

The Dvergar and Trol troop names and terms, and the Sverm hive's goods,
refusals, stage names and brood kinds, follow. Their panels fill TMP texts
themselves, so they localize the names where they draw them.

The jokes have English text only for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 18:50:54 +02:00

256 lines
12 KiB
C#

using System.Collections.Generic;
using System.Text;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class TrolTotemStore
{
private static RectTransform _troopList;
private static readonly List<GameObject> _rows = new List<GameObject>();
/// <summary>
/// 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.
/// </summary>
public static TrolTotemBehaviour ActiveTotem(StoreGui gui)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(gui);
return trader != null ? trader.GetComponent<TrolTotemBehaviour>() : 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<RectTransform>();
_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<float>();
_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<Image>();
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<TMP_Text>().text = Localization.instance.Localize(troop.Display);
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null) price.text = troop.Price.ToString();
UITooltip tooltip = element.GetComponent<UITooltip>();
if (tooltip != null) tooltip.Set(Localization.instance.Localize(troop.Display), Composition(troop), gui.m_tooltipAnchor, default(Vector2));
string id = troop.Id;
element.GetComponent<Button>().onClick.AddListener(() =>
{
totem.HireFromStore(id);
Traverse.Create(gui).Method("FillList").GetValue(); // repaints the column
});
_rows.Add(element);
}
/// <summary>Who actually turns up, so a two thousand coin button is not bought blind.</summary>
private static string Composition(TrolTotem.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));
}
text.Append("\n\n").Append(ModText.Get("rov_troop_trol_terms"));
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 TrolTotemStoreSetupPatch
{
public static void Postfix(StoreGui __instance) => TrolTotemStore.Create(__instance);
}
[HarmonyPatch(typeof(StoreGui), "FillList")]
public static class TrolTotemStoreFillPatch
{
public static void Postfix(StoreGui __instance) => TrolTotemStore.Refresh(__instance);
}
[HarmonyPatch(typeof(StoreGui), "Hide")]
public static class TrolTotemStoreHidePatch
{
public static void Postfix() => TrolTotemStore.Clear();
}
/// <summary>
/// The reason the totem's window opened empty, and it was never this mod's UI code.
///
/// Read out of the IL of THIS build's assembly_valheim, not assumed. StoreGui.FillList ends with:
/// int index = GetSelectedItemIndex(); // returns 0 when there is nothing to select
/// if (index &lt; 0) index = 0;
/// SelectItem(index, false);
/// and the last line of SelectItem is:
/// m_selectedItem = m_trader.GetAvailableItems()[index];
///
/// With an EMPTY catalogue that is element 0 of an empty list. FillList threw on its very last
/// instruction - and a Harmony Postfix does not run when the original throws, so BOTH postfixes on
/// FillList died with it: this file's warband column and the factions sell panel's. The window came
/// up (Show activates the panel before it calls FillList) with nothing drawn in it whatsoever, which
/// is exactly what the player described.
///
/// The totem's catalogue is empty ON PURPOSE - an empty list is how "sells warbands, buys nothing"
/// is expressed - so the crash is guarded rather than dodged. Vanilla merchants are untouched: the
/// prefix only stands in when there is genuinely nothing to select, which for them never happens
/// unless every one of their wares is behind a global key they have not earned. A prefix returning
/// false IS the mechanism on a void method (trap 5.16); there is no __result to fake.
/// </summary>
[HarmonyPatch(typeof(StoreGui), "SelectItem", new[] { typeof(int), typeof(bool) })]
public static class StoreGuiEmptyCatalogueGuardPatch
{
private static bool _reported;
public static bool Prefix(StoreGui __instance)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(__instance);
if (trader == null) return true;
if (trader.GetAvailableItems().Count > 0) return true;
// Nothing to select, and nothing to highlight either: m_itemList is emptied by FillList and
// only refilled from the same catalogue, so skipping the original loses no work.
Traverse.Create(__instance).Field("m_selectedItem").SetValue(null);
if (!_reported)
{
_reported = true;
Jotunn.Logger.LogInfo($"[Trol] '{trader.m_name}' has an empty catalogue; vanilla SelectItem was " +
"skipped so FillList can finish. Said once per session.");
}
return false;
}
}
}