race-chains-and-stations #17
4 changed files with 917 additions and 0 deletions
feat(trol): war totem and its mercenary store
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
commit
df7ce7c893
|
|
@ -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[] {
|
||||
|
|
|
|||
368
JotunnModStub/Trol/TrolTotem.cs
Normal file
368
JotunnModStub/Trol/TrolTotem.cs
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
using System.Collections.Generic;
|
||||
using HarmonyLib;
|
||||
using Jotunn.Configs;
|
||||
using Jotunn.Entities;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class TrolTotem
|
||||
{
|
||||
public const string PieceName = "TrolWarTotem";
|
||||
public const string PieceDisplayName = "War Totem";
|
||||
public const string RaceId = "Trol";
|
||||
|
||||
/// <summary>Core wood. The item is RoundLog - another display name that does not predict the id.</summary>
|
||||
public const string CoreWood = "RoundLog";
|
||||
public const string TrollHead = "TrophyForestTroll";
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private const float HeadSink = 0.35f;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static readonly Quaternion HeadTilt = Quaternion.Euler(90f + 180f, 180f, 0f);
|
||||
|
||||
/// <summary>Written into each hired creature's ZDO so the totem can tell its warbands apart -
|
||||
/// five slots means counting groups, not bodies.</summary>
|
||||
public const string KeyGroup = "RoV_trolGroup";
|
||||
|
||||
public const float LeashRange = 12f;
|
||||
public const float WitherSeconds = 60f;
|
||||
public const float HomeCheckRange = 25f;
|
||||
|
||||
/// <summary>No cap: a hired warband follows as a warband.</summary>
|
||||
public const int MaxFollowers = -1;
|
||||
|
||||
public class Troop
|
||||
{
|
||||
public string Id;
|
||||
public string Display;
|
||||
public int Price;
|
||||
public bool NeedsUpgrade;
|
||||
/// <summary>Trophy of the strongest thing in the band - the face it wears in the rack.</summary>
|
||||
public string Icon;
|
||||
/// <summary>Vanilla creature prefab -> how many of it.</summary>
|
||||
public KeyValuePair<string, int>[] 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<string, int>("Greydwarf", 4),
|
||||
new KeyValuePair<string, int>("Greydwarf_Shaman", 1),
|
||||
new KeyValuePair<string, int>("Greydwarf_Elite", 1),
|
||||
}
|
||||
},
|
||||
new Troop
|
||||
{
|
||||
Id = "troll", Display = "Troll", Price = 700, NeedsUpgrade = false, Icon = "TrophyForestTroll",
|
||||
Members = new[] { new KeyValuePair<string, int>("Troll", 1) }
|
||||
},
|
||||
new Troop
|
||||
{
|
||||
Id = "troll_summoned", Display = "Staff Troll", Price = 900, NeedsUpgrade = false, Icon = "TrophyForestTroll",
|
||||
Members = new[] { new KeyValuePair<string, int>("Troll_Summoned", 1) }
|
||||
},
|
||||
new Troop
|
||||
{
|
||||
Id = "goblin_patrol", Display = "Fuling Patrol", Price = 1400, NeedsUpgrade = true, Icon = "TrophyGoblinBrute",
|
||||
Members = new[]
|
||||
{
|
||||
new KeyValuePair<string, int>("Goblin", 4),
|
||||
new KeyValuePair<string, int>("GoblinShaman", 1),
|
||||
new KeyValuePair<string, int>("GoblinBrute", 1),
|
||||
}
|
||||
},
|
||||
new Troop
|
||||
{
|
||||
Id = "goblin_band", Display = "Fuling War Band", Price = 2000, NeedsUpgrade = true, Icon = "TrophyGoblin",
|
||||
Members = new[]
|
||||
{
|
||||
new KeyValuePair<string, int>("Goblin", 4),
|
||||
new KeyValuePair<string, int>("GoblinArcher", 4),
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
public static Troop Find(string id)
|
||||
{
|
||||
foreach (Troop troop in Troops) if (troop.Id == id) return troop;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Every distinct creature the totem can hire, so their clones exist before anyone buys.</summary>
|
||||
private static readonly Dictionary<string, string> HiredPrefabs = new Dictionary<string, string>();
|
||||
|
||||
public static string HiredNameFor(string vanillaPrefab) =>
|
||||
HiredPrefabs.TryGetValue(vanillaPrefab, out string name) ? name : null;
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
HashSet<string> sources = new HashSet<string>();
|
||||
foreach (Troop troop in Troops)
|
||||
{
|
||||
foreach (KeyValuePair<string, int> member in troop.Members) sources.Add(member.Key);
|
||||
}
|
||||
foreach (string source in sources) RegisterHired(source);
|
||||
|
||||
RegisterPiece();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the hired
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<BaseAI>();
|
||||
if (ai != null) ai.m_randomMoveRange = LeashRange;
|
||||
|
||||
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
|
||||
{
|
||||
if (drops != null) Object.DestroyImmediate(drops);
|
||||
}
|
||||
|
||||
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
|
||||
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<SkeletonSentryBehaviour>();
|
||||
|
||||
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<MonoBehaviour>(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<Renderer>(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<TrolTotemBehaviour>();
|
||||
|
||||
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
|
||||
{
|
||||
if (existing != null) Object.DestroyImmediate(existing);
|
||||
}
|
||||
totem.m_switch = prefab.AddComponent<Switch>();
|
||||
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<Trader>() ?? prefab.AddComponent<Trader>();
|
||||
trader.m_name = PieceDisplayName;
|
||||
trader.m_items = new List<Trader.TradeItem>();
|
||||
trader.m_useItems = new List<Trader.TraderUseItem>();
|
||||
trader.m_randomTalk = new List<string>();
|
||||
trader.m_randomGreets = new List<string>();
|
||||
trader.m_randomGoodbye = new List<string>();
|
||||
trader.m_randomStartTrade = new List<string>();
|
||||
trader.m_randomBuy = new List<string>();
|
||||
trader.m_randomSell = new List<string>();
|
||||
trader.m_randomGiveItemNo = new List<string>();
|
||||
trader.m_randomUseItemAlreadyRecieved = new List<string>();
|
||||
trader.m_randomTalkConditionals = new List<Trader.ConditionalDialog>();
|
||||
|
||||
// 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<Piece>() ?? prefab.AddComponent<Piece>();
|
||||
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>("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<Piece>() : 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<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;
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(Player), "OnSpawned")]
|
||||
public static class TrolTotemKnownPatch
|
||||
{
|
||||
public static void Postfix(Player __instance)
|
||||
{
|
||||
if (__instance != Player.m_localPlayer) return;
|
||||
TrolTotem.EnsureKnown(__instance);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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;
|
||||
}
|
||||
}
|
||||
}
|
||||
288
JotunnModStub/Trol/TrolTotemBehaviour.cs
Normal file
288
JotunnModStub/Trol/TrolTotemBehaviour.cs
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<ZNetView>();
|
||||
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<string>("RoV_TrolHire", RPC_Hire);
|
||||
m_nview.Register("RoV_TrolUpgrade", RPC_Upgrade);
|
||||
|
||||
InvokeRepeating("UpdateHeads", 0.5f, 2f);
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
RaisedThrall.UnregisterStation(transform);
|
||||
}
|
||||
|
||||
/// <summary>Both heads are mounted; the tier decides which one is looking at you.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private bool OpenStore(Player player)
|
||||
{
|
||||
Trader trader = GetComponent<Trader>();
|
||||
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
|
||||
|
||||
/// <summary>Hire by id, from a row the player clicked. Every check TryHire makes still applies.</summary>
|
||||
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<ItemDrop.ItemData>(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<string, int> 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<ZNetView>();
|
||||
if (nview != null && nview.IsValid()) nview.GetZDO().Set(TrolTotem.KeyGroup, group);
|
||||
|
||||
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
|
||||
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<ZNetView>() : null;
|
||||
if (nview == null || !nview.IsValid()) return null;
|
||||
|
||||
string group = nview.GetZDO().GetString(TrolTotem.KeyGroup, "");
|
||||
return string.IsNullOrEmpty(group) ? null : group;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public int CountGroups()
|
||||
{
|
||||
HashSet<string> groups = new HashSet<string>();
|
||||
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[<color=yellow><b>$KEY_Use</b></color>] Call the warbands";
|
||||
|
||||
return Localization.instance.Localize($"{TrolTotem.PieceDisplayName} ({body})");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
257
JotunnModStub/Trol/TrolTotemStore.cs
Normal file
257
JotunnModStub/Trol/TrolTotemStore.cs
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
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 = 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(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\nThey answer the follow command, knit their own wounds shut, drop nothing, and do " +
|
||||
"not come back. A dead warband 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 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 < 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue