RacesOfValheim/JotunnModStub/Skadi/SkadiGolem.cs
kanym b0d18b0654 feat(text): on-screen messages come from translation files
Every message the mod puts in the middle or corner of the screen now reads
its text through ModText.Get, and messages.json holds 191 texts in English
and Italian. Values computed in code become $1, $2 in the text, so a
translator can put them wherever the sentence needs them. Branching
messages get one key per branch.

A few messages travel through a field before they are shown: thralls'
refusals and the building limits now hold a token or key there. Boss and
form names inside messages use tokens too, the bosses the game's own, so
"The Elder" arrives translated.

ModText.Get now localizes each argument before inserting it. A token
argument left for a later pass ran into the text after it: "$1's power"
became the unknown token "enemy_eikthyr's".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 20:30:03 +02:00

459 lines
22 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Skadi station: crystal golems, cut at a stonecutter and bound to it.
///
/// Eighth of the per-race item-progression chains, and the odd one out in two ways that decide
/// everything else in this file.
///
/// FIRST, the station is not ours. Every other chain builds its own bench - a trough, a bone pile,
/// a composter - and can therefore hang a MonoBehaviour on it, count its own garrison from it, and
/// mark its thralls when it falls. The stonecutter is vanilla's, and nothing here modifies it: the
/// golem carries the stonecutter's position in its own ZDO and asks the world whether one still
/// stands there. That is why this chain does not use RaisedThrall, which is otherwise exactly the
/// right component - RaisedThrall's wither depends on the station registering itself, and a vanilla
/// piece never will.
///
/// SECOND, a golem is not a follower. RaisedThrall's whole vocabulary - follow me, stand down, call
/// to arms - is wrong for something that may not leave a twenty metre circle. There is deliberately
/// no Tameable on it either: it is tame, so it will never turn on anyone, but it cannot be named,
/// ordered, or walked away with. It guards the stone that shaped it, and that is all it does.
///
/// The three limits are the design, not decoration:
/// never further than 20 m from its stonecutter (the vanilla station build range)
/// two per stonecutter
/// ten per square mile
/// The first is enforced on the golem (SkadiGolemGuard), the other two at the moment of building,
/// through PieceDensityLimit's single Player.PlacePiece prefix - refusing later would spend a
/// dragon tear before telling anyone no.
/// </summary>
public static class SkadiGolem
{
// ─── Names ───────────────────────────────────────────────────────────
public const string GolemName = "SkadiCrystalGolem";
public const string SeedPieceName = "SkadiCrystalGolemSeed";
public const string DisplayName = "$rov_creature_skadi_crystalgolem_name";
private const string SourceGolem = "StoneGolem";
/// <summary>
/// The seed piece's model, and it is chosen for its BUILD GHOST: the golem itself only exists
/// a frame later, so a standing stone is what the player actually aims with. Everything the
/// ward DOES - the private area above all - is stripped off the clone below; a chain that
/// quietly planted a ward every time you cut a golem would be a much worse bug than a wrong
/// silhouette.
/// </summary>
private const string SourcePiece = "guard_stone";
public const string StationPrefab = "piece_stonecutter";
// ─── The price ───────────────────────────────────────────────────────
// Moder needs no state check of her own to BUILD one - her drop is in the recipe - but the
// gate asks anyway, because the recipe is not the only way an item reaches an inventory.
public const string GolemTrophy = "TrophySGolem";
public const string CrystalItem = "Crystal";
public const int CrystalCost = 10;
public const string ModerDrop = "DragonTear";
public const int ModerProgressionState = 5;
// ─── The limits ──────────────────────────────────────────────────────
/// <summary>
/// How far a golem may get from its stonecutter. Twenty metres because that is the
/// stonecutter's own build range in vanilla, so the circle a golem defends is exactly the
/// circle it could have been built in - one number, visible in game, not two that nearly
/// agree.
/// </summary>
public const float LeashRange = 20f;
/// <summary>
/// Past this it has stopped walking home and started failing to. A golem that has been pushed
/// into water, or that stands on the wrong side of something it cannot path around, would
/// otherwise sit outside its leash forever - so at half again the leash it is simply put back.
/// It is a failsafe for a stuck pathfinder, not a movement mechanic.
/// </summary>
public const float HardLeashRange = 30f;
public const int MaxPerStation = 2;
// Ten per square mile. 2.59 km2, the same area the Fenrir's trough is measured in, so the two
// stations are spaced by the same yardstick even though the numbers differ.
public const int MaxInArea = 10;
public const float DensityAreaKm2 = 2.59f;
/// <summary>
/// How long a golem outlives the stonecutter that cut it. Shorter than the Fenrir trough's
/// five minutes because there is nothing to rebuild: a stonecutter costs ten stone and two
/// wood, so "put it back" is a moment's work, and a longer grace would just mean a garrison
/// that survives being moved.
/// </summary>
public const float WitherSeconds = 60f;
/// <summary>Slack when asking "is my stonecutter still there" - a station never moves.</summary>
public const float StationCheckRange = 2f;
/// <summary>
/// Only asked this close to home, for the reason RaisedThrall's wither carries the same guard:
/// further out the station's zone is probably not loaded, so "nothing stands there" would be a
/// lie. A golem is leashed to 20 m anyway, so this is never the reason one survives.
/// </summary>
public const float HomeCheckRange = 40f;
// ─── Behaviour ───────────────────────────────────────────────────────
/// <summary>Idle wander around the stonecutter. Half the leash, so it never idles onto it.</summary>
private const float WanderRange = 10f;
/// <summary>
/// The station's m_name, read off the stonecutter prefab once at registration.
///
/// It is NOT the prefab name: CraftingStation.HaveBuildStationInRange compares against
/// m_name, which is a localisation token, while Jotunn's PieceConfig.CraftingStation wants the
/// prefab name. Both spellings are needed and they are not the same string, which is exactly
/// the kind of thing worth reading off the game once instead of guessing at twice.
/// </summary>
private static string StationName = "$piece_stonecutter";
public static void Register()
{
CacheStationName();
if (!RegisterGolem()) return;
RegisterSeedPiece();
PieceDensityLimit.RegisterGate(SeedPieceName, MayRaise);
}
private static void CacheStationName()
{
GameObject station = PrefabManager.Cache.GetPrefab<GameObject>(StationPrefab);
CraftingStation component = station != null ? station.GetComponent<CraftingStation>() : null;
if (component == null || string.IsNullOrEmpty(component.m_name))
{
Jotunn.Logger.LogWarning($"[Skadi] Could not read the stonecutter's station name off " +
$"'{StationPrefab}'; falling back to '{StationName}'.");
return;
}
StationName = component.m_name;
}
// ---------------------------------------------------------------- the golem
/// <summary>
/// A vanilla stone golem, tamed, frozen over, and made incapable of the three things it must
/// never do.
///
/// Health, damage and resistances stay exactly as vanilla has them. A mountain golem is a slow
/// wall with a great deal of health, which is precisely what a defender that cannot leave its
/// circle should be - there is nothing to retune, and nothing here does.
///
/// What IS written over:
/// - it does not sleep. Vanilla golems start as rocks and wake when something comes near;
/// a guard that has to be woken up is not a guard.
/// - it does not target player-built anything (m_attackPlayerObjects). That is the first
/// half of "never attacks structures"; the second half is the WearNTear guard below,
/// because an area attack aimed at a greydwarf can still land on a wall.
/// - it does not flee. A golem holds its ground or it dies on it.
/// - it gives up a chase past its leash, measured from its own spawn point, which
/// SkadiGolemGuard pins to the stonecutter. That is vanilla's own leash, used as intended
/// rather than reimplemented.
/// - it drops nothing. Two golems per stonecutter that could be farmed for crystals and
/// trophies would be a mint, and the trophy is this chain's own gate item.
/// It never attacks tamed creatures or players for free: Attack.DoMeleeAttack only lets a
/// tamed attacker through to targets its own AI counts as enemies, which is checked in the
/// game's code rather than assumed here.
/// </summary>
private static bool RegisterGolem()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(GolemName, SourceGolem);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourceGolem}; {DisplayName} not registered.");
return false;
}
Character character = prefab.GetComponent<Character>();
if (character != null) character.m_name = DisplayName;
SkadiIce.Apply(prefab);
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null)
{
ai.m_randomMoveRange = WanderRange;
ai.m_avoidWater = true;
}
MonsterAI monster = prefab.GetComponent<MonsterAI>();
if (monster != null)
{
monster.m_sleeping = false;
monster.m_attackPlayerObjects = false;
// It notices what comes into the circle it defends, and nothing outside it. Being
// hit still turns it around - OnDamaged sets a target whatever the alert range says -
// which is the difference between a defender and a statue.
monster.m_alertRange = LeashRange;
monster.m_maxChaseDistance = LeashRange;
monster.m_fleeIfLowHealth = 0f;
monster.m_fleeIfNotAlerted = false;
monster.m_fleeIfHurtWhenTargetCantBeReached = false;
}
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
foreach (Procreation breeding in prefab.GetComponentsInChildren<Procreation>(true))
{
if (breeding != null) Object.DestroyImmediate(breeding);
}
// "Ten seconds unhurt, then 2% a second" - the Skeleton's sentry regeneration, which three
// chains now share. A guard that cannot heal between raids is a guard you rebuild.
prefab.AddComponent<SkeletonSentryBehaviour>();
prefab.AddComponent<SkadiGolemGuard>();
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Skadi] {GolemName} from '{SourceGolem}': awake, tame, leashed, " +
"blind to structures, drops nothing.");
return true;
}
// ---------------------------------------------------------------- the seed piece
/// <summary>
/// The hammer entry, and the same trick SkeletonSentry uses for the same reason: the hammer
/// builds Piece, a golem is a Character, so a piece is placed and swaps itself for one.
/// </summary>
private static void RegisterSeedPiece()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SeedPieceName, SourcePiece);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePiece}; {DisplayName} cannot be built.");
return;
}
// Everything the ward does goes - PrivateArea and its effect areas above all. What is
// wanted is a placeable shell with the right outline, alive for one frame.
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);
}
AswidBloodRefinery.StripOffensive(prefab, SeedPieceName);
SkadiIce.Apply(prefab);
prefab.AddComponent<SkadiGolemSeed>();
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_resources = new Piece.Requirement[0];
piece.m_name = DisplayName;
piece.m_canBeRemoved = true;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = BorrowIcon(CrystalItem);
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = DisplayName,
Description = "$rov_piece_skadi_crystalgolem_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
// The stonecutter is the station, so vanilla itself refuses to place one anywhere its
// golem could not then be bound - the gate below never has to be the first to say no.
CraftingStation = CraftingStations.Stonecutter,
Icon = BorrowIcon(CrystalItem),
Requirements = new[]
{
new RequirementConfig(GolemTrophy, 1, 0, true),
new RequirementConfig(CrystalItem, CrystalCost, 0, true),
new RequirementConfig(ModerDrop, 1, 0, true),
}
}));
}
// ---------------------------------------------------------------- the gate
/// <summary>
/// The two caps that cannot live on the golem, asked at the moment of building.
///
/// Order matters: race, then boss, then the stonecutter, then its own two, so the first thing
/// a player is told is the thing they can actually do something about.
///
/// HONEST LIMIT, inherited from PieceDensityLimit and worth repeating: the counts are over
/// ZDOs, which on a remote client are only the ZDOs the server has sent. On the host they are
/// exact. Where a count cannot be taken at all the placement is allowed - refusing on no
/// information is worse than a cap that occasionally misses.
/// </summary>
public static bool MayRaise(Player player, Vector3 position)
{
if (player == null) return true;
if (!SkadiRace.IsLocalSkadi())
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_stone_does_not_answer"));
return false;
}
if (BossProgressionManager.GetCurrentProgressionState() < ModerProgressionState)
{
player.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_skadi_tear_cold_nothing_wakes_stone"));
return false;
}
CraftingStation station = FindStonecutter(position);
if (station == null)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_needs_stonecutter_cut_at"));
return false;
}
int bound = CountBoundTo(station.transform.position);
if (bound >= MaxPerStation)
{
player.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_skadi_that_stonecutter_already_holds_will", bound));
return false;
}
int nearby = PieceDensityLimit.Count(GolemName, position, PieceDensityLimit.RadiusForArea(DensityAreaKm2));
if (nearby >= MaxInArea)
{
player.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_skadi_there_are_already_these_within", nearby));
return false;
}
return true;
}
/// <summary>
/// The stonecutter that owns a point, by the station's OWN build range rather than by a number
/// of ours - so the circle a golem may be cut in and the circle it may stand in are the same
/// circle, and stay the same if a game update retunes the station.
/// </summary>
public static CraftingStation FindStonecutter(Vector3 position)
{
return CraftingStation.HaveBuildStationInRange(StationName, position);
}
/// <summary>True if a stonecutter still stands at that exact point.</summary>
public static bool StonecutterStandsAt(Vector3 position)
{
return CraftingStation.FindClosestStationInRange(StationName, position, StationCheckRange) != null;
}
/// <summary>
/// How many golems already answer to the stonecutter at that point, counted over ZDOs and not
/// over loaded creatures.
///
/// That distinction is the whole cap: a golem in an unloaded zone is still a golem, and
/// counting only what is loaded would make walking away and coming back the way to hold six.
/// Dead ones are gone from the world entirely, so a slot frees itself with no bookkeeping.
/// </summary>
public static int CountBoundTo(Vector3 station)
{
List<ZDO> zdos = new List<ZDO>();
if (!PieceDensityLimit.Gather(GolemName, zdos)) return 0;
int count = 0;
foreach (ZDO zdo in zdos)
{
if (zdo == null) continue;
// A generous epsilon: a station never moves, so this only has to survive float
// round-tripping through the ZDO.
Vector3 anchor = zdo.GetVec3(SkadiGolemGuard.KeyAnchor, Vector3.zero);
if (anchor != Vector3.zero && Vector3.SqrMagnitude(anchor - station) < 0.25f) count++;
}
return count;
}
// ---------------------------------------------------------------- known pieces
/// <summary>
/// Learnt by being Skadi, and not by having killed Moder.
///
/// Deliberate: the entry shows up greyed out with its price on it, which is how every vanilla
/// recipe tells you what to go and get. Gating the entry itself on the boss would hide it
/// until a relog anyway - OnSpawned is the only moment this is asked - so the boss check lives
/// where it can be asked every time instead, in MayRaise.
/// </summary>
public static void EnsureKnown(Player player)
{
if (player == null || !SkadiRace.IsLocalSkadi()) return;
GameObject prefab = PrefabManager.Instance.GetPrefab(SeedPieceName);
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;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
Jotunn.Logger.LogWarning($"[Skadi] Could not borrow the icon from '{prefabName}'.");
return null;
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class SkadiGolemKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
SkadiGolem.EnsureKnown(__instance);
}
}
/// <summary>
/// The second half of "it never attacks structures".
///
/// m_attackPlayerObjects stops a golem CHOOSING a wall as a target; it does not stop one landing a
/// swing on the wall behind a greydwarf, because Attack.DoMeleeAttack has no tamed check on the
/// destructible path at all - only on the character one. Read off the game's own code rather than
/// assumed, and it is why this patch exists instead of one field being trusted to do both jobs.
///
/// The signature is spelled out and bound positionally for the reason PieceDensityLimitPatch
/// carries in its own comment: Damage returns VOID, so a prefix returning false is the whole
/// mechanism, and asking for a __result on a void method throws at patch time and takes the rest
/// of the mod's patches down with it.
/// </summary>
[HarmonyPatch(typeof(WearNTear), "Damage", new[] { typeof(HitData) })]
public static class SkadiGolemStructureGuardPatch
{
public static bool Prefix(HitData __0)
{
if (__0 == null) return true;
Character attacker = __0.GetAttacker();
return attacker == null || attacker.GetComponent<SkadiGolemGuard>() == null;
}
}
}