using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using BlaxLaws; using RimWorld; using Verse; using Verse.AI; namespace BlaxLawsTests { /// /// "Jail for N days": the arrest, hook K, "Maintain only" two ticks after the capture, the release, the /// old bed, a late arrest, no prisoner bed, the holds and fallbacks, the early end, and a jailed colonist /// through the save and the removal. /// public static class JailTests { private const string PrisonLaborId = "avius.prisonlabor"; // Prison Labor's About.xml (Workshop 1899474310), read 2026-12-01 private const string CastesId = "blax.castes"; private static int Now => Find.TickManager.TicksGame; // ---- the sentence ----------------------------------------------------------------- [BlaxTest("jail: a did-it binge case with jail 3 days: a prisoner within 2500 ticks, the break over without catharsis, guilt for the sentence plus a day, Maintain only two ticks after the capture; at the release tick Release, a colonist releases it with WasImprisoned and the same work priorities")] public static void JailThreeDays() { EnforceFixtures.PrisonCell(); Pawn o = EnforceFixtures.Offender(); EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); Dictionary priorities = EnforceFixtures.DistinctPriorities(o); EnforceFixtures.ForceBreak(o, EnforceFixtures.DrugBinge, causedByMood: true); LawCase c = EnforceFixtures.BreakCase(o, "Jail", LawStage.DidIt, 3); Enforcement.Enqueue(c, LawStage.DidIt); int arrestStart = -1; bool jailed = EnforceFixtures.RunUntil(() => { if (arrestStart < 0 && c.status == CaseStatus.Enforcing) arrestStart = Now; return o.IsPrisonerOfColony; }, EnforceFixtures.SubdueTicks); T.Check(jailed, "not a prisoner within 2500 ticks; case " + c + ", wait " + c.waitReason); T.Equal(CaseStatus.Jailed, c.status, "the case's status at the capture"); T.Equal(Now, c.captureTick, "the capture tick"); T.Equal(c.captureTick + 3 * GenDate.TicksPerDay, c.releaseTick, "the release tick"); T.Check(o.MentalState == null, "the break goes on in jail: " + o.MentalStateDef?.defName); T.Check(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.Catharsis) == null, "the jailed pawn has Catharsis"); int minGuilt = 4 * GenDate.TicksPerDay - (Now - arrestStart) - 30; T.Check(o.guilt.TicksUntilInnocent >= minGuilt, "guilt " + o.guilt.TicksUntilInnocent + ", expected at least " + minGuilt); Fixtures.Tick(2); T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode two ticks after the capture"); bool labor = LaborOn(o); T.Check(c.maintainOnlyDone, "maintainOnlyDone after the write"); c.releaseTick = Now; EnforceFixtures.TickPastSentenceSweep(); T.Equal(PrisonerInteractionModeDefOf.Release, o.guest.ExclusiveInteractionMode, "the mode at the release tick"); bool released = EnforceFixtures.RunUntil(() => !o.IsPrisonerOfColony, 4000); T.Check(released, "nobody released the pawn"); T.Check(o.IsFreeColonist, o.LabelShort + " isn't a free colonist after the release"); T.NotNull(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.WasImprisoned), "WasImprisoned after the release"); string diff = PriorityDiff(priorities, o, labor); T.Check(diff == null, "work priorities changed: " + diff); EnforceFixtures.TickPastSentenceSweep(); T.Check(c.IsClosed && c.outcome == CaseOutcomes.Served, "the case after the release: " + c); } [BlaxTest("jail: a mode written at capture plus 1 (Enslave with Ideology, else Reduce resistance) reads Maintain only at capture plus 2, with Laws' component first")] public static void MaintainOnlyLandsLast() { MoveLawsComponentFirst(); EnforceFixtures.PrisonCell(); Pawn o = EnforceFixtures.Offender(); // Standing still: a colonist on a job like cleaning walks as fast as the warden, and the arrest can turn // into a chase longer than the test's budget. The test is about the sentence, not the chase. PawnUtility.ForceWait(o, 2 * EnforceFixtures.SubdueTicks); EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); Enforcement.Enqueue(c, LawStage.DidIt); T.Check(EnforceFixtures.RunUntil(() => o.IsPrisonerOfColony, EnforceFixtures.SubdueTicks), "not a prisoner; case " + c + ", wait " + c.waitReason + "; " + EnforceFixtures.WalkStory(c.enforcer) + "; offender " + EnforceFixtures.WalkStory(o)); T.Equal(Now, c.captureTick, "the capture tick"); Fixtures.Tick(1); PrisonerInteractionModeDef other = ModsConfig.IdeologyActive && PrisonerInteractionModeDefOf.Enslave != null ? PrisonerInteractionModeDefOf.Enslave : PrisonerInteractionModeDefOf.ReduceResistance; o.guest.SetExclusiveInteraction(other); T.Equal(other, o.guest.ExclusiveInteractionMode, "the mode written at capture plus 1"); Fixtures.Tick(1); T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode at capture plus 2"); } /// Puts Laws' component before Castes' in Game.components for the test (Castes writes its default a tick after the capture). private static void MoveLawsComponentFirst() { List list = Current.Game.components; GameComponent_BlaxLaws laws = Fixtures.Comp; int at = list.FindIndex(x => x.GetType().FullName == "BlaxCastes.GameComponent_BlaxCastes"); int mine = list.IndexOf(laws); if (at < 0 || mine < 0 || mine < at) return; List before = list.ToList(); list.Remove(laws); list.Insert(at, laws); Fixtures.OnCleanup(() => { list.Clear(); list.AddRange(before); }); } [BlaxTest("jail: with Prison Labor's work option off the released pawn has the work priorities it had before the arrest; with it on only the work types Prison Labor bars prisoners from are off (needs Prison Labor)")] public static void PrisonLaborKeepsPriorities() { if (!Compat.IsActive(PrisonLaborId)) T.Skip("needs Prison Labor"); PrisonerInteractionModeDef work = DefDatabase.GetNamedSilentFail("PrisonLabor_workOption"); T.NotNull(work, "Prison Labor's PrisonLabor_workOption mode"); foreach (bool on in new[] { false, true }) { Pawn o = EnforceFixtures.Offender(); Dictionary priorities = EnforceFixtures.DistinctPriorities(o); LawCase c = JailAndRelease(o, () => o.guest.ToggleNonExclusiveInteraction(work, on)); string diff = PriorityDiff(priorities, o, on); T.Check(diff == null, "work priorities changed with the work option " + (on ? "on" : "off") + ": " + diff); T.Check(c.IsClosed, "the case after the release: " + c); } } /// Prison Labor's work option is on for the prisoner (PrisonLaborUtility.LaborEnabled in its 1.7 PrisonLabor.dll). private static bool LaborOn(Pawn o) { PrisonerInteractionModeDef work = DefDatabase.GetNamedSilentFail("PrisonLabor_workOption"); return work != null && o.guest != null && o.guest.IsInteractionEnabled(work); } /// /// The changed work priorities, or null. While Prison Labor's work option is on, its JobGiver_Labor runs /// WorkSettings.InitWorkSettings, which disables every work type its settings bar prisoners from /// (WorkSettings.WorkDisabled, Pawn_WorkSettings.Disable), and those stay at 0 after the release: Prison /// Labor's call, not Laws' (design: "Jail for N days", Overlaps). Only those may read 0 afterwards. /// private static string PriorityDiff(Dictionary before, Pawn o, bool labor) { Func barred = _ => false; if (labor) { MethodInfo m = GenTypes.GetTypeInAnyAssembly("PrisonLabor.Core.LaborWorkSettings.WorkSettings")? .GetMethod("WorkDisabled", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(WorkTypeDef) }, null); T.NotNull(m, "Prison Labor's WorkSettings.WorkDisabled(WorkTypeDef)"); barred = wt => (bool)m.Invoke(null, new object[] { wt }); } var diff = before.Where(kv => o.workSettings.GetPriority(kv.Key) != kv.Value && !(o.workSettings.GetPriority(kv.Key) == 0 && barred(kv.Key))) .Select(kv => kv.Key.defName + " " + kv.Value + " to " + o.workSettings.GetPriority(kv.Key)).ToList(); return diff.Count == 0 ? null : string.Join(", ", diff); } [BlaxTest("jail: with Blax Castes the released pawn is back in its old caste (needs Blax Castes)")] public static void CastesKeepsCaste() { if (!Compat.IsActive(CastesId)) T.Skip("needs Blax Castes"); GameComponent castes = Current.Game.components.FirstOrDefault(x => x.GetType().FullName == "BlaxCastes.GameComponent_BlaxCastes"); T.NotNull(castes, "Castes' game component"); MethodInfo casteOf = castes.GetType().GetMethod("CasteOf", new[] { typeof(Pawn) }); T.NotNull(casteOf, "GameComponent_BlaxCastes.CasteOf(Pawn)"); // A generated colonist joins no caste (Castes' join hooks see no SetFaction or SetGuestStatus), so the // offender is put into a caste of its own, which no join row names: only "back to its old caste" // brings it back there after the release. Type manager = GenTypes.GetTypeInAnyAssembly("BlaxCastes.CasteManager"); MethodInfo create = manager?.GetMethod("CreateCaste", BindingFlags.Public | BindingFlags.Static); MethodInfo assign = manager?.GetMethod("Assign", BindingFlags.Public | BindingFlags.Static); MethodInfo delete = manager?.GetMethod("DeleteCaste", BindingFlags.Public | BindingFlags.Static); T.Check(create != null && assign != null && delete != null, "CasteManager.CreateCaste, Assign and DeleteCaste"); object caste = create.Invoke(null, new object[] { "BlaxLawsTest caste" }); T.NotNull(caste, "the test caste"); Fixtures.OnCleanup(() => delete.Invoke(null, new[] { caste })); Pawn o = EnforceFixtures.Offender(); T.Check((bool)assign.Invoke(null, new object[] { o, caste, false, null }), "fixture: the offender can't join the test caste"); Fixtures.Tick(2); object before = casteOf.Invoke(castes, new object[] { o }); T.Check(Equals(before, caste), "fixture: the offender isn't in the test caste: " + before); JailAndRelease(o, null); Fixtures.Tick(5); object after = casteOf.Invoke(castes, new object[] { o }); T.Check(Equals(before, after), "the caste after the release isn't the old one: " + before + " to " + after); } /// Jails the pawn through a 1-day row and releases it through the fallback. atJail runs while it is jailed. private static LawCase JailAndRelease(Pawn o, Action atJail) { // The fallback below backdates the release tick by a day. Before day 2 that tick would be negative, // which Sentences.Check reads as "not set yet" and recomputes from the capture, so the game clock // is moved past a day first, before anything of this test is scheduled. if (Now < 2 * Sentences.FallbackTicks) Find.TickManager.DebugSetTicksGame(2 * Sentences.FallbackTicks); EnforceFixtures.PrisonCell(); // Standing still: a colonist on a job like cleaning walks as fast as the warden, and the arrest can turn // into a chase longer than the test's budget. The test is about the sentence, not the chase. PawnUtility.ForceWait(o, 2 * EnforceFixtures.SubdueTicks); EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); LawCase c = EnforceFixtures.ActCase(o, "Jail", 1); Enforcement.Enqueue(c, LawStage.DidIt); // An arrested colonist turns prisoner when the warden picks it up (JobDriver_TakeToBed.cs:124-129) and // stays held, not spawned, until it is tucked in; the fallback releases only a spawned pawn. atJail runs // at the pick-up, before the prisoner thinks once (Prison Labor's default work option is set there). T.Check(EnforceFixtures.RunUntil(() => o.IsPrisonerOfColony, EnforceFixtures.SubdueTicks), "not a prisoner; case " + c + ", wait " + c.waitReason + "; " + EnforceFixtures.WalkStory(c.enforcer) + "; offender " + EnforceFixtures.WalkStory(o)); atJail?.Invoke(); T.Check(EnforceFixtures.RunUntil(() => o.Spawned && o.InBed(), EnforceFixtures.SubdueTicks), "the prisoner isn't in its bed; case " + c + ", prisoner " + o.IsPrisonerOfColony + ", spawned " + o.Spawned); Fixtures.Tick(5); c.releaseTick = Now - Sentences.FallbackTicks - 1; Sentences.Check(c); T.Check(!o.IsPrisonerOfColony, "the fallback didn't release the pawn; case " + c + ", spawned " + o.Spawned + ", in bed " + o.InBed()); return c; } // ---- the arrest ------------------------------------------------------------------- [BlaxTest("jail: an arrest interrupted after its first toil leaves the colonist its old bed by the next sweep; a bed someone else claimed meanwhile stays theirs")] public static void OldBedBack() { PrisonRoom room = EnforceFixtures.PrisonCell(); Pawn o = EnforceFixtures.Offender(); EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f)); Building_Bed own = EnforceFixtures.ColonistBed(o.Position); T.Check(o.ownership.ClaimBedIfNonMedical(own), "fixture: the colonist can't claim its bed"); // Bystanders without a bed would take the freed bed when they go to sleep before the sweep: the case // of a bed someone else claimed, which the second half tests on purpose. EnforceFixtures.BedsForBystanders(o); // A downed bystander draws rescues, the offender's included; an arrest then waits until the offender put // its patient down (JailFlow.TryArrest). The offender stands still for the test, and the retries below // allow a few sweeps. PawnUtility.ForceWait(o, 4 * EnforceFixtures.SubdueTicks); foreach (Pawn d in EnforceFixtures.Map.mapPawns.AllPawnsSpawned.Where(x => x.Downed && !x.Dead)) T.Info("downed on the map at the start: " + d.LabelShort + " (" + d.ThingID + ")"); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); EnforceFixtures.Dispatch(c, LawStage.DidIt); T.Check(JailFlow.ArrestRuns(c), "no arrest started; wait " + c.waitReason); T.Equal(own, c.oldBed, "the old bed noted in the case"); T.Check(o.ownership.OwnedBed == room.bed, "the arrest's first toil didn't claim the prisoner bed: " + o.ownership.OwnedBed); Pawn raider = EnforceFixtures.Raider(); // keeps the retry waiting, so the sweep's give-back shows c.enforcer.jobs.EndCurrentJob(JobCondition.InterruptForced); T.Info("offender " + o.LabelShort + ", enforcer " + c.enforcer.LabelShort + ", prisoner bed " + room.bed + ", old bed " + own); TickWatchingTakeToBed(Enforcement.SweepInterval + 1); T.Check(o.ownership.OwnedBed == own, "the colonist doesn't own its old bed after the sweep: it owns " + (o.ownership.OwnedBed?.ToString() ?? "no bed") + ", the old bed's owners " + Owners(own) + "; case " + c + ", wait " + c.waitReason + ", arrest runs " + JailFlow.ArrestRuns(c)); T.Equal(WaitReasons.Danger, c.waitReason, "the case's wait while the raider is on the map"); raider.Destroy(DestroyMode.Vanish); T.Check(EnforceFixtures.RunUntil(() => { WatchTakeToBed(); return JailFlow.ArrestRuns(c); }, 3 * Enforcement.SweepInterval + 5), "no second arrest; wait " + c.waitReason + ", the offender reserved by " + (EnforceFixtures.Map.reservationManager.FirstRespectedReserver(o, c.enforcer)?.LabelShort ?? "nobody") + ", the prisoner bed by " + (EnforceFixtures.Map.reservationManager.FirstRespectedReserver(room.bed, c.enforcer)?.LabelShort ?? "nobody")); T.Check(o.ownership.OwnedBed == room.bed, "the second arrest didn't claim the prisoner bed"); Pawn other = EnforceFixtures.Offender(EnforceFixtures.CellNear(o.Position, 6f, 12f)); T.Check(other.ownership.ClaimBedIfNonMedical(own), "fixture: another colonist can't claim the free old bed"); EnforceFixtures.Raider(); c.enforcer.jobs.EndCurrentJob(JobCondition.InterruptForced); TickWatchingTakeToBed(Enforcement.SweepInterval + 1); T.Check(own.OwnersForReading.Contains(other), "the other colonist lost the bed it claimed"); T.Check(!own.OwnersForReading.Contains(o), "the offender took back a bed someone else claimed"); } private static readonly HashSet seenTakeToBed = new HashSet(); /// Notes each take-to-bed job (arrest, capture, rescue) a pawn on the map starts, for a failure in OldBedBack. private static void WatchTakeToBed() { foreach (Pawn p in EnforceFixtures.Map.mapPawns.AllPawnsSpawned) { Job j = p.CurJob; if (j?.def?.driverClass == typeof(JobDriver_TakeToBed) && seenTakeToBed.Add(j)) T.Info(p.LabelShort + " started " + j.def.defName + " on " + j.targetA + " to " + j.targetB + " at tick " + Now); } } private static void TickWatchingTakeToBed(int ticks) { for (int i = 0; i < ticks; i++) { WatchTakeToBed(); Find.TickManager.DoSingleTick(); } } [BlaxTest("jail: an offender carrying a downed colonist to a bed gets no arrest until it put the colonist down: the case waits, the rescue ends in the bed with no reservation error, then the arrest starts")] public static void OffenderCarryingWaits() { EnforceFixtures.PrisonCell(); Pawn o = EnforceFixtures.Offender(); Pawn downed = DownedColonist(EnforceFixtures.CellNear(o.Position, 1f, 2f)); Building_Bed medical = EnforceFixtures.ColonistBed(EnforceFixtures.CellNear(downed.Position, 15f, 25f), medical: true); Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f)); EnforceFixtures.OnlyWardens(warden); Job rescue = StartRescue(o, downed, medical); T.Check(EnforceFixtures.RunUntil(() => o.carryTracker.CarriedThing == downed, 600), "fixture: the offender didn't pick up the downed colonist; " + EnforceFixtures.WalkStory(o)); T.Check(o.CurJob == rescue, "fixture: the offender's job after the pick-up: " + (o.CurJobDef?.defName ?? "none")); var logBefore = new HashSet(Log.Messages); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); EnforceFixtures.Dispatch(c, LawStage.DidIt); T.Check(!JailFlow.ArrestRuns(c) && !EnforceFixtures.AnyEnforcementJobOn(o), "an arrest started while the offender carries a colonist; case " + c); EnforceFixtures.CheckWait(c, WaitReasons.Carrying, "the wait while the offender carries a colonist"); T.Check(o.CurJob == rescue && o.carryTracker.CarriedThing == downed, "the offender lost its rescue: job " + (o.CurJobDef?.defName ?? "none")); bool arrested = EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, EnforceFixtures.CarryTicks + 2 * Enforcement.SweepInterval); T.Check(arrested, "no arrest after the rescue; case " + c + ", wait " + c.waitReason + "; offender " + EnforceFixtures.WalkStory(o) + "; " + EnforceFixtures.EnforcerStory(warden, c)); T.Check(o.carryTracker.CarriedThing == null, "the arrest started while the offender still carries " + o.carryTracker.CarriedThing); T.Check(downed.InBed() && downed.CurrentBed() == medical, "the rescued colonist isn't in the medical bed: " + (downed.CurrentBed()?.ToString() ?? "no bed") + ", spawned " + downed.Spawned); var logged = Log.Messages.Where(m => !logBefore.Contains(m) && m.type == LogMessageType.Error).ToList(); T.Check(logged.Count == 0, "errors during the rescue and the arrest: " + string.Join(" | ", logged.Take(3).Select(m => m.text))); } [BlaxTest("jail: an offender walking to rescue a downed colonist has its rescue ended cleanly when the arrest starts: it holds no reservation and no reservation error follows")] public static void ArrestEndsOffenderReservingJob() { EnforceFixtures.PrisonCell(); Pawn o = EnforceFixtures.Offender(); Pawn downed = DownedColonist(EnforceFixtures.CellNear(o.Position, 12f, 20f)); Building_Bed medical = EnforceFixtures.ColonistBed(downed.Position, medical: true); Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f)); EnforceFixtures.OnlyWardens(warden); Job rescue = StartRescue(o, downed, medical); Map map = EnforceFixtures.Map; T.Check(map.reservationManager.ReservedBy(downed, o) && map.reservationManager.ReservedBy(medical, o), "fixture: the offender's rescue holds no reservations"); T.Check(o.carryTracker.CarriedThing == null, "fixture: the offender carries the colonist already"); var logBefore = new HashSet(Log.Messages); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); EnforceFixtures.Dispatch(c, LawStage.DidIt); T.Check(JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, "no arrest started; wait " + c.waitReason); T.Check(o.CurJob != rescue, "the offender still runs the rescue the arrest dropped the reservations of"); T.Check(!map.reservationManager.ReservationsReadOnly.Any(r => r.Claimant == o && r.Job == rescue), "a reservation of the ended rescue is left"); T.Check(EnforceFixtures.RunUntil(() => o.IsPrisonerOfColony && o.Spawned && o.InBed(), EnforceFixtures.CarryTicks), "the offender isn't a prisoner in bed; case " + c + ", wait " + c.waitReason + "; " + EnforceFixtures.WalkStory(c.enforcer)); var logged = Log.Messages.Where(m => !logBefore.Contains(m) && m.type == LogMessageType.Error).ToList(); T.Check(logged.Count == 0, "errors during the arrest: " + string.Join(" | ", logged.Take(3).Select(m => m.text))); } /// A downed fixture colonist at the cell, with no bleeding wound. private static Pawn DownedColonist(IntVec3 at) { Pawn p = EnforceFixtures.Offender(at); HealthUtility.DamageUntilDowned(p, allowBleedingWounds: false); T.Check(p.Downed && !p.Dead, "fixture: the colonist to rescue isn't downed and alive"); return p; } /// Starts a vanilla rescue of the downed pawn to the bed on the rescuer, as a doctor's would run. private static Job StartRescue(Pawn rescuer, Pawn downed, Building_Bed bed) { Job job = JobMaker.MakeJob(JobDefOf.Rescue, downed, bed); job.count = 1; rescuer.jobs.StartJob(job, JobCondition.InterruptForced); T.Check(rescuer.CurJob == job, "fixture: the rescue didn't start: " + (rescuer.CurJobDef?.defName ?? "none")); return job; } [BlaxTest("jail: a raid that lands while the arrest walks to the colonist calls it off, gives the old bed back and waits for the danger; after the raid the sweep arrests")] public static void RaidCallsOffArrest() { PrisonRoom room = EnforceFixtures.PrisonCell(); Pawn o = EnforceFixtures.Offender(); Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f)); EnforceFixtures.OnlyWardens(warden); Building_Bed own = EnforceFixtures.ColonistBed(o.Position); T.Check(o.ownership.ClaimBedIfNonMedical(own), "fixture: the colonist can't claim its bed"); EnforceFixtures.BedsForBystanders(o); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); EnforceFixtures.Dispatch(c, LawStage.DidIt); T.Check(JailFlow.ArrestRuns(c), "fixture: no arrest started; wait " + c.waitReason); T.Check(!c.enforcer.IsCarryingPawn(o), "fixture: the warden already carries the colonist"); Pawn raider = EnforceFixtures.Raider(); // The worker's sweep directly, so the arrest can't finish between the raid and the check. BlaxLawsDefOf.Jail.Worker.Sweep(c); T.Check(!JailFlow.ArrestRuns(c), "the arrest still runs during the raid"); T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "an enforcement job on the colonist during the raid"); T.Equal(CaseStatus.Open, c.status, "status during the raid"); T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid"); T.Check(!o.IsPrisonerOfColony, "a prisoner during the raid"); T.Check(o.ownership.OwnedBed == own, "the old bed wasn't given back: owns " + (o.ownership.OwnedBed?.ToString() ?? "no bed")); raider.Destroy(DestroyMode.Vanish); // The called-off warden may still be on a job Laws never drops (a flee from the raider), so the first // sweep can wait as busy; one of the next few sweeps arrests. T.Check(EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, 4 * Enforcement.SweepInterval + 5), "no arrest four sweeps after the raid; wait " + c.waitReason + "; " + EnforceFixtures.EnforcerStory(warden, c)); T.Check(o.ownership.OwnedBed == room.bed || o.IsPrisonerOfColony, "the second arrest didn't claim the prisoner bed"); } [BlaxTest("jail: a raid that lands while the warden already carries the arrested colonist leaves the jailed case alone: the carry finishes and the colonist ends a prisoner in the cell's bed")] public static void RaidLetsCarryFinish() { PrisonRoom room = EnforceFixtures.PrisonCell(); Map map = EnforceFixtures.Map; // At least 10 cells from the door: next to the cell the whole carry runs inside one tick // (pick-up, a goto already at the bed, tuck-in), and there would be no carry to raid. IntVec3 outside = room.things.First(t => t.def == ThingDefOf.Door).Position + IntVec3.West; Pawn o = EnforceFixtures.Offender(EnforceFixtures.CellNear(outside, 10f, 20f)); EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f)); EnforceFixtures.BedsForBystanders(o); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); Room cell = room.bed.GetRoom(); // An idle colonist may wander into the open cell (WanderUtility.cs:70-78 keeps only the wander root out). T.Check(o.GetRoom() != cell && !o.Position.IsInPrisonCell(map), "fixture: the colonist is in the prison cell before the arrest, at " + o.Position + ", job " + (o.CurJobDef?.defName ?? "none")); EnforceFixtures.Dispatch(c, LawStage.DidIt); T.Check(JailFlow.ArrestRuns(c), "fixture: no arrest started; wait " + c.waitReason); Pawn first = c.enforcer; IntVec3 lastOffender = o.Position, lastEnforcer = first.Position; string lastJob = o.CurJobDef?.defName ?? "none"; // Whoever carries: a sweep may re-send the arrest to another colonist before the carry starts. bool seen = EnforceFixtures.RunUntil(() => { if (o.Spawned) { lastOffender = o.Position; lastJob = o.CurJobDef?.defName ?? "none"; } if (c.enforcer != null && c.enforcer.Spawned) lastEnforcer = c.enforcer.Position; return o.CarriedBy != null || c.status == CaseStatus.Jailed; }, EnforceFixtures.SubdueTicks); T.Check(seen, "fixture: nobody carried the colonist; case " + c + ", first enforcer " + EnforceFixtures.EnforcerStory(first, c) + "; enforcer now " + EnforceFixtures.EnforcerStory(c.enforcer, c)); T.Check(o.CarriedBy != null, "fixture: the arrest finished inside one tick; the colonist was last at " + lastOffender + " (in the cell " + lastOffender.IsInPrisonCell(map) + ", job " + lastJob + "), the enforcer at " + lastEnforcer + ", the bed at " + room.bed.Position); Pawn enforcer = o.CarriedBy; T.Check(enforcer == c.enforcer, "the colonist is carried by " + enforcer.LabelShort + ", not by the case's enforcer " + (c.enforcer?.LabelShort ?? "none")); // The pick-up has made the colonist Laws' prisoner (JobDriver_TakeToBed.cs:121-129; hook K). T.Equal(CaseStatus.Jailed, c.status, "the case's status once the carry started"); EnforceFixtures.Raider(); // A carried pawn is despawned, so the raider counts through the enforcer's map (Raider() checks the threat). T.Check(GenHostility.AnyHostileActiveThreatToPlayer(enforcer.Map), "fixture: the raider is no threat on the warden's map"); // The worker's sweep and the call-off directly, while the warden carries the colonist. BlaxLawsDefOf.Jail.Worker.Sweep(c); T.Check(!JailFlow.CallOffInDanger(c), "the arrest was called off mid-carry"); T.Check(enforcer.IsCarryingPawn(o), "the warden dropped the colonist"); T.Equal(CaseStatus.Jailed, c.status, "the case's status after a sweep during the raid"); T.Check(c.waitReason != WaitReasons.Danger, "the case waits for the danger while the carry goes on"); T.Check(EnforceFixtures.RunUntil(() => o.Spawned && o.InBed(), EnforceFixtures.SubdueTicks), "the carry didn't end in the cell's bed with the raider on the map; case " + c + ", " + EnforceFixtures.WalkStory(enforcer)); T.Check(o.IsPrisonerOfColony && o.ownership.OwnedBed == room.bed, "the colonist isn't a prisoner owning the cell's bed: " + (o.ownership.OwnedBed?.ToString() ?? "no bed")); } private static string Owners(Building_Bed bed) { List owners = bed.OwnersForReading; if (owners.Count == 0) return "none"; return string.Join(", ", owners.Select(p => p.LabelShort + (p.Awake() ? " (awake)" : " (asleep)"))); } [BlaxTest("jail: a 5-day row whose guilt ran out while no prisoner bed existed: once a bed is built the arrest is accepted against Social 0 and the release comes 5 days after the capture")] public static void LateArrest() { Pawn o = EnforceFixtures.Offender(); EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); SocialZeroForAll(); LawCase c = EnforceFixtures.ActCase(o, "Jail", 5); EnforceFixtures.Dispatch(c, LawStage.DidIt); EnforceFixtures.CheckWait(c, WaitReasons.NoBed, "the wait without a prisoner bed"); T.Check(o.guilt.TicksUntilInnocent >= 5 * GenDate.TicksPerDay - 30, "no guilt for the sentence at filing: " + o.guilt.TicksUntilInnocent); o.guilt.Notify_Guilty(0); // the six days without a bed: the guilt from filing has run out T.Check(!o.guilt.IsGuilty, "fixture: the guilt didn't run out"); EnforceFixtures.PrisonCell(); int guiltAtArrest = -1; bool jailed = EnforceFixtures.RunUntil(() => { if (guiltAtArrest < 0 && JailFlow.ArrestRuns(c)) guiltAtArrest = o.guilt.TicksUntilInnocent; return o.IsPrisonerOfColony || o.InMentalState; }, Enforcement.SentenceInterval + EnforceFixtures.SubdueTicks); T.Check(guiltAtArrest >= 6 * GenDate.TicksPerDay - 30, "guilt when the arrest started: " + guiltAtArrest); T.Check(!o.InMentalState, "the arrest was refused: " + o.MentalStateDef?.defName); T.Check(jailed, "no arrest after the bed was built; case " + c + ", wait " + c.waitReason); T.Equal(c.captureTick + 5 * GenDate.TicksPerDay, c.releaseTick, "the release tick"); } /// Every free colonist's Social at 0 for the test, restored after. private static void SocialZeroForAll() { var old = new List<(SkillRecord skill, int level)>(); foreach (Pawn p in EnforceFixtures.Map.mapPawns.FreeColonistsSpawned) { SkillRecord s = p.skills?.GetSkill(SkillDefOf.Social); if (s == null) continue; old.Add((s, s.Level)); s.Level = 0; } Fixtures.OnCleanup(() => { foreach (var (skill, level) in old) skill.Level = level; }); } [BlaxTest("jail: no prisoner bed gives one letter and no arrest; building one leads to the arrest at the next sweep")] public static void NoPrisonerBed() { Pawn o = EnforceFixtures.Offender(); EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); string label = "BlaxLaws_LetterNoBedLabel".Translate(c.OffenderLabel); EnforceFixtures.Dispatch(c, LawStage.DidIt); EnforceFixtures.CheckWait(c, WaitReasons.NoBed, "the wait without a prisoner bed"); EnforceFixtures.TickPastSentenceSweep(); EnforceFixtures.TickPastSentenceSweep(); T.Equal(1, EnforceFixtures.LettersLabeled(label), "no-bed letters"); T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "an arrest started without a bed"); EnforceFixtures.PrisonCell(); bool arrest = EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, Enforcement.SentenceInterval + 5); T.Check(arrest, "no arrest after the bed was built; wait " + c.waitReason); } // ---- holds and fallbacks ---------------------------------------------------------- [BlaxTest("jail: a role holder gets no arrest and one letter; Arrest now arrests (needs Ideology)")] public static void HoldRoleHolder() { T.NeedsDlc("Ideology", ModsConfig.IdeologyActive); Pawn o = null; for (int i = 0; i < 10 && o == null; i++) { Pawn candidate = EnforceFixtures.Offender(); if (GiveRole(candidate)) o = candidate; } if (o == null) T.Skip("ten generated colonists met the requirements of no role of their ideoligion"); Fixtures.Tick(1); T.Check(DlcSupport.HoldsRole(o), "fixture: the colonist holds no role after a tick"); CheckHoldAndArrestNow(o); } [BlaxTest("jail: a mechanitor with a mech gets no arrest and one letter; Arrest now arrests (needs Biotech)")] public static void HoldMechanitor() { T.NeedsDlc("Biotech", ModsConfig.BiotechActive); Pawn o = EnforceFixtures.Offender(); MakeMechanitor(o, keep: false); CheckHoldAndArrestNow(o); } [BlaxTest("jail: a pawn that becomes a mechanitor with a mech while its case waits for a bed is held, not arrested (needs Biotech)")] public static void HoldAfterOtherWait() { T.NeedsDlc("Biotech", ModsConfig.BiotechActive); Pawn o = EnforceFixtures.Offender(); EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); EnforceFixtures.Dispatch(c, LawStage.DidIt); EnforceFixtures.CheckWait(c, WaitReasons.NoBed, "fixture: the wait without a prisoner bed"); MakeMechanitor(o, keep: false); EnforceFixtures.PrisonCell(); JailFlow.TryArrest(c, ignoreHold: false); T.Equal(WaitReasons.Hold, c.waitReason, "the wait after the pawn got a mech"); T.Check(!JailFlow.ArrestRuns(c) && !o.IsPrisonerOfColony, "Laws arrested a mechanitor on its own after a bed wait"); T.Check(!c.holdLifted, "the hold counts as lifted without Arrest now"); } /// /// Gives the colonist a mechlink and a lifter it oversees (needs Biotech). With keep the mech stays for /// phase 2 and the relation is left in place; otherwise the cleanup removes the relation. /// private static void MakeMechanitor(Pawn o, bool keep) { o.health.AddHediff(HediffDefOf.MechlinkImplant, o.health.hediffSet.GetBrain()); T.Check(MechanitorUtility.IsMechanitor(o), "fixture: the mechlink made no mechanitor"); PawnKindDef kind = DefDatabase.GetNamedSilentFail("Mech_Lifter"); T.NotNull(kind, "PawnKindDef Mech_Lifter"); Pawn mech = Fixtures.Spawn(Fixtures.Generate(kind, Faction.OfPlayer), EnforceFixtures.CellNear(o.Position, 2f, 5f)); o.relations.AddDirectRelation(PawnRelationDefOf.Overseer, mech); o.mechanitor.Notify_BandwidthChanged(); // rebuilds ControlledPawns from the control groups (Pawn_MechanitorTracker.cs:268-290) if (keep) Fixtures.Keep(mech); else Fixtures.OnCleanup(() => { if (o.relations.DirectRelationExists(PawnRelationDefOf.Overseer, mech)) o.relations.RemoveDirectRelation(PawnRelationDefOf.Overseer, mech); }); T.Check(DlcSupport.IsMechanitorWithMechs(o), "fixture: the mechanitor controls no mech"); } private static void CheckHoldAndArrestNow(Pawn o) { EnforceFixtures.PrisonCell(); EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); string label = "BlaxLaws_LetterHoldLabel".Translate(c.OffenderLabel); EnforceFixtures.Dispatch(c, LawStage.DidIt); T.Equal(WaitReasons.Hold, c.waitReason, "the wait of a held pawn"); Fixtures.Tick(Enforcement.SweepInterval + 1); T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "a held pawn was arrested"); T.Equal(1, EnforceFixtures.LettersLabeled(label), "hold letters"); T.Check(Sentences.CanArrestNow(c), "Arrest now isn't offered"); o.guilt.Notify_Guilty(0); Sentences.ArrestNow(c); T.Check(JailFlow.ArrestRuns(c), "Arrest now started no arrest; wait " + c.waitReason); T.Check(o.guilt.TicksUntilInnocent >= 4 * GenDate.TicksPerDay - 30, "Arrest now didn't renew the guilt: " + o.guilt.TicksUntilInnocent); Fixtures.Tick(Enforcement.SweepInterval + 1); T.Check(JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, "the sweep put the hold back; wait " + c.waitReason); } /// /// Gives the colonist a role of its ideoligion whose requirements it meets, a multi role when there is /// one, among the active roles; undone before the cleanup. Returns false when no role fits. A role whose requirements the pawn /// misses (a skill, not a child) is taken away again on the next role tick (Precept_RoleSingle.cs:66-70; /// Precept_Role.cs:508-520, 582-597). /// private static bool GiveRole(Pawn o) { Ideo ideo = o.Ideo; if (ideo == null) return false; Precept_Role role = ideo.PreceptsListForReading.OfType().FirstOrDefault(r => r.Active && r.RequirementsMet(o)) ?? (Precept_Role)ideo.PreceptsListForReading.OfType().FirstOrDefault(r => r.Active && r.RequirementsMet(o)); if (role == null) return false; Pawn previous = (role as Precept_RoleSingle)?.ChosenPawnValue; role.Assign(o, addThoughts: false); Fixtures.OnCleanup(() => { if (role.IsAssigned(o)) role.Unassign(o, generateThoughts: false); if (previous != null && !previous.Destroyed && role is Precept_RoleSingle single && single.ChosenPawnValue == null) single.Assign(previous, addThoughts: false); }); return true; } [BlaxTest("jail: a slave in a binge with a jail row is subdued; the same row outside a break warns (needs Ideology)")] public static void SlaveFallsBack() { Pawn slave = EnforceFixtures.Ready(Fixtures.ColonySlave()); EnforceFixtures.Warden(EnforceFixtures.CellNear(slave.Position, 2f, 5f)); LawCase quiet = EnforceFixtures.ActCase(slave, "Jail", 3); EnforceFixtures.Dispatch(quiet, LawStage.DidIt); T.Check(quiet.IsClosed && quiet.outcome == CaseOutcomes.Warned, "the slave's case outside a break: " + quiet); T.Check(!slave.IsPrisoner && !EnforceFixtures.AnyEnforcementJobOn(slave), "the slave was arrested outside a break"); EnforceFixtures.ForceBreak(slave, EnforceFixtures.DrugBinge); LawCase binge = EnforceFixtures.BreakCase(slave, "Jail", LawStage.DidIt, 3); EnforceFixtures.Dispatch(binge, LawStage.DidIt); T.Equal("Subdue", binge.activePunishment, "the binging slave's punishment"); T.Check(SubdueFlow.Runs(binge), "no subdue for the binging slave; wait " + binge.waitReason); T.Check(!slave.IsPrisoner, "the slave was jailed"); } // ---- the early end and the fallback ----------------------------------------------- [BlaxTest("jail: recruiting the jailed pawn closes the sentence as released early")] public static void RecruitEndsEarly() { Pawn o = EnforceFixtures.Offender(); Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f)); LawCase c = EnforceFixtures.JailDirect(o, warden, 3); RecruitUtility.Recruit(o, Faction.OfPlayer, warden); T.Check(!o.IsPrisonerOfColony, "fixture: the recruited pawn is still a prisoner"); Sentences.Check(c); T.Check(c.IsClosed && c.outcome == CaseOutcomes.ReleasedEarly, "the case after the recruitment: " + c); } [BlaxTest("jail: a day after the sentence without a release, Laws releases the pawn in place")] public static void FallbackRelease() { // A release tick a day and a tick in the past must be a real tick (-1 means "not set yet"). if (Now < Sentences.FallbackTicks + 1) Fixtures.Tick(Sentences.FallbackTicks + 1 - Now); Pawn o = EnforceFixtures.Offender(); Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f)); LawCase c = EnforceFixtures.JailDirect(o, warden, 3); c.releaseTick = Now - Sentences.FallbackTicks - 1; Sentences.Check(c); T.Check(!o.IsPrisonerOfColony && o.IsFreeColonist, o.LabelShort + " isn't free after the fallback"); T.NotNull(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.WasImprisoned), "WasImprisoned after the fallback"); T.Check(c.IsClosed && c.outcome == CaseOutcomes.Served, "the case after the fallback: " + c); } [BlaxTest("jail: repealing the law of a jailed pawn sets Release on it")] public static void RepealReleases() { Pawn o = EnforceFixtures.Offender(); Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f)); LawCase c = EnforceFixtures.JailDirect(o, warden, 3); Sentences.WriteMaintainOnly(c); string confirm = LawbookUi.DeleteConfirmText(c.LawFor(LawStage.DidIt)) ?? ""; T.Check(confirm.Contains("Release"), "the delete confirmation doesn't say the jailed pawn is set to Release: " + confirm); T.Equal(1, Lawbook.Delete(c.LawFor(LawStage.DidIt)), "cases the repeal closed"); T.Check(c.IsClosed && c.outcome == CaseOutcomes.Repealed, "the case after the repeal: " + c); T.Equal(PrisonerInteractionModeDefOf.Release, o.guest.ExclusiveInteractionMode, "the jailed pawn's mode after the repeal"); } // ---- save and removal --------------------------------------------------------------- private const string JailSaveKey = "jail.savedPrisoner"; [BlaxTest("jail save: a colonist jailed for 50 days at the first save (setup)")] public static void JailSaveSetup() { T.CarryAtSave(JailSaveKey, JailForSave); } private static string JailForSave() { PrisonRoom room = EnforceFixtures.PrisonCell(keep: true); Pawn o = Fixtures.Keep(EnforceFixtures.Offender(room.inside)); Pawn warden = Fixtures.Keep(EnforceFixtures.Warden()); LawCase c = EnforceFixtures.JailDirect(o, warden, 50); Fixtures.KeepLaw(c.LawFor(LawStage.DidIt)); Sentences.WriteMaintainOnly(c); return c.id + "|" + o.ThingID + "|" + c.captureTick; } [BlaxTest("jail save: the jailed colonist is still Laws' prisoner on Maintain only after the reload", phase: 2)] public static void JailSaveRoundTrip() { T.Check(T.Carry.TryGetValue(JailSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 jail setup did not run"); string[] parts = carry.Split('|'); LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[0])); Pawn o = Fixtures.FindPawnById(parts[1]); T.NotNull(c, "the jail case after the reload"); T.NotNull(o, "the jailed colonist after the reload"); T.Check(c.offender == o, "the case's offender didn't resolve"); T.Equal(CaseStatus.Jailed, c.status, "the case's status"); T.Equal(int.Parse(parts[2]), c.captureTick, "the capture tick"); T.Equal(c.captureTick + 50 * GenDate.TicksPerDay, c.releaseTick, "the release tick"); T.Check(c.maintainOnlyDone, "maintainOnlyDone after the reload"); T.Check(o.IsPrisonerOfColony, o.LabelShort + " isn't a prisoner after the reload"); T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode after the reload"); } private const string HoldSaveKey = "jail.holdLifted"; [BlaxTest("jail save: a mechanitor's case with Arrest now pressed at the first save (setup, needs Biotech)")] public static void HoldLiftSaveSetup() { T.NeedsDlc("Biotech", ModsConfig.BiotechActive); T.CarryAtSave(HoldSaveKey, HoldLiftForSave); } private static string HoldLiftForSave() { Pawn o = Fixtures.Keep(EnforceFixtures.Offender()); Fixtures.Keep(EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f))); MakeMechanitor(o, keep: true); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); Fixtures.KeepLaw(c.LawFor(LawStage.DidIt)); EnforceFixtures.Dispatch(c, LawStage.DidIt); if (c.waitReason != WaitReasons.Hold) throw new InvalidOperationException("the mechanitor's case waits for " + (c.waitReason ?? "nothing") + ", not the hold"); Sentences.ArrestNow(c); // The state a failed arrest leaves (PunishmentWorker_Jail.Sweep): no job, Open, no wait. JailFlow.EndArrest(c); c.status = CaseStatus.Open; c.waitReason = null; return c.id + "|" + o.ThingID; } [BlaxTest("jail save: Arrest now still holds after the reload; a failed arrest retries without a second hold", phase: 2)] public static void HoldLiftRoundTrip() { T.NeedsDlc("Biotech", ModsConfig.BiotechActive); T.Check(T.Carry.TryGetValue(HoldSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 hold setup did not run"); string[] parts = carry.Split('|'); T.Check(parts.Length == 2, "carry: " + carry); LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[0])); Pawn o = Fixtures.FindPawnById(parts[1]); T.NotNull(c, "the held case after the reload"); T.NotNull(o, "the mechanitor after the reload"); T.Check(DlcSupport.IsMechanitorWithMechs(o), "fixture: the mechanitor lost its mech in the reload"); T.Check(c.holdLifted, "holdLifted after the reload"); T.Check(c.waitReason != WaitReasons.Hold, "a sweep after the reload put the hold back"); if (!JailFlow.ArrestRuns(c) && !o.IsPrisonerOfColony) { c.status = CaseStatus.Open; c.waitReason = null; JailFlow.TryArrest(c, ignoreHold: false); T.Check(c.waitReason != WaitReasons.Hold && !Sentences.CanArrestNow(c), "the retry after the reload went back to the hold; wait " + c.waitReason); } } [BlaxTest("removal: the colonist Laws jailed is still a prisoner of the colony", phase: 3)] public static void JailedAfterRemoval() { T.Check(T.Carry.TryGetValue(JailSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 jail setup did not run"); Pawn o = Fixtures.FindPawnById(carry.Split('|')[1]); T.NotNull(o, "the jailed colonist after the removal"); T.Check(o.IsPrisonerOfColony, o.LabelShort + " isn't a prisoner of the colony after the removal"); T.Equal(0, Fixtures.Comp.Cases.Count, "cases in the fresh component"); } } }