RacesOfValheim/JotunnModStub/Butler/BoneServant.cs
kanym b3edb2aed1 feat: marble Bone Servant tables, bigger centred props, fix table hover name
The Smith's and Cook's Tables clone the black marble table: the
cartography table's map is baked into its texture. Anvil or meal and a
skull sit near the centre at the table's measured height. The bank loses
its lantern and its tankard grows. The servant table hover localizes its
title, which showed as a raw token once a servant stood there.
2026-10-28 13:22:56 +01:00

334 lines
16 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 string TableSource = "piece_blackmarble_table";
/// <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)
{
// The black marble table: "a slab of bone and slate". It was the cartography table once,
// whose map is baked into its own texture and could not be taken off.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, TableSource);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Butler] Could not clone {TableSource}; " +
$"the {displayName} is not registered.");
return;
}
// A blanket sweep by capability rather than a named DestroyImmediate. The cartography table
// taught it: its MapTable is Interactable AND Hoverable, so it took the E key before our own
// Switch ever saw it. The marble table carries nothing of the kind today, and the sweep
// keeps a future patch from adding one behind our back.
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);
}
Dress(prefab, family);
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;
// Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
// the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
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(),
}));
}
// The look. The marble table is 2.6 m by 1.5 m; both props sit either side of its centre, the
// trade's tool the bigger of the two. X and Z only: the height is the table's, measured.
private const float MarbleTableTop = 0.82f;
private static readonly Vector3 TradeSpot = new Vector3(-0.35f, 0f, 0f);
private static readonly Vector3 SkullSpot = new Vector3(0.6f, 0f, 0.1f);
private const float AnvilSize = 0.75f;
private const float MealSize = 0.6f;
private const float SkullSize = 0.45f;
/// <summary>
/// "A slab of bone and slate": the black marble table, with the trade's own work in the middle -
/// an anvil for the smith, a meal for the cook - and a skeleton's skull beside it.
/// </summary>
private static void Dress(GameObject prefab, ButlerFamily family)
{
// The table's own height off its own mesh, with vanilla's 0.82 m as the fallback. The mesh
// stands on the piece's origin, so its height IS the height of the top.
Transform model = prefab.transform.Find("new");
float top = model != null ? ModelBorrow.HeightOf(model.gameObject) : 0f;
if (top <= 0f) top = MarbleTableTop;
Vector3 up = Vector3.up * top;
ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton",
SkullSpot + up, Quaternion.Euler(0f, -150f, 0f), SkullSize, "Butler", activeOnly: true);
if (family == ButlerFamily.Forge)
{
ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2",
TradeSpot + up, Quaternion.identity, AnvilSize, "Butler", activeOnly: true);
}
else
{
ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter",
TradeSpot + up, Quaternion.identity, MealSize, "Butler", activeOnly: true);
}
}
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);
}
}
}