using System.Collections.Generic; using System.Linq; using HarmonyLib; using RimWorld; using RimWorld.Planet; using RimWorld.QuestGen; using Verse; namespace BlaxSlaves { public class RunawayRecord : IExposable { public Pawn pawn; public Faction origin; // the slave's SlaveFaction before escaping public Faction finder; // who brings them back public SlaveInteractionModeDef mode; public Map map; public int dueTick; public bool pinnedByUs; public void ExposeData() { if (Scribe.mode == LoadSaveMode.Saving) { if (map != null && !Find.Maps.Contains(map)) map = null; List factions = Find.FactionManager.AllFactionsListForReading; if (origin != null && !factions.Contains(origin)) origin = null; if (finder != null && !factions.Contains(finder)) finder = null; } Scribe_References.Look(ref pawn, "pawn"); Scribe_References.Look(ref origin, "origin"); Scribe_References.Look(ref finder, "finder"); Scribe_Defs.Look(ref mode, "mode"); Scribe_References.Look(ref map, "map"); Scribe_Values.Look(ref dueTick, "dueTick"); Scribe_Values.Look(ref pinnedByUs, "pinnedByUs"); } } /// /// Tracks branded slaves who escaped. A non-hostile faction brings them back after a few days. /// A hostile faction keeps them. /// public class GameComponent_BlaxRunaways : GameComponent { private const int CheckInterval = 250; private List records = new List(); private static readonly HashSet pending = new HashSet(); public static GameComponent_BlaxRunaways Instance => Current.Game?.GetComponent(); public static bool IsPending(Pawn pawn) => pawn != null && pending.Contains(pawn); public GameComponent_BlaxRunaways(Game game) { pending.Clear(); } public void Register(Pawn pawn, Faction origin, SlaveInteractionModeDef mode, Map map) { if (pawn == null || IsPending(pawn)) return; BlaxSlavesSettings settings = BlaxSlavesMod.Settings; Faction finder = pawn.Faction; if (finder != null && finder.HostileTo(Faction.OfPlayer)) { Find.LetterStack.ReceiveLetter( "BlaxSlaves_RunawayKeptLabel".Translate(pawn.Named("PAWN")), "BlaxSlaves_RunawayKeptText".Translate(pawn.Named("PAWN"), finder.Named("FACTION")), LetterDefOf.NegativeEvent, null, finder); return; } if (finder == null || finder.IsPlayer || finder.defeated || finder.Hidden) finder = Find.FactionManager.RandomNonHostileFaction(allowHidden: false, allowDefeated: false, allowNonHumanlike: false); if (!settings.returnRunaways || finder == null || !ModsConfig.IdeologyActive || !Rand.Chance(settings.returnChance)) { Messages.Message("BlaxSlaves_RunawayGoneMessage".Translate(pawn.Named("PAWN")), MessageTypeDefOf.NegativeEvent); return; } int minDays = settings.returnDelayMinDays; int maxDays = settings.returnDelayMaxDays < minDays ? minDays : settings.returnDelayMaxDays; var record = new RunawayRecord { pawn = pawn, origin = origin, finder = finder, mode = mode, map = map, dueTick = Find.TickManager.TicksGame + Rand.RangeInclusive(minDays, maxDays) * GenDate.TicksPerDay, pinnedByUs = Find.WorldPawns.ForcefullyKeptPawns.Add(pawn), }; records.Add(record); pending.Add(pawn); Messages.Message("BlaxSlaves_RunawaySearchMessage".Translate(pawn.Named("PAWN"), finder.Named("FACTION")), MessageTypeDefOf.NeutralEvent); } public override void GameComponentTick() { if (records.Count == 0 || Find.TickManager.TicksGame % CheckInterval != 0) return; int now = Find.TickManager.TicksGame; for (int i = records.Count - 1; i >= 0; i--) { RunawayRecord r = records[i]; if (r.pawn == null || r.pawn.Destroyed || r.pawn.Dead || r.pawn.Discarded) { Drop(i); continue; } // Spawning elsewhere (a visit) drops the pin; restore it once they're back in the world. if (r.pinnedByUs && r.pawn.IsWorldPawn()) Find.WorldPawns.ForcefullyKeptPawns.Add(r.pawn); if (now < r.dueTick) continue; switch (RunawayDelivery.TryDeliver(r)) { case DeliveryResult.Delivered: pending.Remove(r.pawn); records.RemoveAt(i); break; case DeliveryResult.Retry: r.dueTick = now + GenDate.TicksPerDay / 2; break; default: Drop(i); break; } } } private void Drop(int index) { RunawayRecord r = records[index]; if (r.pawn != null) { pending.Remove(r.pawn); if (r.pinnedByUs) Find.WorldPawns.ForcefullyKeptPawns.Remove(r.pawn); } records.RemoveAt(index); } public override void ExposeData() { base.ExposeData(); Scribe_Collections.Look(ref records, "runaways", LookMode.Deep); if (Scribe.mode == LoadSaveMode.PostLoadInit) { if (records == null) records = new List(); records.RemoveAll(r => r == null || r.pawn == null); pending.Clear(); foreach (RunawayRecord r in records) pending.Add(r.pawn); } } } public enum DeliveryResult { Delivered, Retry, Cancel, } public static class RunawayDelivery { public static DeliveryResult TryDeliver(RunawayRecord r) { Pawn pawn = r.pawn; if (!pawn.IsWorldPawn()) { // Out visiting with another mod's guest group, say: wait until they're back in the world. // Recruited or captured by the player: nothing left to return. if (pawn.SpawnedOrAnyParentSpawned && pawn.Faction != Faction.OfPlayer && !pawn.IsPrisoner) return DeliveryResult.Retry; return DeliveryResult.Cancel; } if (Find.WorldPawns.GetSituation(pawn) != WorldPawnSituation.Free || pawn.guest == null) return DeliveryResult.Cancel; Faction holder = pawn.Faction; if (holder != null && holder.HostileTo(Faction.OfPlayer)) { Find.LetterStack.ReceiveLetter( "BlaxSlaves_RunawayKeptLabel".Translate(pawn.Named("PAWN")), "BlaxSlaves_RunawayKeptText".Translate(pawn.Named("PAWN"), holder.Named("FACTION")), LetterDefOf.NegativeEvent, null, holder); return DeliveryResult.Cancel; } List factions = Find.FactionManager.AllFactionsListForReading; Faction deliverer = r.finder; if (deliverer == null || !factions.Contains(deliverer) || deliverer.HostileTo(Faction.OfPlayer) || deliverer.defeated) deliverer = holder != null && !holder.IsPlayer && !holder.Hidden ? holder : Find.FactionManager.RandomNonHostileFaction(allowNonHumanlike: false); if (deliverer == null || !ModsConfig.IdeologyActive) return DeliveryResult.Cancel; Map map = r.map != null && Find.Maps.Contains(r.map) && r.map.IsPlayerHome ? r.map : Find.AnyPlayerHomeMap; if (map == null) return DeliveryResult.Retry; // Put them back under their original faction first, so SlaveFaction (and HomeFaction) is // exactly what it was before the escape, not whoever found them. Null (wild or hidden-faction // origin) and the player (born in the colony) are restored as-is: they decide whether an // emancipated slave stays. Faction origin = r.origin != null && factions.Contains(r.origin) ? r.origin : null; if (pawn.Faction != origin) pawn.SetFaction(origin); pawn.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave); SlaveInteractionModeDef mode = r.mode; if (mode == null || mode == SlaveInteractionModeDefOf.Execute || mode == SlaveInteractionModeDefOf.Emancipate || mode == SlaveInteractionModeDefOf.Imprison) mode = SlaveInteractionModeDefOf.Suppress; pawn.guest.slaveInteractionMode = mode; pawn.apparel?.UnlockAll(); // Weapons come back separately, not in their hands (a relic they ran off with included). var delivery = new List { pawn }; if (pawn.equipment != null) { foreach (ThingWithComps eq in pawn.equipment.AllEquipmentListForReading.ToList()) { pawn.equipment.Remove(eq); delivery.Add(eq); } } bool walkIn = deliverer.def.techLevel < TechLevel.Industrial && map.CanEverExit; IntVec3 cell = IntVec3.Invalid; if (walkIn && !CellFinder.TryFindRandomEdgeCellWith(c => c.Standable(map) && map.reachability.CanReachColony(c), map, CellFinder.EdgeRoadChance_Friendly, out cell) && !CellFinder.TryFindRandomEdgeCellWith(c => c.Standable(map), map, CellFinder.EdgeRoadChance_Friendly, out cell)) { walkIn = false; } if (walkIn) { GenSpawn.Spawn(pawn, cell, map); for (int i = 1; i < delivery.Count; i++) GenPlace.TryPlaceThing(delivery[i], cell, map, ThingPlaceMode.Near); } else { DropPodUtility.DropThingsNear(DropCellFinder.TradeDropSpot(map), map, delivery, canRoofPunch: false, forbid: false, faction: deliverer); } Find.LetterStack.ReceiveLetter( "BlaxSlaves_RunawayReturnedLabel".Translate(pawn.Named("PAWN")), "BlaxSlaves_RunawayReturnedText".Translate(pawn.Named("PAWN"), deliverer.Named("FACTION")), LetterDefOf.PositiveEvent, pawn, deliverer); return DeliveryResult.Delivered; } } /// Main escape path: a branded colony slave walks off the map (slave rebellion). [HarmonyPatch(typeof(Pawn), nameof(Pawn.ExitMap))] public static class Patch_RunawayExitMap { public class State { public Faction origin; public SlaveInteractionModeDef mode; public Map map; } public static void Prefix(Pawn __instance, out State __state) { __state = null; Pawn pawn = __instance; if (!pawn.IsSlaveOfColony || pawn.guest == null || pawn.guest.Released || pawn.teleporting || !pawn.Spawned) return; if (pawn.IsCaravanMember() || pawn.IsQuestLodger() || ThingOwnerUtility.AnyParentIs(pawn) || ThingOwnerUtility.AnyParentIs(pawn)) return; if (!BrandUtility.IsBrandedByPlayer(pawn)) return; __state = new State { origin = pawn.SlaveFaction, mode = pawn.guest.slaveInteractionMode, map = pawn.Map }; } public static void Postfix(Pawn __instance, State __state) { if (__state == null) return; Pawn pawn = __instance; if (pawn.Dead || pawn.Destroyed || !pawn.IsWorldPawn() || pawn.IsCaravanMember()) return; if (Find.WorldPawns.GetSituation(pawn) != WorldPawnSituation.Free) return; GameComponent_BlaxRunaways.Instance?.Register(pawn, __state.origin, __state.mode, __state.map); } } /// /// Second escape path: the last free member of a caravan dies and its slaves walk away. /// Vanilla leaves them as player-faction world pawns, so give them a faction the way an escape would. /// [HarmonyPatch(typeof(Caravan), nameof(Caravan.Notify_MemberDied))] public static class Patch_RunawayCaravanDisband { public static void Prefix(Caravan __instance, Pawn member, out List __state) { __state = null; if (__instance.Faction != Faction.OfPlayer) return; List pawns = __instance.PawnsListForReading; for (int i = 0; i < pawns.Count; i++) { if (pawns[i] != member && __instance.IsOwner(pawns[i])) return; } for (int i = 0; i < pawns.Count; i++) { Pawn p = pawns[i]; if (p != member && p.IsSlaveOfColony && BrandUtility.IsBrandedByPlayer(p)) { if (__state == null) __state = new List(); __state.Add(p); } } } public static void Postfix(List __state) { if (__state == null) return; foreach (Pawn pawn in __state) { if (pawn.Dead || pawn.Destroyed || !pawn.IsWorldPawn() || pawn.IsCaravanMember()) continue; Faction origin = pawn.SlaveFaction; SlaveInteractionModeDef mode = pawn.guest?.slaveInteractionMode; if (pawn.Faction == Faction.OfPlayer) { if (Find.FactionManager.TryGetRandomNonColonyHumanlikeFaction(out Faction faction, tryMedievalOrBetter: false)) pawn.SetFaction(faction); else pawn.SetFaction(null); } GameComponent_BlaxRunaways.Instance?.Register(pawn, origin, mode, null); } } } /// Keep vanilla from recycling a pending runaway into an unrelated raid, trader or slave stock. [HarmonyPatch(typeof(PawnGenerator), "IsValidCandidateToRedress")] public static class Patch_RunawayNoRedress { public static void Postfix(Pawn pawn, ref bool __result) { if (__result && GameComponent_BlaxRunaways.IsPending(pawn)) __result = false; } } /// Keep quest generation from taking a pending runaway. [HarmonyPatch(typeof(QuestNode_GetPawn), "IsGoodPawn")] public static class Patch_RunawayNotForQuests { public static void Postfix(Pawn pawn, ref bool __result) { if (__result && GameComponent_BlaxRunaways.IsPending(pawn)) __result = false; } } }