From b1f5da2249065e16af2884ed8c197a18d05b8413 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Fri, 7 Aug 2026 17:02:34 +0200 Subject: [PATCH] feat: shared foundations for stations and servants RaisedThrall is the common servant base (leash, wither timer, follow command, anchor), used by Draugh, Skeleton and Trol. ModelBorrow lends a vanilla prefab's look without its behaviour. PieceDensityLimit caps how many of a piece fit in an area. Co-Authored-By: Claude Opus 5 --- JotunnModStub/ModelBorrow.cs | 189 +++++++++++ JotunnModStub/PieceDensityLimit.cs | 147 +++++++++ JotunnModStub/RaisedThrall.cs | 491 +++++++++++++++++++++++++++++ 3 files changed, 827 insertions(+) create mode 100644 JotunnModStub/ModelBorrow.cs create mode 100644 JotunnModStub/PieceDensityLimit.cs create mode 100644 JotunnModStub/RaisedThrall.cs diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs new file mode 100644 index 0000000..097f44d --- /dev/null +++ b/JotunnModStub/ModelBorrow.cs @@ -0,0 +1,189 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Borrowing a vanilla prefab's LOOK without borrowing anything it does. + /// + /// This exists because of a bug that shipped: the Trol's war totem mounted trophy models by calling + /// Instantiate and then stripping the components off the copy. Instantiate runs Awake FIRST, so for + /// one frame the copy was a real, live object - and a trophy is an ItemDrop, which means a giant + /// Yagluth head fell out of the sky every time the totem's ghost was drawn. + /// + /// For a world prop (the Trenta grove borrows a Yggdrasil shoot this way) the stray frame does + /// nothing visible, which is why the technique looked fine the first two times it was used. For + /// anything carrying ItemDrop, ZNetView or a Rigidbody it is a live object with physics. + /// + /// The fix is one line and it is the reason this is a shared helper rather than a third copy of the + /// same loop: instantiate into a holder that is ALREADY INACTIVE. Unity does not run Awake on a + /// component that comes up disabled, so the strip happens before anything can wake. + /// + /// SECOND ROUND: the borrowed model is now sized in METRES instead of by a multiplier, because a + /// multiplier against an unknown mesh is a guess and guesses shipped a Yagluth head three times + /// taller than the post it stood on. The mesh is measured and scaled to fit, and it is grounded so + /// the holder's origin is the model's BOTTOM CENTRE rather than whatever the item's author happened + /// to use as a pivot - which is what makes "put the head on top of the totem" a subtraction instead + /// of another guess. This is rule 3.2 of the house guide applied to geometry: a number that was + /// measured is already balanced. + /// + public static class ModelBorrow + { + /// + /// Hangs the renderers of a vanilla prefab under and returns the holder, + /// which the caller can switch on and off. Null-safe: a missing source logs and returns an empty + /// holder rather than throwing, so a wrong name costs a warning and not a startup. + /// + /// is where the model's BOTTOM CENTRE goes. + /// is how big its largest dimension should end up, in metres, + /// measured AFTER has been applied. + /// + public static GameObject Attach(Transform parent, string holderName, string sourcePrefab, + Vector3 localPosition, Quaternion localRotation, float targetSize, + string label) + { + GameObject holder = new GameObject(holderName); + holder.transform.SetParent(parent, false); + holder.transform.localPosition = localPosition; + + // BEFORE the Instantiate below. This single line is the whole point of the class. + holder.SetActive(false); + + GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab(sourcePrefab); + if (source == null) + { + Jotunn.Logger.LogWarning($"[{label}] No '{sourcePrefab}' to borrow a model from; nothing was attached."); + holder.SetActive(true); + return holder; + } + + GameObject copy = Object.Instantiate(source, holder.transform); + copy.name = "model"; + copy.transform.localPosition = Vector3.zero; + copy.transform.localRotation = localRotation; + copy.transform.localScale = Vector3.one; + + // Everything that is not a Renderer or a Transform. Order matters for the same reason it did + // on the Aswid's lights: behaviours first, then the things they hold references to. + foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) + { + if (behaviour != null) Object.DestroyImmediate(behaviour); + } + foreach (Collider collider in copy.GetComponentsInChildren(true)) + { + if (collider != null) Object.DestroyImmediate(collider); + } + foreach (Rigidbody body in copy.GetComponentsInChildren(true)) + { + if (body != null) Object.DestroyImmediate(body); + } + foreach (ZNetView nview in copy.GetComponentsInChildren(true)) + { + if (nview != null) Object.DestroyImmediate(nview); + } + + FitAndGround(copy.transform, holder.transform, targetSize, sourcePrefab, label); + + holder.SetActive(true); + return holder; + } + + /// + /// How tall the borrowed model actually turned out, in the holder's parent's space. Used to stack + /// one borrowed model on top of another without a magic offset. + /// + public static float HeightOf(GameObject holder) + { + if (holder == null) return 0f; + return TryMeasure(holder.transform, holder.transform, out Bounds bounds) ? bounds.size.y : 0f; + } + + // ---------------------------------------------------------------- measuring + + /// + /// Scales the copy so its largest dimension is metres, then slides it + /// so its bottom centre sits on the holder's origin. + /// + private static void FitAndGround(Transform copy, Transform holder, float targetSize, + string sourcePrefab, string label) + { + if (!TryMeasure(copy, holder, out Bounds raw)) + { + Jotunn.Logger.LogWarning($"[{label}] '{sourcePrefab}' has no readable mesh, so it could not be " + + "sized or grounded; it is attached at scale 1 and may sit wrong."); + return; + } + + float biggest = Mathf.Max(raw.size.x, Mathf.Max(raw.size.y, raw.size.z)); + if (biggest <= 0.0001f) + { + Jotunn.Logger.LogWarning($"[{label}] '{sourcePrefab}' measured as a point ({raw.size}); " + + "left at scale 1."); + return; + } + + float scale = targetSize / biggest; + copy.localScale = Vector3.one * scale; + + if (TryMeasure(copy, holder, out Bounds fitted)) + { + copy.localPosition = new Vector3(-fitted.center.x, -fitted.min.y, -fitted.center.z); + } + + Jotunn.Logger.LogInfo($"[{label}] Borrowed '{sourcePrefab}': measured {raw.size}, " + + $"scaled by {scale:0.###} to fit {targetSize} m, grounded on its own base."); + } + + /// + /// Bounds of every mesh under , expressed in 's local + /// coordinates. Read from sharedMesh rather than Renderer.bounds on purpose: the holder is INACTIVE + /// while this runs (that is the whole point of the class) and a renderer that has never been enabled + /// has no world bounds yet, so Renderer.bounds would quietly return zero. + /// + private static bool TryMeasure(Transform root, Transform space, out Bounds bounds) + { + bounds = new Bounds(); + bool any = false; + + Matrix4x4 toSpace = space.worldToLocalMatrix; + + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null) continue; + + Mesh mesh; + if (renderer is SkinnedMeshRenderer skinned) + { + mesh = skinned.sharedMesh; + } + else + { + MeshFilter filter = renderer.GetComponent(); + mesh = filter != null ? filter.sharedMesh : null; + } + if (mesh == null) continue; + + Encapsulate(ref bounds, ref any, toSpace * renderer.transform.localToWorldMatrix, mesh.bounds); + } + + return any; + } + + /// All eight corners, because a rotated box's bounds are not its centre plus its extents. + private static void Encapsulate(ref Bounds bounds, ref bool any, Matrix4x4 matrix, Bounds local) + { + Vector3 centre = local.center; + Vector3 extents = local.extents; + + for (int corner = 0; corner < 8; corner++) + { + Vector3 point = matrix.MultiplyPoint3x4(centre + new Vector3( + (corner & 1) == 0 ? -extents.x : extents.x, + (corner & 2) == 0 ? -extents.y : extents.y, + (corner & 4) == 0 ? -extents.z : extents.z)); + + if (!any) { bounds = new Bounds(point, Vector3.zero); any = true; } + else bounds.Encapsulate(point); + } + } + } +} diff --git a/JotunnModStub/PieceDensityLimit.cs b/JotunnModStub/PieceDensityLimit.cs new file mode 100644 index 0000000..024014f --- /dev/null +++ b/JotunnModStub/PieceDensityLimit.cs @@ -0,0 +1,147 @@ +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// "How many of these may stand in one region." One place, one patch, one line per station. + /// + /// Every station in the per-race item-progression system that produces something continuously has + /// to be capped, or five copies are five times the effect - a field of groves is a carpet of bees, + /// five body piles are fifty draugr. Each chain used to be expected to write its own placement + /// check; this exists so the five races still to come add a limit with one call instead of + /// re-deriving ZDO counting, and so there is exactly one Player.PlacePiece prefix rather than one + /// per race. + /// + /// Counting is done over ZDOs and not over loaded GameObjects, and that distinction is the whole + /// point: Valheim keeps only a handful of zones alive around the player, a few hundred metres at + /// most, so counting objects would let anyone dodge the cap by walking away and building again. + /// + /// HONEST LIMIT: a client only holds the ZDOs the server has sent it. In singleplayer and on the + /// host the count is exact; on a remote client it can undercount, so a cap can be exceeded by + /// someone building far from every other copy. It still closes the case that matters - fifty of + /// them around one base - and no client-side hook can do better without a server-authoritative + /// check. + /// + public static class PieceDensityLimit + { + private class Limit + { + public float Radius; + public int Max; + public string Message; + } + + private static readonly Dictionary Limits = new Dictionary(); + + /// + /// The radius of a circle with the given area, so a limit can be written the way it is + /// actually discussed - "five per 1.6 square kilometres" - instead of as a magic distance. + /// + public static float RadiusForArea(float squareKilometres) + { + return Mathf.Sqrt(squareKilometres * 1000000f / Mathf.PI); + } + + /// + /// Caps a piece. Call once from the chain's Register(); calling twice just replaces the entry, + /// so a Register() that runs more than once cannot stack limits. + /// + public static void Register(string piecePrefabName, float radius, int max, string refusalMessage) + { + if (string.IsNullOrEmpty(piecePrefabName) || max < 1 || radius <= 0f) + { + Jotunn.Logger.LogWarning($"[Density] Refusing a nonsense limit for '{piecePrefabName}' " + + $"(radius {radius}, max {max}); it will not be capped."); + return; + } + + Limits[piecePrefabName] = new Limit { Radius = radius, Max = max, Message = refusalMessage }; + Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: at most {max} within {radius:0} m."); + } + + /// + /// How many of that piece already stand within the radius of a point, or -1 if the world + /// cannot be asked right now - in which case callers must let the placement through rather + /// than refuse on no information. + /// + public static int Count(string piecePrefabName, Vector3 position, float radius) + { + if (ZDOMan.instance == null) return -1; + + List zdos = new List(); + int index = 0; + // The iterative sweep hands back a chunk per call and reports true when it is done. The + // guard is so a pathological world cannot spin here forever. + for (int guard = 0; guard < 1000; guard++) + { + if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(piecePrefabName, zdos, ref index)) break; + } + + float rangeSq = radius * radius; + int count = 0; + foreach (ZDO zdo in zdos) + { + if (zdo == null) continue; + if (Vector3.SqrMagnitude(zdo.GetPosition() - position) <= rangeSq) count++; + } + + return count; + } + + /// + /// True if one more may be placed there. Unknown pieces are always allowed - a station with no + /// registered limit is not this class's business. + /// + public static bool Allow(Player player, string piecePrefabName, Vector3 position) + { + if (!Limits.TryGetValue(piecePrefabName, out Limit limit)) return true; + + int nearby = Count(piecePrefabName, position, limit.Radius); + if (nearby < 0 || nearby < limit.Max) return true; + + if (player != null) + { + player.Message(MessageHud.MessageType.Center, string.Format(limit.Message, nearby, limit.Max)); + } + return false; + } + } + + /// + /// The single enforcement point, at the moment of building - which is the only moment a refusal is + /// both cheap and understandable. Refusing later, or building and then quietly deleting what it + /// produced, would spend the player's gate item before telling them no. + /// + /// + /// The single enforcement point. + /// + /// The signature is spelled out because it is NOT the one every Valheim modding example uses. The + /// familiar `bool PlacePiece(Piece)` does not exist in this build; the real one is + /// + /// void PlacePiece(Piece piece, Vector3 pos, Quaternion rot, bool doAttack) + /// + /// read off the HarmonyX error this patch produced on the first launch. Two things follow, and the + /// first one cost a whole startup: + /// - it returns VOID, so there is no __result to write. Asking for one throws "Cannot get result + /// from void method" at patch time, and that exception propagates out of Harmony.PatchAll() - + /// which means one bad signature here stops the rest of the mod's patches from being applied + /// at all. A prefix returning false is the whole mechanism: the original simply does not run, + /// nothing is placed, and no resources are spent. + /// - the placement position is an ARGUMENT, not the piece's transform. At prefix time the Piece + /// is the build ghost, so `pos` is the authority on where this thing is actually going. + /// Parameters are bound positionally (__0, __1) so a rename cannot break startup either. + /// + [HarmonyPatch(typeof(Player), "PlacePiece", + new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })] + public static class PieceDensityLimitPatch + { + public static bool Prefix(Player __instance, Piece __0, Vector3 __1) + { + if (__instance != Player.m_localPlayer || __0 == null) return true; + + return PieceDensityLimit.Allow(__instance, Utils.GetPrefabName(__0.gameObject), __1); + } + } +} diff --git a/JotunnModStub/RaisedThrall.cs b/JotunnModStub/RaisedThrall.cs new file mode 100644 index 0000000..c838ec8 --- /dev/null +++ b/JotunnModStub/RaisedThrall.cs @@ -0,0 +1,491 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// One conjured servant, of any race. Keeps itself within its leash of the station that made it, + /// unless the right kind of player has told it to follow. + /// + /// This started life as DraughThrall and was generalised the moment the Skeleton needed the same + /// thing - which is the call ItemProgression_Guida.txt 8.3 says to make BEFORE writing the second + /// copy rather than after. Nothing in here is draugr-specific: a leash, a wither timer, a follow + /// command and an anchor are the same problem whoever raised the body. + /// + /// The leash is not custom pathing - it is vanilla's own patrol behaviour, pointed at the station. + /// BaseAI already has m_patrol and m_patrolPoint and already wanders around that point inside + /// m_randomMoveRange, which each prefab sets to its own leash. All this component does is keep the + /// point pinned, which is also what makes "stay" send one home rather than root it wherever it + /// happened to be standing. + /// + /// The anchor lives in the creature's own ZDO as a Vector3 and doubles as the mark of which + /// station owns it - so a station can count its own even when one is three biomes away following + /// its master. + /// + public class RaisedThrall : MonoBehaviour + { + // Deliberately still spelled "draugh". These keys are in players' save files already, on + // thralls raised before this class was generalised; renaming them would leave every existing + // thrall anchorless - no leash, no wither, no orders - for the sake of a tidier string. + public const string KeyAnchor = "RoV_draughAnchor"; + public const string KeyOrphanAt = "RoV_draughOrphanAt"; + + // ─── Set on the prefab at registration ─────────────────────────────── + + /// Groups thralls for follower caps and for a station's per-kind roster. + public string m_kind = ""; + + /// Only a player of this race may give orders. Empty means anyone may. + public string m_commandingRace = ""; + + /// How many of this KIND may follow one player at once. -1 for no limit. + public int m_maxFollowers = -1; + + public float m_witherSeconds = 60f; + public float m_homeCheckRange = 20f; + + /// Shown in the refusal when a station is not this player's to command. + public string m_refusalMessage = "It does not answer to you."; + + /// + /// How many thralls of OTHER kinds, from the same station, come along when this one is + /// commanded directly. 0 for a thrall that only speaks for itself. + /// + /// This is what makes a Rancid Remains a squad leader: clicking it takes it and five of the + /// rank and file, rather than the whole garrison the pile would send. Only applies to a direct + /// click - a station moving its whole line calls SetFollowing itself, so the two cannot nest. + /// + public int m_escortCount = 0; + + // SetPatrolPoint(Vector3) is private - only the parameterless overload, which uses the + // creature's current position, is public. Resolved once here rather than per call. + private static readonly System.Reflection.MethodInfo SetPatrolPointMethod = + AccessTools.Method(typeof(BaseAI), "SetPatrolPoint", new[] { typeof(Vector3) }); + + /// + /// Every station currently loaded that owns thralls. Registered by the station's own behaviour + /// so a thrall can ask "is my station still standing?" without sweeping ZDOs or raycasting on a + /// two-second timer, ten thralls at a time. + /// + /// TRANSFORMS, not positions, and that is the whole bug this once had: the first version cached + /// transform.position at Awake, which is not yet the object's final placement. Every lookup then + /// missed, every thrall decided it was an orphan, and with the Skeleton's zero-second wither the + /// whole garrison died about four seconds after it rose. Reading .position at query time is what + /// the Draugh's own list did before it was generalised, and why that one worked. + /// + private static readonly List LiveStations = new List(); + + public static void RegisterStation(Transform station) + { + if (station != null && !LiveStations.Contains(station)) LiveStations.Add(station); + } + + public static void UnregisterStation(Transform station) => LiveStations.Remove(station); + + /// True if a loaded station stands at that point. Only meaningful when the asker is + /// close enough that the station would be loaded if it existed - see m_homeCheckRange. + public static bool StationStandsAt(Vector3 position) + { + for (int i = LiveStations.Count - 1; i >= 0; i--) + { + Transform station = LiveStations[i]; + if (station == null) { LiveStations.RemoveAt(i); continue; } // destroyed without notice + + if (Vector3.SqrMagnitude(station.position - position) < 0.25f) return true; + } + return false; + } + + private Character m_character; + private BaseAI m_ai; + private MonsterAI m_monsterAI; + private ZNetView m_nview; + + private void Awake() + { + m_character = GetComponent(); + m_ai = GetComponent(); + m_monsterAI = GetComponent(); + m_nview = GetComponent(); + + InvokeRepeating("TickLeash", 2f, 2f); + } + + /// Where the station that made this one stands, or null if it was not made by one. + public Vector3? Anchor + { + get + { + if (m_nview == null || !m_nview.IsValid()) return null; + + Vector3 anchor = m_nview.GetZDO().GetVec3(KeyAnchor, Vector3.zero); + return anchor == Vector3.zero ? (Vector3?)null : anchor; + } + } + + public string Kind => m_kind; + + public bool IsFollowing(Player player) + { + return m_monsterAI != null && player != null && m_monsterAI.GetFollowTarget() == player.gameObject; + } + + /// Called at spawn by the station. Tames it, marks it, and sends it home. + public void Bind(Vector3 anchor) + { + if (m_nview == null || !m_nview.IsValid()) return; + + m_nview.GetZDO().Set(KeyAnchor, anchor); + if (m_monsterAI != null) m_monsterAI.MakeTame(); + if (m_character != null) m_character.SetTamed(true); + + GoHome(); + } + + // ---------------------------------------------------------------- the leash + + private void TickLeash() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + if (m_character == null || m_character.IsDead()) return; + + // Checked before anything else, and NOT skipped while following: a thrall out with its + // master still has to wither if the station behind it has fallen. + if (TickWither()) return; + + // Following overrides the leash entirely; that is the whole point of the command. + if (m_monsterAI != null && m_monsterAI.GetFollowTarget() != null) return; + + GoHome(); + } + + /// Starts the clock when the station is gone, and stops the thrall when it runs out. + /// Returns true once it has killed this one, so the caller stops bothering with it. + private bool TickWither() + { + Vector3? anchor = Anchor; + if (anchor == null || ZNet.instance == null) return false; + + long stamp = m_nview.GetZDO().GetLong(KeyOrphanAt, 0L); + + if (stamp == 0L) + { + // The station marks its own thralls when it falls, but it can only mark the ones that + // are loaded at that moment. This is the other half: a thrall that was away comes + // home, finds nothing there, and marks itself. + // + // Deliberately only asked near home. Further out the station's zone is almost + // certainly unloaded, so "nothing here" would be a lie - and acting on it would kill + // the escort of anyone who walked away from their base. + if (Vector3.SqrMagnitude(transform.position - anchor.Value) > + m_homeCheckRange * m_homeCheckRange) return false; + + if (StationStandsAt(anchor.Value)) return false; + + MarkOrphaned(); + return false; + } + + // Rebuilt in time, on the same spot: the clock is cleared and the thrall lives. Safe to + // ask unconditionally - StationStandsAt can only answer true where one is actually + // loaded, so being far from home simply never rescues anything. And it opens no exploit: + // a station on the same spot adopts these thralls by anchor anyway. + if (StationStandsAt(anchor.Value)) + { + m_nview.GetZDO().Set(KeyOrphanAt, 0L); + return false; + } + + double elapsed = (ZNet.instance.GetTime() - new DateTime(stamp)).TotalSeconds; + if (elapsed < m_witherSeconds) return false; + + Kill(); + return true; + } + + /// + /// Starts the wither clock, once. Called by the station as it is destroyed, and by the thrall + /// itself if it comes home to nothing. Idempotent so the two cannot restart each other's clock + /// and keep an orphan alive forever. + /// + public void MarkOrphaned() + { + if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return; + if (m_nview.GetZDO().GetLong(KeyOrphanAt, 0L) != 0L) return; + + m_nview.ClaimOwnership(); + m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks); + } + + /// + /// Pins the patrol point back onto the station. Cheap enough to call on a timer, and calling it + /// repeatedly is what stops a thrall drifting after it has been pushed, knocked back or told to + /// stay somewhere far from home. + /// + private void GoHome() + { + Vector3? anchor = Anchor; + if (anchor == null || m_ai == null) return; + + if (SetPatrolPointMethod != null) + { + SetPatrolPointMethod.Invoke(m_ai, new object[] { anchor.Value }); + } + else + { + // Fall back to writing the two fields the private method writes. + Traverse traverse = Traverse.Create(m_ai); + traverse.Field("m_patrolPoint").SetValue(anchor.Value); + traverse.Field("m_patrol").SetValue(true); + } + } + + // ---------------------------------------------------------------- commands + + public bool MayBeCommandedBy(Player player) + { + if (player == null) return false; + if (string.IsNullOrEmpty(m_commandingRace)) return true; + + return player.m_customData != null && + player.m_customData.TryGetValue("Race", out string race) && + race == m_commandingRace; + } + + /// Sends it after the player, or home. Returns false if it refused. + public bool SetFollowing(Player player, bool follow, bool announce) + { + if (player == null || m_monsterAI == null || m_character == null) return false; + + if (!MayBeCommandedBy(player)) + { + if (announce) player.Message(MessageHud.MessageType.Center, m_refusalMessage); + return false; + } + + if (!follow) + { + m_monsterAI.SetFollowTarget(null); + GoHome(); + if (announce) player.Message(MessageHud.MessageType.Center, $"{m_character.m_name} returns."); + return true; + } + + // Counted fresh on every command so deaths and dismissals free slots up on their own, + // with no tally to drift out of step. + if (m_maxFollowers >= 0 && CountFollowers(player, m_kind) >= m_maxFollowers) + { + if (announce) + { + player.Message(MessageHud.MessageType.Center, $"Only {m_maxFollowers} may walk with you."); + } + return false; + } + + m_monsterAI.SetFollowTarget(player.gameObject); + if (announce) player.Message(MessageHud.MessageType.Center, $"{m_character.m_name} follows."); + return true; + } + + /// + /// Follow if it is not, come home if it is - the wolf's own single-key behaviour, plus an escort + /// if this thrall leads one. + /// + public void ToggleCommand(Player player) + { + bool follow = !IsFollowing(player); + if (!SetFollowing(player, follow, announce: m_escortCount <= 0)) return; + if (m_escortCount <= 0) return; + + // A squad, not the whole line. Anchor-bound, other kinds only - the rank and file, never + // another leader - and capped at m_escortCount. + Vector3? anchor = Anchor; + if (anchor == null) return; + + int taken = 0; + foreach (RaisedThrall other in BoundTo(anchor.Value)) + { + if (other == this || other.m_kind == m_kind) continue; + + // Going out: only pick up ones that are not already out. Coming home: only send back + // the ones that are actually with this player, so another squad is left alone. + if (follow ? other.IsFollowing(player) : !other.IsFollowing(player)) continue; + if (taken >= m_escortCount) break; + + if (other.SetFollowing(player, follow, announce: false)) taken++; + } + + player.Message(MessageHud.MessageType.Center, follow + ? $"{m_character.m_name} rises with {taken}." + : $"{m_character.m_name} stands down with {taken}."); + } + + private static int CountFollowers(Player player, string kind) + { + int count = 0; + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null || character.IsDead()) continue; + + RaisedThrall thrall = character.GetComponent(); + if (thrall == null || thrall.m_kind != kind) continue; + if (thrall.IsFollowing(player)) count++; + } + return count; + } + + /// Every living thrall bound to the station at this position. + public static List BoundTo(Vector3 anchor) + { + List bound = new List(); + + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null || character.IsDead()) continue; + + RaisedThrall thrall = character.GetComponent(); + if (thrall == null) continue; + + Vector3? own = thrall.Anchor; + // A generous epsilon: a station never moves, so this only has to survive float + // round-tripping through the ZDO. + if (own != null && Vector3.SqrMagnitude(own.Value - anchor) < 0.25f) bound.Add(thrall); + } + + return bound; + } + + // ---------------------------------------------------------------- the call + + /// Earshot. A shouted gesture reaches what is nearby, not the whole world. + public const float TauntRange = 30f; + + /// + /// The emote that calls thralls to their master. A SET rather than one string because the emote + /// names are not in the assembly at all - Valheim builds them from what the player types in + /// chat, so unlike every other name in this project this one could not be read off the game and + /// verified. The patch below logs whatever it actually receives, so a wrong guess here is one + /// line away from being right instead of a mystery. + /// + private static readonly HashSet TauntEmotes = new HashSet + { + "comehere", "come_here", "followme", + }; + + /// + /// Everything within earshot that answers to this player falls in behind them. + /// + /// Only ever a call, never a dismissal: "come here" means come here. Sending them home stays + /// with the station and with a click on the thrall itself. + /// + /// The per-race follower cap needs no special handling - SetFollowing enforces m_maxFollowers + /// itself, so the Skeleton's whole garrison answers (-1, no limit) and the Draugh's gets three + /// draugr and one officer, from exactly the same call. + /// + public static void CallToArms(Player player) + { + if (player == null) return; + + int came = 0; + int refused = 0; + + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null || character.IsDead()) continue; + + RaisedThrall thrall = character.GetComponent(); + if (thrall == null || thrall.IsFollowing(player)) continue; + if (!thrall.MayBeCommandedBy(player)) continue; + if (Vector3.SqrMagnitude(character.transform.position - player.transform.position) > + TauntRange * TauntRange) continue; + + if (thrall.SetFollowing(player, true, announce: false)) came++; + else refused++; + } + + if (came > 0) + { + player.Message(MessageHud.MessageType.Center, $"{came} answer the call."); + } + else if (refused > 0) + { + // The only way SetFollowing refuses a thrall that may be commanded is the cap. + player.Message(MessageHud.MessageType.Center, "No more may walk with you."); + } + } + + public static bool IsTauntEmote(string emote) + { + return emote != null && TauntEmotes.Contains(emote.ToLowerInvariant()); + } + + public void Kill() + { + if (m_character == null || m_character.IsDead()) return; + + HitData hit = new HitData(); + hit.m_damage.m_damage = 1E+10f; + hit.m_hitType = HitData.HitType.Undefined; + m_character.ApplyDamage(hit, true, false); + } + } + + /// + /// Routes E on a thrall to , before vanilla resolves the + /// target itself. + /// + /// This is a prefix on Player.Interact rather than an Interactable on the thrall, and that is not + /// a style choice. AswidPatches' own Character.Awake postfix adds AswidThrall - also Interactable + /// - to essentially every mob carrying a MonsterAI, and it wins vanilla's + /// GetComponentInParent<Interactable>() race on whatever it touches. That is the exact bug + /// FactionMerchantInteractPatch exists to work around, where pressing E called AswidThrall.Interact + /// instead of Trader.Interact, silently and with no error. Handling our own thralls here sidesteps + /// component order entirely instead of depending on it. + /// + /// The feedback is a centre-screen message and not hover text for the same reason: Character is + /// itself Hoverable and sits ahead of everything added later, so hover is a race this cannot win + /// cleanly. The station's own hover text carries the roster and the rules. + /// + /// + /// The "come here" gesture calls every thrall in earshot to its master. + /// + /// A POSTFIX with positional binding and no __result, which is the safest shape available: postfixes + /// need no return value, so this cannot repeat the PlacePiece failure where asking for a __result on + /// a void method threw at patch time and stopped the rest of the mod being patched. + /// + /// The emote name is logged on every emote the local player performs, because the names are the one + /// class of string in this project that could not be verified against the game - they are built from + /// the player's own chat input, not stored in the assembly. Do the gesture once and the log names it. + /// + [HarmonyPatch(typeof(Player), "StartEmote")] + public static class RaisedThrallTauntPatch + { + public static void Postfix(Player __instance, string __0) + { + if (__instance != Player.m_localPlayer) return; + + Jotunn.Logger.LogInfo($"[Thrall] emote '{__0}'" + + (RaisedThrall.IsTauntEmote(__0) ? " - calling thralls." : ".")); + + if (RaisedThrall.IsTauntEmote(__0)) RaisedThrall.CallToArms(__instance); + } + } + + [HarmonyPatch(typeof(Player), "Interact")] + public static class RaisedThrallInteractPatch + { + public static bool Prefix(Player __instance, GameObject go, bool hold, bool alt) + { + if (go == null || hold) return true; + if (__instance != Player.m_localPlayer) return true; + + RaisedThrall thrall = go.GetComponentInParent(); + if (thrall == null) return true; // not ours - let vanilla's own resolution run + + thrall.ToggleCommand(__instance); + return false; + } + } +}