using System; using System.Collections.Generic; using System.Linq; using BlaxSlaves; using RimWorld; using Verse; namespace BlaxSlavesTests { /// /// SlaveHarm: free, non-pacifist colonists take no bad memories when the colony harms its slaves /// (or branded pawns who aren't free members). Each test drives the vanilla path the player /// triggers with observer colonists present, then repeats it on fresh pawns as a control. /// /// Which execution, organ and slave-trade thoughts vanilla gives depends on the quick-test colony's /// random ideoligion, so scenes also use observers whose thoughts don't: a friend of the victim /// (opinion 20+ gives "my friend died") and bystanders who see the death happen. /// public static class MoodGateTests { private const int Seed = 7331; private const string KeptMainKey = "moodgate.reloadMain"; private const string KeptControlKey = "moodgate.reloadControl"; private static readonly List<(Pawn child, Pawn parent)> madeParents = new List<(Pawn child, Pawn parent)>(); private static BlaxSlavesSettings Settings => BlaxSlavesMod.Settings; // ========================================================================================= // harm the gate must suppress // ========================================================================================= [BlaxTest("mood gate: executing a colony slave")] public static void ExecuteSlave() { ExpectSuppressed("executing a colony slave", () => { var s = new Scene(Fixtures.ColonySlave()); s.Add("executioner", Watcher()); Befriend(s.Add("friend", Watcher()), s.victim); s.Add("bystander", Watcher()); PlaceAround(s); return s; }, s => ExecuteLikeWarden(s.victim, s["executioner"])); } [BlaxTest("mood gate: harvesting a kidney from a slave")] public static void HarvestKidney() { ExpectSuppressed("harvesting a kidney from a colony slave", () => SurgeryScene(withFriend: false), s => HarvestOrgan(s.victim, s["surgeon"], "Kidney")); } [BlaxTest("mood gate: harvesting a slave's heart")] public static void HarvestHeart() { ExpectSuppressed("harvesting the heart of a colony slave", () => SurgeryScene(withFriend: true), s => HarvestOrgan(s.victim, s["surgeon"], "Heart")); } [BlaxTest("mood gate: a colonist kills a slave")] public static void ColonistKillsSlave() { ExpectSuppressed("a colonist killing a colony slave", () => { var s = new Scene(Fixtures.ColonySlave()); s.Add("killer", Watcher()); Befriend(s.Add("friend", Watcher()), s.victim); s.Add("bystander", Watcher()); PlaceAround(s); RequireWitnesses(s, "bystander"); return s; }, s => KillBy(s.victim, s["killer"])); } [BlaxTest("mood gate: banishing a downed slave")] public static void BanishDownedSlave() { ExpectSuppressed("banishing a downed colony slave (left to die)", () => { var s = new Scene(Fixtures.ColonySlave()); Befriend(s.Add("friend", Watcher()), s.victim); s.Add("bystander", Watcher()); Down(s.victim); return s; }, s => { PawnBanishUtility.Banish(s.victim); T.Check(s.victim.Faction != Faction.OfPlayer, "banished slave " + s.victim.LabelShort + " still belongs to the colony"); }); } [BlaxTest("mood gate: the banish dialog leaves out thoughts the gate drops")] public static void BanishPreview() { Pawn slave = Fixtures.ColonySlave(); Pawn friend = Watcher(); Befriend(friend, slave); Down(slave); string allColonistsLine = " - " + ThoughtDefOf.PrisonerBanishedToDie.stages[0].LabelCap; string friendHeader = friend.KindLabel.CapitalizeFirst() + " " + friend.LabelShort + ":"; Settings.suppressSlaveHarmMood = false; string vanilla = PawnBanishUtility.GetBanishPawnDialogText(slave); Settings.suppressSlaveHarmMood = true; string gated = PawnBanishUtility.GetBanishPawnDialogText(slave); T.Check(SlaveHarm.Top == null, "a SlaveHarm frame was left open after building the banish dialog text"); T.Info("setting off: " + vanilla); T.Info("setting on: " + gated); if (!vanilla.Contains(allColonistsLine)) T.Skip("vanilla gives no thought here in this setup: the banish dialog for a downed slave lists no '" + allColonistsLine.Trim() + "' line even with suppressSlaveHarmMood off"); T.Check(!gated.Contains(allColonistsLine), "banish dialog still lists '" + allColonistsLine.Trim() + "' with suppressSlaveHarmMood on"); if (vanilla.Contains(friendHeader)) T.Check(!gated.Contains(friendHeader), "banish dialog still lists the friend's thoughts ('" + friendHeader + "') with suppressSlaveHarmMood on"); } [BlaxTest("mood gate: selling a slave to a trader")] public static void SellSlave() { Faction hostile = Fixtures.HostileFaction(); if (hostile == null) T.Skip("no hostile humanlike faction: selling a slave from a friendly faction would turn that faction hostile for the rest of the suite"); ThoughtDef soldThought = DefDatabase.GetNamedSilentFail("SoldMyLovedOne"); WithParentsUndone(() => { Func setup = () => { var s = new Scene(Fixtures.ColonySlave(hostile)); s.Add("negotiator", Watcher()); s.Add("bystander", Watcher()); MakeParent(s.Add("parent", Watcher()), s.victim); return s; }; Action sell = s => SellToTrader(s.victim, s["negotiator"]); Settings.suppressSlaveHarmMood = false; Scene control = Run(setup, sell, "selling a slave (control)"); Settings.suppressSlaveHarmMood = true; Settings.keepRelationGrief = true; Scene withGrief = Run(setup, sell, "selling a slave"); Settings.keepRelationGrief = false; Scene noGrief = Run(setup, sell, "selling a slave, relation grief off"); T.Info("control, suppression off: " + control.Report()); T.Info("suppression on: " + withGrief.Report()); T.Info("suppression on, keepRelationGrief off: " + noGrief.Report()); if (!control.AnyBad) T.Skip("vanilla gives no thought here in this setup: selling a slave gave no bad memories even with suppressSlaveHarmMood off. " + IdeoNote()); foreach (string role in new[] { "negotiator", "bystander" }) T.Check(withGrief.Bad(role).Count == 0, "selling a slave: " + role + " took bad memories with suppressSlaveHarmMood on: " + withGrief.Report() + " (control: " + control.Report() + ")"); if (control.Has("parent", soldThought)) T.Check(withGrief.Has("parent", soldThought), "selling a slave: the slave's parent should keep " + soldThought.defName + " while keepRelationGrief is on, got: " + withGrief.Report()); T.Check(!noGrief.AnyBad, "selling a slave with keepRelationGrief off: expected no bad memories on anyone, got: " + noGrief.Report() + " (control: " + control.Report() + ")"); }); } [BlaxTest("mood gate: executing a branded prisoner, not an unbranded one")] public static void BrandedPrisoner() { Faction hostile = Fixtures.HostileFaction(); if (hostile == null) T.Skip("no hostile humanlike faction to take a prisoner from"); Func> setup = branded => () => { Pawn prisoner = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, hostile)); prisoner.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner); if (branded) BrandUtility.Brand(prisoner, Faction.OfPlayer); T.Check(prisoner.IsPrisonerOfColony, "setup: " + prisoner.LabelShort + " is not a prisoner of the colony"); T.Check(SlaveHarm.IsProtected(prisoner) == branded, "setup: SlaveHarm.IsProtected(" + (branded ? "branded" : "unbranded") + " prisoner) returned " + SlaveHarm.IsProtected(prisoner)); var s = new Scene(prisoner); s.Add("executioner", Watcher()); Befriend(s.Add("friend", Watcher()), prisoner); s.Add("bystander", Watcher()); PlaceAround(s); return s; }; Settings.suppressSlaveHarmMood = true; Scene brandedScene = Run(setup(true), s => ExecuteLikeWarden(s.victim, s["executioner"]), "executing a branded prisoner"); Scene plainScene = Run(setup(false), s => ExecuteLikeWarden(s.victim, s["executioner"]), "executing an unbranded prisoner"); T.Info("branded: " + brandedScene.Report()); T.Info("unbranded: " + plainScene.Report()); T.Check(!brandedScene.AnyBad, "executing a branded prisoner: free colonists took bad memories: " + brandedScene.Report() + " (unbranded, same setting: " + plainScene.Report() + ")"); if (!plainScene.AnyBad) T.Skip("vanilla gives no thought here in this setup: executing an unbranded prisoner gave no bad memories either. " + IdeoNote()); T.Check(plainScene.Has("friend", ThoughtDefOf.PawnWithGoodOpinionDied), "executing an unbranded prisoner should not be suppressed: friend expected " + ThoughtDefOf.PawnWithGoodOpinionDied.defName + ", got: " + plainScene.Report()); } [BlaxTest("mood gate: a slave's corpse in a gibbet cage")] public static void GibbetCageCorpse() { ThingDef cageDef = DefDatabase.GetNamedSilentFail("GibbetCage"); if (cageDef == null) T.Skip("no GibbetCage def (Ideology inactive?)"); Pawn plain = Watcher(); Pawn pacifist = Watcher(pacifist: true); if (plain.Ideo != null && plain.Ideo.IdeoApprovesOfSlavery()) T.Skip("vanilla gives no thought here in this setup: the colony's ideoligion approves of slavery, so gibbet cages scare no one. " + IdeoNote()); Pawn victim = Fixtures.ColonySlave(); Corpse corpse = null; Building_GibbetCage cage = null; try { Seeded(() => victim.Kill(null)); corpse = victim.Corpse; T.NotNull(corpse, "corpse of the killed slave"); IntVec3 cell = FreeBuildCell(corpse.Position); cage = (Building_GibbetCage)GenSpawn.Spawn(ThingMaker.MakeThing(cageDef, GenStuff.DefaultStuffFor(cageDef)), cell, Fixtures.Map); corpse.DeSpawn(); T.Check(cage.GetDirectlyHeldThings().TryAdd(corpse), "could not put the slave's corpse into the gibbet cage"); T.Check(cage.Corpse == corpse, "gibbet cage doesn't report the slave's corpse"); Settings.suppressSlaveHarmMood = false; Thought_Memory control = cage.GiveObservedThought(plain); Settings.suppressSlaveHarmMood = true; Thought_Memory plainThought = cage.GiveObservedThought(plain); Thought_Memory pacifistThought = cage.GiveObservedThought(pacifist); T.Info("setting off: " + (control?.def.defName ?? "null") + "; on, non-pacifist: " + (plainThought?.def.defName ?? "null") + "; on, pacifist: " + (pacifistThought?.def.defName ?? "null")); if (control == null) T.Skip("vanilla gives no thought here in this setup: the gibbet cage gave no observed thought even with suppressSlaveHarmMood off. " + IdeoNote()); T.Check(plainThought == null, "gibbet cage with a slave's corpse still gives a non-pacifist colonist " + plainThought?.def.defName); T.Check(pacifistThought != null, "gibbet cage with a slave's corpse gave the pacifist (Kind) observer no thought; pacifists should keep it"); } finally { if (corpse != null && !corpse.Destroyed) corpse.Destroy(); if (cage != null && !cage.Destroyed) cage.Destroy(); } } // ========================================================================================= // exceptions: what the gate must let through // ========================================================================================= [BlaxTest("mood gate: a raider kills a slave (not suppressed)")] public static void RaiderKillsSlave() { Faction hostile = Fixtures.HostileFaction(); if (hostile == null) T.Skip("no hostile humanlike faction to send a killer from"); ExpectNotSuppressed("a raider killing a colony slave", () => { var s = new Scene(Fixtures.ColonySlave()); Befriend(s.Add("friend", Watcher()), s.victim); s.Add("bystander", Watcher()); PlaceAround(s); RequireWitnesses(s, "bystander"); s.other = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, hostile)); return s; }, s => KillBy(s.victim, s.other)); } [BlaxTest("mood gate: harm to a free colonist is never suppressed")] public static void FreeColonistNotSuppressed() { ExpectNotSuppressed("a colonist killing a free colonist", () => { var s = new Scene(Watcher()); s.Add("killer", Watcher()); Befriend(s.Add("friend", Watcher()), s.victim); s.Add("bystander", Watcher()); PlaceAround(s); RequireWitnesses(s, "bystander"); return s; }, s => KillBy(s.victim, s["killer"])); } [BlaxTest("mood gate: a pacifist observer still takes the bad memory")] public static void PacifistKeepsMemory() { Settings.suppressSlaveHarmMood = true; Scene s = Run(() => { var scene = new Scene(Fixtures.ColonySlave()); scene.Add("killer", Watcher()); scene.Add("bystander", Watcher()); scene.Add("pacifist", Watcher(pacifist: true)); PlaceAround(scene); RequireWitnesses(scene, "bystander", "pacifist"); return scene; }, scene => KillBy(scene.victim, scene["killer"]), "a colonist killing a slave in front of a pacifist"); T.Info(s.Report()); T.Check(s.Has("pacifist", ThoughtDefOf.WitnessedDeathNonAlly), "pacifist (Kind) observer should still get " + ThoughtDefOf.WitnessedDeathNonAlly.defName + " for a slave killed in sight, got: " + s.Report()); T.Check(s.Bad("bystander").Count == 0 && s.Bad("killer").Count == 0, "non-pacifists in the same scene should get no bad memories: " + s.Report()); } [BlaxTest("mood gate: family keeps its grief while keepRelationGrief is on")] public static void FamilyKeepsGrief() { WithParentsUndone(() => { Settings.suppressSlaveHarmMood = true; Settings.keepRelationGrief = true; ThoughtDef grief = null; Scene s = Run(() => { var scene = new Scene(Fixtures.ColonySlave()); scene.Add("killer", Watcher()); scene.Add("bystander", Watcher()); grief = MakeParent(scene.Add("parent", Watcher()), scene.victim); PlaceAround(scene); return scene; }, scene => KillBy(scene.victim, scene["killer"]), "a colonist killing a slave whose parent watches"); T.Info(s.Report()); T.NotNull(grief, "died thought of the parent's relation to the slave"); T.Check(s.Has("parent", grief), "the slave's parent should keep " + grief.defName + " while keepRelationGrief is on, got: " + s.Report()); T.Check(s.Bad("bystander").Count == 0 && s.Bad("killer").Count == 0, "unrelated colonists in the same scene should get no bad memories: " + s.Report()); }); } [BlaxTest("mood gate: family grief is dropped too with keepRelationGrief off")] public static void FamilyGriefOff() { WithParentsUndone(() => { Settings.keepRelationGrief = false; ExpectSuppressed("a colonist killing a slave whose parent watches, keepRelationGrief off", () => { var s = new Scene(Fixtures.ColonySlave()); s.Add("killer", Watcher()); MakeParent(s.Add("parent", Watcher()), s.victim); PlaceAround(s); return s; }, s => KillBy(s.victim, s["killer"])); }); } // ========================================================================================= // save and reload // ========================================================================================= [BlaxTest("mood gate: keep two slaves for the reload check")] public static void KeepSlavesForReload() { T.Carry[KeptMainKey] = Fixtures.Keep(Fixtures.ColonySlave()).ThingID; T.Carry[KeptControlKey] = Fixtures.Keep(Fixtures.ColonySlave()).ThingID; } [BlaxTest("mood gate: executing a slave loaded from the save", phase: 2)] public static void ExecuteReloadedSlave() { Pawn main = KeptSlave(KeptMainKey); Pawn control = KeptSlave(KeptControlKey); var victims = new Queue(new[] { main, control }); try { ExpectSuppressed("executing a slave loaded from the save", () => { var s = new Scene(victims.Dequeue()); s.Add("executioner", Watcher()); Befriend(s.Add("friend", Watcher()), s.victim); s.Add("bystander", Watcher()); PlaceAround(s); return s; }, s => ExecuteLikeWarden(s.victim, s["executioner"])); } finally { // Kept pawns are not part of the per-test cleanup. foreach (Pawn p in new[] { main, control }) if (p.Dead && p.Corpse != null && p.Corpse.Spawned) p.Corpse.Destroy(); } } // ========================================================================================= // runners // ========================================================================================= /// /// The scene with suppression on must leave every observer without new bad memories. The /// same scene on fresh pawns with suppression off must give some, or the test skips. /// private static void ExpectSuppressed(string what, Func setup, Action harm) { Settings.suppressSlaveHarmMood = true; Scene main = Run(setup, harm, what); Settings.suppressSlaveHarmMood = false; Scene control = Run(setup, harm, what + " (control)"); Settings.suppressSlaveHarmMood = true; T.Info("suppression on: " + main.Report()); T.Info("control, suppression off: " + control.Report()); if (main.AnyBad) T.Fail(what + ": free colonists took bad memories with suppressSlaveHarmMood on: " + main.Report() + " (control with it off: " + control.Report() + ")"); if (!control.AnyBad) T.Skip("vanilla gives no thought here in this setup: " + what + " gave no bad memories even with suppressSlaveHarmMood off. " + IdeoNote()); } /// /// For harm the gate must not touch: with suppression on the observers must get what the /// control (suppression off) gave them, at least the thoughts that don't depend on the ideoligion. /// private static void ExpectNotSuppressed(string what, Func setup, Action harm) { Settings.suppressSlaveHarmMood = false; Scene control = Run(setup, harm, what + " (control)"); Settings.suppressSlaveHarmMood = true; Scene main = Run(setup, harm, what); T.Info("control, suppression off: " + control.Report()); T.Info("suppression on: " + main.Report()); if (!control.AnyBad) T.Skip("vanilla gives no thought here in this setup: " + what + " gave no bad memories even with suppressSlaveHarmMood off. " + IdeoNote()); T.Check(main.AnyBad, what + ": expected bad memories with suppressSlaveHarmMood on (nothing to suppress here), got none. Control: " + control.Report()); var steady = new[] { ThoughtDefOf.WitnessedDeathNonAlly, ThoughtDefOf.WitnessedDeathAlly, ThoughtDefOf.PawnWithGoodOpinionDied }; foreach (string role in control.Roles) foreach (ThoughtDef def in steady) if (control.Has(role, def)) T.Check(main.Has(role, def), what + ": " + role + " got " + def.defName + " with suppressSlaveHarmMood off but not with it on. On: " + main.Report() + "; off: " + control.Report()); } private static Scene Run(Func setup, Action harm, string what) { Scene s = setup(); s.Snapshot(); Seeded(() => harm(s)); s.Freeze(); T.Check(SlaveHarm.Top == null, "a SlaveHarm frame was left open after " + what); return s; } private static void Seeded(Action action) { Rand.PushState(Seed); try { action(); } finally { Rand.PopState(); } } private static void WithParentsUndone(Action body) { try { body(); } finally { foreach ((Pawn child, Pawn parent) in madeParents) child?.relations?.TryRemoveDirectRelation(PawnRelationDefOf.Parent, parent); madeParents.Clear(); } } // ========================================================================================= // vanilla paths // ========================================================================================= /// What the execute toil of JobDriver_ExecuteSlave and JobDriver_Execute does. private static void ExecuteLikeWarden(Pawn victim, Pawn executioner) { ExecutionUtility.DoExecutionByCut(executioner, victim); ThoughtUtility.GiveThoughtsForPawnExecuted(victim, executioner, PawnExecutionKind.GenericBrutal); T.Check(victim.Dead, "execution by cut left " + victim.LabelShort + " alive"); } /// A lethal cut from the instigator, the way ExecutionUtility applies one. private static void KillBy(Pawn victim, Thing instigator) { BodyPartRecord neck = ExecutionUtility.ExecuteCutPart(victim); var dinfo = new DamageInfo(DamageDefOf.Cut, 9999f, 999f, -1f, instigator, neck, null, DamageInfo.SourceCategory.ThingOrUnknown, null, instigatorGuilty: false); dinfo.SetIgnoreArmor(true); victim.TakeDamage(dinfo); if (!victim.Dead) victim.Kill(dinfo); T.Check(victim.Dead, "a 9999 cut from " + (instigator?.LabelShort ?? "nobody") + " left " + victim.LabelShort + " alive"); } /// The remove-part recipe worker, as when a surgeon finishes the bill. private static void HarvestOrgan(Pawn patient, Pawn surgeon, string partDefName) { BodyPartRecord part = patient.health.hediffSet.GetNotMissingParts() .FirstOrDefault(r => r.def.defName == partDefName && MedicalRecipesUtility.IsClean(patient, r)); if (part == null) T.Skip("setup: " + patient.LabelShort + " has no clean " + partDefName + " to harvest"); bool lethal = part.def == BodyPartDefOf.Heart; Map map = surgeon.Map; ThingDef organDef = part.def.spawnThingOnRemoved; var organsBefore = organDef == null ? new HashSet() : new HashSet(map.listerThings.ThingsOfDef(organDef)); // The first random roll in ApplyOnPawn is the surgery success check (quality is capped at 0.98). Rand.PushState(SeedWithFirstRollBelow(0.3f)); try { RecipeDefOf.RemoveBodyPart.Worker.ApplyOnPawn(patient, part, surgeon, new List(), null); } finally { Rand.PopState(); } if (organDef != null) foreach (Thing organ in map.listerThings.ThingsOfDef(organDef).ToList()) if (!organsBefore.Contains(organ) && !organ.Destroyed) organ.Destroy(); bool done = lethal ? patient.Dead : patient.health.hediffSet.PartIsMissing(part); if (!done) T.Skip("setup: removing " + partDefName + " from " + patient.LabelShort + " did not " + (lethal ? "kill the patient (deathless?)" : "remove the part (surgery failed)")); } /// Tradeable_Pawn.ResolveTrade, as when the trade dialog is accepted, selling to an orbital trader. private static void SellToTrader(Pawn slave, Pawn negotiator) { TraderKindDef kind = DefDatabase.AllDefsListForReading.FirstOrDefault(d => d.orbital); T.NotNull(kind, "an orbital TraderKindDef"); var ship = new TradeShip(kind); ITrader oldTrader = TradeSession.trader; Pawn oldNegotiator = TradeSession.playerNegotiator; TradeDeal oldDeal = TradeSession.deal; bool oldGiftMode = TradeSession.giftMode; try { TradeSession.trader = ship; TradeSession.playerNegotiator = negotiator; TradeSession.giftMode = false; var tradeable = new Tradeable_Pawn(); tradeable.AddThing(slave, Transactor.Colony); tradeable.ForceToDestination(1); T.Equal(TradeAction.PlayerSells, tradeable.ActionToDo, "trade action for one colony pawn moved to the trader"); tradeable.ResolveTrade(); } finally { TradeSession.trader = oldTrader; TradeSession.playerNegotiator = oldNegotiator; TradeSession.deal = oldDeal; TradeSession.giftMode = oldGiftMode; // What TradeShip.Depart does with its stock: pawns go to the world. ship.GetDirectlyHeldThings().ClearAndDestroyContentsOrPassToWorld(); } T.Check(!slave.Spawned && !slave.IsSlave, "sold slave " + slave.LabelShort + " is still a spawned slave"); } // ========================================================================================= // setup helpers // ========================================================================================= /// /// A spawned free colonist who can see and has no trait that blanks the death thoughts /// (Psychopath, Bloodlust). Non-pacifist unless asked: no Kind and capable of violence. /// Rejected candidates stay for the per-test cleanup. /// private static Pawn Watcher(bool pacifist = false) { for (int i = 0; i < 30; i++) { Pawn p = Fixtures.Colonist(pacifist); if (PawnUtility.IsBiologicallyOrArtificiallyBlind(p)) continue; DropTrait(p, TraitDefOf.Psychopath); DropTrait(p, TraitDefOf.Bloodlust); if (SlaveHarm.IsPacifist(p) != pacifist) continue; return p; } T.Fail("could not generate a seeing " + (pacifist ? "pacifist" : "non-pacifist") + " colonist in 30 tries"); return null; } private static void DropTrait(Pawn p, TraitDef def) { Trait trait = def == null ? null : p.story?.traits?.GetTrait(def); if (trait != null) p.story.traits.RemoveTrait(trait); } private static Scene SurgeryScene(bool withFriend) { var s = new Scene(Fixtures.ColonySlave()); Pawn surgeon = s.Add("surgeon", Watcher()); SkillRecord medicine = surgeon.skills?.GetSkill(SkillDefOf.Medicine); if (medicine != null) medicine.Level = 20; if (withFriend) Befriend(s.Add("friend", Watcher()), s.victim); s.Add("bystander", Watcher()); PlaceAround(s); return s; } /// /// Positive social memories about the victim until opinion reaches 20+, which gives "my friend /// died" on death. More are added only if the victim's looks or traits pull the opinion down. /// private static void Befriend(Pawn watcher, Pawn victim) { MemoryThoughtHandler memories = watcher.needs.mood.thoughts.memories; var boosts = new[] { ThoughtDefOf.CrashedTogether, ThoughtDefOf.RescuedMeByOfferingHelp, ThoughtDefOf.RescuedMe, ThoughtDefOf.HoneymoonPhase, ThoughtDefOf.RecruitedMe, ThoughtDefOf.RescuedMe, ThoughtDefOf.RescuedMe, }; int opinion = watcher.relations.OpinionOf(victim); for (int i = 0; i < boosts.Length && (i < 3 || opinion < 20); i++) { if (boosts[i] != null) memories.TryGainMemory(boosts[i], victim); opinion = watcher.relations.OpinionOf(victim); } T.Check(opinion >= 20, "setup: " + watcher.LabelShort + "'s opinion of " + victim.LabelShort + " is " + opinion + " after " + boosts.Length + " positive memories; the friend-died thought needs 20+"); } /// Makes parent the victim's parent. Returns the thought vanilla gives the parent when the child dies. private static ThoughtDef MakeParent(Pawn parent, Pawn child) { child.relations.AddDirectRelation(PawnRelationDefOf.Parent, parent); madeParents.Add((child, parent)); PawnRelationDef relation = parent.GetMostImportantRelation(child); T.NotNull(relation, "setup: relation from " + parent.LabelShort + " to their child " + child.LabelShort); return relation.GetGenderSpecificDiedThought(child); } private static void Down(Pawn p) { p.health.AddHediff(HediffDefOf.Anesthetic); if (!p.Downed) T.Skip("setup: anesthetic did not down " + p.LabelShort); } /// Moves the watchers onto free cells next to the victim with line of sight, so they see the death. private static void PlaceAround(Scene s) { Map map = s.victim.Map; IntVec3 at = s.victim.Position; var taken = new HashSet { at }; foreach (Pawn w in s.Watchers) { IntVec3 spot = IntVec3.Invalid; foreach (IntVec3 c in GenRadial.RadialCellsAround(at, 5.9f, false)) { if (taken.Contains(c) || !c.InBounds(map) || !c.Standable(map) || c.Fogged(map)) continue; Pawn there = c.GetFirstPawn(map); if (there != null && there != w) continue; if (!GenSight.LineOfSight(at, c, map)) continue; spot = c; break; } if (!spot.IsValid) T.Skip("setup: no free cell with line of sight near " + at + " for " + w.LabelShort); taken.Add(spot); if (w.Position != spot) { w.Position = spot; w.Notify_Teleported(); } } } private static void RequireWitnesses(Scene s, params string[] roles) { foreach (string role in roles) if (!ThoughtUtility.Witnessed(s[role], s.victim)) T.Skip("setup: " + role + " " + s[role].LabelShort + " can't see " + s.victim.LabelShort + " (asleep, blind or no line of sight)"); } private static IntVec3 FreeBuildCell(IntVec3 near) { Map map = Fixtures.Map; foreach (IntVec3 c in GenRadial.RadialCellsAround(near, 8.9f, false)) { if (c.InBounds(map) && c.Standable(map) && !c.Fogged(map) && c.GetEdifice(map) == null && c.GetFirstItem(map) == null && c.GetFirstPawn(map) == null && c.GetFirstBuilding(map) == null) return c; } T.Skip("setup: no free cell for a gibbet cage near " + near); return IntVec3.Invalid; } private static int SeedWithFirstRollBelow(float limit) { for (int seed = 1; seed < 1000; seed++) { Rand.PushState(seed); float roll = Rand.Value; Rand.PopState(); if (roll < limit) return seed; } return 1; } private static Pawn KeptSlave(string key) { if (!T.Carry.TryGetValue(key, out string id)) T.Skip("phase 1 did not store " + key); Pawn p = Fixtures.FindPawnById(id); if (p == null || p.Dead || !p.Spawned || !p.IsSlaveOfColony) T.Skip("kept slave " + id + " is no longer a spawned colony slave after the reload (" + (p == null ? "not found" : p.Dead ? "dead" : !p.Spawned ? "not spawned" : "not a colony slave") + ")"); return p; } private static string IdeoNote() { Ideo ideo = Faction.OfPlayer?.ideos?.PrimaryIdeo; if (ideo == null) return "Player ideoligion: none."; IEnumerable precepts = ideo.PreceptsListForReading .Where(p => p?.def?.issue != null && (p.def.issue.defName.Contains("Execution") || p.def.issue.defName.Contains("Organ") || p.def.issue.defName.Contains("Slave"))) .Select(p => p.def.defName); return "Player ideoligion " + ideo.name + ": " + string.Join(", ", precepts) + (ideo.IdeoApprovesOfSlavery() ? " (approves of slavery)" : "") + "."; } // ========================================================================================= // scene // ========================================================================================= /// A victim and named observer colonists, with a memory snapshot taken just before the harm. private sealed class Scene { public readonly Pawn victim; public Pawn other; private readonly List> roles = new List>(); private readonly Dictionary> before = new Dictionary>(); public Scene(Pawn victim) { this.victim = victim; } public Pawn this[string role] { get { foreach (KeyValuePair r in roles) if (r.Key == role) return r.Value; throw new TestFailure("test bug: no role '" + role + "' in this scene"); } } public IEnumerable Roles => roles.Select(r => r.Key); public IEnumerable Watchers => roles.Select(r => r.Value); public Pawn Add(string role, Pawn watcher) { roles.Add(new KeyValuePair(role, watcher)); return watcher; } public void Snapshot() { before.Clear(); foreach (KeyValuePair r in roles) before[r.Value] = Fixtures.Memories(r.Value); } private Dictionary> frozen; /// /// Records what each observer got from this scene's harm. Observers stay alive into the next /// run (the control), whose colony-wide thoughts would otherwise count against this scene. /// public void Freeze() { frozen = null; var result = new Dictionary>(); foreach (KeyValuePair r in roles) result[r.Key] = Bad(r.Key); frozen = result; } public List Bad(string role) { if (frozen != null && frozen.TryGetValue(role, out List got)) return got; Pawn p = this[role]; return before.TryGetValue(p, out Dictionary snapshot) ? Fixtures.NewBadMemories(p, snapshot) : new List(); } public bool AnyBad => roles.Any(r => Bad(r.Key).Count > 0); public bool Has(string role, ThoughtDef def) => def != null && Bad(role).Any(m => m.def == def); public string Report() => string.Join("; ", roles.Select(r => r.Key + " " + r.Value.LabelShort + " [" + Fixtures.Describe(Bad(r.Key)) + "]")); } } }