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

227 lines
8.8 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
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. 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.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);
}
}
/// <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 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>
/// 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;
}
}
}