RacesOfValheim/JotunnModStub/Butler/BoneServant.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

292 lines
14 KiB
C#

using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The two Bone Servants and their tables. Servants that work the stations around them and never
/// lift a hand against anything.
///
/// TWO TRADES, and that was the first thing the working version asked for. One servant serving a
/// whole yard spends its life walking: with the kitchen at one edge of the circle and the furnaces
/// at the other, travel eats the margin that keeps food off the fire. So there is a SMITH for the
/// Smelter family and a COOK for cooking stations and mead, each with its own table, each with its
/// own twenty-metre circle - and the two circles may sit on top of each other, because the servants
/// never look at the same station. PieceDensityLimit counts by prefab name, so "no second table
/// within forty metres" keeps smith away from smith and cook away from cook, and needed no change
/// at all to let a smith and a cook stand side by side.
///
/// The smith keeps the ORIGINAL prefab names, BoneServant and ServantTable. That is not tidiness -
/// it means a table already standing in a test world keeps working and keeps its servant instead of
/// becoming a missing prefab at the next load.
///
/// TWO PREFABS EACH, forced the same way the sentry's are: a Character cannot sit in the hammer's
/// piece table, so the buildable thing is the table and the servant is instantiated by it. Unlike
/// the sentry there is no seed piece to throw away, because here the table is not scaffolding - it
/// is the anchor, the summoning point and the only interface the feature has.
///
/// WHAT WAS DELIBERATELY NOT REUSED. The design said the servant would be a RaisedThrall, and it is
/// not. RaisedThrall brings the anchor, the leash and the withering, all of which are wanted - but
/// it also brings RaisedThrallInteractPatch, which turns E on the creature into a follow command.
/// A servant that can be told to follow you out of its own circle is a servant that stops serving,
/// and "E does nothing on the servant" was decided explicitly. So the useful half is reused as a
/// static - RaisedThrall.RegisterStation / StationStandsAt, which is what makes the table findable -
/// and the anchor and wither clock are thirty lines inside BoneServantAI. The alternative was
/// editing RaisedThrall.cs, which is shared with five other chains.
/// </summary>
public static class BoneServant
{
// The smith inherits the names the single servant had, so nothing already built is orphaned.
public const string SmithName = "BoneServant";
public const string SmithTableName = "ServantTable";
public const string SmithDisplay = "$rov_creature_bonesmith_name";
public const string SmithTableDisplay = "$rov_piece_smithtable_name";
public const string CookName = "BoneCook";
public const string CookTableName = "CookTable";
public const string CookDisplay = "$rov_creature_bonecook_name";
public const string CookTableDisplay = "$rov_piece_cooktable_name";
/// <summary>Vanilla's guaranteed-melee skeleton: the plain one rolls its own weapon, and the
/// point here is to have none at all.</summary>
private const string ServantSource = "Skeleton_NoArcher";
public const float Health = 100f;
/// <summary>Two circles of twenty metres cannot overlap if the tables are forty apart, which is
/// how the question of two servants of the SAME trade fighting over one chest was answered - by
/// making the situation impossible to build rather than by sharing state between them.</summary>
public const float TableSpacing = 40f;
private const float TableScale = 0.8f;
/// <summary>
/// One skull, one wishbone, eight stone - the same price for both tables.
///
/// The skull is TrophySkeleton and NOT this mod's own CursedSkull, and that is forced rather
/// than chosen: the cursed skull is bought from the Skeleton faction's merchant, so building it
/// into the cook's price would make the cook unbuildable by the only race allowed to build it.
/// A skeleton trophy is a skull anyone can go and get.
///
/// The wishbone is a real cost and worth knowing about: it is Bonemass's drop and the only
/// treasure-finder in the game, so a standing table keeps yours locked up. Recovered in full
/// when the table is removed, like every other recipe in this mod.
/// </summary>
private static RequirementConfig[] Recipe()
{
return new[]
{
new RequirementConfig("TrophySkeleton", 1, 0, true),
new RequirementConfig("Wishbone", 1, 0, true),
new RequirementConfig("Stone", 8, 0, true),
};
}
public static void Register()
{
if (RegisterServant(SmithName, SmithDisplay, ButlerFamily.Forge))
{
RegisterTable(SmithTableName, SmithTableDisplay, SmithName, ButlerFamily.Forge,
"$rov_piece_smithtable_desc",
"Coal");
PieceDensityLimit.Register(SmithTableName, TableSpacing, 1,
"rov_msg_build_limit_smithtable");
// Two races, and it is the wider of the two locks: the Skeleton raises the dead to work
// for it, and Skadi's hold is a forge under ice.
PieceDensityLimit.RegisterGate(SmithTableName, (player, position) =>
{
if (SkeletonRace.IsSkeleton() || SkadiRace.IsLocalSkadi()) return true;
if (player != null)
{
player.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_butler_bones_do_not_answer_blood"));
}
return false;
});
}
if (RegisterServant(CookName, CookDisplay, ButlerFamily.Kitchen))
{
RegisterTable(CookTableName, CookTableDisplay, CookName, ButlerFamily.Kitchen,
"$rov_piece_cooktable_desc",
"CookedMeat");
PieceDensityLimit.Register(CookTableName, TableSpacing, 1,
"rov_msg_build_limit_cooktable");
// Skadi alone. A hearth kept by something dead is hers, not the Skeleton's.
PieceDensityLimit.RegisterGate(CookTableName, (player, position) =>
{
if (SkadiRace.IsLocalSkadi()) return true;
if (player != null)
{
player.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_butler_only_skadi_s_hearth_kept"));
}
return false;
});
}
}
// ---------------------------------------------------------------- the servants
private static bool RegisterServant(string prefabName, string displayName, ButlerFamily family)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, ServantSource);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Butler] Could not clone {ServantSource}; " +
$"{displayName} is not registered.");
return false;
}
Character character = prefab.GetComponent<Character>();
if (character != null)
{
character.m_name = displayName;
character.m_health = Health;
character.m_faction = Character.Faction.Players;
}
// Nothing in its hands, and nothing to roll for. Belt and braces with the AI prefix: the
// code that would swing a weapon never runs, but a servant carrying a rusty sword around
// the kitchen would still look like a mistake.
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid != null)
{
humanoid.m_defaultItems = new GameObject[0];
humanoid.m_randomWeapon = new GameObject[0];
humanoid.m_randomArmor = new GameObject[0];
humanoid.m_randomShield = new GameObject[0];
humanoid.m_randomSets = new Humanoid.ItemSet[0];
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null)
{
ai.m_randomMoveRange = 0f; // it never wanders: every step it takes is a decision
ai.m_avoidFire = false; // it works next to kilns for a living
ai.m_afraidOfFire = false;
}
// A servant that dropped bones would be a bone mill, exactly as with the garrison.
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
// Ten seconds unhurt, then two percent a second. The sentry's regeneration, whole.
prefab.AddComponent<SkeletonSentryBehaviour>();
BoneServantAI servant = prefab.AddComponent<BoneServantAI>();
servant.m_family = family;
PrefabManager.Instance.AddPrefab(prefab);
return true;
}
// ---------------------------------------------------------------- the tables
private static void RegisterTable(string pieceName, string displayName, string servantPrefab,
ButlerFamily family, string description, string iconSource)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, "piece_cartographytable");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Butler] Could not clone piece_cartographytable; " +
$"the {displayName} is not registered.");
return;
}
// The MapTable trap, and it is the reason this is a blanket sweep by capability rather than
// a named DestroyImmediate: MapTable is Interactable AND Hoverable, so it takes the E key
// before our own Switch ever sees it and opens the shared map instead. Same bug as the
// barrel's Container on the Fenrir trough and the Trader on the vanilla wolf; the Dvergar
// contract bank pays for this lesson already.
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);
}
prefab.transform.localScale = Vector3.one * TableScale;
ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>();
table.m_switch = prefab.AddComponent<Switch>();
table.m_switch.m_name = displayName;
table.m_title = displayName;
table.m_servantPrefab = servantPrefab;
table.m_family = family;
Sprite icon = BorrowIcon(iconSource) ?? BorrowIcon("TrophySkeleton");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
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 = icon;
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 = displayName,
Description = description,
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = icon,
Requirements = Recipe(),
}));
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
Traverse traverse = Traverse.Create(player);
LearnPiece(traverse, SmithTableName);
LearnPiece(traverse, CookTableName);
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
private static void LearnPiece(Traverse player, string pieceName)
{
GameObject prefab = PrefabManager.Instance.GetPrefab(pieceName);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) return;
player.Method("AddKnownPiece", piece).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 BoneServantKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
BoneServant.EnsureKnown(__instance);
}
}
}