feat(skeleton): bound bone pile and bound sentry

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Ferdinando 2026-08-07 17:02:35 +02:00
commit b67a324cb8
5 changed files with 1077 additions and 1 deletions

View file

@ -0,0 +1,383 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Skeleton station: a bone pile from the crypts that raises a standing garrison.
///
/// Same family as the Draugh's body pile and it shares that feature's whole thrall layer
/// (<see cref="RaisedThrall"/>), but the economy is the opposite way round on purpose. The Draugh
/// pays per draugr out of a reserve that empties; the Skeleton pays ONCE PER SLOT and that slot
/// then refills itself forever. Skeletons are fragile - a troll or a drake clears the whole line
/// in one swing - so an army you have to re-buy after every fight is an army nobody would take
/// out of the house.
///
/// That permanent slot is also, by itself, the "skeletons leave exactly the materials that made
/// them" idea: the bones are not dropped and re-fed, they simply get up again. Nothing is
/// generated, nothing is consumed, and the same twenty fragments stand back up as many times as
/// they are knocked down. It needs no death hook and no drop table - which is why the thralls have
/// their CharacterDrop stripped like the Draugh's, rather than filled in.
///
/// Two differences from the Draugh worth stating because they are deliberate, not oversights:
/// - a destroyed pile kills its garrison INSTANTLY, where a body pile gives its draugr a minute.
/// Free perpetual regeneration is the trade for a hard off switch.
/// - melee and ranged are the same vanilla creature with different hands. There is no ranged
/// skeleton prefab: Skeleton_NoArcher is vanilla's own guaranteed-melee variant, and the
/// archer is a plain Skeleton whose loadout is forced to the bow.
/// </summary>
public static class SkeletonBonePile
{
// ─── Names ───────────────────────────────────────────────────────────
public const string PieceName = "SkeletonBonePile";
public const string PieceDisplayName = "Bound Bone Pile";
// The Soul Stone: a green ruby, sold by the Skeleton bench, and the thing that binds a skull and
// ten fragments into a sentry that cannot walk. Cheap on purpose - 50 coins - because the real
// cost of a sentry is the skull, which has to be taken off a skeleton rather than bought.
public const string SoulStoneName = "SoulStone";
public const string SoulStoneDisplayName = "Soul Stone";
public const int SoulStonePrice = 50;
private static readonly Color SoulStoneTint = new Color(0.15f, 0.85f, 0.35f, 1f);
public const string SkullName = "CursedSkull";
public const string SkullDisplayName = "Cursed Skull";
public const string GreaterSkullName = "GreaterCursedSkull";
public const string GreaterSkullDisplayName = "Greater Cursed Skull";
public const string ThrallMeleeName = "SkeletonThrall_Melee";
public const string ThrallRangedName = "SkeletonThrall_Ranged";
public const string ThrallRancidName = "SkeletonThrall_Rancid";
public const string ThrallMeleeDisplay = "Bound Skeleton";
public const string ThrallRangedDisplay = "Bound Archer";
public const string ThrallRancidDisplay = "Bound Rancid Remains";
public const string KindMelee = "SkeletonMelee";
public const string KindRanged = "SkeletonRanged";
public const string KindRancid = "SkeletonRancid";
public const string RaceId = "Skeleton";
/// <summary>The one material a slot is bought with. Fixed, not a fungible bone tank - see the
/// class comment on why "exactly the materials that made them" needs a recipe.</summary>
public const string BonePrefab = "BoneFragments";
public const int BonesPerSlot = 20;
/// <summary>Buys a Rancid slot outright, the way an Elite trophy buys the Draugh an officer.</summary>
public const string RancidTrophy = "TrophySkeletonPoison";
// ─── Balance ─────────────────────────────────────────────────────────
public const int MeleeSlots = 4;
public const int RangedSlots = 4;
public const int MeleeSlotsUpgraded = 5;
public const int RangedSlotsUpgraded = 5;
public const int RancidSlots = 0; // none at all until upgraded
public const int RancidSlotsUpgraded = 2;
// Local seconds, and only while the zone is loaded - a garrison should not quietly rebuild
// itself in an unloaded zone. Faster once upgraded: the pile gets better at it.
public const float RespawnSeconds = 20f;
public const float RespawnSecondsUpgraded = 15f;
// NOT the "instant" from the design conversation - that lives in the pile's OnDestroyed, which
// calls Kill() on the spot. This number only governs the FALLBACK: a skeleton that was in an
// unloaded zone when the pile fell and finds nothing at home when it loads again.
//
// It was 0, and zero has no tolerance for a hiccup: a pile whose zone unloads for a moment
// while a skeleton at the boundary stays loaded reads as "no pile" and wipes the garrison with
// no appeal. Five seconds costs nothing anyone can perceive - the deliberate destruction path
// is still immediate - and it means one bad frame is not a wipe.
public const float OrphanWitherSeconds = 5f;
public const float HomeCheckRange = 20f;
public const float LeashRange = 10f;
// No cap: the whole point of the new command is that the garrison moves as one.
public const int MaxFollowers = -1;
// A Rancid Remains clicked directly takes five of the rank and file with it, instead of the
// whole line the pile would send. Its own squad, and small enough that it stays a squad.
public const int RancidEscort = 5;
public const int UpgradeProgressionState = 4; // Bonemass, same gate as the Draugh's officers
public const int MaxPilesInRange = 5;
public const float DensityAreaKm2 = 1.6f;
// ─── Looks ───────────────────────────────────────────────────────────
private const float ModelScale = 1.2f;
// Cold bone-white, so it never reads as the Draugh's green pile at a glance.
private static readonly Color PileTint = new Color(0.82f, 0.84f, 0.78f, 1f);
private static readonly Color SkullTint = new Color(0.78f, 0.80f, 0.74f, 1f);
private static readonly Color GreaterSkullTint = new Color(0.62f, 0.72f, 0.80f, 1f);
public static void Register()
{
RegisterSkull(SkullName, SkullDisplayName, SkullTint,
"A skull that keeps counting. Set it down and the ground starts answering.");
RegisterSkull(GreaterSkullName, GreaterSkullDisplayName, GreaterSkullTint,
"Older, and it counts higher. A pile given one of these raises the rotten too.");
RegisterSoulStone();
RegisterThrall(ThrallMeleeName, "Skeleton_NoArcher", ThrallMeleeDisplay, KindMelee, null);
RegisterThrall(ThrallRangedName, "Skeleton", ThrallRangedDisplay, KindRanged, "skeleton_bow");
RegisterThrall(ThrallRancidName, "Skeleton_Poison", ThrallRancidDisplay, KindRancid, null, RancidEscort);
RegisterPiece();
// The standing sentry. Registered after the archer it clones, so that prefab exists first.
SkeletonSentry.Register();
PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange,
"There are already {0} of these listening nearby. Take it further out.");
}
// ---------------------------------------------------------------- items
private static void RegisterSkull(string prefabName, string displayName, Color tint, string description)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "TrophySkeleton");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] Could not clone TrophySkeleton; {displayName} not registered.");
return;
}
Recolour(prefab, tint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = displayName;
shared.m_description = description;
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_weight = 1f;
shared.m_maxStackSize = 10;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
}
/// <summary>
/// A ruby, turned green. Cloned rather than tinted in place so real rubies keep being red, the
/// same discipline every other borrowed prefab in this project follows.
///
/// One caveat that always applies and is worth repeating on a gemstone: the tint reaches the
/// world and held models but NOT the inventory icon, because icons are atlas sprites and
/// repainting one produces an empty slot. In the inventory this reads as a ruby; the name and
/// the tooltip are what tell it apart. If that matters, borrow the icon of a green vanilla item
/// instead - it is one line.
/// </summary>
private static void RegisterSoulStone()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SoulStoneName, "Ruby");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Skeleton] Could not clone Ruby; Soul Stone not registered.");
return;
}
Recolour(prefab, SoulStoneTint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = SoulStoneDisplayName;
shared.m_description = "Something is still in there, and it is still angry. Bind it to a skull " +
"and it will stand watch as long as the bones hold.";
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_weight = 0.5f;
shared.m_maxStackSize = 20;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
}
// ---------------------------------------------------------------- thralls
/// <summary>
/// One kind of bound skeleton, born tame and leashed to its pile.
///
/// The weapon argument is what separates melee from ranged, because the distinction does not
/// exist at the prefab level: Skeleton_NoArcher is vanilla's guaranteed-melee variant, and a
/// plain Skeleton rolls its own weapon. Forcing m_defaultItems and clearing the random lists is
/// what makes an archer an archer every time instead of four times in eight.
///
/// CharacterDrop is destroyed for the same reason as the Draugh's, plus one of its own: a
/// garrison that regenerates for free and drops its bones on death would be a bone mill.
/// </summary>
private static void RegisterThrall(string prefabName, string source, string displayName,
string kind, string forcedWeapon, int escortCount = 0)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] Could not clone {source}; {displayName} not registered.");
return;
}
Character character = prefab.GetComponent<Character>();
if (character != null) character.m_name = displayName;
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = LeashRange;
if (forcedWeapon != null)
{
Humanoid humanoid = prefab.GetComponent<Humanoid>();
GameObject weapon = PrefabManager.Cache.GetPrefab<GameObject>(forcedWeapon);
if (humanoid != null && weapon != null)
{
humanoid.m_defaultItems = new[] { weapon };
humanoid.m_randomWeapon = new GameObject[0];
humanoid.m_randomSets = new Humanoid.ItemSet[0];
Jotunn.Logger.LogInfo($"[Skeleton] {prefabName}: loadout forced to '{forcedWeapon}'.");
}
else
{
Jotunn.Logger.LogWarning($"[Skeleton] {prefabName}: could not force '{forcedWeapon}'; " +
"it will roll a random weapon like a wild one.");
}
}
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = kind;
thrall.m_commandingRace = RaceId;
thrall.m_maxFollowers = MaxFollowers;
thrall.m_witherSeconds = OrphanWitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = "These bones answer only to their own kind.";
thrall.m_escortCount = escortCount;
PrefabManager.Instance.AddPrefab(prefab);
}
// ---------------------------------------------------------------- piece
private static void RegisterPiece()
{
// BonePileSpawner is the skeleton's own crypt spawner - the right base rather than a
// repainted body pile, and it already has hit and destruction effects of its own.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "BonePileSpawner");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Skeleton] Could not clone BonePileSpawner; the bone pile is not registered.");
return;
}
// Its whole vanilla job is throwing hostile skeletons at whoever walks past. All of it goes.
foreach (SpawnArea area in prefab.GetComponentsInChildren<SpawnArea>(true))
{
if (area != null) Object.DestroyImmediate(area);
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
SkeletonBonePileBehaviour behaviour = prefab.AddComponent<SkeletonBonePileBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
{
if (existing != null) Object.DestroyImmediate(existing);
}
behaviour.m_switch = prefab.AddComponent<Switch>();
behaviour.m_switch.m_name = PieceDisplayName;
prefab.transform.localScale = Vector3.one * ModelScale;
Recolour(prefab, PileTint);
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("TrophySkeleton");
// A Piece added to world scenery is born with no icon and no place effect - the Furling's
// bushes taught this the hard way, where the entry existed as a blank unclickable square.
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 = "Twenty fragments buy a place in the line. The one who fills it will keep standing up.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("TrophySkeleton"),
Requirements = new[]
{
new RequirementConfig(SkullName, 1, 0, true),
new RequirementConfig("BoneFragments", 30, 0, true),
new RequirementConfig("Ooze", 10, 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();
}
// ---------------------------------------------------------------- helpers
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($"[Skeleton] Could not borrow the icon from '{prefabName}'.");
return null;
}
private static void Recolour(GameObject root, Color tint)
{
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
foreach (Material material in renderer.materials)
{
if (material == null) continue;
material.color = tint;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
}
}
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class SkeletonBonePileKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
SkeletonBonePile.EnsureKnown(__instance);
SkeletonSentry.EnsureKnown(__instance);
}
}
}