using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using BlaxLaws; using HarmonyLib; using RimWorld; using Verse; using Verse.AI; namespace BlaxLawsTests { /// /// The detection hooks and case filing (design: "Act catalogue and detection", Tests): every hook files /// the act it watches on the right pawn, a break's linked act moves its case to did it, the most specific /// row decides, player orders, other pawns' doses, quest lodgers and visitors file nothing, the cooldown keeps the log from /// flooding, a throwing hook leaves vanilla running, and an empty book costs nothing. /// /// The tests call the hooked vanilla methods themselves and never tick, so no punishment runs: rows use /// Warn and are deleted after each test. A pawn "acts on its own job" through DetectionKit.WithOwnJob, /// which sets the job the vanilla toils would have running (hook C and U read only its targets). /// public static class DetectionTests { // ---- A: breaks, C: binge doses --------------------------------------------------------- [BlaxTest("detection A: under a wake-up row a wake-up binge opens one planning case, a yayo binge none")] public static void BingePlanningByChemical() { DetectionKit.ClearDrugsOnMap(); Law row = DetectionKit.Row("Break/@anyDrugBinge", LawStage.Planning, "WakeUp"); Pawn p = DetectionKit.Colonist(); Thing wake = DetectionKit.ItemNear(p, ThingDefOf.WakeUp, 5); T.Check(DetectionKit.Start(p, "Binging_DrugExtreme"), "the extreme binge didn't start"); T.Equal("WakeUp", (p.MentalState as MentalState_BingingDrug)?.chemical?.defName, "the binge's chemical with only wake-up on the map"); LawCase c = DetectionKit.OnlyCase(p, "the wake-up binger"); T.Equal(LawStage.Planning, c.stage, "stage"); T.Equal(row.id, c.planningLawId, "planning row"); T.Equal("Binging_DrugExtreme", c.breakState, "break state"); T.Equal(0, c.count, "count before any dose"); wake.Destroy(); Pawn q = DetectionKit.Colonist(); DetectionKit.ItemNear(q, ThingDefOf.Yayo, 5); T.Check(DetectionKit.Start(q, "Binging_DrugExtreme"), "the second extreme binge didn't start"); T.Equal("Psychite", (q.MentalState as MentalState_BingingDrug)?.chemical?.defName, "the binge's chemical with only yayo on the map"); DetectionKit.NoCase(q, "the yayo binger"); } [BlaxTest("detection C: a wake-up dose during the binge moves its case to did it with count 1, a second dose counts 2; a dose outside a binge files nothing")] public static void BingeDoses() { DetectionKit.ClearDrugsOnMap(); DetectionKit.NoOverdose(ThingDefOf.WakeUp); Law plan = DetectionKit.Row("Break/@anyDrugBinge", LawStage.Planning, "WakeUp"); Law did = DetectionKit.Row("Break/@anyDrugBinge", LawStage.DidIt, "WakeUp"); Pawn p = DetectionKit.Colonist(); Thing wake = DetectionKit.ItemNear(p, ThingDefOf.WakeUp, 5); T.Check(DetectionKit.Start(p, "Binging_DrugExtreme"), "the extreme binge didn't start"); LawCase c = DetectionKit.OnlyCase(p, "the binger before the dose"); T.Equal(plan.id, c.planningLawId, "planning row"); DetectionKit.Eat(p, wake); T.Equal(4, wake.stackCount, "fixture: wake-up left after the first dose"); T.Equal(LawStage.DidIt, c.stage, "stage after the first dose"); T.Equal(1, c.count, "count after the first dose"); T.Equal(did.id, c.didItLawId, "did-it row"); T.Equal("WakeUp", c.matchedDef, "the matched def"); DetectionKit.Eat(p, wake); T.Equal(2, c.count, "count after the second dose; the binger's state " + (p.MentalStateDef?.defName ?? "none") + (p.Downed ? ", downed" : "") + ", overdose " + (p.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.DrugOverdose)?.Severity.ToString("0.##") ?? "none")); T.Equal(1, DetectionKit.CasesOf(p).Count, "cases of the binger after two doses"); Pawn sober = DetectionKit.Colonist(); Thing other = DetectionKit.ItemNear(sober, ThingDefOf.WakeUp, 2); DetectionKit.Eat(sober, other); T.Equal(1, other.stackCount, "fixture: wake-up left after the sober dose"); DetectionKit.NoCase(sober, "a colonist dosing outside a binge"); } [BlaxTest("detection A: an any-drug binge row catches a beer binge (Binging_DrugMajor)")] public static void AnyDrugRowCatchesBeerBinge() { DetectionKit.ClearDrugsOnMap(); Law row = DetectionKit.Row("Break/@anyDrugBinge", LawStage.Planning, DrugOptions.Any); Pawn p = DetectionKit.Colonist(); DetectionKit.ItemNear(p, ThingDefOf.Beer, 5); T.Check(DetectionKit.Start(p, "Binging_DrugMajor"), "the major binge didn't start"); T.Equal("Alcohol", (p.MentalState as MentalState_BingingDrug)?.chemical?.defName, "the binge's chemical with only beer on the map"); LawCase c = DetectionKit.OnlyCase(p, "the beer binger"); T.Equal(row.id, c.planningLawId, "planning row"); T.Equal("Binging_DrugMajor", c.breakState, "break state"); } [BlaxTest("detection C: the starter lawbook plus 'wake-up, did it, jail 10 days' gives a wake-up binger one case and 10 days")] public static void StarterPlusWakeUpRow() { DetectionKit.ClearDrugsOnMap(); DetectionKit.NoOverdose(ThingDefOf.WakeUp); Lawbook.AddStarter(); Law starterPlan = Lawbook.Find("Break/@anyDrugBinge", DrugOptions.Any, LawStage.Planning); T.NotNull(starterPlan, "starter row 'any drug binge, planning'"); Law ten = DetectionKit.Row("Break/@anyDrugBinge", LawStage.DidIt, "WakeUp", "Jail", LawSeverity.Serious, 10); Pawn p = DetectionKit.Colonist(); Thing wake = DetectionKit.ItemNear(p, ThingDefOf.WakeUp, 3); T.Check(DetectionKit.Start(p, "Binging_DrugExtreme"), "the extreme binge didn't start"); DetectionKit.Eat(p, wake); LawCase c = DetectionKit.OnlyCase(p, "the wake-up binger"); T.Equal(starterPlan.id, c.planningLawId, "planning row"); T.Equal(ten.id, c.didItLawId, "did-it row: the wake-up row beats the starter's any drug"); T.Equal(10, c.LawFor(LawStage.DidIt).days, "days of the did-it row"); T.Equal(1, c.count, "doses counted"); } // ---- A, I: fire --------------------------------------------------------------------- [BlaxTest("detection I: a fire-starting spree opens planning, its ignite moves it to did it with count 1; a raider's ignite files nothing")] public static void FireSpree() { DetectionKit.PutOutFiresAfter(); Law plan = DetectionKit.Row("Break/FireStartingSpree", LawStage.Planning); Law did = DetectionKit.Row("Break/FireStartingSpree", LawStage.DidIt); // A row of its own on the act too: the break's case still takes it (one act, one case). DetectionKit.Row("Special/SetFire", LawStage.DidIt); Pawn p = DetectionKit.Colonist(); T.Check(DetectionKit.Start(p, "FireStartingSpree"), "the fire-starting spree didn't start"); LawCase c = DetectionKit.OnlyCase(p, "the pyromaniac at the start"); T.Equal(LawStage.Planning, c.stage, "stage at the start"); T.Equal(plan.id, c.planningLawId, "planning row"); DetectionKit.Ignite(p, DetectionKit.WoodWallNear(p)); T.Equal(LawStage.DidIt, c.stage, "stage after the ignite"); T.Equal(1, c.count, "count after the ignite"); T.Equal(did.id, c.didItLawId, "did-it row: the break's row on a tie with Special/SetFire"); T.Equal(1, DetectionKit.CasesOf(p).Count, "cases of the pyromaniac: one act, one case"); Pawn raider = DetectionKit.Stranger(Fixtures.HostileFaction() ?? Fixtures.FriendlyFaction(), p.Position); DetectionKit.Ignite(raider, DetectionKit.WoodWallNear(raider)); DetectionKit.NoCase(raider, "a raider who set a fire"); } // ---- A: breaks other pawns cause, self-cast breaks on a player order --------------------- [BlaxTest("detection A: a break another pawn's ability forces on a colonist opens no case; the same break started without a caster does")] public static void AbilityForcedBreakFilesNothing() { DetectionKit.Row("Break/@anyAggressive", LawStage.Planning); MentalStateDef tantrum = DefDatabase.GetNamed("Tantrum"); Pawn control = DetectionKit.Colonist(); T.Check(control.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true), "fixture: control tantrum did not start"); DetectionKit.OnlyCase(control, "a colonist whose own tantrum starts"); Pawn victim = DetectionKit.Colonist(); Pawn caster = DetectionKit.ColonistNear(victim); // As CompAbilityEffect_GiveMentalState.TryGiveMentalState calls it (RimWorld/CompAbilityEffect_GiveMentalState.cs:59). bool started = victim.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true, causedByMood: false, otherPawn: caster, transitionSilently: false, causedByDamage: false, causedByPsycast: true); T.Check(started && victim.MentalStateDef == tantrum, "fixture: the forced tantrum did not start"); DetectionKit.NoCase(victim, "a colonist a caster's psycast put in a tantrum"); DetectionKit.NoCase(caster, "the caster"); } [BlaxTest("detection A: a drafted colonist's self-cast break opens nothing while player orders are exempt and a case when the setting is off; a drafted colonist's own break still files")] public static void SelfCastBreakOnPlayerOrder() { DetectionKit.Row("Break/@anyAggressive", LawStage.Planning); MentalStateDef tantrum = DefDatabase.GetNamed("Tantrum"); // A mood break that hits a drafted pawn is no order: the exemption must not reach it. Pawn moody = DetectionKit.Colonist(); moody.drafter.Drafted = true; T.Check(moody.Drafted, "fixture: the colonist isn't drafted"); T.Check(moody.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true, causedByMood: true), "fixture: mood tantrum did not start"); DetectionKit.OnlyCase(moody, "a drafted colonist whose own mood break starts"); // A self-cast ability (the Berserk trance passes the caster as otherPawn, onlyApplyToSelf) while drafted. Pawn caster = DetectionKit.Colonist(); caster.drafter.Drafted = true; T.Check(caster.Drafted, "fixture: the caster isn't drafted"); T.Check(caster.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true, causedByMood: false, otherPawn: caster, causedByPsycast: false), "fixture: self-cast tantrum did not start"); T.Check(!caster.Drafted, "vanilla left the caster drafted, so the test no longer covers the undraft"); DetectionKit.NoCase(caster, "a drafted colonist that put itself in the state"); // The same cast from an undrafted pawn on a player-forced job (a role ability's gizmo shows undrafted): // vanilla ends that job before the state starts, so only a read before it sees the order. Pawn ordered = DetectionKit.Colonist(); T.Check(ordered.jobs.TryTakeOrderedJob(JobMaker.MakeJob(JobDefOf.Wait, 600)), "fixture: the colonist took no ordered job"); Job order = ordered.CurJob; T.Check(order != null && order.playerForced && !ordered.Drafted, "fixture: no undrafted pawn on a player-forced job"); T.Check(ordered.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true, causedByMood: false, otherPawn: ordered, causedByPsycast: false), "fixture: ordered self-cast tantrum did not start"); T.Check(ordered.CurJob != order, "vanilla left the ordered job running, so the test no longer covers the job being ended"); DetectionKit.NoCase(ordered, "an undrafted colonist on a player-forced job that put itself in the state"); Fixtures.Settings.playerOrdersExempt = false; Pawn caster2 = DetectionKit.Colonist(); caster2.drafter.Drafted = true; T.Check(caster2.mindState.mentalStateHandler.TryStartMentalState(tantrum, null, forced: true, forceWake: true, causedByMood: false, otherPawn: caster2), "fixture: second self-cast tantrum did not start"); DetectionKit.OnlyCase(caster2, "a drafted self-caster with the setting off"); } // ---- A, J: corpse obsession ---------------------------------------------------------- [BlaxTest("detection J: an obsession over a buried corpse opens planning with 'dug up'; the corpse shown on a table moves it to did it with 'on a table', once")] public static void CorpseObsession() { var (p, c, state, _, did) = ShownCorpseObsession(keep: false); T.Equal(LawStage.DidIt, c.stage, "stage after the display"); T.Equal(1, c.count, "count after the display"); T.Equal(did.id, c.didItLawId, "did-it row"); T.Equal(CaseNotes.DugUp | CaseNotes.OnTable, c.notes, "notes after the display"); state.MentalStateTick(1); state.MentalStateTick(1); T.Equal(1, c.count, "count after more ticks of the same obsession"); T.Equal(1, DetectionKit.CasesOf(p).Count, "cases of the obsessed colonist"); } /// /// A colonist obsessed over a buried corpse that it then shows on a table, filed at did it with count 1. /// Checks the planning case on the way. With keep, the pawns, the grave, the table and both rows stay for /// phase 2. /// private static (Pawn p, LawCase c, MentalState_CorpseObsession state, Law plan, Law did) ShownCorpseObsession(bool keep) { Law plan = DetectionKit.Row("Break/CorpseObsession", LawStage.Planning); Law did = DetectionKit.Row("Break/CorpseObsession", LawStage.DidIt); Pawn p = DetectionKit.Colonist(); Pawn dead = DetectionKit.Stranger(Fixtures.FriendlyFaction(), p.Position); dead.Kill(null); Corpse corpse = dead.Corpse; T.NotNull(corpse, "fixture: the dead pawn's corpse"); var grave = (Building_Grave)ThingMaker.MakeThing(ThingDefOf.Grave); grave.SetFaction(Faction.OfPlayer); DetectionKit.Place(grave, DetectionKit.FreeCell(p.Position, ThingDefOf.Grave.size)); corpse.DeSpawn(); T.Check(grave.TryAcceptThing(corpse, false), "fixture: the grave refused the corpse"); T.Check(DetectionKit.Start(p, "CorpseObsession"), "the corpse obsession didn't start"); var state = p.MentalState as MentalState_CorpseObsession; T.Check(state != null && state.corpse == corpse, "the obsession chose another corpse: " + state?.corpse); LawCase c = DetectionKit.OnlyCase(p, "the obsessed colonist"); T.Equal(LawStage.Planning, c.stage, "stage at the start"); T.Equal(plan.id, c.planningLawId, "planning row"); T.Equal(CaseNotes.DugUp, c.notes, "notes at the start"); // A tick while the corpse is still buried, then what the haul job leaves behind: the corpse // placed on a table and the flag set by its last toil (RimWorld/JobDriver_HaulCorpseToPublicPlace.cs:54-55, 90). state.MentalStateTick(1); T.Equal(0, c.count, "count before the corpse is shown"); Thing table = ThingMaker.MakeThing(ThingDefOf.Table1x2c, ThingDefOf.WoodLog); table.SetFaction(Faction.OfPlayer); IntVec3 tableCell = DetectionKit.FreeCell(p.Position, ThingDefOf.Table1x2c.size); DetectionKit.Place(table, tableCell); T.Check(grave.GetDirectlyHeldThings().TryDrop(corpse, tableCell, Fixtures.Map, ThingPlaceMode.Direct, out Thing _), "fixture: the corpse didn't land on the table"); T.Check(corpse.Spawned && DetectionHooks.OnTable(corpse), "fixture: the corpse lies at " + corpse.PositionHeld + ", not on the table"); state.Notify_CorpseHauled(); state.MentalStateTick(1); if (keep) { // Built outside a test (CarryAtSave): kept, so the first phase-2 test's cleanup leaves them. Fixtures.Keep(p); Fixtures.Keep(dead); Fixtures.Keep(grave); Fixtures.Keep(table); Fixtures.KeepLaw(plan); Fixtures.KeepLaw(did); // Kept on its table: the quick test's colonists would otherwise haul it into the kept grave // (HaulCorpses), and two of them can race for it in the first ticks after the reload. corpse.SetForbidden(true, warnOnFail: false); } return (p, c, state, plan, did); } private const string CorpseSaveKey = "detect.corpseSave"; [BlaxTest("detection J: an obsession that already showed its corpse runs at the first save (setup)")] public static void CorpseObsessionSaveSetup() { // Built right before the save, after every phase-1 test, so no later test's ticks end the obsession. T.CarryAtSave(CorpseSaveKey, CorpseObsessionForSave); } private static string CorpseObsessionForSave() { var (p, c, state, _, _) = ShownCorpseObsession(keep: true); T.Check(state.alreadyHauledCorpse, "fixture: the flag isn't set at the save"); T.Equal(LawStage.DidIt, c.stage, "stage at the save"); return string.Join("|", p.ThingID, c.id, c.count, DetectionKit.CasesOf(p).Count); } [BlaxTest("detection J: after a reload with the corpse already shown, the obsession files no second did-it", phase: 2)] public static void CorpseObsessionAfterReload() { T.Check(T.Carry.TryGetValue(CorpseSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 corpse obsession save setup did not run"); string[] parts = carry.Split('|'); T.Check(parts.Length == 4, "carry: " + carry); Pawn p = Fixtures.FindPawnById(parts[0]); T.NotNull(p, "the obsessed colonist after the reload"); LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[1])); T.NotNull(c, "the obsession's case after the reload"); T.Check(c.offender == p, "the case's offender didn't resolve"); int count = int.Parse(parts[2]), cases = int.Parse(parts[3]); T.Equal(count, c.count, "count right after the reload"); MentalState_CorpseObsession state = p.MentalState as MentalState_CorpseObsession; if (state == null) T.Fail("the obsession is gone after the reload (" + (p.MentalStateDef?.defName ?? "no state") + ")"); T.Check(state.alreadyHauledCorpse, "the reloaded obsession lost its displayed corpse"); // The setup kept its did-it row; adding it again would be refused as a duplicate. T.Check(Lawbook.Laws.Any(l => l.actKey == ActKey.Of(ActCategories.Break, "CorpseObsession") && l.stage == LawStage.DidIt && l.enabled), "the kept did-it row is missing after the reload"); DetectionKit.Row("Special/DisplayedCorpse", LawStage.DidIt); for (int i = 0; i < 3; i++) state.MentalStateTick(1); T.Equal(count, c.count, "count of the phase-1 case after ticks of the reloaded obsession"); T.Equal(cases, DetectionKit.CasesOf(p).Count, "cases of the obsessed colonist after the reload"); } // ---- F, E: fights and interactions ---------------------------------------------------- [BlaxTest("detection F: StartSocialFight files on the recipient who swings first, not on the provoker")] public static void SocialFight() { Law row = DetectionKit.Row("Special/StartedSocialFight", LawStage.DidIt); Pawn provoker = DetectionKit.Colonist(); Pawn fighter = DetectionKit.ColonistNear(provoker); fighter.interactions.StartSocialFight(provoker); T.Equal(MentalStateDefOf.SocialFighting, fighter.MentalStateDef, "fixture: the recipient's state"); LawCase c = DetectionKit.OnlyCase(fighter, "the recipient"); T.Equal(row.id, c.didItLawId, "did-it row"); T.Check(c.victim == provoker, "the provoker isn't the victim"); DetectionKit.NoCase(provoker, "the provoker"); } [BlaxTest("detection E: an insult files on the initiator; a slight only under insult or slight; a second insult within a day counts, with the cooldown at 0 it files")] public static void InsultsAndCooldown() { DetectionKit.QuietSocialFights(); Law insult = DetectionKit.Row("Interaction/Insult", LawStage.DidIt); Pawn a = DetectionKit.Colonist(); Pawn b = DetectionKit.ColonistNear(a); DetectionKit.Interact(a, b, InteractionDefOf.Insult); LawCase first = DetectionKit.OnlyCase(a, "the insulter"); T.Equal(insult.id, first.didItLawId, "did-it row of the insult"); T.Check(first.victim == b, "the insulted pawn isn't the victim"); DetectionKit.NoCase(b, "the insulted pawn"); InteractionDef slight = DefDatabase.GetNamed("Slight"); DetectionKit.Interact(a, b, slight); T.Equal(1, DetectionKit.CasesOf(a).Count, "cases after a slight under an Insult row"); T.Equal(1, first.count, "the insult case counted a slight"); Law group = DetectionKit.Row("Interaction/@insultOrSlight", LawStage.DidIt); DetectionKit.Interact(a, b, slight); T.Equal(2, DetectionKit.CasesOf(a).Count, "cases after a slight under insult or slight"); T.Equal(group.id, DetectionKit.CasesOf(a).Last().didItLawId, "the slight's row"); DetectionKit.Interact(a, b, InteractionDefOf.Insult); T.Equal(2, DetectionKit.CasesOf(a).Count, "cases after a second insult within the cooldown"); T.Equal(2, first.count, "count of the insult case after the second insult"); Fixtures.Settings.cooldownDays = 0; DetectionKit.Interact(a, b, InteractionDefOf.Insult); T.Equal(3, DetectionKit.CasesOf(a).Count, "cases after an insult with the cooldown at 0"); T.Equal(insult.id, DetectionKit.CasesOf(a).Last().didItLawId, "the new insult case's row"); } [BlaxTest("detection E: the cooldown counts from a closed case's open tick: acts at 0 h and 20 h give one case, a third at 30 h opens a second")] public static void CooldownCountsFromOpenTick() { DetectionKit.QuietSocialFights(); Fixtures.Settings.cooldownDays = 1; Law insult = DetectionKit.Row("Interaction/Insult", LawStage.DidIt); Pawn a = DetectionKit.Colonist(); Pawn b = DetectionKit.ColonistNear(a); DetectionKit.Interact(a, b, InteractionDefOf.Insult); LawCase first = DetectionKit.OnlyCase(a, "the insulter"); Fixtures.Tick(1); // the Warn runs and closes the case T.Check(first.IsClosed, "fixture: the warned insult case is open: " + first); // Backdating the case's ticks stands in for game hours without ticking. int now = Find.TickManager.TicksGame; first.openTick = now - 20 * GenDate.TicksPerHour; first.lastActTick = first.openTick; DetectionKit.Interact(a, b, InteractionDefOf.Insult); T.Equal(1, DetectionKit.CasesOf(a).Count, "cases after a second insult 20 h after the first"); T.Equal(2, first.count, "count after the second insult"); first.openTick = now - 30 * GenDate.TicksPerHour; first.lastActTick = now - 10 * GenDate.TicksPerHour; DetectionKit.Interact(a, b, InteractionDefOf.Insult); T.Equal(2, DetectionKit.CasesOf(a).Count, "cases after a third insult 30 h after the first (10 h after the second)"); T.Equal(insult.id, DetectionKit.CasesOf(a).Last().didItLawId, "the new insult case's row"); T.Equal(2, first.count, "the first case did not count the third insult"); } [BlaxTest("detection E: a case still open takes every repeat of its act whatever its age: no second case, no flood")] public static void OpenCaseTakesRepeats() { DetectionKit.QuietSocialFights(); Fixtures.Settings.cooldownDays = 1; DetectionKit.Row("Interaction/Insult", LawStage.DidIt); Pawn a = DetectionKit.Colonist(); Pawn b = DetectionKit.ColonistNear(a); DetectionKit.Interact(a, b, InteractionDefOf.Insult); LawCase first = DetectionKit.OnlyCase(a, "the insulter"); // Not ticked, so the case is still open, as a jail case waiting for "Arrest now" or a bed stays open. T.Check(!first.IsClosed, "fixture: the insult case closed before a tick"); int now = Find.TickManager.TicksGame; first.openTick = now - 30 * GenDate.TicksPerHour; first.lastActTick = first.openTick; DetectionKit.Interact(a, b, InteractionDefOf.Insult); T.Equal(1, DetectionKit.CasesOf(a).Count, "cases after a second insult 30 h after the first, the first still open"); T.Equal(2, first.count, "count of the open case after the second insult"); } [BlaxTest("detection E: a Chitchat row files a chitchat on the initiator")] public static void Chitchat() { DetectionKit.QuietSocialFights(); Law row = DetectionKit.Row("Interaction/Chitchat", LawStage.DidIt); Pawn a = DetectionKit.Colonist(); Pawn b = DetectionKit.ColonistNear(a); DetectionKit.Interact(a, b, InteractionDefOf.Chitchat); T.Equal(row.id, DetectionKit.OnlyCase(a, "the chatter").didItLawId, "did-it row"); DetectionKit.NoCase(b, "the listener"); } [BlaxTest("detection A, E: a jailbreaker break opens planning, its SparkJailbreak talk moves it to did it")] public static void Jailbreaker() { DetectionKit.QuietSocialFights(); Law plan = DetectionKit.Row("Break/Jailbreaker", LawStage.Planning); Law did = DetectionKit.Row("Break/Jailbreaker", LawStage.DidIt); Pawn j = DetectionKit.Colonist(); Pawn prisoner = DetectionKit.StrangerNear(Fixtures.HostileFaction() ?? Fixtures.FriendlyFaction(), j); prisoner.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner); T.Check(prisoner.IsPrisonerOfColony, "fixture: the prisoner"); // A released prisoner isn't secure, so the talk starts no real prison break // (RimWorld/InteractionWorker_SparkJailbreak.cs:11; RimWorld/Pawn_GuestTracker.cs:137-140). prisoner.guest.Released = true; T.Check(DetectionKit.Start(j, "Jailbreaker"), "the jailbreaker break didn't start"); LawCase c = DetectionKit.OnlyCase(j, "the jailbreaker"); T.Equal(plan.id, c.planningLawId, "planning row"); DetectionKit.Interact(j, prisoner, InteractionDefOf.SparkJailbreak); T.Equal(LawStage.DidIt, c.stage, "stage after the talk"); T.Equal(1, c.count, "count after the talk"); T.Equal(did.id, c.didItLawId, "did-it row"); T.Check(c.victim == prisoner, "the prisoner isn't the victim"); } // ---- C: eating --------------------------------------------------------------------- [BlaxTest("detection C: raw meat, a meal with meat, human meat and a meal with human meat each go to the smallest matching meat group; a vegetable meal to none")] public static void MeatGroups() { Law any = DetectionKit.Row("Ate/@anyMeat", LawStage.DidIt); Law raw = DetectionKit.Row("Ate/@rawMeatOrCorpse", LawStage.DidIt); Law human = DetectionKit.Row("Ate/@humanMeat", LawStage.DidIt); ThingDef cowMeat = ThingDefOf.Cow.race.meatDef; Pawn p1 = DetectionKit.Colonist(); DetectionKit.Eat(p1, DetectionKit.ItemNear(p1, cowMeat, 10)); T.Equal(raw.id, DetectionKit.OnlyCase(p1, "the raw meat eater").didItLawId, "row for raw cow meat"); Pawn p2 = DetectionKit.Colonist(); DetectionKit.Eat(p2, DetectionKit.MealNear(p2, cowMeat)); T.Equal(any.id, DetectionKit.OnlyCase(p2, "the meat meal eater").didItLawId, "row for a simple meal with cow meat"); Pawn p3 = DetectionKit.Colonist(); DetectionKit.Eat(p3, DetectionKit.ItemNear(p3, ThingDefOf.Meat_Human, 10)); T.Equal(human.id, DetectionKit.OnlyCase(p3, "the human meat eater").didItLawId, "row for raw human meat"); Pawn p4 = DetectionKit.Colonist(); DetectionKit.Eat(p4, DetectionKit.MealNear(p4, ThingDefOf.Meat_Human)); T.Equal(human.id, DetectionKit.OnlyCase(p4, "the human meat meal eater").didItLawId, "row for a simple meal with human meat"); Pawn p5 = DetectionKit.Colonist(); DetectionKit.Eat(p5, DetectionKit.MealNear(p5, ThingDefOf.RawPotatoes)); DetectionKit.NoCase(p5, "the potato meal eater"); } [BlaxTest("detection C: a row on the simple meal catches the simple meal, not raw meat")] public static void SimpleMealRow() { Law meal = DetectionKit.Row("Ate/MealSimple", LawStage.DidIt); Pawn a = DetectionKit.Colonist(); DetectionKit.Eat(a, DetectionKit.ItemNear(a, ThingDefOf.Cow.race.meatDef, 10)); DetectionKit.NoCase(a, "the raw meat eater"); Pawn b = DetectionKit.Colonist(); DetectionKit.Eat(b, DetectionKit.ItemNear(b, ThingDefOf.MealSimple, 1)); LawCase c = DetectionKit.OnlyCase(b, "the simple meal eater"); T.Equal(meal.id, c.didItLawId, "did-it row"); T.Equal("MealSimple", c.matchedDef, "matched def"); } [BlaxTest("detection C: a drafted pawn or a player-forced eat job opens nothing while player orders are exempt; with the setting off the forced job files")] public static void PlayerOrdersExempt() { DetectionKit.Row("Ate/MealSimple", LawStage.DidIt); Pawn control = DetectionKit.Colonist(); DetectionKit.Eat(control, DetectionKit.ItemNear(control, ThingDefOf.MealSimple, 1)); DetectionKit.OnlyCase(control, "a colonist eating on its own"); Pawn drafted = DetectionKit.Colonist(); drafted.drafter.Drafted = true; T.Check(drafted.Drafted, "fixture: the colonist isn't drafted"); DetectionKit.Eat(drafted, DetectionKit.ItemNear(drafted, ThingDefOf.MealSimple, 1)); DetectionKit.NoCase(drafted, "a drafted colonist"); Pawn forced = DetectionKit.Colonist(); DetectionKit.Eat(forced, DetectionKit.ItemNear(forced, ThingDefOf.MealSimple, 1), playerForced: true); DetectionKit.NoCase(forced, "a colonist on a player-forced eat job"); Fixtures.Settings.playerOrdersExempt = false; DetectionKit.Eat(forced, DetectionKit.ItemNear(forced, ThingDefOf.MealSimple, 1), playerForced: true); DetectionKit.OnlyCase(forced, "a colonist on a player-forced eat job with the setting off"); } [BlaxTest("detection C, E: a quest lodger's meat meal and insult open nothing, and the same pawn files both once its quest is gone; a visitor's meat meal opens nothing")] public static void QuestLodgerAndVisitor() { DetectionKit.QuietSocialFights(); Law meat = DetectionKit.Row("Ate/@anyMeat", LawStage.DidIt); Law insult = DetectionKit.Row("Interaction/Insult", LawStage.DidIt); Faction home = Fixtures.FriendlyFaction() ?? Fixtures.HostileFaction(); if (home == null) { T.Skip("no other humanlike faction to be the lodger's home"); return; } ThingDef cowMeat = ThingDefOf.Cow.race.meatDef; Pawn lodger = DetectionKit.Colonist(); Pawn b = DetectionKit.ColonistNear(lodger); Quest quest = DetectionKit.MakeQuestLodger(lodger, home); T.Check(lodger.IsQuestLodger(), "fixture: the pawn isn't a quest lodger"); T.Check(lodger.IsFreeColonist, "fixture: the lodger isn't IsFreeColonist, so only the lodger check could be tested"); T.Check(!Offenders.IsCovered(lodger), "a quest lodger is covered by the laws"); DetectionKit.Eat(lodger, DetectionKit.MealNear(lodger, cowMeat)); DetectionKit.NoCase(lodger, "the quest lodger after a meat meal"); DetectionKit.Interact(lodger, b, InteractionDefOf.Insult); DetectionKit.NoCase(lodger, "the quest lodger after an insult"); // Control: the same pawn without its quest is a plain colonist, so the lodger check alone blocked both acts. Find.QuestManager.Remove(quest); T.Check(!lodger.IsQuestLodger(), "fixture: still a quest lodger after its quest was removed"); DetectionKit.Eat(lodger, DetectionKit.MealNear(lodger, cowMeat)); T.Equal(meat.id, DetectionKit.OnlyCase(lodger, "the former lodger after a meat meal").didItLawId, "row of the meat meal"); DetectionKit.Interact(lodger, b, InteractionDefOf.Insult); T.Equal(2, DetectionKit.CasesOf(lodger).Count, "cases of the former lodger after an insult"); T.Equal(insult.id, DetectionKit.CasesOf(lodger).Last().didItLawId, "row of the insult"); Pawn visitor = DetectionKit.Stranger(Fixtures.FriendlyFaction() ?? home, b.Position); visitor.guest.SetGuestStatus(Faction.OfPlayer); T.Check(visitor.HostFaction == Faction.OfPlayer && !visitor.IsPrisoner, "fixture: the visitor isn't a guest of the colony"); T.Check(!Offenders.IsCovered(visitor), "a visitor is covered by the laws"); DetectionKit.Eat(visitor, DetectionKit.MealNear(visitor, cowMeat)); DetectionKit.NoCase(visitor, "the visitor after a meat meal"); } [BlaxTest("detection C: a doctor administering a drug to a patient opens nothing for either pawn")] public static void DoctorsDose() { DetectionKit.Row("Ate/@anyDrug", LawStage.DidIt); Pawn doctor = DetectionKit.Colonist(); Pawn patient = DetectionKit.ColonistNear(doctor); Thing pill = DetectionKit.ItemNear(doctor, ThingDefOf.Penoxycyline, 3); Job bill = JobMaker.MakeJob(JobDefOf.DoBill, patient, pill); DetectionKit.WithOwnJob(doctor, bill, () => new Recipe_AdministerIngestible().ApplyOnPawn(patient, null, doctor, new List { pill }, null)); T.Check(pill.Destroyed || pill.stackCount < 3, "fixture: the patient took no dose"); DetectionKit.NoCase(patient, "the patient"); DetectionKit.NoCase(doctor, "the doctor"); } [BlaxTest("detection C: a beer drunk while socially relaxing at a table files under 'Ate: beer'")] public static void BeerAtGatheringSpot() { Law row = DetectionKit.Row("Ate/Beer", LawStage.DidIt); Pawn p = DetectionKit.Colonist(); Thing beer = DetectionKit.ItemNear(p, ThingDefOf.Beer, 1); Thing table = ThingMaker.MakeThing(ThingDefOf.Table1x2c, ThingDefOf.WoodLog); table.SetFaction(Faction.OfPlayer); DetectionKit.Place(table, DetectionKit.FreeCell(p.Position, ThingDefOf.Table1x2c.size)); // JobDriver_SocialRelax: A the gathering spot, B the seat, C the drink (RimWorld/JobDriver_SocialRelax.cs:10-14, 75). Job relax = JobMaker.MakeJob(DefDatabase.GetNamed("SocialRelax"), table, p.Position, beer); DetectionKit.WithOwnJob(p, relax, () => beer.Ingested(p, 0f)); LawCase c = DetectionKit.OnlyCase(p, "the beer drinker"); T.Equal(row.id, c.didItLawId, "did-it row"); T.Equal("Beer", c.matchedDef, "matched def"); } [BlaxTest("detection C: 60 colonists eating three meat meals each under 'any meat, warn' make 60 cases and queue 60 punishments")] public static void SixtyMeatEaters() { Law row = DetectionKit.Row("Ate/@anyMeat", LawStage.DidIt); ThingDef cowMeat = ThingDefOf.Cow.race.meatDef; int queuedBefore = Enforcement.Pending; var pawns = new List(); for (int i = 0; i < 60; i++) pawns.Add(DetectionKit.Colonist()); var sw = Stopwatch.StartNew(); foreach (Pawn p in pawns) { for (int meal = 0; meal < 3; meal++) DetectionKit.Eat(p, DetectionKit.Meal(cowMeat)); } sw.Stop(); T.Info("180 meals eaten in " + sw.ElapsedMilliseconds + " ms"); foreach (Pawn p in pawns) { LawCase c = DetectionKit.OnlyCase(p, p.LabelShort); T.Equal(row.id, c.didItLawId, "did-it row of " + p.LabelShort); T.Equal(3, c.count, "meals counted on " + p.LabelShort + "'s case"); } T.Equal(60, Enforcement.Pending - queuedBefore, "punishments queued (one message each)"); } // ---- U: used items ------------------------------------------------------------------- [BlaxTest("detection U: a colonist using a healer mech serum on its own job files; a doctor's serum files for neither pawn; a use CanBeUsedBy refuses files nothing")] public static void UsedSerum() { ThingDef serumDef = DefDatabase.GetNamed("MechSerumHealer"); Law row = DetectionKit.Row("Used/MechSerumHealer", LawStage.DidIt); Pawn user = DetectionKit.Colonist(); DetectionKit.LoseHand(user); Thing serum = DetectionKit.ItemNear(user, serumDef, 1); CompUsable comp = serum.TryGetComp(); T.Check(comp.CanBeUsedBy(user, false, true).Accepted, "fixture: the serum refuses a colonist missing a hand"); DetectionKit.WithOwnJob(user, JobMaker.MakeJob(comp.Props.useJob, serum), () => comp.UsedBy(user)); T.Equal(row.id, DetectionKit.OnlyCase(user, "the serum user").didItLawId, "did-it row"); Pawn doctor = DetectionKit.Colonist(); Pawn patient = DetectionKit.ColonistNear(doctor); DetectionKit.LoseHand(patient); Thing serum2 = DetectionKit.ItemNear(doctor, serumDef, 1); DetectionKit.WithOwnJob(doctor, JobMaker.MakeJob(JobDefOf.DoBill, patient, serum2), () => new Recipe_AdministerUsableItem().ApplyOnPawn(patient, null, doctor, new List { serum2 }, null)); T.Check(serum2.Destroyed, "fixture: the doctor's serum wasn't used"); DetectionKit.NoCase(patient, "the patient"); DetectionKit.NoCase(doctor, "the doctor"); Pawn healthy = DetectionKit.Colonist(); healthy.health.RemoveAllHediffs(); Thing serum3 = DetectionKit.ItemNear(healthy, serumDef, 1); CompUsable comp3 = serum3.TryGetComp(); T.Check(!comp3.CanBeUsedBy(healthy, false, true).Accepted, "fixture: the serum accepts a colonist with nothing to heal"); DetectionKit.WithOwnJob(healthy, JobMaker.MakeJob(comp3.Props.useJob, serum3), () => comp3.UsedBy(healthy)); DetectionKit.NoCase(healthy, "a colonist the serum refused"); } // ---- R, H, B --------------------------------------------------------------------------- [BlaxTest("detection R: an increment files one case, a second the same day raises its count; AddTo files only when the record goes up")] public static void Records() { Law stripped = DetectionKit.Row("Record/BodiesStripped", LawStage.DidIt); Law eaten = DetectionKit.Row("Record/NutritionEaten", LawStage.DidIt); Pawn p = DetectionKit.Colonist(); p.records.Increment(RecordDefOf.BodiesStripped); LawCase c = DetectionKit.OnlyCase(p, "the stripper"); T.Equal(stripped.id, c.didItLawId, "did-it row"); T.Equal(1, c.count, "count after one increment"); p.records.Increment(RecordDefOf.BodiesStripped); T.Equal(2, c.count, "count after the second increment"); T.Equal(1, DetectionKit.CasesOf(p).Count, "cases after two increments"); Pawn q = DetectionKit.Colonist(); q.records.AddTo(RecordDefOf.NutritionEaten, 0f); DetectionKit.NoCase(q, "a record that didn't go up"); q.records.AddTo(RecordDefOf.NutritionEaten, 0.9f); T.Equal(eaten.id, DetectionKit.OnlyCase(q, "the eater by record").didItLawId, "did-it row of the Float record"); } [BlaxTest("detection H: an ExecutedPrisoner event with a doer files on the doer; the same event without one files nothing")] public static void RecordedAct() { Law row = DetectionKit.Row("RecordedAct/ExecutedPrisoner", LawStage.DidIt); Pawn p = DetectionKit.Colonist(); int before = Fixtures.Comp.Cases.Count; // As vanilla records it, with the thought stage; the executioner may be null (RimWorld/ThoughtUtility.cs:52-56). Find.HistoryEventsManager.RecordEvent(new HistoryEvent(HistoryEventDefOf.ExecutedPrisoner, ((Pawn)null).Named(HistoryEventArgsNames.Doer), 0.Named(HistoryEventArgsNames.ExecutionThoughtStage))); T.Equal(before, Fixtures.Comp.Cases.Count, "cases after the event without a doer"); Find.HistoryEventsManager.RecordEvent(new HistoryEvent(HistoryEventDefOf.ExecutedPrisoner, p.Named(HistoryEventArgsNames.Doer), 0.Named(HistoryEventArgsNames.ExecutionThoughtStage))); T.Equal(row.id, DetectionKit.OnlyCase(p, "the executioner").didItLawId, "did-it row"); } [BlaxTest("detection B: a finished simple meal bill files on the cook; a surgery files on the doctor with the patient as victim")] public static void Bills() { Law cookRow = DetectionKit.Row("Bill/CookMealSimple", LawStage.DidIt); Law surgeryRow = DetectionKit.Row("Bill/@anySurgery", LawStage.DidIt); Pawn cook = DetectionKit.Colonist(); Job cooking = JobMaker.MakeJob(JobDefOf.DoBill, cook.Position); cooking.bill = DefDatabase.GetNamed("CookMealSimple").MakeNewBill(); DetectionKit.WithOwnJob(cook, cooking, () => RecordsUtility.Notify_BillDone(cook, new List { DetectionKit.Meal(null) })); T.Equal(cookRow.id, DetectionKit.OnlyCase(cook, "the cook").didItLawId, "did-it row of the cook"); Pawn doctor = DetectionKit.Colonist(); Pawn patient = DetectionKit.ColonistNear(doctor); var surgery = new Bill_Medical(RecipeDefOf.RemoveBodyPart, null); patient.health.surgeryBills.AddBill(surgery); Job operating = JobMaker.MakeJob(JobDefOf.DoBill, patient); operating.bill = surgery; DetectionKit.WithOwnJob(doctor, operating, () => RecordsUtility.Notify_BillDone(doctor, new List())); LawCase c = DetectionKit.OnlyCase(doctor, "the surgeon"); T.Equal(surgeryRow.id, c.didItLawId, "did-it row of the surgeon"); T.Check(c.victim == patient, "the patient isn't the victim"); DetectionKit.NoCase(patient, "the patient"); } [BlaxTest("detection B: a mech gestation bill files on the pawn who finishes it (needs Biotech)")] public static void MechGestationBill() { T.NeedsDlc("Biotech", ModsConfig.BiotechActive); RecipeDef gestation = DefDatabase.AllDefsListForReading.FirstOrDefault(r => r.gestationCycles > 0); T.NotNull(gestation, "a mech gestation recipe"); Law row = DetectionKit.Row(ActKey.Of(ActCategories.Bill, gestation.defName), LawStage.DidIt); Pawn mechanitor = DetectionKit.Colonist(); Job job = JobMaker.MakeJob(JobDefOf.DoBill, mechanitor.Position); job.bill = gestation.MakeNewBill(); DetectionKit.WithOwnJob(mechanitor, job, () => RecordsUtility.Notify_BillDone(mechanitor, new List())); T.Equal(row.id, DetectionKit.OnlyCase(mechanitor, "the pawn finishing the gestation").didItLawId, "did-it row"); } // ---- guards and cost ---------------------------------------------------------------- [BlaxTest("detection: a hook whose filing throws logs once and the interaction still happens")] public static void ThrowingHookKeepsVanilla() { DetectionKit.QuietSocialFights(); DetectionKit.Row("Interaction/Insult", LawStage.DidIt); Pawn a = DetectionKit.Colonist(); Pawn b = DetectionKit.ColonistNear(a); LawsLog.ResetOnce(); LawsTestHooks.ReportThrows = true; T.ExpectErrors(Patch_Pawn_InteractionsTracker_TryInteractWith.Where + " failed", 1); DetectionKit.Interact(a, b, InteractionDefOf.Insult); T.Equal(InteractionDefOf.Insult, a.interactions.LastInteractionDef, "the insult vanilla recorded"); DetectionKit.Interact(a, b, InteractionDefOf.Insult); DetectionKit.NoCase(a, "the insulter while filing throws"); } [BlaxTest("cost: with an empty book the hooks of TryInteractWith, Increment and RecordEvent allocate nothing and cost under 2% of 100000 calls (at least 3 ns a call allowed)")] public static void EmptyBookCost() { T.Check(!Watch.Interaction && !Watch.Record && !Watch.RecordedAct, "a row kept by an earlier test watches interactions, records or recorded acts"); DetectionKit.QuietSocialFights(); const int N = 100000; Pawn a = DetectionKit.Colonist(); Pawn b = DetectionKit.ColonistNear(a); Pawn_RecordsTracker records = a.records; RecordDef rec = RecordDefOf.BodiesStripped; HistoryEventsManager history = Find.HistoryEventsManager; // An event no precept reacts to and without a doer: the cost is RecordEvent's own. var ev = new HistoryEvent(DefDatabase.GetNamed("Traded")); InteractionDef chat = InteractionDefOf.Chitchat; // The calls: the first interaction happens, the rest return early as too soon (Pawn_InteractionsTracker.cs:154-157). long interact = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) a.interactions.TryInteractWith(b, chat); }); long increment = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) records.Increment(rec); }); long record = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) history.RecordEvent(ev, false); }); // The hooks alone, as Harmony calls them after each of those calls. long hookE = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) Patch_Pawn_InteractionsTracker_TryInteractWith.Postfix(a, b, chat, true); }); long hookR = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) Patch_Pawn_RecordsTracker_Increment.Postfix(records, rec); }); long hookH = DetectionKit.BestOf(() => { for (int i = 0; i < N; i++) Patch_HistoryEventsManager_RecordEvent.Postfix(ev); }); long allocated = GC.GetAllocatedBytesForCurrentThread(); for (int i = 0; i < N; i++) { Patch_Pawn_InteractionsTracker_TryInteractWith.Postfix(a, b, chat, true); Patch_Pawn_RecordsTracker_Increment.Postfix(records, rec); Patch_HistoryEventsManager_RecordEvent.Postfix(ev); } allocated = GC.GetAllocatedBytesForCurrentThread() - allocated; T.Equal(0L, allocated, "bytes the empty-book hooks allocated in " + N + " calls each"); double floor = 3e-9 * N * Stopwatch.Frequency; void Within(string what, long hook, long method) { double limit = Math.Max(0.02 * method, floor); T.Info(what + ": " + N + " calls " + DetectionKit.Ms(method) + " ms, hook " + DetectionKit.Ms(hook) + " ms, limit " + DetectionKit.Ms((long)limit) + " ms"); T.Check(hook <= limit, what + ": the empty-book hook costs " + DetectionKit.Ms(hook) + " ms, over " + DetectionKit.Ms((long)limit) + " ms"); } Within("TryInteractWith", hookE, interact); Within("Increment", hookR, increment); Within("RecordEvent", hookH, record); } } /// Fixtures for the detection tests: rows, pawns, things on free cells, a pawn's own job. internal static class DetectionKit { public static Law Row(string key, LawStage stage, string option = null, string punishment = "Warn", LawSeverity severity = LawSeverity.Minor, int days = 1) => Fixtures.LawRow(key, option, stage, severity, punishment, days); public static List CasesOf(Pawn p) => Fixtures.Comp.CasesOf(p).ToList(); public static LawCase OnlyCase(Pawn p, string who) { List list = CasesOf(p); T.Equal(1, list.Count, "cases of " + who); return list[0]; } public static void NoCase(Pawn p, string who) => T.Equal(0, CasesOf(p).Count, "cases of " + who); /// A spawned free colonist without addictions: a binge would pick the addiction's chemical (Verse.AI/MentalState_BingingDrug.cs:51-66). public static Pawn Colonist() => Clean(Fixtures.Colonist()); /// A free colonist on a free cell next to the other pawn, close enough to talk. public static Pawn ColonistNear(Pawn other) => Clean(Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Colonist, Faction.OfPlayer), TalkCell(other))); /// A pawn of another faction (or none) next to the position. public static Pawn Stranger(Faction faction, IntVec3 near) => Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, faction), FreeCell(near)); /// A pawn of another faction (or none) on a free cell the other pawn can talk to. public static Pawn StrangerNear(Faction faction, Pawn other) => Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, faction), TalkCell(other)); /// /// Makes the pawn a quest lodger: an ongoing quest names another faction as its home faction /// (RimWorld/QuestUtility.cs:524-531, 706-720). acceptanceTick alone makes the quest Ongoing /// (RimWorld/Quest.cs:154-183) without sending its Initiate signal. Returns the quest; the cleanup removes it. /// public static Quest MakeQuestLodger(Pawn p, Faction home) { Quest quest = Quest.MakeRaw(); quest.acceptanceTick = Find.TickManager.TicksGame; var part = new QuestPart_ExtraFaction { extraFaction = new ExtraFaction(home, ExtraFactionType.HomeFaction) }; part.affectedPawns.Add(p); quest.AddPart(part); Find.QuestManager.Add(quest); Fixtures.OnCleanup(() => { if (Find.QuestManager.Contains(quest)) Find.QuestManager.Remove(quest); }); return quest; } private static Pawn Clean(Pawn p) { foreach (Hediff h in p.health.hediffSet.hediffs.OfType().ToList()) p.health.RemoveHediff(h); return p; } /// The nearest cell (or spot for a bigger thing) that is standable, in a district and holds nothing. /// /// A free cell from which a pawn can talk to the other: within 6 cells and in sight /// (RimWorld/SocialInteractionUtility.cs:148-155). FreeCell alone may pick a cell up to 15 cells away. /// public static IntVec3 TalkCell(Pawn other) => FreeCell(other.Position, default, c => SocialInteractionUtility.IsGoodPositionForInteraction(c, other.Position, other.Map)); public static IntVec3 FreeCell(IntVec3 near, IntVec2 size = default, Func also = null) { Map map = Fixtures.Map; IntVec2 s = size.x <= 0 || size.z <= 0 ? IntVec2.One : size; foreach (IntVec3 c in GenRadial.RadialCellsAround(near, 15f, false)) { bool ok = true; foreach (IntVec3 x in GenAdj.OccupiedRect(c, Rot4.North, s).Cells) { if (!x.InBounds(map) || !x.Standable(map) || x.Fogged(map) || x.GetDistrict(map) == null || x.GetFirstItem(map) != null || x.GetFirstPawn(map) != null || x.GetEdifice(map) != null) { ok = false; break; } } if (ok && (also == null || also(c))) return c; } T.Fail("no free " + s + " spot near " + near); return IntVec3.Invalid; } public static TT Place(TT thing, IntVec3 cell) where TT : Thing { Fixtures.Track(thing); GenSpawn.Spawn(thing, cell, Fixtures.Map, Rot4.North); return thing; } public static Thing ItemNear(Pawn p, ThingDef def, int count) { Thing t = ThingMaker.MakeThing(def); t.stackCount = count; return Place(t, FreeCell(p.Position)); } /// An unspawned simple meal with one ingredient (none for null). public static Thing Meal(ThingDef ingredient) { Thing meal = Fixtures.Track(ThingMaker.MakeThing(ThingDefOf.MealSimple)); if (ingredient != null) meal.TryGetComp().RegisterIngredient(ingredient); return meal; } public static Thing MealNear(Pawn p, ThingDef ingredient) { Thing meal = ThingMaker.MakeThing(ThingDefOf.MealSimple); meal.TryGetComp().RegisterIngredient(ingredient); return Place(meal, FreeCell(p.Position)); } public static Thing WoodWallNear(Pawn p) { Thing wall = ThingMaker.MakeThing(ThingDefOf.Wall, ThingDefOf.WoodLog); wall.SetFaction(Faction.OfPlayer); return Place(wall, FreeCell(p.Position)); } /// /// Runs the action while the job is the pawn's current job, as the vanilla toils would have it, and /// puts the pawn's own job back. Hooks C and U read only the job's targets and playerForced. /// public static void WithOwnJob(Pawn p, Job job, Action act) { Job before = p.jobs.curJob; p.jobs.curJob = job; try { act(); } finally { if (p.jobs != null && p.jobs.curJob == job) p.jobs.curJob = before; } } /// The pawn eats one portion of the food on its own Ingest job (RimWorld/Toils_Ingest.cs:402-428). public static void Eat(Pawn p, Thing food, bool playerForced = false) { Job job = JobMaker.MakeJob(JobDefOf.Ingest, food); job.count = 1; job.playerForced = playerForced; // A small want takes one unit (Verse/Thing.cs:2192-2202). WithOwnJob(p, job, () => food.Ingested(p, 0.01f)); } public static bool Start(Pawn p, string stateDefName) => p.mindState.mentalStateHandler.TryStartMentalState(DefDatabase.GetNamed(stateDefName), forced: true, forceWake: true); /// Removes the drugs lying on the map, so a binge can only choose the test's drug (RimWorld/AddictionUtility.cs:120-139). public static void ClearDrugsOnMap() { List drugs = Fixtures.Map.listerThings.ThingsInGroup(ThingRequestGroup.Drug).ToList(); if (drugs.Count > 0) T.Info("removed " + drugs.Count + " drug stack(s) lying on the map"); foreach (Thing t in drugs) { if (!t.Destroyed) t.Destroy(); } } /// /// The drug gives no overdose during the test. Each wake-up dose adds 0.18 to 0.35 overdose, or with a /// chance of 0.005 jumps it to 0.85 to 0.99 (RimWorld/CompDrug.cs:62-93; Defs/Drugs/WakeUp.xml). From /// 0.5 the overdose caps Consciousness at 0.5, from 0.75 at 0.1 (Defs/HediffDefs/Hediffs_Global_Misc.xml), /// which can down the pawn inside the dose and end its binge, so that dose would rightly file nothing. /// public static void NoOverdose(ThingDef drug) { CompProperties_Drug props = drug.GetCompProperties(); T.NotNull(props, "fixture: " + drug.defName + " is no drug"); float chance = props.largeOverdoseChance; FloatRange offset = props.overdoseSeverityOffset; props.largeOverdoseChance = 0f; props.overdoseSeverityOffset = FloatRange.Zero; Fixtures.OnCleanup(() => { props.largeOverdoseChance = chance; props.overdoseSeverityOffset = offset; }); } /// No social fight starts from an interaction during the test (Pawn_InteractionsTracker.cs:357-360). public static void QuietSocialFights() { bool was = DebugSettings.enableRandomMentalStates; DebugSettings.enableRandomMentalStates = false; Fixtures.OnCleanup(() => DebugSettings.enableRandomMentalStates = was); } /// The initiator talks to the recipient now, however recently it talked (the 120-tick minimum, :154-157). public static void Interact(Pawn initiator, Pawn recipient, InteractionDef def) { AccessTools.Field(typeof(Pawn_InteractionsTracker), "lastInteractionTime").SetValue(initiator.interactions, -9999); T.Check(initiator.interactions.TryInteractWith(recipient, def), "fixture: " + initiator.LabelShort + " couldn't " + def.defName + " " + recipient.LabelShort + ": position " + (recipient.Spawned && SocialInteractionUtility.IsGoodPositionForInteraction(initiator, recipient)) + " (" + initiator.Position + " to " + recipient.Position + "), can initiate " + SocialInteractionUtility.CanInitiateInteraction(initiator, def) + ", can receive " + SocialInteractionUtility.CanReceiveInteraction(recipient, def) + ", awake " + initiator.Awake() + "/" + recipient.Awake() + ", talking " + initiator.health.capacities.CapableOf(PawnCapacityDefOf.Talking)); } /// Casts the pawn's native ignite verb on the target at once, skipping the warmup (Verse/Verb.cs:324-368, 375-380). public static void Ignite(Pawn p, Thing target) { Verb_Ignite verb = p.natives.IgniteVerb; T.NotNull(verb, "ignite verb of " + p.LabelShort); T.Check(verb.TryStartCastOn(target), "fixture: " + p.LabelShort + "'s ignite verb refused " + target); verb.WarmupComplete(); p.stances.CancelBusyStanceHard(); } /// Fires the test started are put out after it. public static void PutOutFiresAfter() => Fixtures.OnCleanup(() => { foreach (Thing f in Fixtures.Map.listerThings.ThingsOfDef(ThingDefOf.Fire).ToList()) { if (!f.Destroyed) f.Destroy(); } }); /// A missing hand: the healer mech serum's condition to fix (Verse/HealthUtility.cs:620-625). public static void LoseHand(Pawn p) { BodyPartRecord hand = p.health.hediffSet.GetNotMissingParts().FirstOrDefault(x => x.def == BodyPartDefOf.Hand); T.NotNull(hand, "fixture: a hand of " + p.LabelShort); p.health.AddHediff(HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, p, hand), hand); } /// The faster of two runs after a warm-up run, in Stopwatch ticks. public static long BestOf(Action run) { // Warm up for a while first: the runtime compiles a method unoptimized at first and swaps in the // optimized code in the background after a delay of about 100 ms (tiered compilation), so a few // quick runs measure the first compile, not the hook. var warm = Stopwatch.StartNew(); do run(); while (warm.ElapsedMilliseconds < 400); long best = long.MaxValue; for (int r = 0; r < 3; r++) { var sw = Stopwatch.StartNew(); run(); sw.Stop(); best = Math.Min(best, sw.ElapsedTicks); } return best; } public static string Ms(long ticks) => (ticks * 1000.0 / Stopwatch.Frequency).ToString("0.000"); } }