rimworld-blax-castes/Source/BlaxCastes/JoinHooks.cs

380 lines
16 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using Verse;
namespace BlaxCastes
{
/// <summary>A pawn's faction, guest status and host faction, taken before a status change.</summary>
internal struct JoinSnapshot
{
public bool valid;
public Faction faction;
public bool hasGuest;
public GuestStatus status;
public Faction host;
/// <summary>The former-caste record the pawn would leave, taken before the change (colonists and slaves with a record only).</summary>
public FormerCaste former;
public static JoinSnapshot Of(Pawn pawn)
{
Pawn_GuestTracker guest = pawn.guest;
return new JoinSnapshot
{
valid = true,
faction = pawn.Faction,
hasGuest = guest != null,
status = guest != null ? guest.guestStatusInt : GuestStatus.Guest,
host = guest?.HostFaction,
};
}
public JoinSide Side => JoinDefaults.Classify(faction, hasGuest, status, host);
}
/// <summary>
/// Shared bodies of the join hooks. The prefixes snapshot the pawn, the postfixes compare. Only a
/// change into player colonist, player slave or player prisoner queues a join, so the
/// SetGuestStatus(null) that vanilla runs on existing members (inside SetFaction, before a trade)
/// queues nothing. Every change between colonist, slave and prisoner queues one, so the status rows
/// see arrests, releases, recruiting, enslaving and freeing. A change out of the player side is
/// noted, and the membership ends on the next tick if the pawn is still gone by then. A colonist or
/// slave that leaves the player side or becomes a prisoner leaves a former-caste record, taken in the
/// prefix, so it holds the pawn's settings from before the game changed any of them. Inside a
/// sale nothing is queued; the sale writes the record itself. Leaving the map (Pawn.ExitMap, a closing
/// map) is judged as a whole, from the status before it to the status after it (AfterLeaving).
/// Nothing is applied here: SetFaction and SetGuestStatus reset medical care, areas, work and slave
/// mode right after, so joins wait for the next tick.
/// </summary>
internal static class JoinHooks
{
private static readonly HashSet<string> logged = new HashSet<string>();
/// <summary>Logs a hook failure once per hook and game, so a Castes bug can never break a trade or a capture.</summary>
public static void LogOnce(string where, Exception e)
{
try
{
if (logged.Add(where))
Log.Error("[Blax Castes] " + where + " failed (logged once per game): " + e);
}
catch
{
}
}
/// <summary>Called when a game starts or loads, so a failure in a later game is logged again.</summary>
public static void ResetLogOnce() => logged.Clear();
internal static bool Watching(Pawn pawn) =>
pawn != null && Current.Game != null && Scribe.mode == LoadSaveMode.Inactive
&& pawn.RaceProps != null && pawn.RaceProps.Humanlike;
public static JoinSnapshot Before(Pawn pawn)
{
JoinSnapshot snapshot;
try
{
if (!Watching(pawn))
return default;
snapshot = JoinSnapshot.Of(pawn);
}
catch (Exception e)
{
LogOnce("Join snapshot", e);
return default;
}
snapshot.former = CaptureFormer(pawn, snapshot.Side);
return snapshot;
}
/// <summary>
/// The former-caste record, taken before the game changes anything (it resets medical care inside
/// SetFaction and SetGuestStatus). A failure here only loses the record, never the join.
/// </summary>
public static FormerCaste CaptureFormer(Pawn pawn, JoinSide side)
{
try
{
return JoinDefaults.Capture(pawn, side);
}
catch (Exception e)
{
LogOnce("Former caste snapshot", e);
return null;
}
}
public static void After(Pawn pawn, JoinSnapshot before)
{
if (!before.valid)
return;
try
{
JoinSide was = before.Side;
JoinSide now = JoinSnapshot.Of(pawn).Side;
if (was == now)
return;
string scope = JoinScopes.ReasonFor(pawn);
if (scope == JoinScopes.Leaving)
return; // AfterLeaving judges the whole departure once it is over
if (scope == JoinScopes.Sold)
{
if (now == JoinSide.None)
JoinDefaults.NoteLeft(pawn);
return;
}
if ((was == JoinSide.Colonist || was == JoinSide.Slave) && (now == JoinSide.None || now == JoinSide.Prisoner))
JoinDefaults.NoteFormer(pawn, was, before.former);
if (now != JoinSide.None)
JoinDefaults.Enqueue(pawn, scope ?? JoinDefaults.StatusFallback);
else
JoinDefaults.NoteLeft(pawn);
}
catch (Exception e)
{
LogOnce("Join check", e);
}
}
// ---- leaving the map ---------------------------------------------------------------------
/// <summary>
/// Before a pawn leaves the map (Pawn.ExitMap) or is passed to the world by a closing map: the
/// snapshot, and a Leaving scope, so the status changes inside the departure wait for AfterLeaving.
/// Only for pawns that are player-side or have a membership record; the rest change nothing here.
/// </summary>
public static LeaveState BeforeLeaving(Pawn pawn)
{
var state = new LeaveState { pawn = pawn };
JoinSnapshot before = Before(pawn);
if (!before.valid)
return state;
try
{
if (before.Side == JoinSide.None && GameComponent_BlaxCastes.Instance?.MembershipOf(pawn) == null)
return state;
state.before = before;
state.travelling = pawn.teleporting || InTransporter(pawn);
state.token = JoinScopes.Push(JoinScopes.Leaving, pawn);
}
catch (Exception e)
{
LogOnce("Leaving snapshot", e);
}
return state;
}
/// <summary>
/// After the departure: the status before it is compared with the status now, the way After compares
/// one status change. A pawn the game moved out of the faction (a freed slave from another faction
/// that walked off, an escaped slave, a colonist left behind on a closing map) therefore leaves its
/// caste with the status it had before it left, never as a colonist who joined. Leaving in a caravan,
/// a transport pod or a shuttle, or being kidnapped, changes nothing: the game keeps those pawns in the
/// faction, so they keep their caste. A pawn that walked off for good while the game still counts it
/// as player-side (an escaped prisoner keeps its prisoner status in the world; a freed slave a quest
/// holds stays in the faction) leaves its caste at once, since nothing would end the membership later.
/// </summary>
public static void AfterLeaving(LeaveState state)
{
JoinScopes.Pop(state.token);
if (!state.before.valid)
return;
Pawn pawn = state.pawn;
try
{
JoinSide was = state.before.Side;
JoinSide now = JoinDefaults.SideOf(pawn);
if (now != JoinSide.None && LeftForGood(pawn, state) && (now != was || pawn.Faction != Faction.OfPlayer))
JoinDefaults.NoteGone(pawn, was, state.before.former);
else
After(pawn, state.before);
}
catch (Exception e)
{
LogOnce("Leaving check", e);
}
}
/// <summary>A closing map: BeforeLeaving for each of its pawns that matters. Null when none does.</summary>
public static List<LeaveState> BeforeMapClosed(Map map)
{
List<LeaveState> states = null;
try
{
if (map?.mapPawns == null || Current.Game == null)
return null;
foreach (Pawn pawn in map.mapPawns.AllPawns.ToList())
{
LeaveState state = BeforeLeaving(pawn);
if (state.before.valid)
(states ??= new List<LeaveState>()).Add(state);
}
}
catch (Exception e)
{
LogOnce("Closing map snapshot", e);
}
return states;
}
/// <summary>After a closing map passed its pawns to the world: every scope closes first, then each pawn is judged.</summary>
public static void AfterMapClosed(List<LeaveState> states)
{
if (states == null || states.Count == 0)
return;
JoinScopes.Pop(states[0].token);
foreach (LeaveState state in states)
AfterLeaving(state);
}
/// <summary>Inside a transport pod or a shuttle, on the map or travelling.</summary>
private static bool InTransporter(Pawn pawn) =>
ThingOwnerUtility.AnyParentIs<ActiveTransporterInfo>(pawn) || ThingOwnerUtility.AnyParentIs<TravellingTransporters>(pawn);
/// <summary>
/// The pawn is off every map and does not travel on: a living world pawn outside caravans, transport
/// pods and shuttles, not teleporting and not kidnapped.
/// </summary>
private static bool LeftForGood(Pawn pawn, LeaveState state) =>
!state.travelling && !pawn.Spawned && !pawn.Dead && pawn.IsWorldPawn() && !pawn.IsCaravanMember()
&& !InTransporter(pawn) && !pawn.IsKidnapped();
/// <summary>A sale finished: a colonist or slave that left the player side leaves the former-caste record taken before the sale.</summary>
public static void AfterSale(Pawn pawn, JoinSide before, FormerCaste former)
{
try
{
if (JoinDefaults.SideOf(pawn) == JoinSide.None)
JoinDefaults.NoteFormer(pawn, before, former);
}
catch (Exception e)
{
LogOnce("Sale check", e);
}
}
}
/// <summary>What the leaving prefixes hand their finalizers (JoinHooks.BeforeLeaving).</summary>
internal struct LeaveState
{
public Pawn pawn;
/// <summary>The Leaving scope's token, 0 when none was opened.</summary>
public int token;
/// <summary>Invalid when the departure does not matter to Castes.</summary>
public JoinSnapshot before;
/// <summary>The pawn travels on: it was teleporting, or inside a transport pod or shuttle, when it left.</summary>
public bool travelling;
}
/// <summary>What the PreTraded prefix hands its finalizer.</summary>
internal struct TradeState
{
public int token;
public bool selling;
public JoinSide side;
public FormerCaste former;
}
[HarmonyPatch(typeof(Pawn), nameof(Pawn.SetFaction), new[] { typeof(Faction), typeof(Pawn) })]
internal static class Patch_Pawn_SetFaction
{
public static void Prefix(Pawn __instance, out JoinSnapshot __state) => __state = JoinHooks.Before(__instance);
public static void Postfix(Pawn __instance, JoinSnapshot __state) => JoinHooks.After(__instance, __state);
}
[HarmonyPatch(typeof(Pawn_GuestTracker), nameof(Pawn_GuestTracker.SetGuestStatus))]
internal static class Patch_GuestTracker_SetGuestStatus
{
public static void Prefix(Pawn ___pawn, out JoinSnapshot __state) => __state = JoinHooks.Before(___pawn);
public static void Postfix(Pawn ___pawn, JoinSnapshot __state) => JoinHooks.After(___pawn, __state);
}
/// <summary>
/// A pawn leaves the map. A freed slave from another faction is set free at the map edge (inside this
/// call) and then moved out of the faction when the game passes it to the world, so the departure is
/// judged as a whole (JoinHooks.AfterLeaving). The finalizer runs even when ExitMap throws.
/// </summary>
[HarmonyPatch(typeof(Pawn), nameof(Pawn.ExitMap))]
internal static class Patch_Pawn_ExitMap
{
public static void Prefix(Pawn __instance, out LeaveState __state) => __state = JoinHooks.BeforeLeaving(__instance);
public static Exception Finalizer(Exception __exception, LeaveState __state)
{
JoinHooks.AfterLeaving(__state);
return __exception;
}
}
/// <summary>
/// A map closes (an abandoned settlement, a caravan site left behind) and passes the pawns still on it to
/// the world: a slave there is set free, then moved out of the faction. Judged per pawn like ExitMap.
/// </summary>
[HarmonyPatch(typeof(MapDeiniter), "PassPawnsToWorld")]
internal static class Patch_MapDeiniter_PassPawnsToWorld
{
public static void Prefix(Map map, out List<LeaveState> __state) => __state = JoinHooks.BeforeMapClosed(map);
public static Exception Finalizer(Exception __exception, List<LeaveState> __state)
{
JoinHooks.AfterMapClosed(__state);
return __exception;
}
}
/// <summary>
/// Buying: the pawn's status changes inside Pawn.PreTraded, so a "bought" scope covers it. Blax Slaves
/// and Trade as Slave or Colonist only set guest.joinStatus before this call, so the final status
/// (slave or not) picks the row. Selling: a "sold" scope keeps the slave-to-free step inside the sale
/// from queueing a join, and the finalizer writes the former-caste record with the status the pawn
/// had before the sale. The finalizer pops the scope even when PreTraded throws.
/// </summary>
[HarmonyPatch(typeof(Pawn), nameof(Pawn.PreTraded))]
internal static class Patch_Pawn_PreTraded
{
public static void Prefix(Pawn __instance, TradeAction action, out TradeState __state)
{
__state = default;
try
{
if (action == TradeAction.PlayerBuys)
{
__state.token = JoinScopes.Push(JoinScopes.Bought, __instance);
}
else if (action == TradeAction.PlayerSells && JoinHooks.Watching(__instance))
{
__state.selling = true;
__state.side = JoinDefaults.SideOf(__instance);
__state.former = JoinHooks.CaptureFormer(__instance, __state.side);
__state.token = JoinScopes.Push(JoinScopes.Sold, __instance);
}
}
catch (Exception e)
{
JoinHooks.LogOnce("Trade scope", e);
}
}
public static Exception Finalizer(Exception __exception, Pawn __instance, TradeState __state)
{
try
{
JoinScopes.Pop(__state.token);
if (__state.selling && __exception == null)
JoinHooks.AfterSale(__instance, __state.side, __state.former);
}
catch (Exception e)
{
JoinHooks.LogOnce("Trade scope", e);
}
return __exception;
}
}
}