RacesOfValheim/JotunnModStub/Butler/BoneServantAI.cs
2026-09-12 10:42:01 +02:00

1451 lines
58 KiB
C#

using System.Collections.Generic;
using System.Text;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Bone Servant's own head. Everything it does is here; vanilla's MonsterAI never runs on it.
///
/// HOW IT MOVES, which was the one open question in the design and is answered here rather than in
/// the doc. Three candidates were on the table: a ghost follow-target, pinning m_patrolPoint the way
/// RaisedThrall does, and calling BaseAI.MoveTo directly. The IL settled it:
///
/// - BaseAI has NO Update and NO FixedUpdate. UpdateAI(dt) is driven centrally by
/// MonoUpdaters.FixedUpdate over BaseAI.Instances, and that list is maintained by OnEnable /
/// OnDisable. So "disable the AI and drive MoveTo yourself" kills the only thing that would
/// call anything: a disabled BaseAI is not ticked at all. That candidate is dead.
/// - BaseAI.UpdateAI itself does almost nothing - IsOwner, UpdateTakeoffLanding,
/// UpdateRegeneration - so skipping it costs a flying check we do not need and a regeneration
/// we already have from SkeletonSentryBehaviour.
///
/// So: a PREFIX on MonsterAI.UpdateAI that hands the tick to this class and returns false. The
/// servant keeps its place in the central tick, keeps vanilla pathing through BaseAI.MoveTo, and
/// vanilla's own AI - targeting, fleeing, wandering, attacking - never executes a single line. That
/// is also why the servant cannot fight: not because its weapon was taken (it was), but because the
/// code that would swing it is never reached.
///
/// MoveTo(dt, point, dist, run) is private, hence the cached MethodInfo. It returns TRUE on arrival
/// (read in the IL: DistanceXZ under the threshold calls StopMoving and returns 1), which is the
/// whole arrival test - no distance maths of our own.
///
/// THE PAYLOAD IS VIRTUAL. The servant has no inventory. Every station's input RPC takes a STRING,
/// so what it carries is a list of prefab names and counts in its own ZDO, which survives saving,
/// zone reload and - the case that matters - a change of owner mid-job in multiplayer. The one
/// thing this costs is that the goods do not exist as objects while in transit, so they have to be
/// put back into the world by hand if the servant dies holding them. That is <see cref="DropPayload"/>,
/// and it is the reason nothing here can quietly delete a player's ore.
/// </summary>
public class BoneServantAI : MonoBehaviour
{
// ─── ZDO keys ────────────────────────────────────────────────────────
public const string KeyAnchor = "RoV_butlerAnchor";
public const string KeyOrphanAt = "RoV_butlerOrphanAt";
public const string KeyLoad = "RoV_butlerLoad";
public const string KeySource = "RoV_butlerSource";
public const string KeyTarget = "RoV_butlerTarget";
public const string KeyStatus = "RoV_butlerStatus";
/// <summary>Written into a STATION's ZDO: the chest whose material is in it right now, so the
/// product goes home to where the raw came from even after a reload, and even if a different
/// client collects it.</summary>
public const string KeyFedBy = "RoV_butlerFedBy";
// ─── numbers that are not worth a config entry ───────────────────────
private const float PlanInterval = 1.5f;
/// <summary>
/// How close is close enough. Measured to the piece's ORIGIN, which on a furnace or a kiln sits
/// inside a metre or so of solid collider - so anything tight enough to look like hugging the
/// thing is a distance the servant can never actually reach, and it would time out and put a
/// perfectly good station in the penalty box. Two and a half metres is roughly where a player
/// stands to use one.
/// </summary>
private const float ArriveDistance = 2.5f;
private const float CollectRadius = 3.5f;
private const float JobTimeout = 25f;
private const float PenaltySeconds = 180f;
/// <summary>Set aside briefly when a job was reached but achieved nothing. Without this, a job
/// that arrives and finds nothing to do is re-planned identically on the next tick and the
/// servant stands there deciding the same thing forever.</summary>
private const float ShortPenaltySeconds = 20f;
private const float FleeSeconds = 6f;
private const float WitherSeconds = 30f;
private const float HomeCheckRange = 25f;
/// <summary>A cooking slot inside this many seconds of burning outranks everything else. Twelve
/// seconds is a walk of about twenty metres with room to spare, which is the whole radius.</summary>
private const float SpoilPanicSeconds = 12f;
/// <summary>How long a station may sit unserved before its wait starts outweighing distance.
/// This is what stops a furnace at the edge of the circle from starving while the servant
/// shuttles between two closer ones.</summary>
private const float WaitToMetres = 0.25f;
private const int PayloadCap = 120;
private static readonly System.Reflection.MethodInfo MoveToMethod =
AccessTools.Method(typeof(BaseAI), "MoveTo",
new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) });
private static readonly System.Reflection.FieldInfo AllPiecesField =
AccessTools.Field(typeof(Piece), "s_allPieces");
private static readonly System.Reflection.MethodInfo ContainerSaveMethod =
AccessTools.Method(typeof(Container), "Save");
private static int s_itemMask = -1;
/// <summary>Which stations this one serves. Set on the prefab at registration, so it travels
/// with every instance the table raises.</summary>
public ButlerFamily m_family = ButlerFamily.Forge;
/// <summary>
/// Whether this one stands and fights instead of walking home when trouble comes. Off for the
/// Bone Servants, which are pacifists by decision; on for the Sverm's Seeker Workers, which
/// keep the forge AND defend the nest. See <see cref="HandsToVanilla"/>.
/// </summary>
public bool m_fightsBack = false;
/// <summary>
/// How close to the anchor counts as home, and how far past the configured radius it works.
/// 2.5 and 0 for a table. A Sverm nest is metres of collider that grows with its stage, so
/// SvermWorkerBehaviour sets both to the nest's measured edge - otherwise an idle worker would
/// spend its life walking into the trunk, and the work circle would be mostly nest.
/// </summary>
public float m_homeDistance = 2.5f;
public float m_radiusBonus = 0f;
/// <summary>For a servant that fights back: how close an enemy has to be to stop the work, how
/// often that is asked, and how long the fight holds after the last sign of one.</summary>
private const float FightRange = 12f;
private const float FightScanInterval = 1f;
private const float FightLinger = 5f;
private float m_nextFightScan;
private float m_fightUntil;
private ZNetView m_nview;
private Character m_character;
private MonsterAI m_ai;
private readonly object[] m_moveArgs = new object[4];
private readonly List<Load> m_payload = new List<Load>();
private readonly Dictionary<ZDOID, float> m_penalties = new Dictionary<ZDOID, float>();
private readonly Dictionary<ZDOID, float> m_idleSince = new Dictionary<ZDOID, float>();
private readonly List<ButlerStation> m_stations = new List<ButlerStation>();
private readonly List<Container> m_chests = new List<Container>();
private float m_scannedAt = -99f;
private Job m_job;
private float m_nextPlan;
private float m_jobDeadline;
private float m_fleeUntil;
private string m_status = "";
private class Load
{
public string Name;
public int Count;
}
private class Job
{
public string Kind; // load | fuel | collect | deposit | drop
public ZDOID Target;
public Vector3 Point;
public bool Hurry;
public string Label;
}
// ================================================================ life
private void Awake()
{
m_nview = GetComponent<ZNetView>();
m_character = GetComponent<Character>();
m_ai = GetComponent<MonsterAI>();
ReadPayload();
}
private void OnDestroy()
{
// Only a DEATH scatters the load. A zone unloading destroys this object too, and there the
// payload must stay in the ZDO where it will be read again on the way back in - dropping it
// would mint a copy every time the player walked away.
if (m_character != null && m_character.IsDead()) DropPayload();
}
/// <summary>Called by the table the moment it raises one.</summary>
public void Bind(Vector3 anchor)
{
if (m_nview == null || !m_nview.IsValid()) return;
m_nview.GetZDO().Set(KeyAnchor, anchor);
if (m_ai != null) m_ai.MakeTame();
if (m_character != null) m_character.SetTamed(true);
}
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 bool IsBoundTo(Vector3 anchor)
{
Vector3? own = Anchor;
return own != null && Vector3.SqrMagnitude(own.Value - anchor) < 0.25f;
}
/// <summary>The one line the table's hover shows. Read from the ZDO so a client that does not
/// own the servant still sees what it is doing.</summary>
public string Status
{
get
{
if (m_nview == null || !m_nview.IsValid()) return m_status;
return m_nview.GetZDO().GetString(KeyStatus, m_status);
}
}
private void SetStatus(string text)
{
if (text == m_status) return;
m_status = text;
if (m_nview != null && m_nview.IsValid() && m_nview.IsOwner())
{
m_nview.GetZDO().Set(KeyStatus, text);
}
}
/// <summary>Hit by something: stop working and walk home. It never fights back - there is
/// nothing in this class that could. A servant that fights back ignores this: vanilla already
/// holds the attacker as its target (MonsterAI.OnDamaged calls SetTarget, read off the IL), and
/// <see cref="HandsToVanilla"/> gives it the tick on the next frame.</summary>
public void NoteDamage()
{
if (m_fightsBack) return;
m_fleeUntil = Time.time + FleeSeconds;
m_job = null;
}
/// <summary>
/// True while vanilla's MonsterAI should have the tick instead of the work - only ever for a
/// servant that fights back, and only on the client that runs it.
///
/// VANILLA DOES THE FIGHTING, this only decides when. Two things start a fight: a target the
/// MonsterAI already holds - which covers being hit, see NoteDamage - and an enemy inside
/// FightRange, found with BaseAI.FindClosestEnemy. That one is a static sweep of distance and
/// IsEnemy with no line of sight (IL), which is why the range is short. Either holds the fight
/// for FightLinger seconds, so the worker does not flicker between swinging and walking to the
/// chest on alternate ticks.
///
/// The job is dropped, not the payload: whatever it was carrying stays in the ZDO, and the
/// first plan after the fight carries it on to where it was going.
/// </summary>
public bool HandsToVanilla()
{
if (!m_fightsBack || m_ai == null || m_character == null || m_character.IsDead()) return false;
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false;
Character target = m_ai.GetTargetCreature();
if (target != null && !target.IsDead())
{
m_fightUntil = Time.time + FightLinger;
}
else if (Time.time >= m_nextFightScan)
{
m_nextFightScan = Time.time + FightScanInterval;
if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null)
{
m_fightUntil = Time.time + FightLinger;
}
}
if (Time.time >= m_fightUntil) return false;
m_job = null;
m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back
SetStatus("Fighting.");
return true;
}
// ================================================================ the tick
/// <summary>Everything. Returns what MonsterAI.UpdateAI would have returned.</summary>
public bool Tick(float dt)
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false;
if (m_character == null || m_character.IsDead()) return false;
if (TickWither()) return true;
if (Time.time < m_fleeUntil)
{
SetStatus("Driven off.");
GoHome(dt);
return true;
}
if (Time.time >= m_nextPlan)
{
m_nextPlan = Time.time + PlanInterval;
Plan();
}
Execute(dt);
return true;
}
/// <summary>
/// The table is gone: start the clock, and stop when it runs out. Same shape as RaisedThrall's,
/// and deliberately only asked near home - further out the table's zone is simply not loaded, so
/// "nothing there" would be a lie.
/// </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)
{
if (Vector3.SqrMagnitude(transform.position - anchor.Value) >
HomeCheckRange * HomeCheckRange) return false;
if (RaisedThrall.StationStandsAt(anchor.Value)) return false;
m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks);
return false;
}
if (RaisedThrall.StationStandsAt(anchor.Value))
{
m_nview.GetZDO().Set(KeyOrphanAt, 0L);
return false;
}
double elapsed = (ZNet.instance.GetTime() - new System.DateTime(stamp)).TotalSeconds;
if (elapsed < WitherSeconds) return false;
HitData hit = new HitData();
hit.m_damage.m_damage = 1E+10f;
hit.m_hitType = HitData.HitType.Undefined;
m_character.ApplyDamage(hit, true, false);
return true;
}
// ================================================================ planning
private void Plan()
{
Vector3? anchor = Anchor;
if (anchor == null) { m_job = null; return; }
Scan(anchor.Value);
ExpirePenalties();
if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; }
// The forge has no clock: a smelter holds its ore indefinitely and puts its own output on
// the floor, so PlanRescue would ask a question whose answer is always no. The smith is a
// four-state machine and the cook is a five-state one, and that is the whole of the
// simplification the split bought.
// REFUEL BEFORE LOAD, and that order is the whole of the blast furnace fix. FreeSlots goes
// back above zero the instant a furnace eats one ore, so while there is scrap left in any
// chest PlanLoad always has an answer and PlanFuel, sitting behind it, never got a turn -
// the furnace was topped up forever and burned down to nothing. Fuel cannot starve loading
// in return, because FuelWanted is zero for a station with no work: an empty furnace asks
// for no coal, gets filled, and only then becomes worth stoking.
Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null;
job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
{
m_jobDeadline = Time.time + JobTimeout;
}
m_job = job;
}
/// <summary>
/// Everything within the radius, once every planning tick. Piece.s_allPieces is the cheap way in
/// - it is the list the game already keeps of every built piece - so there is no OverlapSphere
/// and no guessing at layer masks for the part that runs constantly.
/// </summary>
private void Scan(Vector3 anchor)
{
if (Time.time - m_scannedAt < PlanInterval * 0.5f) return;
m_scannedAt = Time.time;
m_stations.Clear();
m_chests.Clear();
List<Piece> pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List<Piece> : null;
if (pieces == null) return;
float radius = ButlerConfig.WorkRadius.Value + m_radiusBonus;
float radiusSq = radius * radius;
for (int i = 0; i < pieces.Count; i++)
{
Piece piece = pieces[i];
if (piece == null) continue;
if (Vector3.SqrMagnitude(piece.transform.position - anchor) > radiusSq) continue;
// A station of the other trade is not this servant's business, but it is still not a
// chest - hence the continue either way.
ButlerStation station = ButlerStation.From(piece.gameObject);
if (station != null)
{
if (station.Family == m_family) m_stations.Add(station);
continue;
}
Container container = piece.GetComponent<Container>();
if (container != null && IsSealed(container)) m_chests.Add(container);
}
}
/// <summary>A chest is the servant's only if it holds the sigil. The sigil itself is never
/// counted as material and never carried away - see TakeFrom.</summary>
private static bool IsSealed(Container container)
{
if (container == null || container.IsInUse()) return false;
Inventory inventory = container.GetInventory();
if (inventory == null) return false;
string sigil = SigilSharedName();
if (string.IsNullOrEmpty(sigil)) return false;
return inventory.CountItems(sigil) > 0;
}
private static string s_sigilShared;
private static string s_sigilFor;
/// <summary>Inventory.CountItems matches on the SHARED name ($item_...), not on the prefab name
/// the stations use, so the configured prefab is resolved once into the other kind of name.</summary>
private static string SigilSharedName()
{
string wanted = ButlerConfig.SigilItem.Value;
if (s_sigilFor == wanted) return s_sigilShared;
s_sigilFor = wanted;
s_sigilShared = null;
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(wanted) : null;
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null)
{
s_sigilShared = drop.m_itemData.m_shared.m_name;
}
else
{
Jotunn.Logger.LogWarning($"[Butler] No item '{wanted}' to use as the sigil; " +
"no chest can be marked until that name is right.");
}
return s_sigilShared;
}
// ---------------------------------------------------------------- the five states
/// <summary>1. SAVE. A slot about to burn beats everything, and it is the only job it runs to.</summary>
private Job PlanRescue()
{
ButlerStation best = null;
float soonest = SpoilPanicSeconds;
foreach (ButlerStation station in m_stations)
{
if (!station.Alive || IsPenalised(station.Id)) continue;
if (!station.HasOutput) continue; // nothing pullable yet, panic changes nothing
float left = station.SecondsToSpoil;
if (left >= soonest) continue;
soonest = left;
best = station;
}
if (best == null) return null;
return new Job
{
Kind = "collect",
Target = best.Id,
Point = best.Position,
Hurry = true,
Label = "Saving the food",
};
}
/// <summary>2. COLLECT. Anything finished, and anything already lying under a station.</summary>
private Job PlanCollect()
{
ButlerStation best = null;
float bestScore = float.MaxValue;
foreach (ButlerStation station in m_stations)
{
if (!station.Alive || IsPenalised(station.Id)) continue;
if (!station.HasOutput && !HasDropsNear(station.Position)) continue;
float score = Vector3.Distance(transform.position, station.Position);
if (score >= bestScore) continue;
bestScore = score;
best = station;
}
if (best == null) return null;
return new Job
{
Kind = "collect",
Target = best.Id,
Point = best.Position,
Label = "Collecting",
};
}
/// <summary>
/// 4. LOAD. Urgency, then distance - and the urgency of a station with nothing wrong with it is
/// how long it has been waiting. A metre of walking is worth four seconds of a station standing
/// idle, so the far furnace wins eventually instead of never.
/// </summary>
private Job PlanLoad()
{
ButlerStation best = null;
string bestItem = null;
Container bestChest = null;
float bestScore = float.MaxValue;
foreach (ButlerStation station in m_stations)
{
if (!station.Alive || IsPenalised(station.Id)) continue;
if (!station.Operable || station.FreeSlots <= 0) continue;
Container chest;
string item = FindMaterialFor(station, out chest);
if (item == null) { m_idleSince.Remove(station.Id); continue; }
float waited = NoteIdle(station.Id);
float score = Vector3.Distance(transform.position, chest.transform.position) +
Vector3.Distance(chest.transform.position, station.Position) -
waited * WaitToMetres;
if (score >= bestScore) continue;
bestScore = score;
best = station;
bestItem = item;
bestChest = chest;
}
if (best == null) return null;
// The chest first - the station is where the payload goes afterwards, and PlanDelivery
// works that out from the target written on the load.
return new Job
{
Kind = "load",
Target = ZdoOf(bestChest),
Point = bestChest.transform.position,
Label = "Fetching " + bestItem,
};
}
/// <summary>
/// 3. REFUEL. Only stations that actually have something to work on.
///
/// Scored by the walk, the same way PlanLoad is, and for a reason that only appeared once this
/// moved up the list: taking the first station in scan order was harmless while refuelling was
/// the job of last resort, but ahead of loading it lets one furnace at the edge of the circle
/// hold the servant while a cold one two metres away waits.
/// </summary>
private Job PlanFuel()
{
Container bestChest = null;
string bestFuel = null;
float bestScore = float.MaxValue;
foreach (ButlerStation station in m_stations)
{
if (!station.Alive || IsPenalised(station.Id)) continue;
if (!station.Operable) continue;
int wanted = station.FuelWanted;
if (wanted <= 0) continue;
string fuel = station.FuelPrefab;
if (string.IsNullOrEmpty(fuel)) continue;
Container chest = FindChestWith(fuel);
if (chest == null) continue;
float score = Vector3.Distance(transform.position, chest.transform.position) +
Vector3.Distance(chest.transform.position, station.Position);
if (score >= bestScore) continue;
bestScore = score;
bestChest = chest;
bestFuel = fuel;
}
if (bestChest == null) return null;
return new Job
{
Kind = "fuel",
Target = ZdoOf(bestChest),
Point = bestChest.transform.position,
Label = "Fetching " + bestFuel,
};
}
/// <summary>Where the load in hand is going: on to its station, or back into a chest.</summary>
private Job PlanDelivery(Vector3 anchor)
{
ZDOID target = m_nview.GetZDO().GetZDOID(KeyTarget);
if (target != ZDOID.None)
{
// NO FreeSlots CHECK HERE, and that was the first bug found in play: fuel does not go
// into a slot. A furnace filled to m_maxOre with copper has FreeSlots 0 and still wants
// coal, so gating the delivery on free slots sent the servant back to the chest with
// the coal it had just fetched - and then PlanFuel sent it out for the same coal again,
// forever. AcceptsAnything already asks the right question of both doors.
ButlerStation station = StationById(target);
if (station != null && station.Alive && station.Operable && AcceptsAnything(station))
{
return new Job
{
Kind = "deposit_station",
Target = target,
Point = station.Position,
Label = "Loading " + Describe(),
};
}
// The station is gone, full or cold. The goods are ours to put back, not to hold.
m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
}
Container chest = ChestForProduct();
if (chest != null)
{
return new Job
{
Kind = "deposit",
Target = ZdoOf(chest),
Point = chest.transform.position,
Label = "Storing " + Describe(),
};
}
// Every sealed chest is full - but a chest is not the only place a thing can go. A station
// that BURNS what is in hand is a destination too, and for the smith it is usually the
// right one: the charcoal kiln releases its whole batch in one go (verified in the IL -
// UpdateSmelter only calls SpawnProcessed once the ore queue empties), which is exactly the
// delivery a nearly full chest cannot absorb, and the coal it makes is what the furnace
// beside it is waiting for. Offering the load to a consumer before giving up is what turns
// "nowhere to put 20x Coal" into a full blast furnace.
//
// It comes AFTER the chest and not before, so a product still goes home to the chest that
// paid for it whenever there is room; this is the step before the floor, not instead of
// storing.
ButlerStation consumer = StationWanting();
if (consumer != null)
{
return new Job
{
Kind = "deposit_station",
Target = consumer.Id,
Point = consumer.Position,
Label = "Loading " + Describe(),
};
}
// Nothing will take it. Beside the table it goes: a stalled chain is worse than a tidy
// floor, and nothing may vanish (sec. 7.3).
return new Job
{
Kind = "drop",
Target = ZDOID.None,
Point = anchor,
Label = "Nowhere to put " + Describe(),
};
}
/// <summary>The nearest station that will take something out of the payload, as material or as
/// fuel. No FreeSlots check, for the reason spelled out above the KeyTarget branch: fuel does
/// not go into a slot, and AcceptsAnything already asks the right question of both doors.</summary>
private ButlerStation StationWanting()
{
ButlerStation best = null;
float bestDistance = float.MaxValue;
foreach (ButlerStation station in m_stations)
{
if (!station.Alive || IsPenalised(station.Id)) continue;
if (!station.Operable || !AcceptsAnything(station)) continue;
float distance = Vector3.Distance(transform.position, station.Position);
if (distance >= bestDistance) continue;
bestDistance = distance;
best = station;
}
return best;
}
// ================================================================ execution
private void Execute(float dt)
{
if (m_job == null)
{
SetStatus(m_stations.Count == 0 ? "Nothing to serve." : "Nothing to do.");
GoHome(dt);
return;
}
SetStatus(m_job.Label);
if (!MoveToPoint(dt, m_job.Point, ArriveDistance, m_job.Hurry))
{
// Doors do not open for pathfinding. A target it cannot reach goes into the penalty box
// and the servant gets on with something it can do.
if (Time.time > m_jobDeadline)
{
Penalise(m_job.Target);
Jotunn.Logger.LogInfo($"[Butler] Could not reach {m_job.Kind} target; " +
"setting it aside for a few minutes.");
m_job = null;
m_nextPlan = 0f;
}
return;
}
bool achieved;
switch (m_job.Kind)
{
case "load": achieved = DoLoad(); break;
case "fuel": achieved = DoFuel(); break;
case "collect": achieved = DoCollect(); break;
case "deposit_station": achieved = DoDepositStation(); break;
case "deposit": achieved = DoDeposit(); break;
case "drop": DropPayload(); achieved = true; break;
default: achieved = true; break;
}
// Arrived and nothing happened: the world moved while it walked. Set that target aside for
// twenty seconds so the next plan picks something else instead of re-deciding the same
// errand on every tick.
if (!achieved) PenaliseShort(m_job.Target);
m_job = null;
m_nextPlan = 0f; // arriving changes the world; re-plan on the next tick rather than in 1.5 s
}
/// <summary>At the chest: take what the chosen station will eat, and remember where it came from.</summary>
private bool DoLoad()
{
Container chest = ContainerById(m_job.Target);
if (chest == null) return false;
// The station is chosen again here rather than carried on the job, because the walk took
// time and the world may have moved on.
ButlerStation station = null;
string item = null;
foreach (ButlerStation candidate in m_stations)
{
if (!candidate.Alive || !candidate.Operable || candidate.FreeSlots <= 0) continue;
if (IsPenalised(candidate.Id)) continue;
string found = FirstAccepted(candidate, chest);
if (found == null) continue;
station = candidate;
item = found;
break;
}
if (station == null || item == null) return false;
int taken = TakeFrom(chest, item, station.FreeSlots);
if (taken <= 0) return false;
AddToPayload(item, taken);
m_nview.GetZDO().Set(KeySource, ZdoOf(chest));
m_nview.GetZDO().Set(KeyTarget, station.Id);
WritePayload();
return true;
}
/// <summary>At the chest, for fuel. Same shape as DoLoad, and kept separate because fuel goes in
/// through a different door and is never the thing being processed.</summary>
private bool DoFuel()
{
Container chest = ContainerById(m_job.Target);
if (chest == null) return false;
foreach (ButlerStation station in m_stations)
{
if (!station.Alive || !station.Operable || IsPenalised(station.Id)) continue;
int wanted = station.FuelWanted;
string fuel = station.FuelPrefab;
if (wanted <= 0 || string.IsNullOrEmpty(fuel)) continue;
int taken = TakeFrom(chest, fuel, wanted);
if (taken <= 0) continue;
AddToPayload(fuel, taken);
m_nview.GetZDO().Set(KeySource, ZdoOf(chest));
m_nview.GetZDO().Set(KeyTarget, station.Id);
WritePayload();
return true;
}
return false;
}
/// <summary>
/// At a station with something finished. Pull first, sweep second - and the sweep is the only
/// place the servant ever picks anything up off the ground, which is what keeps it from tidying
/// away things the player left lying about on purpose.
///
/// THE ORDER IS THE POINT, and it used to be the other way round. Sweeping first meant every
/// visit collected what the LAST visit had thrown on the floor and then threw a fresh one down;
/// since Plan() hands the servant to PlanDelivery the moment it is carrying anything, it walked
/// off to the chest the instant the sweep landed and abandoned the item it had just pulled.
/// While a hearth kept working there was therefore always exactly one cooked meat lying on the
/// ground - the "loses one per batch, whether that is two or five" the testers reported.
///
/// The loop is the other half of it. RPC_RemoveDoneItem empties ONE slot per call, so a hearth
/// with five done slots needs five calls; one per visit turned one batch into five round trips
/// to the chest. It runs against OutputPulls rather than against HasOutput alone because the
/// fermenter's Ready survives its own tap for the length of the animation.
/// </summary>
private bool DoCollect()
{
ButlerStation station = StationById(m_job.Target);
if (station == null || !station.Alive) return false;
bool pulled = false;
for (int i = 0; i < station.OutputPulls && station.HasOutput; i++)
{
station.PullOutput(transform.position);
pulled = true;
}
int before = PayloadCount();
SweepDrops(station.Position);
bool swept = PayloadCount() > before;
if (swept)
{
// The product belongs to whoever fed the station. If nothing was written there - the
// player loaded it by hand - it goes to the nearest sealed chest instead, which is the
// "yes, it collects your work too" decision paying its own way.
ZDOID fedBy = station.Nview.GetZDO().GetZDOID(KeyFedBy);
m_nview.GetZDO().Set(KeySource, fedBy);
m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
WritePayload();
}
return swept || pulled;
}
/// <summary>At the station, with raw material in hand.</summary>
private bool DoDepositStation()
{
ButlerStation station = StationById(m_job.Target);
if (station == null || !station.Alive || !station.Operable) return false;
bool loadedAny = false;
for (int i = m_payload.Count - 1; i >= 0; i--)
{
Load load = m_payload[i];
while (load.Count > 0 && station.FreeSlots > 0 && station.Accepts(load.Name))
{
station.Add(load.Name);
load.Count--;
loadedAny = true;
}
// Fuel goes in through its own door, and only for as long as it is wanted.
if (load.Count > 0 && load.Name == station.FuelPrefab)
{
int wanted = station.FuelWanted;
while (load.Count > 0 && wanted > 0)
{
station.AddFuel();
load.Count--;
wanted--;
loadedAny = true;
}
}
if (load.Count <= 0) m_payload.RemoveAt(i);
}
if (loadedAny)
{
// Whoever fed it, gets it back.
ZDOID source = m_nview.GetZDO().GetZDOID(KeySource);
if (source != ZDOID.None && station.Nview.IsValid())
{
if (!station.Nview.IsOwner()) station.Nview.ClaimOwnership();
station.Nview.GetZDO().Set(KeyFedBy, source);
}
}
if (m_payload.Count == 0) m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
WritePayload();
return loadedAny;
}
/// <summary>At a chest, with the finished goods.</summary>
private bool DoDeposit()
{
Container chest = ContainerById(m_job.Target);
if (chest == null) return false;
ZNetView nview = chest.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return false;
if (!nview.IsOwner()) nview.ClaimOwnership();
Inventory inventory = chest.GetInventory();
if (inventory == null) return false;
bool wrote = false;
for (int i = m_payload.Count - 1; i >= 0; i--)
{
Load load = m_payload[i];
GameObject prefab = ObjectDB.instance != null
? ObjectDB.instance.GetItemPrefab(load.Name)
: null;
if (prefab == null) continue;
// One at a time: it stacks correctly, it stops exactly when the chest is full, and the
// counts are small enough that being tidy costs nothing.
while (load.Count > 0 && inventory.CanAddItem(prefab, 1) && inventory.AddItem(prefab, 1))
{
load.Count--;
wrote = true;
}
if (load.Count <= 0) m_payload.RemoveAt(i);
}
if (wrote && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null);
WritePayload();
// Still holding something: that chest is full, so do not choose it again on the next pass.
if (m_payload.Count > 0) Penalise(m_job.Target);
return wrote;
}
// ================================================================ moving
/// <summary>Vanilla pathing, through the private MoveTo. True the moment it has arrived.</summary>
private bool MoveToPoint(float dt, Vector3 point, float distance, bool run)
{
if (m_ai == null || MoveToMethod == null) return true; // cannot walk: act in place
m_moveArgs[0] = dt;
m_moveArgs[1] = point;
m_moveArgs[2] = distance;
m_moveArgs[3] = run;
return (bool)MoveToMethod.Invoke(m_ai, m_moveArgs);
}
private void GoHome(float dt)
{
Vector3? anchor = Anchor;
if (anchor == null)
{
if (m_ai != null) m_ai.StopMoving();
return;
}
MoveToPoint(dt, anchor.Value, m_homeDistance, false);
}
// ================================================================ the ground
private static int ItemMask()
{
if (s_itemMask >= 0) return s_itemMask;
int mask = LayerMask.GetMask("item");
s_itemMask = mask != 0 ? mask : ~0;
return s_itemMask;
}
private bool HasDropsNear(Vector3 point)
{
Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask());
foreach (Collider hit in hits)
{
if (hit == null) continue;
ItemDrop drop = hit.GetComponentInParent<ItemDrop>();
if (drop != null && drop.m_itemData != null) return true;
}
return false;
}
/// <summary>
/// Picks up everything lying around a station. The drop is destroyed and its contents become
/// entries in the virtual payload, which is the same road the smelter's bars, the oven's bread
/// and the fermenter's bottles all arrive by - one pickup routine for three families.
/// </summary>
private void SweepDrops(Vector3 point)
{
Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask());
foreach (Collider hit in hits)
{
if (hit == null) continue;
if (PayloadCount() >= PayloadCap) return;
ItemDrop drop = hit.GetComponentInParent<ItemDrop>();
if (drop == null || drop.m_itemData == null) continue;
ZNetView nview = drop.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) continue;
if (!nview.IsOwner()) nview.ClaimOwnership();
string name = drop.m_itemData.m_dropPrefab != null
? drop.m_itemData.m_dropPrefab.name
: Utils.GetPrefabName(drop.gameObject);
if (string.IsNullOrEmpty(name)) continue;
AddToPayload(name, Mathf.Max(1, drop.m_itemData.m_stack));
if (ZNetScene.instance != null) ZNetScene.instance.Destroy(drop.gameObject);
}
}
/// <summary>
/// Puts the virtual load back into the world as real objects. Called when the servant dies and
/// when there is nowhere left to put anything - the two ends of the same promise, which is that
/// nothing the player owns is ever deleted by this feature.
/// </summary>
public void DropPayload()
{
if (m_payload.Count == 0) return;
if (ObjectDB.instance == null) { m_payload.Clear(); return; }
Vector3 at = transform.position + Vector3.up * 0.4f;
foreach (Load load in m_payload)
{
GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name);
ItemDrop template = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (template == null || template.m_itemData == null) continue;
int left = load.Count;
int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize);
while (left > 0)
{
int stack = Mathf.Min(left, max);
// ItemDrop.DropItem instantiates item.m_dropPrefab - a clone off a raw ObjectDB
// prefab does not carry that (see AswidBloodPotions.MakeFood for the same fix).
// Without this, dropping a payload throws instantiating null and never clears
// it, so the same broken load is retried - and crashes - on every AI tick after.
ItemDrop.ItemData clone = template.m_itemData.Clone();
clone.m_dropPrefab = prefab;
ItemDrop.DropItem(clone, stack,
at + Random.insideUnitSphere * 0.3f, Quaternion.identity);
left -= stack;
}
}
m_payload.Clear();
WritePayload();
}
// ================================================================ chests
/// <summary>
/// Takes up to <paramref name="want"/> of a prefab out of a chest. The sigil is skipped by name,
/// which is the one thing in here that must never be got wrong: carrying it off would unmark the
/// chest halfway through a job.
/// </summary>
private int TakeFrom(Container chest, string prefabName, int want)
{
if (chest == null || want <= 0) return 0;
if (prefabName == ButlerConfig.SigilItem.Value) return 0;
ZNetView nview = chest.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return 0;
if (!nview.IsOwner()) nview.ClaimOwnership();
Inventory inventory = chest.GetInventory();
if (inventory == null) return 0;
List<ItemDrop.ItemData> matches = new List<ItemDrop.ItemData>();
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null || item.m_dropPrefab == null) continue;
if (item.m_dropPrefab.name != prefabName) continue;
matches.Add(item);
}
int taken = 0;
foreach (ItemDrop.ItemData item in matches)
{
if (taken >= want) break;
int amount = Mathf.Min(item.m_stack, want - taken);
if (amount <= 0) continue;
inventory.RemoveItem(item, amount);
taken += amount;
}
if (taken > 0 && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null);
return taken;
}
/// <summary>The first thing in any sealed chest that this station will take.</summary>
private string FindMaterialFor(ButlerStation station, out Container chest)
{
foreach (Container candidate in m_chests)
{
if (candidate == null || candidate.IsInUse()) continue;
string item = FirstAccepted(station, candidate);
if (item == null) continue;
chest = candidate;
return item;
}
chest = null;
return null;
}
private string FirstAccepted(ButlerStation station, Container chest)
{
Inventory inventory = chest != null ? chest.GetInventory() : null;
if (inventory == null) return null;
string sigil = ButlerConfig.SigilItem.Value;
string fuel = station.FuelPrefab;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null || item.m_dropPrefab == null) continue;
string name = item.m_dropPrefab.name;
if (name == sigil) continue;
if (name == fuel) continue; // fuel has its own errand
if (!station.Accepts(name)) continue;
return name;
}
return null;
}
private Container FindChestWith(string prefabName)
{
foreach (Container chest in m_chests)
{
if (chest == null || chest.IsInUse()) continue;
Inventory inventory = chest.GetInventory();
if (inventory == null) continue;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName)
{
return chest;
}
}
}
return null;
}
/// <summary>Where the finished goods go: the chest that fed the station, or the nearest sealed
/// one with room if that chest is gone, full, or never existed.</summary>
private Container ChestForProduct()
{
ZDOID source = m_nview.GetZDO().GetZDOID(KeySource);
Container home = ContainerById(source);
if (home != null && !IsPenalised(source) && HasRoomFor(home)) return home;
Container best = null;
float bestDistance = float.MaxValue;
foreach (Container chest in m_chests)
{
if (chest == null || chest.IsInUse()) continue;
if (IsPenalised(ZdoOf(chest))) continue;
if (!HasRoomFor(chest)) continue;
float distance = Vector3.Distance(transform.position, chest.transform.position);
if (distance >= bestDistance) continue;
bestDistance = distance;
best = chest;
}
return best;
}
private bool HasRoomFor(Container chest)
{
Inventory inventory = chest != null ? chest.GetInventory() : null;
if (inventory == null || ObjectDB.instance == null) return false;
foreach (Load load in m_payload)
{
GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name);
if (prefab != null && inventory.CanAddItem(prefab, 1)) return true;
}
return false;
}
// ================================================================ payload
private bool AcceptsAnything(ButlerStation station)
{
foreach (Load load in m_payload)
{
if (station.Accepts(load.Name)) return true;
if (load.Name == station.FuelPrefab && station.FuelWanted > 0) return true;
}
return false;
}
private void AddToPayload(string name, int count)
{
if (string.IsNullOrEmpty(name) || count <= 0) return;
foreach (Load load in m_payload)
{
if (load.Name != name) continue;
load.Count += count;
WritePayload();
return;
}
m_payload.Add(new Load { Name = name, Count = count });
WritePayload();
}
private int PayloadCount()
{
int total = 0;
foreach (Load load in m_payload) total += load.Count;
return total;
}
private string Describe()
{
if (m_payload.Count == 0) return "nothing";
if (m_payload.Count == 1) return m_payload[0].Count + "x " + m_payload[0].Name;
return PayloadCount() + " items";
}
/// <summary>"Copper:8;Coal:12". Small, readable in a ZDO dump, and enough to survive a handover
/// mid-job - which is the whole reason the payload lives in the ZDO instead of in this class.</summary>
private void WritePayload()
{
if (m_nview == null || !m_nview.IsValid()) return;
StringBuilder builder = new StringBuilder();
foreach (Load load in m_payload)
{
if (load.Count <= 0) continue;
if (builder.Length > 0) builder.Append(';');
builder.Append(load.Name).Append(':').Append(load.Count);
}
m_nview.GetZDO().Set(KeyLoad, builder.ToString());
}
private void ReadPayload()
{
m_payload.Clear();
if (m_nview == null || !m_nview.IsValid()) return;
string raw = m_nview.GetZDO().GetString(KeyLoad, "");
if (string.IsNullOrEmpty(raw)) return;
foreach (string entry in raw.Split(';'))
{
if (string.IsNullOrEmpty(entry)) continue;
int split = entry.LastIndexOf(':');
if (split <= 0) continue;
int count;
if (!int.TryParse(entry.Substring(split + 1), out count) || count <= 0) continue;
m_payload.Add(new Load { Name = entry.Substring(0, split), Count = count });
}
}
// ================================================================ small change
private static ZDOID ZdoOf(Component component)
{
ZNetView nview = component != null ? component.GetComponent<ZNetView>() : null;
return nview != null && nview.IsValid() ? nview.GetZDO().m_uid : ZDOID.None;
}
private Container ContainerById(ZDOID id)
{
if (id == ZDOID.None || ZNetScene.instance == null) return null;
GameObject go = ZNetScene.instance.FindInstance(id);
return go != null ? go.GetComponent<Container>() : null;
}
private ButlerStation StationById(ZDOID id)
{
foreach (ButlerStation station in m_stations)
{
if (station.Id == id) return station;
}
if (id == ZDOID.None || ZNetScene.instance == null) return null;
GameObject go = ZNetScene.instance.FindInstance(id);
return go != null ? ButlerStation.From(go) : null;
}
private void Penalise(ZDOID id)
{
if (id == ZDOID.None) return;
m_penalties[id] = Time.time + PenaltySeconds;
}
/// <summary>Never shortens a penalty already running: a target set aside for three minutes
/// because it could not be reached must not be let back in after twenty seconds.</summary>
private void PenaliseShort(ZDOID id)
{
if (id == ZDOID.None) return;
float until;
float wanted = Time.time + ShortPenaltySeconds;
if (m_penalties.TryGetValue(id, out until) && until > wanted) return;
m_penalties[id] = wanted;
}
private bool IsPenalised(ZDOID id)
{
float until;
return m_penalties.TryGetValue(id, out until) && Time.time < until;
}
private void ExpirePenalties()
{
if (m_penalties.Count == 0) return;
List<ZDOID> done = null;
foreach (KeyValuePair<ZDOID, float> entry in m_penalties)
{
if (Time.time < entry.Value) continue;
if (done == null) done = new List<ZDOID>();
done.Add(entry.Key);
}
if (done == null) return;
foreach (ZDOID id in done) m_penalties.Remove(id);
}
/// <summary>Seconds this station has been waiting with work available.</summary>
private float NoteIdle(ZDOID id)
{
float since;
if (!m_idleSince.TryGetValue(id, out since))
{
m_idleSince[id] = Time.time;
return 0f;
}
return Time.time - since;
}
}
/// <summary>
/// The whole of the servant's mind, in one prefix.
///
/// Returning false skips MonsterAI.UpdateAI entirely - targeting, alerting, fleeing, wandering and
/// attacking with it - so the servant is peaceful by construction rather than by having its weapon
/// confiscated. __result is legitimate here and not the old PlacePiece trap: that one threw because
/// the patched method was VOID. This one returns bool, which is exactly what a prefix may write.
///
/// Bound positionally (__0) so a parameter rename in a future patch cannot stop the mod from
/// applying its patches at startup.
/// </summary>
[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
public static class BoneServantUpdateAIPatch
{
public static bool Prefix(MonsterAI __instance, float __0, ref bool __result)
{
if (__instance == null) return true;
BoneServantAI servant = __instance.GetComponent<BoneServantAI>();
if (servant == null) return true;
// The one way back into vanilla: a servant that fights back hands over the whole tick for
// as long as there is a fight. Always false for the Bone Servants themselves.
if (servant.HandsToVanilla()) return true;
__result = servant.Tick(__0);
return false;
}
}
/// <summary>Hit and it walks home. The same postfix shape the sentry's regeneration uses, on the
/// same method, which is a shape known to work in this project.</summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class BoneServantDamagePatch
{
public static void Postfix(Character __instance)
{
if (__instance == null) return;
BoneServantAI servant = __instance.GetComponent<BoneServantAI>();
if (servant != null) servant.NoteDamage();
}
}
}