RacesOfValheim/JotunnModStub/Butler/BoneServant.cs
kanym 35476eb8ef feat: chainmail over the map on the Smith's Table
The smith goes back to the cartography table, like the cook. Its map is
painted over with 4-in-1 mail by scripts/paint_smith_mail.py at 512 px:
colour, rusted worn colour, a normal map from the rings' height and a
metallic map so they shine. Both tables now share one Dress/LayCover path.
2026-10-28 13:47:49 +01:00

356 lines
18 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;
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, in the table's own space BEFORE TableScale, so sizes are divided by it to come out
// in real metres. The cover lies where the map was: x -2.06 to 0.62, read off the mesh. Its top
// is the Dvergar bank's PileHeight, on the same vanilla mesh; the mesh's own height is no use
// here, since the writing desk stands taller than the map.
private const float CoverTop = 1.05f;
private static readonly Vector3 TradeSpot = new Vector3(-0.75f, CoverTop, 0.2f);
private static readonly Vector3 SkullSpot = new Vector3(-1.55f, CoverTop, 0.35f);
private const float AnvilSize = 0.75f;
private const float MealSize = 0.6f;
private const float SkullSize = 0.45f;
/// <summary>
/// The map painted over - a sheet of chainmail for the smith, a red and white tablecloth for the
/// cook - with the trade's own work on it (an anvil, a meal) and a skeleton's skull beside it.
/// </summary>
private static void Dress(GameObject prefab, ButlerFamily family)
{
bool forge = family == ButlerFamily.Forge;
LayCover(prefab, forge ? "SmithMail" : "CookCloth", metal: forge);
float metres = 1f / TableScale;
if (forge)
{
ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2",
TradeSpot, Quaternion.identity, AnvilSize * metres, "Butler", activeOnly: true);
}
else
{
ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter",
TradeSpot, Quaternion.identity, MealSize * metres, "Butler", activeOnly: true);
}
ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton",
SkullSpot, Quaternion.Euler(0f, -150f, 0f), SkullSize * metres, "Butler", activeOnly: true);
}
/// <summary>
/// The cartography table's own textures with the map painted over, offline:
/// scripts/paint_cook_cloth.py (CookCloth) and scripts/paint_smith_mail.py (SmithMail). Each set
/// has its own worn texture for a damaged table (a stained cloth, rusted mail) and its own normal
/// map, so the coastline's relief does not show through. The mail also brings a metallic map,
/// which is what makes the rings shine; the cloth keeps vanilla's, which is metal nowhere.
/// </summary>
private static void LayCover(GameObject prefab, string set, bool metal)
{
var cover = new System.Collections.Generic.Dictionary<string, Texture>();
AddCover(cover, "Cartographer_d", set + "_d.png", false);
AddCover(cover, "Cartographer_worn_d", set + "_worn_d.png", false);
AddCover(cover, "Cartographer_n", set + "_n.png", true);
if (metal) AddCover(cover, "Cartographer_m", set + "_m.png", true);
PieceLook.Retexture(prefab.transform, cover);
}
private static void AddCover(System.Collections.Generic.Dictionary<string, Texture> cover,
string vanilla, string resource, bool linear)
{
Texture2D texture = PieceLook.LoadTexture(resource, linear);
if (texture != null) cover[vanilla] = texture;
}
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);
}
}
}