using System; using System.Collections.Generic; using System.Linq; using HarmonyLib; using RimWorld; using RimWorld.Planet; using Verse; namespace BlaxCastes { /// A pawn's faction, guest status and host faction, taken before a status change. internal struct JoinSnapshot { public bool valid; public Faction faction; public bool hasGuest; public GuestStatus status; public Faction host; /// The former-caste record the pawn would leave, taken before the change (colonists and slaves with a record only). 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); } /// /// 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, a map a gravship leaves behind) 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. /// internal static class JoinHooks { private static readonly HashSet logged = new HashSet(); /// Logs a hook failure once per hook and game, so a Castes bug can never break a trade or a capture. 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 { } } /// Called when a game starts or loads, so a failure in a later game is logged again. 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; } /// /// 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. /// 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 --------------------------------------------------------------------- /// /// 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. /// 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; } /// /// 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. /// 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); } } /// A closing map: BeforeLeaving for each of its pawns that matters. Null when none does. public static List BeforeMapClosed(Map map) => BeforePawnsLeave(map?.mapPawns?.AllPawns); /// /// Pawns left behind together (a closing map, a map a gravship leaves): BeforeLeaving for each that /// matters. Null when none does. /// public static List BeforePawnsLeave(IEnumerable pawns) { List states = null; try { if (pawns == null || Current.Game == null) return null; foreach (Pawn pawn in pawns.ToList()) { LeaveState state = BeforeLeaving(pawn); if (state.before.valid) (states ??= new List()).Add(state); } } catch (Exception e) { LogOnce("Closing map snapshot", e); } return states; } /// After a closing map passed its pawns to the world: every scope closes first, then each pawn is judged. public static void AfterMapClosed(List states) { if (states == null || states.Count == 0) return; JoinScopes.Pop(states[0].token); foreach (LeaveState state in states) AfterLeaving(state); } /// Inside a transport pod or a shuttle, on the map or travelling. private static bool InTransporter(Pawn pawn) => ThingOwnerUtility.AnyParentIs(pawn) || ThingOwnerUtility.AnyParentIs(pawn); /// /// 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. /// private static bool LeftForGood(Pawn pawn, LeaveState state) => !state.travelling && !pawn.Spawned && !pawn.Dead && pawn.IsWorldPawn() && !pawn.IsCaravanMember() && !InTransporter(pawn) && !pawn.IsKidnapped(); /// A sale finished: a colonist or slave that left the player side leaves the former-caste record taken before the sale. 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); } } } /// What the leaving prefixes hand their finalizers (JoinHooks.BeforeLeaving). internal struct LeaveState { public Pawn pawn; /// The Leaving scope's token, 0 when none was opened. public int token; /// Invalid when the departure does not matter to Castes. public JoinSnapshot before; /// The pawn travels on: it was teleporting, or inside a transport pod or shuttle, when it left. public bool travelling; } /// What the PreTraded prefix hands its finalizer. 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); } /// /// 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. /// [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; } } /// /// 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. /// [HarmonyPatch(typeof(MapDeiniter), "PassPawnsToWorld")] internal static class Patch_MapDeiniter_PassPawnsToWorld { public static void Prefix(Map map, out List __state) => __state = JoinHooks.BeforeMapClosed(map); public static Exception Finalizer(Exception __exception, List __state) { JoinHooks.AfterMapClosed(__state); return __exception; } } /// /// A gravship takes off from a map without a grav anchor (Odyssey): GravshipUtility.AbandonMap despawns /// the pawns left on it and passes them to the world itself, without MapDeiniter.PassPawnsToWorld and /// without ending a prisoner's status, so it is judged per pawn like a closing map. A prisoner left /// behind leaves its caste; colonists and slaves left behind stay in the faction and keep theirs. The /// method is in the 1.7 game with or without Odyssey and returns at once without it, so this patch /// applies everywhere and does nothing without Odyssey. /// [HarmonyPatch(typeof(GravshipUtility), nameof(GravshipUtility.AbandonMap))] internal static class Patch_GravshipUtility_AbandonMap { public static void Prefix(Map map, out List __state) => __state = JoinHooks.BeforePawnsLeave(map?.mapPawns?.AllPawnsSpawned); public static Exception Finalizer(Exception __exception, List __state) { JoinHooks.AfterMapClosed(__state); return __exception; } } /// /// 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. /// [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; } } }