RacesOfValheim/JotunnModStub/Draugh/DraughSpawner.cs
kanym 916ba5bd6f fix(pieces): placement ghost vanished off terrain for most stations
Eleven pieces set m_groundPiece. Player.UpdatePlacementGhost switches
the ghost off outright and returns whenever the aim is not on a
Heightmap, which vanilla means for hoe and cultivator pieces. Floors,
rocks and a troll cave's mesh floor are not a Heightmap, so players
saw no ghost at all there, and with either flag Valheim never shows
the blue placement marker. Reported for the Trol War Totem.

m_groundPiece is off everywhere now. The stations (War Totem, Cursed
Body Pile, Dvergar Bank, Rune Barrel, Pack Trough, Skadi Golem, Bone
Servants) drop m_groundOnly too and go on floors, foundations and in
caves, like the Bone Pile since 1.5.8. The living pieces (Furling
bushes, Sverm nest and Hive Market, Trenta Elder Root) keep
m_groundOnly: terrain only, and the ghost shows red elsewhere.
2026-10-17 15:59:08 +02:00

339 lines
17 KiB
C#

using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Draugh station: a smaller, green body pile that eats raw flesh and answers with tamed
/// draugr. Third of the per-race station chains, after the Aswid's Blood Refinery and the
/// Trenta's Composter, and it takes its input rules straight from the second one - 100 units of
/// flesh valued by <see cref="AswidBloodRefinery.FleshValue"/>, one batch, one draugr.
///
/// What makes it a Draugh thing rather than a piece of furniture anyone can use: the pile itself
/// works for whoever built it, but the draugr only take ORDERS from a Draugh. Anyone else gets a
/// grave that defends its own ten metres; a Draugh gets an escort. That asymmetry is the design,
/// not a limitation.
///
/// Two special inputs, both of them draugr remains, because the pile is not fussy about where the
/// meat comes from: a Draugr trophy is worth a whole batch, and an Elite trophy is worth an elite
/// outright once the pile has been upgraded to hold any.
/// </summary>
public static class DraughSpawner
{
// ─── Names ───────────────────────────────────────────────────────────
public const string PieceName = "DraughBodyPile";
public const string PieceDisplayName = "$rov_piece_draugh_bodypile_name";
public const string BoneName = "CursedBone";
public const string BoneDisplayName = "$rov_item_draugh_cursedbone_name";
public const string GreaterBoneName = "GreaterCursedBone";
public const string GreaterBoneDisplayName = "$rov_item_draugh_greatercursedbone_name";
public const string ThrallName = "DraughThrall_Draugr";
public const string ThrallEliteName = "DraughThrall_DraugrElite";
public const string ThrallDisplayName = "$rov_creature_draugh_thrall_name";
public const string ThrallEliteDisplayName = "$rov_creature_draugh_thrallelite_name";
// RaisedThrall groups by kind for follower caps and for the roster, so these are the strings
// that decide "is this one an officer" - no longer a display-name comparison.
public const string KindNormal = "DraughDraugr";
public const string KindElite = "DraughDraugrElite";
public const string RaceId = "Draugh";
// The two trophies the pile accepts in place of meat.
public const string TrophyDraugr = "TrophyDraugr";
public const string TrophyDraugrElite = "TrophyDraugrElite";
// ─── Balance ─────────────────────────────────────────────────────────
// 100 units is one full Composter batch on the same FleshValue scale, which is deliberate:
// it makes a Draugr trophy (worth exactly one batch) the real currency and raw meat the
// fallback. A trophy drops from roughly one draugr in ten, so the pile is fed mostly by
// doing the thing it is thematically about.
public const float FleshPerThrall = 100f;
public const int AliveCap = 5;
public const int AliveCapUpgraded = 7; // +2 normals, as designed
public const int EliteCap = 0; // none at all until upgraded
public const int EliteCapUpgraded = 3;
public const int ReserveCap = 5;
public const int ReserveCapElite = 3;
// Local seconds, and only while the zone is loaded - see DraughSpawnerBehaviour.
public const float RespawnSeconds = 60f;
// How long a thrall outlives the pile that made it. The same minute as the respawn on
// purpose: the player learns one number and it reads as "this pile thinks in minutes".
//
// Not zero, which is what it used to be. Killing them on the spot closed the duplication
// exploit but read terribly - dismantle your own pile and ten bodies drop with no
// explanation - and it disarmed you mid-fight if a raid took the pile down while your
// escort was out with you. A minute is short enough that rebuilding elsewhere to keep the
// old thralls is not worth the walk, and the anchor check in RaisedThrall is what actually
// closes that door rather than the length of this timer.
//
// World time, not local: an orphan has to keep withering while its zone is unloaded, or
// walking away would be a way to keep a dead pile's army alive indefinitely.
public const float OrphanWitherSeconds = 60f;
// A thrall only asks "is my pile still standing?" when it is this close to home, because the
// answer can only be trusted where the pile would be loaded if it existed. Further out - out
// following its master, most of the time - the question is unanswerable and gets skipped.
// The leash is 10 m; this leaves room for one that has been knocked about.
public const float HomeCheckRange = 20f;
// How far a thrall strays from the pile when it is not following anybody. Written onto the
// clone's BaseAI.m_randomMoveRange, which is the radius vanilla's own patrol wandering uses.
public const float LeashRange = 10f;
// An escort, not a doomstack. The pile can hold ten; it can lend you four.
public const int MaxFollowers = 3;
public const int MaxEliteFollowers = 1;
// Upgrading is gated on the lord of the swamp dead rather than on money alone.
public const int UpgradeProgressionState = 4; // Bonemass
// ─── Density ─────────────────────────────────────────────────────────
// Five piles per 1.6 square kilometres, enforced by PieceDensityLimit. For scale, a Valheim
// zone is 64 m square, so 1.6 km2 is a disc about 22 zones across - big enough that five
// piles is a regional army rather than base decoration.
public const int MaxPilesInRange = 5;
public const float DensityAreaKm2 = 1.6f;
// ─── Looks ───────────────────────────────────────────────────────────
// Bigger than the vanilla pile, not smaller. The first pass went to 0.8 on the assumption that
// a buildable wants to be unobtrusive; in game it read as a scrap heap rather than as something
// that raises the dead. 1.2 gives it the presence the feature deserves.
private const float ModelScale = 1.2f;
// Green, and far enough from the vanilla pile's brown-grey to be told apart across a swamp.
private static readonly Color PileTint = new Color(0.22f, 0.52f, 0.24f, 1f);
private static readonly Color BoneTint = new Color(0.35f, 0.45f, 0.30f, 1f);
private static readonly Color GreaterBoneTint = new Color(0.20f, 0.55f, 0.25f, 1f);
public static void Register()
{
RegisterBone(BoneName, BoneDisplayName, BoneTint,
"$rov_item_draugh_cursedbone_desc");
RegisterBone(GreaterBoneName, GreaterBoneDisplayName, GreaterBoneTint,
"$rov_item_draugh_greatercursedbone_desc");
RegisterThrall(ThrallName, "Draugr", ThrallDisplayName, KindNormal, MaxFollowers);
RegisterThrall(ThrallEliteName, "Draugr_Elite", ThrallEliteDisplayName, KindElite, MaxEliteFollowers);
RegisterPiece();
PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange,
"rov_msg_build_limit_draugh_bodypile");
}
// ---------------------------------------------------------------- items
private static void RegisterBone(string prefabName, string displayName, Color tint, string description)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "BoneFragments");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Draugh] Could not clone BoneFragments; {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));
}
// ---------------------------------------------------------------- thralls
/// <summary>
/// A draugr that is born tame and on a leash.
///
/// Cloned rather than tamed in place so the leash range, the name and the loot table are the
/// prefab's own business and no vanilla draugr is touched. Its CharacterDrop is destroyed
/// outright: a conjured corpse leaves nothing behind. Without that, killing your own thralls
/// would farm the entrails and bone fragments this whole chain is built out of - and, at a one
/// in ten trophy rate, hand back a slice of the flesh that paid for it.
/// </summary>
private static void RegisterThrall(string prefabName, string source, string displayName,
string kind, int maxFollowers)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Draugh] 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)
{
// The radius vanilla's own patrol wandering keeps to around m_patrolPoint, which
// RaisedThrall pins to the pile.
ai.m_randomMoveRange = LeashRange;
}
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; // only a Draugh may give these orders
thrall.m_maxFollowers = maxFollowers;
thrall.m_witherSeconds = OrphanWitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = "$rov_msg_thrall_refusal_draugh";
PrefabManager.Instance.AddPrefab(prefab);
}
// ---------------------------------------------------------------- piece
private static void RegisterPiece()
{
// Spawner_DraugrPile is the visible, destructible body pile of the swamps - the only one
// of the seven Spawner_Draugr* prefabs with hit and destruction effects of its own, which
// is what says it has a model rather than being a world-generation spawn point.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "Spawner_DraugrPile");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Draugh] Could not clone Spawner_DraugrPile; the body pile is not registered.");
return;
}
// The vanilla pile's whole job is spawning hostile draugr on a timer at anyone who walks
// past. Every bit of that goes: what it produces, when, and for whom is ours now.
foreach (SpawnArea area in prefab.GetComponentsInChildren<SpawnArea>(true))
{
if (area != null) Object.DestroyImmediate(area);
}
// Same belt as the Composter: a bone pile carries nothing that shoots, but the eitr
// refinery taught this codebase not to assume. A silent log is the proof.
AswidBloodRefinery.StripOffensive(prefab, PieceName);
DraughSpawnerBehaviour behaviour = prefab.AddComponent<DraughSpawnerBehaviour>();
// One interaction point, as on the Composter: what is in your hand decides what the click
// means. Any Switch the prefab happened to carry goes first so it cannot win the hover
// from a child collider - the components only, never their colliders.
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;
// 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 = BorrowIcon(TrophyDraugr);
// Learned on the Furling's bushes: a Piece added to world scenery is born with no icon
// and no place effect, and a null icon is a blank, unclickable square in the build menu.
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 = "$rov_piece_draugh_bodypile_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon(TrophyDraugr),
Requirements = new[]
{
new RequirementConfig(BoneName, 1, 0, true),
new RequirementConfig("Entrails", 10, 0, true),
new RequirementConfig("BoneFragments", 20, 0, true),
}
}));
}
/// <summary>
/// Same reason as the Composter's and the Furling's: a piece registered after the vanilla
/// learning pass never reaches the hammer on its own. The purchased Cursed Bone is the gate.
/// </summary>
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($"[Draugh] 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 DraughSpawnerKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
DraughSpawner.EnsureKnown(__instance);
}
}
}