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 <noreply@anthropic.com>
491 lines
22 KiB
C#
491 lines
22 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using HarmonyLib;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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 ───────────────────────────────
|
|
|
|
/// <summary>Groups thralls for follower caps and for a station's per-kind roster.</summary>
|
|
public string m_kind = "";
|
|
|
|
/// <summary>Only a player of this race may give orders. Empty means anyone may.</summary>
|
|
public string m_commandingRace = "";
|
|
|
|
/// <summary>How many of this KIND may follow one player at once. -1 for no limit.</summary>
|
|
public int m_maxFollowers = -1;
|
|
|
|
public float m_witherSeconds = 60f;
|
|
public float m_homeCheckRange = 20f;
|
|
|
|
/// <summary>Shown in the refusal when a station is not this player's to command.</summary>
|
|
public string m_refusalMessage = "It does not answer to you.";
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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) });
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private static readonly List<Transform> LiveStations = new List<Transform>();
|
|
|
|
public static void RegisterStation(Transform station)
|
|
{
|
|
if (station != null && !LiveStations.Contains(station)) LiveStations.Add(station);
|
|
}
|
|
|
|
public static void UnregisterStation(Transform station) => LiveStations.Remove(station);
|
|
|
|
/// <summary>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.</summary>
|
|
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<Character>();
|
|
m_ai = GetComponent<BaseAI>();
|
|
m_monsterAI = GetComponent<MonsterAI>();
|
|
m_nview = GetComponent<ZNetView>();
|
|
|
|
InvokeRepeating("TickLeash", 2f, 2f);
|
|
}
|
|
|
|
/// <summary>Where the station that made this one stands, or null if it was not made by one.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>Called at spawn by the station. Tames it, marks it, and sends it home.</summary>
|
|
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();
|
|
}
|
|
|
|
/// <summary>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.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>Sends it after the player, or home. Returns false if it refused.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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<RaisedThrall>();
|
|
if (thrall == null || thrall.m_kind != kind) continue;
|
|
if (thrall.IsFollowing(player)) count++;
|
|
}
|
|
return count;
|
|
}
|
|
|
|
/// <summary>Every living thrall bound to the station at this position.</summary>
|
|
public static List<RaisedThrall> BoundTo(Vector3 anchor)
|
|
{
|
|
List<RaisedThrall> bound = new List<RaisedThrall>();
|
|
|
|
foreach (Character character in Character.GetAllCharacters())
|
|
{
|
|
if (character == null || character.IsDead()) continue;
|
|
|
|
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
|
|
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
|
|
|
|
/// <summary>Earshot. A shouted gesture reaches what is nearby, not the whole world.</summary>
|
|
public const float TauntRange = 30f;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private static readonly HashSet<string> TauntEmotes = new HashSet<string>
|
|
{
|
|
"comehere", "come_here", "followme",
|
|
};
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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<RaisedThrall>();
|
|
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);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Routes E on a thrall to <see cref="RaisedThrall.ToggleCommand"/>, 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.
|
|
/// </summary>
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
[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<RaisedThrall>();
|
|
if (thrall == null) return true; // not ours - let vanilla's own resolution run
|
|
|
|
thrall.ToggleCommand(__instance);
|
|
return false;
|
|
}
|
|
}
|
|
}
|