RacesOfValheim/JotunnModStub/Trol/TrolTotem.cs
2026-08-16 07:44:44 +02:00

379 lines
19 KiB
C#

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;
// DISABLED ON PURPOSE, and it is the line that keeps the log clean. Trader was written for
// Haldor, who is a creature with an animator and a LookAt rig: Trader.Update() calls
// m_animator.SetBool("Stand", ...) and m_lookAt.ResetTarget() with no null check on every
// frame no player is nearby, and Trader.Start() calls InvokeRepeating("RandomTalk", 0, 0)
// on a component nobody authored in the editor. On a totem both of those are null, so the
// piece threw a NullReferenceException every frame from the moment it was raised. A
// disabled component runs neither, and StoreGui needs neither: Show() only reads fields off
// the Trader and asks it for its item list, and GetComponent finds it disabled just the
// same. This is the same fix SvermHiveStore.Mount already carries for the Hive Market.
trader.enabled = false;
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;
}
}
}