1756 lines
107 KiB
C#
1756 lines
107 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using BlaxLaws;
|
|
using RimWorld;
|
|
using RimWorld.Planet;
|
|
using Verse;
|
|
using Verse.AI;
|
|
|
|
namespace BlaxLawsTests
|
|
{
|
|
/// <summary>A walled 5x5 prison cell with a door and one prisoner bed (EnforceFixtures.PrisonCell).</summary>
|
|
public sealed class PrisonRoom
|
|
{
|
|
public Building_Bed bed;
|
|
|
|
/// <summary>A free cell inside the room, beside the bed.</summary>
|
|
public IntVec3 inside;
|
|
|
|
public readonly List<Thing> things = new List<Thing>();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Fixtures of the enforcement and jail tests. Pawns and things go through Fixtures, so the runner removes
|
|
/// them after each test unless kept. Rows use act keys no catalogue knows ("Ate/BlaxLawsTest_Enforce3"),
|
|
/// so no detection hook ever files a second case for them; cases are opened with CaseFiler.Open and
|
|
/// queued with Enforcement.Enqueue, the way CaseFiler.Report does it.
|
|
/// </summary>
|
|
public static class EnforceFixtures
|
|
{
|
|
public const int SubdueTicks = 2500;
|
|
|
|
/// <summary>A tantrum or a rage walks from target to target, so the warden lands about half its hits (about 1300 ticks to down one, against about 1000 for a binge).</summary>
|
|
public const int MovingSubdueTicks = 2 * SubdueTicks;
|
|
|
|
/// <summary>A pawn with both arms bionic offers only the torso, legs and feet to the subdue, so it takes far more hits to down.</summary>
|
|
public const int BionicSubdueTicks = 3 * SubdueTicks;
|
|
|
|
/// <summary>
|
|
/// A carry to the prisoner bed. PrisonCell puts the cell up to 50 cells from the pawns, and on a swamp or
|
|
/// mud map (path cost 14 a cell on mud, 30 on marsh: Terrain_Natural.xml, Terrain_Water.xml) such a carry can take over 2000 ticks.
|
|
/// </summary>
|
|
public const int CarryTicks = 2 * SubdueTicks;
|
|
|
|
/// <summary>Cells per second a warden fixture walks at least; a healthy adult walks 4.6.</summary>
|
|
public const float MinWardenSpeed = 4f;
|
|
|
|
private static int keyCounter;
|
|
|
|
public static Map Map => Find.CurrentMap;
|
|
|
|
public static int Now => Find.TickManager.TicksGame;
|
|
|
|
/// <summary>The social drug binge: Core, the recovery thought is Catharsis (MentalStates_Mood.xml:276).</summary>
|
|
public static MentalStateDef DrugBinge => DefDatabase<MentalStateDef>.GetNamed("Binging_DrugMajor");
|
|
|
|
public static HediffDef Bruise => DefDatabase<HediffDef>.GetNamed("Bruise");
|
|
|
|
// ---- pawns -----------------------------------------------------------------------
|
|
|
|
/// <summary>Rested, fed and on "anything" every hour, so it neither sleeps nor eats during a test.</summary>
|
|
public static Pawn Ready(Pawn p)
|
|
{
|
|
if (p.needs?.rest != null)
|
|
p.needs.rest.CurLevel = 1f;
|
|
if (p.needs?.food != null)
|
|
p.needs.food.CurLevel = p.needs.food.MaxLevel;
|
|
if (p.needs?.joy != null)
|
|
p.needs.joy.CurLevel = 1f;
|
|
if (p.timetable != null)
|
|
{
|
|
for (int h = 0; h < GenDate.HoursPerDay; h++)
|
|
p.timetable.SetAssignment(h, TimeAssignmentDefOf.Anything);
|
|
}
|
|
return p;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A spawned free adult colonist with normal pain, ready. The subdue tests count on a normal adult going
|
|
/// down at about 64 points of bruises (design: "Subdue"); a colonist with halved pain (Biotech's reduced
|
|
/// pain gene) needs twice the hits, more than SubdueTicks allows.
|
|
/// </summary>
|
|
public static Pawn Offender(IntVec3? at = null)
|
|
{
|
|
for (int i = 0; i < 40; i++)
|
|
{
|
|
Pawn p = Fixtures.Generate(PawnKindDefOf.Colonist, Faction.OfPlayer);
|
|
// An addict is generated with its drug in its pocket (PawnInventoryGenerator.cs:51, 82-110) and a binger
|
|
// doses what it carries: a go-juice dose cuts pain to a tenth and the subdue gives up.
|
|
// A colonist vanilla sends to medical rest (a disease, an injury that needs tending) walks to a bed
|
|
// instead of its job (JobGiver_PatientGoToBed.cs:15-47).
|
|
if (p.health.hediffSet.hediffs.Any(h => h is Hediff_Addiction || h is Hediff_High) || HealthAIUtility.ShouldSeekMedicalRest(p))
|
|
continue;
|
|
if (Math.Abs(PainFactor(p) - 1f) < 0.001f)
|
|
{
|
|
foreach (Thing t in p.inventory.innerContainer.Where(t => t.def.IsDrug).ToList())
|
|
p.inventory.innerContainer.Remove(t);
|
|
Ready(Fixtures.Spawn(p, at));
|
|
Fixtures.CheckAlive(p, "its spawn");
|
|
return p;
|
|
}
|
|
}
|
|
T.Fail("no generated colonist had normal pain");
|
|
return null;
|
|
}
|
|
|
|
/// <summary>Every pain factor of the pawn's hediffs, genes and traits multiplied (HediffSet.cs:1351-1365): 1 for most colonists.</summary>
|
|
public static float PainFactor(Pawn p)
|
|
{
|
|
float f = 1f;
|
|
foreach (Hediff h in p.health.hediffSet.hediffs)
|
|
f *= h.PainFactor;
|
|
if (p.genes != null)
|
|
f *= p.genes.PainFactor;
|
|
if (p.story?.traits != null)
|
|
{
|
|
foreach (Trait t in p.story.traits.allTraits)
|
|
f *= t.CurrentData.painFactor;
|
|
}
|
|
return f;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A spawned colonist with Warden work at priority 1 who can do violence and carry people, and walks at a
|
|
/// normal pace: a generated colonist with an old leg wound or a bad back can walk at half speed, which
|
|
/// doubles every chase.
|
|
/// </summary>
|
|
public static Pawn Warden(IntVec3? at = null)
|
|
{
|
|
for (int i = 0; i < 40; i++)
|
|
{
|
|
Pawn p = Fixtures.Generate(PawnKindDefOf.Colonist, Faction.OfPlayer);
|
|
// A colonist vanilla sends to medical rest walks to a bed instead (JobGiver_PatientGoToBed.cs:15-47,
|
|
// ahead of work in the think tree) and is never free to enforce (LayDown is not casually interruptible).
|
|
if (p.WorkTypeIsDisabled(WorkTypeDefOf.Warden) || p.WorkTagIsDisabled(WorkTags.Violent) || p.GetStatValue(StatDefOf.MoveSpeed) < MinWardenSpeed ||
|
|
HealthAIUtility.ShouldSeekMedicalRest(p))
|
|
continue;
|
|
Fixtures.Spawn(p, at);
|
|
p.workSettings?.EnableAndInitializeIfNotAlreadyInitialized();
|
|
p.workSettings?.SetPriority(WorkTypeDefOf.Warden, 1);
|
|
// Tending and rescuing are jobs Laws never pulls a pawn off (Enforcers.MustNotDrop, TendPatient and
|
|
// Rescue are not casually interruptible), and a multi-injury tend outlasts a test's sweep window. A
|
|
// test that wants a doctor makes its own.
|
|
if (!p.WorkTypeIsDisabled(WorkTypeDefOf.Doctor))
|
|
p.workSettings?.SetPriority(WorkTypeDefOf.Doctor, 0);
|
|
T.Check(Enforcers.IsWarden(p), "warden fixture has no active Warden work");
|
|
return Ready(p);
|
|
}
|
|
T.Fail("no generated colonist could do Warden work and violence at a normal walking pace");
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Only these wardens enforce during the test: "Wardens only", and Warden work off for every other free
|
|
/// colonist on the map (the quick test's starting colonists), put back after the test.
|
|
/// </summary>
|
|
public static void OnlyWardens(params Pawn[] wardens)
|
|
{
|
|
Fixtures.Settings.enforcers = EnforcerMode.WardensOnly;
|
|
var old = new List<(Pawn pawn, int priority)>();
|
|
foreach (Pawn p in Map.mapPawns.FreeColonistsSpawned)
|
|
{
|
|
if (wardens.Contains(p) || !Enforcers.IsWarden(p))
|
|
continue;
|
|
old.Add((p, p.workSettings.GetPriority(WorkTypeDefOf.Warden)));
|
|
p.workSettings.SetPriority(WorkTypeDefOf.Warden, 0);
|
|
}
|
|
Fixtures.OnCleanup(() =>
|
|
{
|
|
foreach (var (pawn, priority) in old)
|
|
{
|
|
if (!pawn.Destroyed && pawn.workSettings != null)
|
|
pawn.workSettings.SetPriority(WorkTypeDefOf.Warden, priority);
|
|
}
|
|
});
|
|
}
|
|
|
|
/// <summary>A standable cell in the root's district, between the distances, with nobody on it.</summary>
|
|
public static IntVec3 CellNear(IntVec3 root, float minDist, float maxDist)
|
|
{
|
|
Map map = Map;
|
|
District district = root.GetDistrict(map);
|
|
if (CellFinder.TryFindRandomCellNear(root, map, (int)maxDist + 1, c =>
|
|
c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) == district && c.GetFirstPawn(map) == null &&
|
|
c.InHorDistOf(root, maxDist) && !c.InHorDistOf(root, minDist), out IntVec3 cell))
|
|
return cell;
|
|
T.Fail("no free cell " + minDist + " to " + maxDist + " cells from " + root);
|
|
return IntVec3.Invalid;
|
|
}
|
|
|
|
/// <summary>A hostile pawn far from the colony, unarmed so it can't shoot in the few ticks a test keeps it.</summary>
|
|
public static Pawn Raider()
|
|
{
|
|
Faction f = Fixtures.HostileFaction();
|
|
if (f == null)
|
|
T.Skip("this world has no hostile humanlike faction");
|
|
Map map = Map;
|
|
IntVec3 anchor = Fixtures.PawnCell();
|
|
District district = anchor.GetDistrict(map);
|
|
if (!CellFinder.TryFindRandomCellNear(anchor, map, 80, c => c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) == district &&
|
|
c.GetFirstPawn(map) == null && !c.InHorDistOf(anchor, 45f), out IntVec3 cell))
|
|
T.Fail("no cell 45 or more cells from the colony for a raider");
|
|
Pawn p = Fixtures.Generate(f.def.basicMemberKind ?? PawnKindDefOf.Villager, f);
|
|
p.equipment?.DestroyAllEquipment();
|
|
Fixtures.Spawn(p, cell);
|
|
T.Check(GenHostility.AnyHostileActiveThreatToPlayer(map), "the raider fixture is no active threat");
|
|
return p;
|
|
}
|
|
|
|
// ---- breaks, rows and cases -----------------------------------------------------
|
|
|
|
public static void ForceBreak(Pawn p, MentalStateDef def, bool causedByMood = true, Pawn otherPawn = null)
|
|
{
|
|
bool started = p.mindState.mentalStateHandler.TryStartMentalState(def, null, forced: true, forceWake: true, causedByMood: causedByMood, otherPawn: otherPawn);
|
|
T.Check(started && p.MentalStateDef == def, "could not start " + def.defName + " on " + p.LabelShort);
|
|
}
|
|
|
|
/// <summary>A row on an act key no catalogue knows, so only CaseFiler.Open files cases for it.</summary>
|
|
public static Law Row(string category, string punishment, LawStage stage, int days, LawSeverity severity = LawSeverity.Serious) =>
|
|
Fixtures.LawRow(category + "/BlaxLawsTest_Enforce" + (++keyCounter), null, stage, severity, punishment, days);
|
|
|
|
/// <summary>A did-it case outside a break under a new row.</summary>
|
|
public static LawCase ActCase(Pawn offender, string punishment, int days)
|
|
{
|
|
Law law = Row(ActCategories.Ate, punishment, LawStage.DidIt, days);
|
|
LawCase c = CaseFiler.Open(law, new ActEvent(ActCategories.Ate, ThingDefOf.MealSimple, offender), LawStage.DidIt);
|
|
T.NotNull(c, "CaseFiler.Open");
|
|
return c;
|
|
}
|
|
|
|
/// <summary>A case for the break the offender is in, at the stage, under a new row.</summary>
|
|
public static LawCase BreakCase(Pawn offender, string punishment, LawStage stage, int days)
|
|
{
|
|
T.Check(offender.InMentalState, offender.LabelShort + " is in no break");
|
|
Law law = Row(ActCategories.Break, punishment, stage, days);
|
|
var act = new ActEvent(ActCategories.Break, offender.MentalStateDef, offender) { mentalState = offender.MentalState };
|
|
LawCase c = CaseFiler.Open(law, act, stage);
|
|
T.NotNull(c, "CaseFiler.Open");
|
|
c.breakState = offender.MentalStateDef.defName;
|
|
c.breakStartTick = CaseFiler.BreakStartTick(offender.MentalState);
|
|
T.Check(CaseFiler.StillInBreak(c), "the break case doesn't recognise its own break");
|
|
return c;
|
|
}
|
|
|
|
/// <summary>Queues the stage's punishment and runs the one tick that dispatches it.</summary>
|
|
public static void Dispatch(LawCase c, LawStage stage)
|
|
{
|
|
Enforcement.Enqueue(c, stage);
|
|
Fixtures.Tick(1);
|
|
}
|
|
|
|
/// <summary>Ticks one at a time until done is true, at most maxTicks. Returns done.</summary>
|
|
public static bool RunUntil(Func<bool> done, int maxTicks)
|
|
{
|
|
for (int i = 0; i < maxTicks; i++)
|
|
{
|
|
if (done())
|
|
return true;
|
|
Find.TickManager.DoSingleTick();
|
|
}
|
|
return done();
|
|
}
|
|
|
|
/// <summary>Ticks through the next 2500-tick sentence sweep.</summary>
|
|
public static void TickPastSentenceSweep()
|
|
{
|
|
int ticks = Enforcement.SentenceInterval - Now % Enforcement.SentenceInterval + 1;
|
|
Fixtures.Tick(ticks);
|
|
}
|
|
|
|
// ---- things ----------------------------------------------------------------------
|
|
|
|
/// <summary>
|
|
/// A walled 5x5 room with a door and one prisoner bed, on clear ground near the map center. A closed
|
|
/// door keeps the room's district off the map edge, so a prisoner inside never tries to escape
|
|
/// (JobGiver_PrisonerEscape.cs:28-58).
|
|
/// </summary>
|
|
public static PrisonRoom PrisonCell(bool keep = false)
|
|
{
|
|
Map map = Map;
|
|
const int size = 5;
|
|
IntVec3 anchor = Fixtures.PawnCell();
|
|
District district = anchor.GetDistrict(map);
|
|
// A roof marked to collapse drops on the next map tick (Map.cs:945) and would crush the prisoner.
|
|
bool Clear(IntVec3 c) => c.InBounds(map) && c.Standable(map) && !c.Fogged(map) && c.GetEdifice(map) == null &&
|
|
c.GetFirstItem(map) == null && c.GetFirstPawn(map) == null && c.GetDistrict(map) == district &&
|
|
!c.GetTerrain(map).IsWater && !map.roofCollapseBuffer.IsMarkedToCollapse(c);
|
|
bool Square(IntVec3 o, Func<IntVec3, bool> ok)
|
|
{
|
|
for (int x = -1; x <= size; x++)
|
|
{
|
|
for (int z = -1; z <= size; z++)
|
|
{
|
|
if (!ok(o + new IntVec3(x, 0, z)))
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
// Clear ground first; else a square a player would clear of plants and loose items first (a wild map
|
|
// such as a dense jungle has few 7x7 squares without a tree or a starting item).
|
|
bool Buildable(IntVec3 c) => Fixtures.Buildable(c, map, district) && c.GetFirstPawn(map) == null && !map.roofCollapseBuffer.IsMarkedToCollapse(c);
|
|
if (!CellFinder.TryFindRandomCellNear(anchor, map, 50, o => Square(o, Clear), out IntVec3 origin))
|
|
{
|
|
if (!CellFinder.TryFindRandomCellNear(anchor, map, 50, o => Square(o, Buildable), out origin))
|
|
T.Fail("no clear 7x7 square near the colony for a prison cell; " + GroundStory(anchor, 50, Buildable));
|
|
Fixtures.ClearGround(CellRect.FromLimits(origin.x - 1, origin.z - 1, origin.x + size, origin.z + size).Cells, map);
|
|
}
|
|
|
|
var room = new PrisonRoom();
|
|
CellRect footprint = CellRect.FromLimits(origin.x - 1, origin.z - 1, origin.x + size, origin.z + size);
|
|
if (!keep)
|
|
LeaveNoRoof(footprint, map);
|
|
IntVec3 doorCell = origin + new IntVec3(0, 0, 2);
|
|
for (int x = 0; x < size; x++)
|
|
{
|
|
for (int z = 0; z < size; z++)
|
|
{
|
|
if (x != 0 && x != size - 1 && z != 0 && z != size - 1)
|
|
continue;
|
|
IntVec3 cell = origin + new IntVec3(x, 0, z);
|
|
Thing t = ThingMaker.MakeThing(cell == doorCell ? ThingDefOf.Door : ThingDefOf.Wall, ThingDefOf.WoodLog);
|
|
t.SetFaction(Faction.OfPlayer);
|
|
GenSpawn.Spawn(t, cell, map);
|
|
room.things.Add(t);
|
|
}
|
|
}
|
|
map.regionAndRoomUpdater.TryRebuildDirtyRegionsAndRooms();
|
|
var bed = (Building_Bed)ThingMaker.MakeThing(ThingDefOf.Bed, ThingDefOf.WoodLog);
|
|
bed.SetFaction(Faction.OfPlayer);
|
|
GenSpawn.Spawn(bed, origin + new IntVec3(2, 0, 2), map, Rot4.North);
|
|
bed.ForPrisoners = true;
|
|
room.things.Add(bed);
|
|
room.bed = bed;
|
|
room.inside = origin + new IntVec3(1, 0, 1);
|
|
map.regionAndRoomUpdater.TryRebuildDirtyRegionsAndRooms();
|
|
// The ForPrisoners setter only marks the room's stats dirty (Building_Bed.cs:72, Room.cs:673-676);
|
|
// a room becomes a prison cell in Notify_RoomShapeChanged (Room.cs:686-728), which the bed gizmo
|
|
// calls after it changes the owner type (Building_Bed.cs:466-473).
|
|
bed.GetDistrict()?.Notify_RoomShapeOrContainedBedsChanged();
|
|
bed.GetRoom()?.Notify_RoomShapeChanged();
|
|
foreach (Thing t in room.things)
|
|
{
|
|
if (keep)
|
|
Fixtures.Keep(t);
|
|
else
|
|
Fixtures.Track(t);
|
|
}
|
|
T.Check(bed.GetRoom()?.IsPrisonCell == true, "the prison cell fixture is no prison cell");
|
|
return room;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Puts the roof and the build-roof area over the cells back as they are now when the test ends, before the
|
|
/// fixture walls go. A walled player room gets an auto build-roof area (Room.cs:699-701,
|
|
/// AutoBuildRoofAreaSetter.cs:43ff) and colonists roof it; once the walls vanish the roof is marked to
|
|
/// collapse (Building.cs:206-214, RoofCollapseCellsFinder.cs:19-41) and drops on the next test's pawns.
|
|
/// </summary>
|
|
private static void LeaveNoRoof(CellRect rect, Map map)
|
|
{
|
|
var before = rect.Cells.Where(c => c.InBounds(map))
|
|
.Select(c => (cell: c, roof: map.roofGrid.RoofAt(c), area: map.areaManager.BuildRoof[c])).ToList();
|
|
Fixtures.OnCleanup(() =>
|
|
{
|
|
if (map.Disposed)
|
|
return;
|
|
int roofs = 0;
|
|
foreach (var (cell, roof, area) in before)
|
|
{
|
|
if (map.areaManager.BuildRoof[cell] != area)
|
|
map.areaManager.BuildRoof[cell] = area;
|
|
if (map.roofGrid.RoofAt(cell) != roof)
|
|
{
|
|
map.roofGrid.SetRoof(cell, roof);
|
|
roofs++;
|
|
}
|
|
}
|
|
if (roofs > 0)
|
|
TestRunner.Note("removed " + roofs + " roof cells colonists built over the prison cell fixture");
|
|
});
|
|
}
|
|
|
|
/// <summary>Why the cells around the anchor refuse a fixture building: counts by the first reason, for a failure message.</summary>
|
|
public static string GroundStory(IntVec3 anchor, int radius, Func<IntVec3, bool> ok)
|
|
{
|
|
Map map = Map;
|
|
District district = anchor.GetDistrict(map);
|
|
int all = 0, good = 0, fogged = 0, otherDistrict = 0, water = 0, edifice = 0, pawn = 0, other = 0;
|
|
var blockers = new Dictionary<string, int>();
|
|
void Count(string key) => blockers[key] = (blockers.TryGetValue(key, out int n) ? n : 0) + 1;
|
|
foreach (IntVec3 c in GenRadial.RadialCellsAround(anchor, radius, true))
|
|
{
|
|
if (!c.InBounds(map))
|
|
continue;
|
|
all++;
|
|
if (ok(c)) good++;
|
|
else if (c.Fogged(map)) fogged++;
|
|
else if (c.GetDistrict(map) != district) otherDistrict++;
|
|
else if (c.GetTerrain(map).IsWater || c.GetTerrain(map).passability != Traversability.Standable) water++;
|
|
else if (c.GetEdifice(map) is Building b)
|
|
{
|
|
edifice++;
|
|
Count(b.def.defName);
|
|
}
|
|
else if (c.GetFirstPawn(map) != null) pawn++;
|
|
else
|
|
{
|
|
other++;
|
|
foreach (Thing t in c.GetThingList(map))
|
|
Count(t.def.defName);
|
|
}
|
|
}
|
|
return "anchor " + anchor + " in a district of " + (district?.CellCount ?? 0) + " cells (map edge " + (district?.TouchesMapEdge ?? false) +
|
|
"); of " + all + " cells " + good + " fit, fogged " + fogged + ", other district " + otherDistrict + ", water or impassable " + water +
|
|
", building " + edifice + ", pawn " + pawn + ", other " + other + "; blockers " +
|
|
string.Join(", ", blockers.OrderByDescending(kv => kv.Value).Take(8).Select(kv => kv.Key + " " + kv.Value));
|
|
}
|
|
|
|
/// <summary>A colonist bed (or a medical one) near the cell.</summary>
|
|
public static Building_Bed ColonistBed(IntVec3 near, bool medical = false)
|
|
{
|
|
Map map = Map;
|
|
District district = near.GetDistrict(map);
|
|
// Every cell the bed covers is free ground in the same district, so it never stands in a wall or on a pawn.
|
|
bool Fits(IntVec3 c) => c.InHorDistOf(near, 10f) && !c.InHorDistOf(near, 2f) &&
|
|
GenAdj.OccupiedRect(c, Rot4.North, ThingDefOf.Bed.size).Cells.All(x =>
|
|
x.InBounds(map) && x.Standable(map) && !x.Fogged(map) && x.GetEdifice(map) == null &&
|
|
x.GetFirstItem(map) == null && x.GetFirstPawn(map) == null && x.GetDistrict(map) == district);
|
|
if (!CellFinder.TryFindRandomCellNear(near, map, 11, Fits, out IntVec3 cell))
|
|
{
|
|
// A wild map: a spot a player would clear of plants and loose items first.
|
|
bool Buildable(IntVec3 c) => c.InHorDistOf(near, 10f) && !c.InHorDistOf(near, 2f) &&
|
|
GenAdj.OccupiedRect(c, Rot4.North, ThingDefOf.Bed.size).Cells.All(x =>
|
|
Fixtures.Buildable(x, map, district) && x.GetFirstPawn(map) == null);
|
|
if (!CellFinder.TryFindRandomCellNear(near, map, 11, Buildable, out cell))
|
|
T.Fail("no free spot for a bed 2 to 10 cells from " + near + "; " + GroundStory(near, 10, c => Fixtures.Buildable(c, map, district)));
|
|
Fixtures.ClearGround(GenAdj.OccupiedRect(cell, Rot4.North, ThingDefOf.Bed.size).Cells, map);
|
|
}
|
|
var bed = (Building_Bed)ThingMaker.MakeThing(ThingDefOf.Bed, ThingDefOf.WoodLog);
|
|
bed.SetFaction(Faction.OfPlayer);
|
|
GenSpawn.Spawn(bed, cell, Map, Rot4.North);
|
|
if (medical)
|
|
bed.Medical = true;
|
|
Fixtures.Track(bed);
|
|
return bed;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A bed of its own for every other free colonist on the map that has none (the quick test's starting
|
|
/// colonists sleep on the ground), so none of them claims a bed the test frees: a pawn going to sleep
|
|
/// takes its own bed first and an unowned one only without it (RestUtility.cs:294-324). The beds go
|
|
/// after the test, and with them the ownership.
|
|
/// </summary>
|
|
public static void BedsForBystanders(params Pawn[] except)
|
|
{
|
|
foreach (Pawn p in Map.mapPawns.FreeColonistsSpawned.ToList())
|
|
{
|
|
if (except.Contains(p) || p.ownership == null || p.ownership.OwnedBed != null)
|
|
continue;
|
|
Building_Bed bed = ColonistBed(p.Position);
|
|
T.Check(p.ownership.ClaimBedIfNonMedical(bed), "fixture: " + p.LabelShort + " can't claim a bed of its own");
|
|
}
|
|
}
|
|
|
|
// ---- reads -----------------------------------------------------------------------
|
|
|
|
/// <summary>Some pawn on the map runs or has queued a subdue, arrest or capture of the offender.</summary>
|
|
public static bool AnyEnforcementJobOn(Pawn offender)
|
|
{
|
|
foreach (Pawn p in Map.mapPawns.AllPawnsSpawned)
|
|
{
|
|
if (EnforcerJobs.IsEnforcementJob(p.CurJob, offender))
|
|
return true;
|
|
JobQueue q = p.jobs?.jobQueue;
|
|
for (int i = 0; q != null && i < q.Count; i++)
|
|
{
|
|
if (EnforcerJobs.IsEnforcementJob(q[i]?.job, offender))
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// <summary>The pawns on the map whose current job is a subdue, arrest or capture of the offender.</summary>
|
|
public static IEnumerable<Pawn> EnforcersOn(Pawn offender) =>
|
|
Map.mapPawns.AllPawnsSpawned.Where(p => EnforcerJobs.IsEnforcementJob(p.CurJob, offender));
|
|
|
|
public static HashSet<Hediff_Injury> Injuries(Pawn p) => new HashSet<Hediff_Injury>(p.health.hediffSet.hediffs.OfType<Hediff_Injury>());
|
|
|
|
/// <summary>
|
|
/// The part's HP: its maximum minus its injuries, as HediffSet.GetPartHealth counts it (HediffSet.cs:581-605) but
|
|
/// not rounded, since the rounding would hide up to half a point below the subdue's cap.
|
|
/// </summary>
|
|
public static float PartHealth(Pawn p, BodyPartRecord part)
|
|
{
|
|
float hp = part.def.GetMaxHealth(p);
|
|
foreach (Hediff_Injury h in p.health.hediffSet.hediffs.OfType<Hediff_Injury>().Where(h => h.Part == part))
|
|
hp = h.destroysBodyParts ? hp - h.Severity : Math.Max(hp - h.Severity, 1f);
|
|
return hp;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Where a walk or carry stands, for a failure message: the pawn's cell, terrain, snow, move speed, job
|
|
/// and toil, path, and the job's target B (the bed of an arrest) with its distance and reachability.
|
|
/// </summary>
|
|
public static string WalkStory(Pawn p)
|
|
{
|
|
if (p == null)
|
|
return "no pawn";
|
|
if (!p.Spawned)
|
|
return p.LabelShort + " not spawned, held by " + (p.ParentHolder?.ToString() ?? "nothing");
|
|
Map m = p.Map;
|
|
Job j = p.CurJob;
|
|
string s = p.LabelShort + " at " + p.Position + " on " + (p.Position.GetTerrain(m)?.defName ?? "?") +
|
|
", snow " + m.snowGrid.GetDepth(p.Position).ToString("0.00") + ", move speed " + p.GetStatValue(StatDefOf.MoveSpeed).ToString("0.00") +
|
|
", biome " + (m.Biome?.defName ?? "?") + ", job " + (j?.def?.defName ?? "none");
|
|
if (j != null)
|
|
s += " for " + (Now - j.startTick) + " ticks, toil " + (p.jobs?.curDriver?.CurToilIndex ?? -1);
|
|
s += ", moving " + p.pather.Moving + " to " + p.pather.Destination + ", path nodes left " + (p.pather.curPath?.NodesLeftCount ?? -1);
|
|
if (j != null && j.targetB.IsValid)
|
|
{
|
|
IntVec3 b = j.targetB.Cell;
|
|
s += ", target B " + j.targetB + " at " + b + ", distance " + p.Position.DistanceTo(b).ToString("0") + ", reach " + p.CanReach(j.targetB, PathEndMode.OnCell, Danger.Deadly);
|
|
}
|
|
return s;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The threat that keeps a case waiting for the danger, for a failure message: its label, mental state and
|
|
/// whether a fixture made it, or the enemies near the offender.
|
|
/// </summary>
|
|
public static string ThreatStory(Pawn offender)
|
|
{
|
|
Map map = offender?.MapHeld ?? Map;
|
|
if (map != null && GenHostility.AnyHostileActiveThreatTo(map, Faction.OfPlayer, out IAttackTarget t) && t?.Thing != null)
|
|
{
|
|
Pawn p = t.Thing as Pawn;
|
|
return "threat " + t.Thing.LabelShort + " (" + t.Thing.ThingID + ") at " + t.Thing.PositionHeld + ", mental state " + (p?.MentalStateDef?.defName ?? "none") +
|
|
", faction " + (t.Thing.Faction?.Name ?? "none") + ", fixture " + (p != null && Fixtures.IsFixturePawn(p));
|
|
}
|
|
return offender != null && offender.Spawned && PawnUtility.EnemiesAreNearby(offender) ? "enemies near the offender" : "no threat found";
|
|
}
|
|
|
|
/// <summary>
|
|
/// Checks the case waits for the reason. A wait for the danger where another one was expected is a bystander
|
|
/// turning hostile during the test (a berserk pet), not the product: it fails as a fixture error naming the threat.
|
|
/// </summary>
|
|
public static void CheckWait(LawCase c, string expected, string what)
|
|
{
|
|
if (c.waitReason == WaitReasons.Danger && expected != WaitReasons.Danger)
|
|
T.Fail("fixture: a threat came up during the test, so the case waits for the danger instead of " + expected + " (" + what + "); " + ThreatStory(c.offender));
|
|
T.Equal(expected, c.waitReason, what);
|
|
}
|
|
|
|
/// <summary>Why an enforcer is or isn't sent: its job, lord and the checks Enforcers.Pick makes, for a failure message.</summary>
|
|
public static string EnforcerStory(Pawn p, LawCase c)
|
|
{
|
|
if (p == null)
|
|
return "no pawn";
|
|
Pawn o = c?.offender;
|
|
Thing target = p.CurJob?.targetA.Thing;
|
|
return p.LabelShort + ": job " + (p.CurJobDef?.defName ?? "none") + (target != null ? " on " + target.LabelShort + " (" + target.ThingID + ")" : "") +
|
|
(p.CurJob?.playerForced == true ? " (forced)" : "") +
|
|
", queue " + (p.jobs?.jobQueue?.Count ?? 0) + ", lord " + (Verse.AI.Group.LordUtility.GetLord(p)?.LordJob?.GetType().Name ?? "none") +
|
|
", drafted " + p.Drafted + ", awake " + p.Awake() + ", mental " + (p.MentalStateDef?.defName ?? "none") +
|
|
", warden " + Enforcers.IsWarden(p) + ", able " + (o != null && Enforcers.IsAble(p, o, EnforcerNeed.SubdueAndArrest, Fixtures.Settings.enforcers == EnforcerMode.WardensOnly)) +
|
|
", free " + Enforcers.IsFree(p, c) + ", reach " + (o != null && o.Spawned && p.Spawned && p.CanReach(o, PathEndMode.Touch, Danger.Deadly)) +
|
|
", danger " + (o != null && Enforcers.DangerBlocks(o)) + ", enforcer " + (c?.enforcer?.LabelShort ?? "none") +
|
|
", medrest " + HealthAIUtility.ShouldSeekMedicalRest(p) + ", hediffs " +
|
|
string.Join(" ", p.health.hediffSet.hediffs.Where(h => !h.IsPermanent()).Select(h => h.def.defName));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Where a subdue stands, for a message: the case, the hits so far, any other injuries by what made them,
|
|
/// whether the offender is dead and how, the pain, and what both pawns do. A hit is a bruise made with the
|
|
/// enforcer's race as the weapon (SubdueFlow.Hit passes weapon: enforcer.def, which becomes the injury's
|
|
/// sourceDef, DamageWorker_AddInjury.cs:209), so a predator's bites are not counted as subdue hits.
|
|
/// </summary>
|
|
public static string SubdueStory(LawCase c, Pawn offender, HashSet<Hediff_Injury> before)
|
|
{
|
|
List<Hediff_Injury> fresh = NewInjuries(offender, before);
|
|
Pawn e = c.enforcer;
|
|
ThingDef hitter = e?.def ?? ThingDefOf.Human;
|
|
List<Hediff_Injury> hits = fresh.Where(h => h.def == Bruise && h.sourceDef == hitter).ToList();
|
|
List<Hediff_Injury> other = fresh.Where(h => !hits.Contains(h)).ToList();
|
|
string others = other.Count == 0
|
|
? "no other injuries"
|
|
: "other injuries " + other.Sum(h => h.Severity).ToString("0") + " points from " +
|
|
string.Join(", ", other.GroupBy(h => h.sourceLabel.NullOrEmpty() ? "?" : h.sourceLabel).Select(g => g.Key + " " + g.Sum(h => h.Severity).ToString("0")));
|
|
string death = "alive";
|
|
if (offender.Dead)
|
|
{
|
|
DeathLetter letter = Find.LetterStack.LettersListForReading.OfType<DeathLetter>().LastOrDefault(l => l.Label.ToString().Contains(offender.LabelShort));
|
|
string text = letter?.Text.Resolve() ?? "";
|
|
int end = text.IndexOf('\n');
|
|
death = "dead" + (text.NullOrEmpty() ? "" : ", " + (end > 0 ? text.Substring(0, end) : text).Trim());
|
|
}
|
|
return "case " + c + ", wait " + c.waitReason + "; " + hits.Count + " hits (" + hits.Sum(h => h.Severity).ToString("0") + " points); " + others + "; " + death + "; pain " +
|
|
offender.health.hediffSet.PainTotal.ToString("0.00") + " of " + offender.GetStatValue(StatDefOf.PainShockThreshold).ToString("0.00") +
|
|
", room left " + SubdueHits.RoomToLive(offender).ToString("0") + ", drugs " +
|
|
(offender.health.hediffSet.hediffs.Any(h => h is Hediff_High) ? string.Join(" ", offender.health.hediffSet.hediffs.Where(h => h is Hediff_High).Select(h => h.def.defName)) : "none") +
|
|
"; the offender " + (offender.CurJobDef?.defName ?? "idle") +
|
|
(e == null ? ", no enforcer" : "; the enforcer " + e.LabelShort + " " + (e.CurJobDef?.defName ?? "idle") + ", " +
|
|
e.Position.DistanceTo(offender.Position).ToString("0") + " cells off, speed " + e.GetStatValue(StatDefOf.MoveSpeed).ToString("0.0"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// No predator hunts a colonist during the test: the difficulty's "predators hunt humanlikes" off
|
|
/// (RimWorld/FoodUtility.cs:783), restored after, and a hunt on a colonist already running ended. A predator
|
|
/// hunting a colonist is a hostile active threat (GenHostility.cs:311-333), which rightly calls off a subdue
|
|
/// (Enforcers.DangerBlocks), so a chance wolf on the map would otherwise decide a test that ticks a subdue.
|
|
/// </summary>
|
|
public static void NoPredatorsHuntColonists()
|
|
{
|
|
Difficulty d = Find.Storyteller.difficulty;
|
|
bool was = d.predatorsHuntHumanlikes;
|
|
d.predatorsHuntHumanlikes = false;
|
|
Fixtures.OnCleanup(() => d.predatorsHuntHumanlikes = was);
|
|
foreach (Pawn a in Map.mapPawns.AllPawnsSpawned.ToList())
|
|
{
|
|
if (a.CurJobDef == JobDefOf.PredatorHunt && a.CurJob.targetA.Thing is Pawn prey && prey.Faction == Faction.OfPlayer)
|
|
{
|
|
T.Info("ended " + a.LabelShort + "'s hunt on " + prey.LabelShort);
|
|
a.jobs.EndCurrentJob(JobCondition.InterruptForced);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>An injury for a message: def, part, severity and what made it.</summary>
|
|
public static string Describe(Hediff_Injury h) =>
|
|
h.def.defName + " on " + (h.Part?.Label ?? "the whole body") + " " + h.Severity.ToString("0.###") + " from " +
|
|
(h.sourceLabel.NullOrEmpty() ? "?" : h.sourceLabel) + (h.sourceToolLabel.NullOrEmpty() ? "" : " (" + h.sourceToolLabel + ")") +
|
|
(h.IsPermanent() ? ", permanent" : "");
|
|
|
|
public static List<Hediff_Injury> NewInjuries(Pawn p, HashSet<Hediff_Injury> before) =>
|
|
p.health.hediffSet.hediffs.OfType<Hediff_Injury>().Where(h => !before.Contains(h)).ToList();
|
|
|
|
/// <summary>Live letters with exactly this label.</summary>
|
|
public static int LettersLabeled(string label) =>
|
|
Find.LetterStack.LettersListForReading.Count(l => l.Label.ToString() == label);
|
|
|
|
/// <summary>Archived messages containing the text (messages start with a capital letter).</summary>
|
|
public static int MessagesWith(string text) =>
|
|
Find.Archive.ArchivablesListForReading.OfType<Message>().Count(m => m.text != null && m.text.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0);
|
|
|
|
public static Dictionary<WorkTypeDef, int> Priorities(Pawn p) =>
|
|
DefDatabase<WorkTypeDef>.AllDefsListForReading.ToDictionary(w => w, w => p.workSettings.GetPriority(w));
|
|
|
|
/// <summary>
|
|
/// Gives the pawn work priorities no re-initialization reproduces, for a "same work priorities" check, and
|
|
/// returns their snapshot. Manual priorities go on for the test (with them off GetPriority reads 3 for any
|
|
/// value above 0, Pawn_WorkSettings.cs:160-168), and every work type the pawn can do, except keep, is set
|
|
/// to 1, 2, 4 in turn, including types the generator left at 0 (a pawn may have none). EnableAndInitialize, which the generator
|
|
/// and Pawn.SetFaction run (Pawn_WorkSettings.cs:89-124, Pawn.cs:2737-2739), only sets 3 or 0, so a reset
|
|
/// shows on every one of them.
|
|
/// </summary>
|
|
public static Dictionary<WorkTypeDef, int> DistinctPriorities(Pawn p, params WorkTypeDef[] keep)
|
|
{
|
|
PlaySettings play = Find.PlaySettings;
|
|
if (!play.useWorkPriorities)
|
|
{
|
|
// Only when this call turns it on, so a second call in the same test can't restore "on".
|
|
play.useWorkPriorities = true;
|
|
Fixtures.OnCleanup(() => play.useWorkPriorities = false);
|
|
}
|
|
int[] cycle = { 1, 2, 4 };
|
|
int i = 0;
|
|
bool turnedOn = false;
|
|
foreach (WorkTypeDef w in DefDatabase<WorkTypeDef>.AllDefsListForReading)
|
|
{
|
|
if (keep.Contains(w) || p.WorkTypeIsDisabled(w))
|
|
continue;
|
|
if (p.workSettings.GetPriority(w) == 0)
|
|
turnedOn = true;
|
|
p.workSettings.SetPriority(w, cycle[i++ % cycle.Length]);
|
|
}
|
|
if (!turnedOn)
|
|
T.Info(p.LabelShort + " had every work type it can do on already; 1, 2 and 4 still differ from the 3 a reset sets");
|
|
return Priorities(p);
|
|
}
|
|
|
|
public static string PriorityDiff(Dictionary<WorkTypeDef, int> before, Pawn p)
|
|
{
|
|
var diff = before.Where(kv => p.workSettings.GetPriority(kv.Key) != kv.Value)
|
|
.Select(kv => kv.Key.defName + " " + kv.Value + " to " + p.workSettings.GetPriority(kv.Key)).ToList();
|
|
return diff.Count == 0 ? null : string.Join(", ", diff);
|
|
}
|
|
|
|
/// <summary>Runs the body while the pawn's current job reads as the given one, for the enforcer filter. No tick passes.</summary>
|
|
public static void WithCurJob(Pawn p, Job job, Action body)
|
|
{
|
|
Job old = p.jobs.curJob;
|
|
p.jobs.curJob = job;
|
|
try
|
|
{
|
|
body();
|
|
}
|
|
finally
|
|
{
|
|
p.jobs.curJob = old;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// A jail case whose enforcer has just made the capture: the case set up as an Arrest leaves it, then
|
|
/// the vanilla CapturedBy, so hook K starts the sentence. No tick passes.
|
|
/// </summary>
|
|
public static LawCase JailDirect(Pawn offender, Pawn enforcer, int days)
|
|
{
|
|
LawCase c = ActCase(offender, "Jail", days);
|
|
c.MarkPunished(LawStage.DidIt);
|
|
c.activePunishment = "Jail";
|
|
c.activeStage = LawStage.DidIt;
|
|
c.enforcer = enforcer;
|
|
c.status = CaseStatus.Enforcing;
|
|
offender.guest.CapturedBy(Faction.OfPlayer, enforcer);
|
|
T.Check(offender.IsPrisonerOfColony, "CapturedBy left " + offender.LabelShort + " free");
|
|
T.Equal(CaseStatus.Jailed, c.status, "status after the capture (hook K)");
|
|
return c;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// "Enforcement and cases", "Warn and guilty" and "Subdue": the enforcer pick, danger and reservation
|
|
/// waits, the hand-over between stages, "Enforce laws" off, a berserk jail, guilt, and the subdue job
|
|
/// with its save rule.
|
|
/// </summary>
|
|
public static class EnforcementTests
|
|
{
|
|
// ---- Enforcement and cases -------------------------------------------------------
|
|
|
|
[BlaxTest("enforcement: a warden tending, beating a fire, carrying a downed colonist or doing surgery is never picked; the next one is")]
|
|
public static void BusyWardensSkipped()
|
|
{
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
Pawn busy = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 1f, 3f));
|
|
Pawn next = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 6f, 12f));
|
|
LawCase c = EnforceFixtures.ActCase(offender, "Jail", 3);
|
|
var candidates = new List<Pawn> { busy, next };
|
|
|
|
T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out _) == busy, "with both free, the nearer warden isn't picked");
|
|
|
|
foreach (JobDef def in new[] { JobDefOf.TendPatient, JobDefOf.BeatFire })
|
|
{
|
|
EnforceFixtures.WithCurJob(busy, JobMaker.MakeJob(def, offender), () =>
|
|
T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out _) == next, "a warden doing " + def.defName + " was picked"));
|
|
}
|
|
RecipeDef surgery = DefDatabase<RecipeDef>.AllDefsListForReading.FirstOrDefault(r => r.IsSurgery);
|
|
T.NotNull(surgery, "a surgery recipe");
|
|
Job doBill = JobMaker.MakeJob(JobDefOf.DoBill, offender);
|
|
doBill.bill = new Bill_Medical(surgery, null);
|
|
EnforceFixtures.WithCurJob(busy, doBill, () =>
|
|
T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out _) == next, "a warden doing surgery was picked"));
|
|
|
|
Pawn downed = EnforceFixtures.Offender(EnforceFixtures.CellNear(busy.Position, 1f, 3f));
|
|
HealthUtility.DamageUntilDowned(downed, allowBleedingWounds: false);
|
|
T.Check(downed.Downed, "fixture: the colonist to carry isn't downed");
|
|
downed.DeSpawn();
|
|
T.Check(busy.carryTracker.TryStartCarry(downed), "fixture: the warden can't carry the downed colonist");
|
|
Fixtures.OnCleanup(() =>
|
|
{
|
|
if (busy.carryTracker.CarriedThing != null)
|
|
busy.carryTracker.TryDropCarriedThing(busy.Position, ThingPlaceMode.Near, out Thing _);
|
|
});
|
|
T.Check(busy.IsCarryingPawn(downed), "fixture: the warden isn't carrying the colonist");
|
|
T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out _) == next, "a warden carrying a downed colonist was picked");
|
|
busy.carryTracker.TryDropCarriedThing(busy.Position, ThingPlaceMode.Near, out Thing _);
|
|
T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out _) == busy, "after the drop the nearer warden isn't picked again");
|
|
|
|
Settings.enforcers = EnforcerMode.WardensOnly;
|
|
next.workSettings.SetPriority(WorkTypeDefOf.Warden, 0);
|
|
busy.workSettings.SetPriority(WorkTypeDefOf.Warden, 0);
|
|
T.Check(Enforcers.PickFrom(c, EnforcerNeed.Arrest, candidates, out string reason) == null, "'Wardens only' picked a pawn without Warden work");
|
|
T.Equal(WaitReasons.NoEnforcer, reason, "wait reason with nobody able");
|
|
}
|
|
|
|
[BlaxTest("enforcement: during a raid a binge case waits and nobody is sent; after the raid the sweep enforces it")]
|
|
public static void RaidBlocks()
|
|
{
|
|
// No drug to binge on and no social fight: either could down the binger or end its break during the
|
|
// wait, which would close the case for a reason this test isn't about.
|
|
DetectionKit.ClearDrugsOnMap();
|
|
DetectionKit.QuietSocialFights();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 6f));
|
|
EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge);
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3);
|
|
Pawn raider = EnforceFixtures.Raider();
|
|
EnforceFixtures.Dispatch(c, LawStage.Planning);
|
|
T.Equal(CaseStatus.Open, c.status, "status during the raid");
|
|
T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid");
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "someone was sent during the raid");
|
|
raider.Destroy(DestroyMode.Vanish);
|
|
bool sent = EnforceFixtures.RunUntil(() => SubdueFlow.Runs(c), Enforcement.SweepInterval + 5);
|
|
T.Check(sent, "no subdue within a sweep after the raid; status " + c.status + ", wait " + c.waitReason);
|
|
}
|
|
|
|
[BlaxTest("enforcement: a raid that lands while a subdue runs calls the warden off and the case waits for the danger; after the raid the sweep subdues again")]
|
|
public static void RaidCallsOffSubdue()
|
|
{
|
|
// No drug to binge on and no social fight: either could down the binger or end its break during the
|
|
// wait, which would close the case for a reason this test isn't about.
|
|
DetectionKit.ClearDrugsOnMap();
|
|
DetectionKit.QuietSocialFights();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 6f));
|
|
EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge);
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3);
|
|
EnforceFixtures.Dispatch(c, LawStage.Planning);
|
|
T.Check(SubdueFlow.Runs(c), "fixture: no subdue before the raid; wait " + c.waitReason);
|
|
Pawn raider = EnforceFixtures.Raider();
|
|
// The worker's sweep directly, so the warden can't down the binger between the raid and the check.
|
|
BlaxLawsDefOf.Subdue.Worker.Sweep(c);
|
|
T.Check(!SubdueFlow.Runs(c), "the subdue still runs during the raid");
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "an enforcement job on the offender during the raid");
|
|
T.Check(!c.IsClosed, "the case closed: " + c);
|
|
T.Equal(CaseStatus.Open, c.status, "status during the raid");
|
|
T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid");
|
|
raider.Destroy(DestroyMode.Vanish);
|
|
T.Check(EnforceFixtures.RunUntil(() => SubdueFlow.Runs(c), Enforcement.SweepInterval + 5),
|
|
"no subdue within a sweep after the raid; case " + c + ", wait " + c.waitReason + ", offender " + (offender.MentalStateDef?.defName ?? "no break") + (offender.Downed ? ", downed" : ""));
|
|
}
|
|
|
|
[BlaxTest("enforcement: a raid that lands while the beating of 'Subdue then jail' runs calls the warden off and the case waits for the danger")]
|
|
public static void RaidCallsOffSubdueThenJail()
|
|
{
|
|
EnforceFixtures.PrisonCell();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 6f));
|
|
EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge);
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "SubdueThenJail", LawStage.DidIt, 3);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Check(SubdueFlow.Runs(c), "fixture: no subdue before the raid; wait " + c.waitReason);
|
|
EnforceFixtures.Raider();
|
|
BlaxLawsDefOf.SubdueThenJail.Worker.Sweep(c);
|
|
T.Check(!SubdueFlow.Runs(c), "the subdue still runs during the raid");
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "an enforcement job on the offender during the raid");
|
|
T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid");
|
|
T.Check(!offender.IsPrisonerOfColony, "jailed during the raid");
|
|
}
|
|
|
|
/// <summary>After a raid lands and the jail sweep runs: the capture is called off and the case waits for the danger.</summary>
|
|
private static void CheckCaptureCalledOff(LawCase c, Pawn warden, Pawn offender)
|
|
{
|
|
T.Check(!JailFlow.ArrestRuns(c), "the capture still runs or waits in the queue during the raid");
|
|
T.Check(!CaptureBy(warden, offender), "a capture of the offender on the warden during the raid: " + (warden.CurJobDef?.defName ?? "no job"));
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "an enforcement job on the offender during the raid");
|
|
T.Check(!warden.IsCarryingPawn(offender), "the warden carries the offender during the raid");
|
|
T.Check(!c.IsClosed, "the case closed: " + c);
|
|
T.Equal(CaseStatus.Open, c.status, "status during the raid");
|
|
T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid");
|
|
T.Check(!offender.IsPrisonerOfColony, "jailed during the raid");
|
|
}
|
|
|
|
[BlaxTest("enforcement: a raid that lands while 'Subdue then jail' has its capture queued after the downing hit calls the capture off and the case waits for the danger")]
|
|
public static void RaidCallsOffQueuedCapture()
|
|
{
|
|
EnforceFixtures.PrisonCell();
|
|
DetectionKit.QuietSocialFights();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f));
|
|
EnforceFixtures.OnlyWardens(warden);
|
|
EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge);
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "SubdueThenJail", LawStage.DidIt, 3);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Check(SubdueFlow.Runs(c) && c.enforcer == warden, "fixture: no subdue; enforcer " + c.enforcer?.LabelShort + ", wait " + c.waitReason);
|
|
DownByHits(warden, offender);
|
|
// As the driver does it: OnDowned inside the toil queues the capture, then the subdue job ends.
|
|
InvokeSubdueFlow("OnDowned", c, warden);
|
|
SubdueFlow.End(c);
|
|
T.Equal("Jail", c.activePunishment, "fixture: the running punishment after the downing");
|
|
T.Check(EnforcerJobs.Queued(warden, JobDefOf.Capture, offender) && !warden.IsCarryingPawn(offender),
|
|
"fixture: no queued capture before the raid: " + (warden.CurJobDef?.defName ?? "no job") + ", wait " + c.waitReason);
|
|
Pawn raider = EnforceFixtures.Raider();
|
|
BlaxLawsDefOf.Jail.Worker.Sweep(c);
|
|
CheckCaptureCalledOff(c, warden, offender);
|
|
raider.Destroy(DestroyMode.Vanish);
|
|
}
|
|
|
|
[BlaxTest("enforcement: a raid that lands while the warden walks to capture a downed offender for a jail row calls the capture off and the case waits for the danger")]
|
|
public static void RaidCallsOffRunningCapture()
|
|
{
|
|
EnforceFixtures.PrisonCell();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 10f, 18f));
|
|
EnforceFixtures.OnlyWardens(warden);
|
|
HealthUtility.DamageUntilDowned(offender, allowBleedingWounds: false);
|
|
T.Check(offender.Downed, "fixture: the offender isn't downed");
|
|
LawCase c = EnforceFixtures.ActCase(offender, "Jail", 3);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Check(EnforcerJobs.Runs(warden, JobDefOf.Capture, offender) && !warden.IsCarryingPawn(offender),
|
|
"fixture: the warden isn't on its way to capture the offender: " + (warden.CurJobDef?.defName ?? "no job") + ", wait " + c.waitReason);
|
|
Pawn raider = EnforceFixtures.Raider();
|
|
BlaxLawsDefOf.Jail.Worker.Sweep(c);
|
|
CheckCaptureCalledOff(c, warden, offender);
|
|
raider.Destroy(DestroyMode.Vanish);
|
|
}
|
|
|
|
[BlaxTest("enforcement: a downed offender a doctor reserved gets no capture and no reservation error; the sweep captures it once the reservation is gone")]
|
|
public static void ReservedOffenderWaits()
|
|
{
|
|
EnforceFixtures.PrisonCell();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 6f));
|
|
Pawn doctor = EnforceFixtures.Offender(EnforceFixtures.CellNear(offender.Position, 1f, 3f));
|
|
HealthUtility.DamageUntilDowned(offender, allowBleedingWounds: false);
|
|
T.Check(offender.Downed, "fixture: the offender isn't downed");
|
|
Job hold = JobMaker.MakeJob(JobDefOf.Wait);
|
|
hold.expiryInterval = 20000;
|
|
hold.playerForced = true;
|
|
doctor.jobs.StartJob(hold, JobCondition.InterruptForced);
|
|
T.Check(doctor.Reserve(offender, doctor.CurJob, errorOnFailed: false), "fixture: the doctor can't reserve the offender");
|
|
|
|
LawCase c = EnforceFixtures.ActCase(offender, "Jail", 3);
|
|
var logBefore = new HashSet<LogMessage>(Log.Messages);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Equal(WaitReasons.Reserved, c.waitReason, "wait reason while the doctor holds the offender");
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "a capture started on a reserved offender");
|
|
var logged = Log.Messages.Where(m => !logBefore.Contains(m) && (m.type == LogMessageType.Warning || m.type == LogMessageType.Error)).ToList();
|
|
T.Check(logged.Count == 0, "logged on a reserved offender: " + string.Join(" | ", logged.Take(3).Select(m => m.text)));
|
|
|
|
doctor.jobs.EndCurrentJob(JobCondition.InterruptForced);
|
|
bool captured = EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || offender.IsPrisonerOfColony, EnforceFixtures.SubdueTicks);
|
|
T.Check(captured, "no capture after the reservation was released; status " + c.status + ", wait " + c.waitReason);
|
|
}
|
|
|
|
[BlaxTest("enforcement: hand-over: a binger beside its drug under the starter rows meets one enforcer, ends a prisoner never in a medical bed, with one did-it outcome")]
|
|
public static void HandOver()
|
|
{
|
|
T.Check(ActCatalogue.Get(ActKey.OfGroup(ActCategories.Break, ActGroups.AnyDrugBinge)) != null,
|
|
"the catalogue has no 'any drug binge' entry: the hand-over needs the catalogue and detection packages");
|
|
EnforceFixtures.PrisonCell();
|
|
DetectionKit.ClearDrugsOnMap();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
// The warden is sent at the binge's start from far off, so the binger reaches its drug first: a dose
|
|
// beside the drug takes it about 150 ticks (the walk, CarryIngestibleToChewSpot and 100 ticks of
|
|
// chewing, JobDriver_Ingest.cs:140-167; WakeUp's baseIngestTicks, Defs/Drugs/DrugBases.xml), the
|
|
// warden 40 cells off over 400. A warden that gets there first wins every time: each hit re-thinks
|
|
// the binger's job (at most every 180 ticks, Pawn_JobTracker.cs:974-990), and with the drug in its
|
|
// hands the binge finds no drug on the map (JobGiver_BingeDrug.cs:83) and wanders off, dropping it.
|
|
// That path, the subdue before any dose, is the subdue tests'.
|
|
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 40f, 60f));
|
|
// A second warden beside the binger, drafted until the first is on its way: a did-it arrest that picked
|
|
// its enforcer anew instead of handing over would take this one.
|
|
Pawn near = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f));
|
|
near.drafter.Drafted = true;
|
|
EnforceFixtures.OnlyWardens(warden, near);
|
|
EnforceFixtures.ColonistBed(offender.Position, medical: true);
|
|
Lawbook.AddStarter();
|
|
T.NotNull(Lawbook.Find(ActKey.OfGroup(ActCategories.Break, ActGroups.AnyDrugBinge), DrugOptions.Any, LawStage.DidIt), "starter row 'any drug binge, did it'");
|
|
ThingDef wakeUp = DefDatabase<ThingDef>.GetNamed("WakeUp");
|
|
DetectionKit.NoOverdose(wakeUp);
|
|
IntVec3 drugCell = EnforceFixtures.CellNear(offender.Position, 1f, 1.9f);
|
|
Thing drug = Fixtures.Track(GenSpawn.Spawn(ThingMaker.MakeThing(wakeUp), drugCell, EnforceFixtures.Map));
|
|
|
|
EnforceFixtures.ForceBreak(offender, DefDatabase<MentalStateDef>.GetNamed("Binging_DrugExtreme"));
|
|
((MentalState_BingingDrug)offender.MentalState).chemical = wakeUp.GetCompProperties<CompProperties_Drug>().chemical;
|
|
LawCase c = Fixtures.Comp.CasesOf(offender).LastOrDefault(x => x.IsBreakCase && !x.IsClosed);
|
|
T.NotNull(c, "the binge opened no planning case");
|
|
|
|
var enforcers = new HashSet<Pawn>();
|
|
var timeline = new List<string>();
|
|
bool everColonistBed = false;
|
|
int start = EnforceFixtures.Now;
|
|
HashSet<Hediff_Injury> injuriesBefore = EnforceFixtures.Injuries(offender);
|
|
bool hit = false, dosed = false, handOver = false;
|
|
string lastJob = null, arrest = null;
|
|
bool jailed = EnforceFixtures.RunUntil(() =>
|
|
{
|
|
int at = EnforceFixtures.Now - start;
|
|
if (near.Drafted && SubdueFlow.Runs(c))
|
|
near.drafter.Drafted = false;
|
|
if (!hit && EnforceFixtures.NewInjuries(offender, injuriesBefore).Count > 0)
|
|
{
|
|
hit = true;
|
|
timeline.Add("[hit at " + at + "]");
|
|
}
|
|
if (!dosed && c.stage == LawStage.DidIt)
|
|
{
|
|
// The dose filed in the last tick; Enforcement hands over in the next one.
|
|
dosed = true;
|
|
handOver = SubdueFlow.Runs(c) && c.enforcer == warden && !hit;
|
|
timeline.Add("[dose at " + at + ", warden " + (int)warden.Position.DistanceTo(offender.Position) + " cells off; " + EnforceFixtures.EnforcerStory(warden, c) + "]");
|
|
}
|
|
if (dosed && arrest == null && c.activePunishment == "Jail")
|
|
arrest = "the arrest went to " + (c.enforcer?.LabelShort ?? "nobody") + " (wait " + c.waitReason + "), the warden sent to subdue was on " + (warden.CurJobDef?.defName ?? "no job") + " at " + at;
|
|
string job = offender.CurJobDef?.defName ?? "none";
|
|
if (job != lastJob)
|
|
{
|
|
lastJob = job;
|
|
timeline.Add(job + "@" + at);
|
|
}
|
|
foreach (Pawn p in EnforceFixtures.EnforcersOn(offender))
|
|
enforcers.Add(p);
|
|
if (offender.InBed() && !offender.CurrentBed().ForPrisoners)
|
|
everColonistBed = true;
|
|
return offender.IsPrisonerOfColony && c.status == CaseStatus.Jailed;
|
|
}, 4000);
|
|
string story = "case " + c + ", wait " + c.waitReason + "; at the end " + EnforceFixtures.EnforcerStory(warden, c) + "; the binger's jobs " + string.Join(" > ", timeline) +
|
|
", wake-up left " + (drug.Destroyed ? 0 : drug.stackCount) + ", mental state " + (offender.MentalStateDef?.defName ?? "none");
|
|
T.Check(handOver, "fixture: the binger didn't dose while the warden was on its way to subdue it; " + story);
|
|
T.Check(jailed, "the binger isn't jailed; " + story);
|
|
T.Equal(1, enforcers.Count, "pawns that enforced (" + string.Join(", ", enforcers.Select(p => p.LabelShort)) + "); " + arrest);
|
|
T.Check(enforcers.Contains(warden), "the warden sent to subdue didn't make the arrest; " + arrest);
|
|
T.Check(!everColonistBed, "the binger lay in a colonist or medical bed");
|
|
int didIt = Fixtures.Comp.CasesOf(offender).Count(x => x.stage == LawStage.DidIt);
|
|
T.Equal(1, didIt, "did-it cases of the binger");
|
|
T.Equal(LawStage.DidIt, c.stage, "the binge case's stage");
|
|
}
|
|
|
|
[BlaxTest("enforcement: hand-over: the did-it arrest goes to the warden whose subdue it ends, even with a player order waiting in that warden's queue")]
|
|
public static void HandOverKeepsEnforcer()
|
|
{
|
|
EnforceFixtures.PrisonCell();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 20f, 30f));
|
|
Pawn near = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f));
|
|
near.drafter.Drafted = true;
|
|
EnforceFixtures.OnlyWardens(warden, near);
|
|
EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge);
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3);
|
|
EnforceFixtures.Dispatch(c, LawStage.Planning);
|
|
T.Check(SubdueFlow.Runs(c) && c.enforcer == warden, "fixture: the far warden isn't on the subdue; enforcer " + c.enforcer?.LabelShort);
|
|
near.drafter.Drafted = false;
|
|
// Ending the subdue would let the think tree hand the warden its next job at once, and a queued job
|
|
// comes first (ThinkNode_QueuedJob.cs:29-31): here a player order, which Laws never pulls a pawn off.
|
|
Job order = JobMaker.MakeJob(JobDefOf.Wait, 600);
|
|
order.playerForced = true;
|
|
warden.jobs.jobQueue.EnqueueLast(order);
|
|
|
|
// The dose, as CaseFiler.Report files it during a binge.
|
|
c.SetLaw(LawStage.DidIt, EnforceFixtures.Row(ActCategories.Break, "Jail", LawStage.DidIt, 3));
|
|
c.stage = LawStage.DidIt;
|
|
c.count = 1;
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Check(JailFlow.ArrestRuns(c), "no arrest after the hand-over; wait " + c.waitReason + ", the warden on " + (warden.CurJobDef?.defName ?? "no job"));
|
|
T.Check(c.enforcer == warden, "the arrest went to " + c.enforcer?.LabelShort + ", not to the warden whose subdue it ended");
|
|
T.Check(!EnforcerJobs.Runs(near, JobDefOf.Arrest, offender), "the warden beside the binger makes the arrest");
|
|
}
|
|
|
|
// A did-it Jail filed while the planning subdue runs, queued just before the subdue would close the case.
|
|
|
|
/// <summary>A binger under a planning Subdue row with the only warden on the subdue. With alignToSweep the subdue starts on the tick before the one before a sweep.</summary>
|
|
private static LawCase SubdueRunning(out Pawn offender, out Pawn warden, bool alignToSweep = false)
|
|
{
|
|
EnforceFixtures.PrisonCell();
|
|
DetectionKit.QuietSocialFights();
|
|
offender = EnforceFixtures.Offender();
|
|
warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f));
|
|
EnforceFixtures.OnlyWardens(warden);
|
|
EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge);
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3);
|
|
if (alignToSweep)
|
|
{
|
|
// Dispatch ticks once, so the subdue then starts at SweepInterval - 1 and the next tick sweeps.
|
|
for (int i = 0; i < Enforcement.SweepInterval && EnforceFixtures.Now % Enforcement.SweepInterval != Enforcement.SweepInterval - 2; i++)
|
|
Fixtures.Tick(1);
|
|
}
|
|
EnforceFixtures.Dispatch(c, LawStage.Planning);
|
|
T.Check(SubdueFlow.Runs(c) && c.enforcer == warden, "fixture: no subdue; enforcer " + c.enforcer?.LabelShort + ", wait " + c.waitReason);
|
|
return c;
|
|
}
|
|
|
|
/// <summary>Files the dose as CaseFiler.Report does during a binge, under a did-it Jail row, and queues it.</summary>
|
|
private static void FileDidItJail(LawCase c, int delay)
|
|
{
|
|
c.SetLaw(LawStage.DidIt, EnforceFixtures.Row(ActCategories.Break, "Jail", LawStage.DidIt, 3));
|
|
c.stage = LawStage.DidIt;
|
|
c.count = 1;
|
|
Enforcement.Schedule(c, CaseTask.Punish, LawStage.DidIt, delay); // delay 1 is what CaseFiler.Enqueue uses
|
|
}
|
|
|
|
/// <summary>Downs the offender as JobDriver_Subdue.Hit does, without ticking.</summary>
|
|
private static void DownByHits(Pawn warden, Pawn offender)
|
|
{
|
|
for (int i = 0; i < 60 && !offender.Downed; i++)
|
|
SubdueHits.Hit(warden, offender);
|
|
T.Check(offender.Downed, "fixture: 60 hits didn't down the offender");
|
|
}
|
|
|
|
private static void InvokeSubdueFlow(string method, LawCase c, Pawn warden)
|
|
{
|
|
MethodInfo m = typeof(SubdueFlow).GetMethod(method, BindingFlags.NonPublic | BindingFlags.Static);
|
|
T.NotNull(m, "SubdueFlow." + method);
|
|
m.Invoke(null, new object[] { c, warden });
|
|
}
|
|
|
|
private static bool CaptureBy(Pawn warden, Pawn offender) =>
|
|
EnforcerJobs.Runs(warden, JobDefOf.Capture, offender) || EnforcerJobs.Queued(warden, JobDefOf.Capture, offender);
|
|
|
|
[BlaxTest("enforcement: hand-over: a did-it jail filed in the tick the subdue downs the offender still runs, as a capture")]
|
|
public static void DidItSurvivesDowningHit()
|
|
{
|
|
LawCase c = SubdueRunning(out Pawn offender, out Pawn warden);
|
|
FileDidItJail(c, 1);
|
|
DownByHits(warden, offender);
|
|
InvokeSubdueFlow("OnDowned", c, warden);
|
|
T.Check(!c.IsClosed, "the downing closed the case before the queued did-it: " + c);
|
|
Fixtures.Tick(1);
|
|
T.Check(!c.IsClosed, "the case closed: " + c);
|
|
T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped");
|
|
T.Equal("Jail", c.activePunishment, "the running punishment after the hand-over");
|
|
T.Check(JailFlow.ArrestRuns(c), "no capture after the hand-over; wait " + c.waitReason);
|
|
T.Check(CaptureBy(warden, offender), "the warden doesn't capture the downed offender: " + (warden.CurJobDef?.defName ?? "no job"));
|
|
T.Check(EnforceFixtures.RunUntil(() => offender.IsPrisonerOfColony && c.status == CaseStatus.Jailed, 2500),
|
|
"not jailed within 2500 ticks; case " + c + ", wait " + c.waitReason);
|
|
}
|
|
|
|
[BlaxTest("enforcement: hand-over: a did-it jail filed in the tick the subdue gives up still arrests")]
|
|
public static void DidItSurvivesGaveUp()
|
|
{
|
|
LawCase c = SubdueRunning(out Pawn offender, out Pawn warden);
|
|
FileDidItJail(c, 1);
|
|
// The driver gives up and its job ends.
|
|
SubdueFlow.End(c);
|
|
InvokeSubdueFlow("OnGaveUp", c, warden);
|
|
T.Check(!c.IsClosed, "giving up closed the case before the queued did-it: " + c);
|
|
Fixtures.Tick(1);
|
|
T.Check(!c.IsClosed, "the case closed: " + c);
|
|
T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped");
|
|
T.Equal("Jail", c.activePunishment, "the running punishment after the hand-over");
|
|
T.Check(JailFlow.ArrestRuns(c), "no arrest after the hand-over; wait " + c.waitReason);
|
|
}
|
|
|
|
[BlaxTest("enforcement: hand-over: a subdue sweep in the tick before a queued did-it jail doesn't close the case")]
|
|
public static void DidItSurvivesSubdueSweep()
|
|
{
|
|
LawCase c = SubdueRunning(out Pawn offender, out Pawn warden, alignToSweep: true);
|
|
T.Equal(Enforcement.SweepInterval - 1, EnforceFixtures.Now % Enforcement.SweepInterval, "fixture: the tick before the sweep");
|
|
DownByHits(warden, offender);
|
|
SubdueFlow.End(c); // status stays Enforcing, the job is gone: the sweep's downed branch
|
|
T.Equal(CaseStatus.Enforcing, c.status, "fixture: status after the downing");
|
|
FileDidItJail(c, 2); // the next tick sweeps, the one after drains
|
|
Fixtures.Tick(1);
|
|
T.Check(!c.IsClosed, "the sweep closed the case before the queued did-it: " + c);
|
|
Fixtures.Tick(1);
|
|
T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped");
|
|
T.Equal("Jail", c.activePunishment, "the running punishment after the hand-over");
|
|
T.Check(JailFlow.ArrestRuns(c), "no capture after the hand-over; wait " + c.waitReason);
|
|
T.Check(CaptureBy(warden, offender), "the warden doesn't capture the downed offender: " + (warden.CurJobDef?.defName ?? "no job"));
|
|
}
|
|
|
|
/// <summary>Files the dose as CaseFiler.Report does during a binge, under a did-it row with the punishment, and queues it.</summary>
|
|
private static void FileDidIt(LawCase c, string punishment, int delay)
|
|
{
|
|
c.SetLaw(LawStage.DidIt, EnforceFixtures.Row(ActCategories.Break, punishment, LawStage.DidIt, 3));
|
|
c.stage = LawStage.DidIt;
|
|
c.count = 1;
|
|
Enforcement.Schedule(c, CaseTask.Punish, LawStage.DidIt, delay);
|
|
}
|
|
|
|
private static bool SubdueJobOn(Pawn warden, Pawn offender) =>
|
|
EnforcerJobs.Runs(warden, BlaxLawsDefOf.BlaxLaws_Subdue, offender) || EnforcerJobs.Queued(warden, BlaxLawsDefOf.BlaxLaws_Subdue, offender);
|
|
|
|
[BlaxTest("enforcement: a did-it subdue filed in the tick the planning subdue downs the offender closes the case as subdued with the did-it stage done, no second beating")]
|
|
public static void DidItSubdueOnDowningHit()
|
|
{
|
|
LawCase c = SubdueRunning(out Pawn offender, out Pawn warden);
|
|
FileDidIt(c, "Subdue", 1);
|
|
DownByHits(warden, offender);
|
|
InvokeSubdueFlow("OnDowned", c, warden);
|
|
SubdueFlow.End(c); // the driver's job ends after its only toil
|
|
Fixtures.Tick(1);
|
|
T.Check(c.IsClosed, "the case is open: " + c);
|
|
T.Equal(CaseOutcomes.Subdued, c.outcome, "outcome");
|
|
T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped");
|
|
T.Check(!SubdueJobOn(warden, offender), "a second subdue job on the downed offender");
|
|
}
|
|
|
|
[BlaxTest("enforcement: a did-it subdue filed in the tick the planning subdue gives up closes the case as not subdued and starts no second beating")]
|
|
public static void DidItSubdueOnGaveUp()
|
|
{
|
|
LawCase c = SubdueRunning(out Pawn offender, out Pawn warden);
|
|
FileDidIt(c, "Subdue", 1);
|
|
// As the driver does it: OnGaveUp inside the toil, then the job ends.
|
|
InvokeSubdueFlow("OnGaveUp", c, warden);
|
|
SubdueFlow.End(c);
|
|
Fixtures.Tick(1);
|
|
T.Check(c.IsClosed, "the case is open: " + c);
|
|
T.Equal(EnforcementOutcomes.NotSubdued, c.outcome, "outcome");
|
|
T.Check(!SubdueJobOn(warden, offender), "a second subdue job after the subdue gave up");
|
|
Fixtures.Tick(Enforcement.SweepInterval);
|
|
T.Check(!SubdueJobOn(warden, offender), "a subdue job a sweep after the subdue gave up");
|
|
}
|
|
|
|
[BlaxTest("enforcement: a subdue sweep in the tick before a queued did-it subdue on the downed offender closes the case as subdued with the did-it stage done")]
|
|
public static void DidItSubdueSurvivesSubdueSweep()
|
|
{
|
|
LawCase c = SubdueRunning(out Pawn offender, out Pawn warden, alignToSweep: true);
|
|
T.Equal(Enforcement.SweepInterval - 1, EnforceFixtures.Now % Enforcement.SweepInterval, "fixture: the tick before the sweep");
|
|
DownByHits(warden, offender);
|
|
SubdueFlow.End(c); // status stays Enforcing, the job is gone: the sweep's downed branch
|
|
T.Equal(CaseStatus.Enforcing, c.status, "fixture: status after the downing");
|
|
FileDidIt(c, "Subdue", 2);
|
|
Fixtures.Tick(1);
|
|
T.Check(c.IsClosed, "the case is open after the sweep: " + c);
|
|
T.Equal(CaseOutcomes.Subdued, c.outcome, "outcome");
|
|
T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped");
|
|
T.Check(!SubdueJobOn(warden, offender), "a second subdue job on the downed offender");
|
|
}
|
|
|
|
[BlaxTest("enforcement: a did-it guilty filed in the tick the planning subdue downs the offender still makes it guilty; the case closes as subdued")]
|
|
public static void DidItGuiltyOnDowningHit()
|
|
{
|
|
LawCase c = SubdueRunning(out Pawn offender, out Pawn warden);
|
|
T.Equal(0, offender.guilt.TicksUntilInnocent, "fixture: guilt before the dose");
|
|
FileDidIt(c, "Guilty", 1);
|
|
DownByHits(warden, offender);
|
|
InvokeSubdueFlow("OnDowned", c, warden);
|
|
SubdueFlow.End(c);
|
|
Fixtures.Tick(1);
|
|
T.Check(c.HasPunished(LawStage.DidIt), "the did-it stage was dropped");
|
|
T.Check(offender.guilt.IsGuilty, "the offender isn't guilty after the did-it guilty row");
|
|
Fixtures.Tick(Enforcement.SweepInterval);
|
|
T.Check(c.IsClosed, "the case is open a sweep later: " + c);
|
|
T.Equal(CaseOutcomes.Subdued, c.outcome, "outcome");
|
|
}
|
|
|
|
[BlaxTest("enforcement: with 'Enforce laws' off cases open and close and nothing is enforced")]
|
|
public static void EnforceLawsOff()
|
|
{
|
|
Settings.enforceLaws = false;
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 6f));
|
|
EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge);
|
|
LawCase subdue = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3);
|
|
LawCase jail = EnforceFixtures.ActCase(offender, "Jail", 3);
|
|
Enforcement.Enqueue(subdue, LawStage.Planning);
|
|
Enforcement.Enqueue(jail, LawStage.DidIt);
|
|
Fixtures.Tick(1);
|
|
T.Check(Fixtures.Comp.Cases.Contains(subdue) && Fixtures.Comp.Cases.Contains(jail), "the cases aren't in the store");
|
|
T.Check(subdue.IsClosed && subdue.outcome == CaseOutcomes.NotEnforced, "subdue case: " + subdue);
|
|
T.Check(jail.IsClosed && jail.outcome == CaseOutcomes.NotEnforced, "jail case: " + jail);
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "something was enforced");
|
|
T.Equal(0, offender.guilt.TicksUntilInnocent, "guilt without enforcement");
|
|
}
|
|
|
|
[BlaxTest("enforcement: a berserk pawn under a jail row waits while it rages; after the break a raid still blocks, then it is arrested")]
|
|
public static void BerserkJailWaits()
|
|
{
|
|
EnforceFixtures.PrisonCell();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 10f, 18f));
|
|
EnforceFixtures.ForceBreak(offender, MentalStateDefOf.Berserk);
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "Jail", LawStage.Planning, 3);
|
|
EnforceFixtures.Dispatch(c, LawStage.Planning);
|
|
T.Check(c.status == CaseStatus.Open && (c.waitReason == WaitReasons.HostileBreak || c.waitReason == WaitReasons.Danger),
|
|
"while it rages: " + c.status + ", wait " + c.waitReason);
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "someone was sent at a berserk pawn");
|
|
|
|
Pawn raider = EnforceFixtures.Raider();
|
|
offender.MentalState.RecoverFromState();
|
|
T.Check(!offender.InMentalState, "fixture: the berserk break didn't end");
|
|
Fixtures.Tick(Enforcement.SweepInterval + 2);
|
|
T.Equal(WaitReasons.Danger, c.waitReason, "wait reason after the break with a raider on the map");
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "someone was sent during the raid");
|
|
raider.Destroy(DestroyMode.Vanish);
|
|
bool arrest = EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || offender.IsPrisonerOfColony, Enforcement.SweepInterval + 5);
|
|
T.Check(arrest, "no arrest after the break and the raid; wait " + c.waitReason);
|
|
}
|
|
|
|
[BlaxTest("enforcement: a berserk pawn under a jail row is captured once it is downed")]
|
|
public static void BerserkDownedCaptured()
|
|
{
|
|
EnforceFixtures.PrisonCell();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 10f, 18f));
|
|
EnforceFixtures.ForceBreak(offender, MentalStateDefOf.Berserk);
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "Jail", LawStage.Planning, 3);
|
|
EnforceFixtures.Dispatch(c, LawStage.Planning);
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "someone was sent at a berserk pawn");
|
|
HealthUtility.DamageUntilDowned(offender, allowBleedingWounds: false);
|
|
T.Check(offender.Downed, "fixture: the berserk pawn isn't downed");
|
|
bool captured = EnforceFixtures.RunUntil(() => offender.IsPrisonerOfColony ||
|
|
(c.enforcer != null && EnforcerJobs.Runs(c.enforcer, JobDefOf.Capture, offender)), EnforceFixtures.SubdueTicks);
|
|
T.Check(captured, "the downed berserk pawn wasn't captured; wait " + c.waitReason);
|
|
}
|
|
|
|
// ---- Warn and guilty --------------------------------------------------------------
|
|
|
|
[BlaxTest("guilty: a 3-day row leaves TicksUntilInnocent at 180000; a longer guilt stays")]
|
|
public static void GuiltyDays()
|
|
{
|
|
Pawn p = EnforceFixtures.Offender();
|
|
LawCase c = EnforceFixtures.ActCase(p, "Guilty", 3);
|
|
BlaxLawsDefOf.Guilty.Worker.Start(c, c.LawFor(LawStage.DidIt), LawStage.DidIt);
|
|
T.Equal(180000, p.guilt.TicksUntilInnocent, "ticks until innocent after a 3-day row");
|
|
T.Check(c.IsClosed && c.outcome == CaseOutcomes.Guilty, "the case after guilty: " + c);
|
|
|
|
Pawn q = EnforceFixtures.Offender();
|
|
q.guilt.Notify_Guilty(500000);
|
|
LawCase d = EnforceFixtures.ActCase(q, "Guilty", 3);
|
|
EnforceFixtures.Dispatch(d, LawStage.DidIt);
|
|
T.Check(q.guilt.TicksUntilInnocent > 400000, "a longer guilt was shortened to " + q.guilt.TicksUntilInnocent);
|
|
T.Check(d.IsClosed && d.outcome == CaseOutcomes.Guilty, "the queued case after guilty: " + d);
|
|
}
|
|
|
|
[BlaxTest("warn: a warn row closes the case as warned and touches nothing else")]
|
|
public static void WarnCloses()
|
|
{
|
|
Pawn p = EnforceFixtures.Offender();
|
|
LawCase c = EnforceFixtures.ActCase(p, "Warn", 1);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Check(c.IsClosed && c.outcome == CaseOutcomes.Warned, "the case after warn: " + c);
|
|
T.Equal(0, p.guilt.TicksUntilInnocent, "guilt after a warning");
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(p), "a warning sent an enforcer");
|
|
}
|
|
|
|
[BlaxTest("guilty: a guilty colonist accepts the arrest of a Social 0 arrester")]
|
|
public static void GuiltyAcceptsArrest()
|
|
{
|
|
Pawn p = EnforceFixtures.Offender();
|
|
Pawn arrester = EnforceFixtures.Warden();
|
|
arrester.skills.GetSkill(SkillDefOf.Social).Level = 0;
|
|
LawCase c = EnforceFixtures.ActCase(p, "Guilty", 3);
|
|
BlaxLawsDefOf.Guilty.Worker.Start(c, c.LawFor(LawStage.DidIt), LawStage.DidIt);
|
|
T.Equal(1f, p.GetAcceptArrestChance(arrester), "accept-arrest chance of a guilty colonist");
|
|
}
|
|
|
|
[BlaxTest("guilty: banishing a guilty colonist lists no colony-wide thought; banishing it to die lists its spouse's grief and none colony-wide")]
|
|
public static void GuiltyBanishThoughts()
|
|
{
|
|
Pawn victim = EnforceFixtures.Offender();
|
|
Pawn spouse = EnforceFixtures.Offender();
|
|
victim.relations.AddDirectRelation(PawnRelationDefOf.Spouse, spouse);
|
|
Fixtures.OnCleanup(() =>
|
|
{
|
|
if (victim.relations.DirectRelationExists(PawnRelationDefOf.Spouse, spouse))
|
|
victim.relations.RemoveDirectRelation(PawnRelationDefOf.Spouse, spouse);
|
|
});
|
|
victim.relations.everSeenByPlayer = true;
|
|
var individual = new List<IndividualThoughtToAdd>();
|
|
var all = new List<ThoughtToAddToAll>();
|
|
|
|
// Innocent first: the colony-wide thought exists, so the check below can fail.
|
|
PawnDiedOrDownedThoughtsUtility.GetThoughts(victim, null, PawnDiedOrDownedThoughtsKind.Banished, individual, all);
|
|
T.Check(all.Any(t => t.thoughtDef == ThoughtDefOf.ColonistBanished), "fixture: an innocent banishment gives no ColonistBanished");
|
|
|
|
LawCase c = EnforceFixtures.ActCase(victim, "Guilty", 3);
|
|
BlaxLawsDefOf.Guilty.Worker.Start(c, c.LawFor(LawStage.DidIt), LawStage.DidIt);
|
|
PawnDiedOrDownedThoughtsUtility.GetThoughts(victim, null, PawnDiedOrDownedThoughtsKind.Banished, individual, all);
|
|
T.Check(all.Count == 0, "colony-wide thoughts for banishing a guilty colonist: " + string.Join(", ", all.Select(t => t.thoughtDef.defName)));
|
|
PawnDiedOrDownedThoughtsUtility.GetThoughts(victim, null, PawnDiedOrDownedThoughtsKind.BanishedToDie, individual, all);
|
|
T.Check(all.Count == 0, "colony-wide thoughts for banishing a guilty colonist to die: " + string.Join(", ", all.Select(t => t.thoughtDef.defName)));
|
|
T.Check(individual.Any(t => t.addTo == spouse), "the spouse's grief is missing for banishing to die");
|
|
}
|
|
|
|
// ---- Subdue ---------------------------------------------------------------------
|
|
|
|
/// <summary>A binging offender, a warden beside it, a planning Subdue case queued; runs until downed or the ticks (SubdueTicks by default).</summary>
|
|
private static LawCase SubdueBinge(Pawn offender, out HashSet<Hediff_Injury> before, string punishment = "Subdue", LawStage stage = LawStage.Planning, int ticks = EnforceFixtures.SubdueTicks)
|
|
{
|
|
// Only the subdue hits the offender: no social fight (a fistfight of its own, Pawn_InteractionsTracker.cs:355-370)
|
|
// and no random break of a bystander, and no predator hunts it (a hunt is danger, which calls off the subdue).
|
|
DetectionKit.QuietSocialFights();
|
|
EnforceFixtures.NoPredatorsHuntColonists();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f));
|
|
before = EnforceFixtures.Injuries(offender);
|
|
EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge, causedByMood: true);
|
|
LawCase c = EnforceFixtures.BreakCase(offender, punishment, stage, 3);
|
|
Enforcement.Enqueue(c, stage);
|
|
EnforceFixtures.RunUntil(() => offender.Downed || c.IsClosed, ticks);
|
|
return c;
|
|
}
|
|
|
|
private static void CheckSubdued(Pawn offender, LawCase c, HashSet<Hediff_Injury> before, bool catharsisRemoved)
|
|
{
|
|
T.Check(offender.Downed, "not downed within " + EnforceFixtures.SubdueTicks + " ticks; " + EnforceFixtures.SubdueStory(c, offender, before));
|
|
List<Hediff_Injury> fresh = EnforceFixtures.NewInjuries(offender, before);
|
|
T.Check(fresh.Count > 0, "downed without a hit");
|
|
List<string> notBruises = fresh.Where(h => h.def != EnforceFixtures.Bruise).Select(EnforceFixtures.Describe).ToList();
|
|
T.Check(notBruises.Count == 0, "injuries that aren't bruises: " + string.Join("; ", notBruises));
|
|
List<string> onHead = fresh.Where(h => h.Part == null || SubdueHits.InHeadOrNeck(offender, h.Part)).Select(EnforceFixtures.Describe).ToList();
|
|
T.Check(onHead.Count == 0, "hits on the head or neck: " + string.Join("; ", onHead));
|
|
var low = new List<string>();
|
|
foreach (BodyPartRecord part in fresh.Select(h => h.Part).Distinct())
|
|
{
|
|
float max = part.def.GetMaxHealth(offender);
|
|
float hp = EnforceFixtures.PartHealth(offender, part);
|
|
if (hp < max * 0.5f - 0.001f)
|
|
{
|
|
low.Add(part.Label + " at " + hp.ToString("0.###") + " of " + max + " (" +
|
|
string.Join(", ", offender.health.hediffSet.hediffs.OfType<Hediff_Injury>().Where(h => h.Part == part).Select(EnforceFixtures.Describe)) + ")");
|
|
}
|
|
}
|
|
T.Check(low.Count == 0, low.Count + " hit part(s) below half their HP: " + string.Join("; ", low));
|
|
Thought_Memory catharsis = offender.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.Catharsis);
|
|
if (catharsisRemoved)
|
|
T.Check(catharsis == null, "the subdued pawn has Catharsis");
|
|
else
|
|
T.Check(catharsis != null, "with the setting off the subdued pawn has no Catharsis");
|
|
T.NotNull(c.enforcer, "the case's enforcer");
|
|
T.Check(!c.enforcer.guilt.IsGuilty, "the enforcer is guilty");
|
|
T.Check(offender.mindState.meleeThreat == null, "the offender has a melee threat: " + offender.mindState.meleeThreat);
|
|
T.Check(c.IsClosed && c.outcome == CaseOutcomes.Subdued, "the case after the subdue: " + c);
|
|
}
|
|
|
|
[BlaxTest("subdue: a binge planning case is downed within 2500 ticks with bruises only, every hit part at half its HP or more, no head hit, no catharsis, an innocent enforcer and no melee threat")]
|
|
public static void SubdueDowns()
|
|
{
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
LawCase c = SubdueBinge(offender, out HashSet<Hediff_Injury> before);
|
|
CheckSubdued(offender, c, before, catharsisRemoved: true);
|
|
}
|
|
|
|
[BlaxTest("subdue: with the camera off the map the subdue still downs the binger within 2500 ticks")]
|
|
public static void SubdueOffCamera()
|
|
{
|
|
WorldRenderer renderer = Find.World.renderer;
|
|
WorldRenderMode old = renderer.wantedMode;
|
|
renderer.wantedMode = WorldRenderMode.Planet;
|
|
Fixtures.OnCleanup(() => renderer.wantedMode = old);
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
T.Equal(15, GenTicks.GetCameraUpdateRate(offender), "the pawns' tick interval with the camera off the map");
|
|
LawCase c = SubdueBinge(offender, out HashSet<Hediff_Injury> before);
|
|
CheckSubdued(offender, c, before, catharsisRemoved: true);
|
|
}
|
|
|
|
[BlaxTest("subdue: with 'Subdued pawns lose their catharsis' off the subdued binger keeps its catharsis")]
|
|
public static void SubdueKeepsCatharsis()
|
|
{
|
|
Settings.subdueRemovesCatharsis = false;
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
LawCase c = SubdueBinge(offender, out HashSet<Hediff_Injury> before);
|
|
CheckSubdued(offender, c, before, catharsisRemoved: false);
|
|
}
|
|
|
|
[BlaxTest("subdue: hits until nothing is left to hit keep the pawn alive, its injuries at nine tenths of the lethal sum, every hit part at half its HP or more, for a plain and a Tough colonist and through a race's rounded blunt multiplier")]
|
|
public static void SubdueCapHolds()
|
|
{
|
|
Pawn enforcer = EnforceFixtures.Warden();
|
|
foreach (string variant in new[] { "plain", "Tough", "blunt x1.3", "bionic arms and legs" })
|
|
{
|
|
Pawn target = EnforceFixtures.Offender(EnforceFixtures.CellNear(enforcer.Position, 2f, 12f));
|
|
if (variant == "Tough")
|
|
target.story.traits.GainTrait(new Trait(DefDatabase<TraitDef>.GetNamed("Tough")));
|
|
if (variant == "bionic arms and legs")
|
|
{
|
|
// Only the torso is left to hit, so its own cap ends the beating before the total does.
|
|
foreach (BodyPartRecord shoulder in target.RaceProps.body.GetPartsWithDef(BodyPartDefOf.Shoulder))
|
|
target.health.AddHediff(DefDatabase<HediffDef>.GetNamed("BionicArm"), shoulder);
|
|
foreach (BodyPartRecord leg in target.RaceProps.body.GetPartsWithDef(BodyPartDefOf.Leg))
|
|
target.health.AddHediff(DefDatabase<HediffDef>.GetNamed("BionicLeg"), leg);
|
|
}
|
|
if (variant == "blunt x1.3")
|
|
{
|
|
// Thing.TakeDamage multiplies by the race's factor and rounds to a whole point (Thing.cs:1487-1497).
|
|
ThingDef race = target.def;
|
|
List<DamageMultiplier> old = race.damageMultipliers;
|
|
race.damageMultipliers = new List<DamageMultiplier> { new DamageMultiplier { damageDef = DamageDefOf.Blunt, multiplier = 1.3f } };
|
|
Fixtures.OnCleanup(() => race.damageMultipliers = old);
|
|
}
|
|
HashSet<Hediff_Injury> before = EnforceFixtures.Injuries(target);
|
|
int hits = 0;
|
|
while (hits < 300 && SubdueHits.PickPart(target, out _) != null)
|
|
{
|
|
SubdueHits.Hit(enforcer, target);
|
|
hits++;
|
|
}
|
|
T.Check(!target.Dead, variant + ": the target died after " + hits + " hits");
|
|
T.Check(SubdueHits.PickPart(target, out _) == null, variant + ": parts still had room after " + hits + " hits");
|
|
// Vanilla kills at an injury sum of 150 times the health scale (Pawn_HealthTracker.cs:73, 705-719).
|
|
float sum = target.health.hediffSet.hediffs.OfType<Hediff_Injury>().Sum(h => h.Severity);
|
|
float cap = 150f * target.HealthScale * 0.9f;
|
|
T.Check(sum <= cap + 0.001f, variant + ": injuries add up to " + sum.ToString("0.###") + ", over " + cap.ToString("0.###"));
|
|
List<Hediff_Injury> fresh = EnforceFixtures.NewInjuries(target, before);
|
|
var low = new List<string>();
|
|
foreach (BodyPartRecord part in fresh.Select(h => h.Part).Distinct())
|
|
{
|
|
float max = part.def.GetMaxHealth(target);
|
|
float hp = EnforceFixtures.PartHealth(target, part);
|
|
if (hp < max * 0.5f - 0.001f)
|
|
low.Add(part.Label + " at " + hp.ToString("0.###") + " of " + max);
|
|
}
|
|
T.Check(low.Count == 0, variant + ": " + low.Count + " hit part(s) below half their HP after " + hits + " hits: " + string.Join("; ", low));
|
|
T.Check(fresh.All(h => h.def == EnforceFixtures.Bruise), variant + ": an injury that isn't a bruise");
|
|
}
|
|
}
|
|
|
|
[BlaxTest("subdue: a Tough colonist and one with two bionic arms both go down; the bionic arms take no injury")]
|
|
public static void SubdueToughAndBionic()
|
|
{
|
|
Pawn tough = EnforceFixtures.Offender();
|
|
tough.story.traits.GainTrait(new Trait(DefDatabase<TraitDef>.GetNamed("Tough")));
|
|
T.Check(tough.GetStatValue(StatDefOf.IncomingDamageFactor) < 0.99f, "fixture: Tough doesn't lower the incoming damage");
|
|
LawCase c1 = SubdueBinge(tough, out HashSet<Hediff_Injury> before1);
|
|
T.Check(tough.Downed, "the Tough colonist isn't downed; case " + c1);
|
|
T.Check(EnforceFixtures.NewInjuries(tough, before1).All(h => h.def == EnforceFixtures.Bruise), "the Tough colonist has an injury that isn't a bruise");
|
|
|
|
Pawn bionic = EnforceFixtures.Offender(EnforceFixtures.CellNear(Fixtures.PawnCell(), 0f, 20f));
|
|
HediffDef arm = DefDatabase<HediffDef>.GetNamed("BionicArm");
|
|
foreach (BodyPartRecord shoulder in bionic.RaceProps.body.GetPartsWithDef(BodyPartDefOf.Shoulder))
|
|
bionic.health.AddHediff(arm, shoulder);
|
|
T.Check(bionic.RaceProps.body.GetPartsWithDef(BodyPartDefOf.Shoulder).All(s => bionic.health.hediffSet.HasDirectlyAddedPartFor(s)),
|
|
"fixture: the bionic arms aren't installed");
|
|
// Without the arms only the torso, the legs and the feet are left to hit, each down to half its HP: about 75
|
|
// points of room against the 64 that down a normal adult, so the beating nearly fills them, with capped hits
|
|
// clipped, and takes far more hits than on a pawn with its arms.
|
|
LawCase c2 = SubdueBinge(bionic, out HashSet<Hediff_Injury> before2, ticks: EnforceFixtures.BionicSubdueTicks);
|
|
T.Check(bionic.Downed, "the colonist with bionic arms isn't downed within " + EnforceFixtures.BionicSubdueTicks + " ticks; " + EnforceFixtures.SubdueStory(c2, bionic, before2));
|
|
List<Hediff_Injury> onArms = EnforceFixtures.NewInjuries(bionic, before2)
|
|
.Where(h => h.Part != null && bionic.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(h.Part)).ToList();
|
|
T.Check(onArms.Count == 0, "the bionic arms took injuries: " + string.Join(", ", onArms.Select(h => h.Part.Label)));
|
|
}
|
|
|
|
[BlaxTest("subdue: on a go-juice offender the job ends after three hits without new pain, with one message")]
|
|
public static void SubdueGivesUpOnGoJuice()
|
|
{
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
offender.health.AddHediff(DefDatabase<HediffDef>.GetNamed("GoJuiceHigh"));
|
|
LawCase c = SubdueBinge(offender, out HashSet<Hediff_Injury> before);
|
|
T.Check(c.IsClosed && c.outcome == EnforcementOutcomes.NotSubdued, "the case after the beating: " + c);
|
|
T.Check(!offender.Downed, "the go-juice offender went down");
|
|
T.Equal(3, EnforceFixtures.NewInjuries(offender, before).Count, "hits on the go-juice offender");
|
|
T.NotNull(c.enforcer, "the case's enforcer");
|
|
T.Check(!SubdueFlow.Runs(c), "the subdue job still runs");
|
|
string text = "BlaxLaws_MsgSubdueGaveUp".Translate(offender.LabelShort, c.enforcer.LabelShort);
|
|
T.Equal(1, EnforceFixtures.MessagesWith(text), "messages that the subdue gave up");
|
|
}
|
|
|
|
[BlaxTest("subdue: a child with a subdue row is warned, with a subdue then jail row jailed without a beating (needs Biotech)")]
|
|
public static void SubdueChild()
|
|
{
|
|
Pawn child = EnforceFixtures.Ready(Fixtures.Child());
|
|
EnforceFixtures.PrisonCell();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(child.Position, 2f, 5f));
|
|
HashSet<Hediff_Injury> before = EnforceFixtures.Injuries(child);
|
|
LawCase warn = EnforceFixtures.ActCase(child, "Subdue", 1);
|
|
EnforceFixtures.Dispatch(warn, LawStage.DidIt);
|
|
T.Check(warn.IsClosed && warn.outcome == CaseOutcomes.Warned, "the child's subdue case: " + warn);
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(child), "someone was sent at the child");
|
|
|
|
LawCase jail = EnforceFixtures.ActCase(child, "SubdueThenJail", 3);
|
|
bool everSubdued = false;
|
|
Enforcement.Enqueue(jail, LawStage.DidIt);
|
|
bool jailed = EnforceFixtures.RunUntil(() =>
|
|
{
|
|
if (EnforceFixtures.EnforcersOn(child).Any(p => p.CurJobDef == BlaxLawsDefOf.BlaxLaws_Subdue))
|
|
everSubdued = true;
|
|
return child.IsPrisonerOfColony;
|
|
}, EnforceFixtures.SubdueTicks);
|
|
T.Check(jailed, "the child isn't jailed; case " + jail + ", wait " + jail.waitReason);
|
|
T.Check(!everSubdued, "the child was subdued");
|
|
T.Equal(0, EnforceFixtures.NewInjuries(child, before).Count, "injuries of the child");
|
|
}
|
|
|
|
[BlaxTest("subdue: subdue then jail ends with the pawn a prisoner in a prisoner bed, never in the medical bed a doctor could rescue it to")]
|
|
public static void SubdueThenJail()
|
|
{
|
|
EnforceFixtures.NoPredatorsHuntColonists();
|
|
PrisonRoom room = EnforceFixtures.PrisonCell();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
Pawn doctor = EnforceFixtures.Offender(EnforceFixtures.CellNear(offender.Position, 3f, 8f));
|
|
doctor.workSettings?.EnableAndInitializeIfNotAlreadyInitialized();
|
|
if (!doctor.WorkTypeIsDisabled(WorkTypeDefOf.Doctor))
|
|
doctor.workSettings.SetPriority(WorkTypeDefOf.Doctor, 1);
|
|
EnforceFixtures.ColonistBed(doctor.Position, medical: true);
|
|
HashSet<Hediff_Injury> before = EnforceFixtures.Injuries(offender);
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f));
|
|
EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge);
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "SubdueThenJail", LawStage.DidIt, 3);
|
|
Enforcement.Enqueue(c, LawStage.DidIt);
|
|
bool everColonistBed = false;
|
|
bool jailed = EnforceFixtures.RunUntil(() =>
|
|
{
|
|
if (offender.InBed() && !offender.CurrentBed().ForPrisoners)
|
|
everColonistBed = true;
|
|
return offender.IsPrisonerOfColony && offender.InBed();
|
|
}, EnforceFixtures.SubdueTicks + EnforceFixtures.CarryTicks);
|
|
T.Check(jailed, "not a prisoner in bed; case " + c + ", wait " + c.waitReason + "; " + EnforceFixtures.WalkStory(offender.CarriedBy ?? c.enforcer) + "; offender " + EnforceFixtures.WalkStory(offender));
|
|
T.Check(!everColonistBed, "the pawn lay in a colonist or medical bed");
|
|
T.Check(offender.CurrentBed() == room.bed, "the pawn lies in " + offender.CurrentBed() + ", not the prisoner bed");
|
|
T.Check(EnforceFixtures.NewInjuries(offender, before).Any(h => h.def == EnforceFixtures.Bruise), "jailed without the beating");
|
|
T.Equal(CaseStatus.Jailed, c.status, "the case's status");
|
|
}
|
|
|
|
[BlaxTest("subdue: a forced tantrum goes down and never attacks the enforcer")]
|
|
public static void SubdueTantrum()
|
|
{
|
|
EnforceFixtures.NoPredatorsHuntColonists();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f));
|
|
HashSet<Hediff_Injury> offenderBefore = EnforceFixtures.Injuries(offender);
|
|
EnforceFixtures.ForceBreak(offender, DefDatabase<MentalStateDef>.GetNamed("Tantrum"));
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3);
|
|
var injuriesBefore = Fixtures.Map.mapPawns.FreeColonistsSpawned.ToDictionary(p => p, EnforceFixtures.Injuries);
|
|
Enforcement.Enqueue(c, LawStage.Planning);
|
|
EnforceFixtures.RunUntil(() => offender.Downed || c.IsClosed, EnforceFixtures.MovingSubdueTicks);
|
|
T.Check(offender.Downed, "the tantrum isn't downed; " + EnforceFixtures.SubdueStory(c, offender, offenderBefore));
|
|
T.NotNull(c.enforcer, "the case's enforcer");
|
|
if (injuriesBefore.TryGetValue(c.enforcer, out HashSet<Hediff_Injury> before))
|
|
T.Equal(0, EnforceFixtures.NewInjuries(c.enforcer, before).Count, "injuries of the enforcer");
|
|
}
|
|
|
|
[BlaxTest("subdue: a forced murderous rage goes down; its named victim is never the enforcer, and the enforcer is never attacked")]
|
|
public static void SubdueMurderousRage()
|
|
{
|
|
EnforceFixtures.NoPredatorsHuntColonists();
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
Pawn victim = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 1f, 2f));
|
|
Pawn other = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 4f, 8f));
|
|
EnforceFixtures.ForceBreak(offender, DefDatabase<MentalStateDef>.GetNamed("MurderousRage"), otherPawn: victim);
|
|
((MentalState_MurderousRage)offender.MentalState).target = victim;
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3);
|
|
T.Check(!Enforcers.IsFree(victim, c), "the rage's victim counts as free to enforce");
|
|
HashSet<Hediff_Injury> offenderBefore = EnforceFixtures.Injuries(offender);
|
|
var injuriesBefore = Fixtures.Map.mapPawns.FreeColonistsSpawned.ToDictionary(p => p, EnforceFixtures.Injuries);
|
|
Enforcement.Enqueue(c, LawStage.Planning);
|
|
Pawn firstEnforcer = null;
|
|
EnforceFixtures.RunUntil(() =>
|
|
{
|
|
if (firstEnforcer == null && c.enforcer != null)
|
|
firstEnforcer = c.enforcer;
|
|
return offender.Downed || c.IsClosed;
|
|
}, EnforceFixtures.MovingSubdueTicks);
|
|
T.Check(firstEnforcer != victim && c.enforcer != victim, "the rage's victim was sent");
|
|
T.Check(offender.Downed, "the rage isn't downed; " + EnforceFixtures.SubdueStory(c, offender, offenderBefore));
|
|
if (injuriesBefore.TryGetValue(c.enforcer, out HashSet<Hediff_Injury> before))
|
|
T.Equal(0, EnforceFixtures.NewInjuries(c.enforcer, before).Count, "injuries of the enforcer");
|
|
}
|
|
|
|
// ---- the subdue job never enters a save ---------------------------------------------
|
|
|
|
private const string SubdueSaveKey = "enforce.subdueSave";
|
|
|
|
[BlaxTest("subdue save: two subdues run at the first save, one enforcer vomiting with resumeCurJobAfterwards (setup)")]
|
|
public static void SubdueSaveSetup()
|
|
{
|
|
// The jobs start right before the save, after every phase-1 test, so no other test's ticks end them.
|
|
T.CarryAtSave(SubdueSaveKey, StartSubduesForSave);
|
|
}
|
|
|
|
private static string StartSubduesForSave()
|
|
{
|
|
Pawn o1 = Fixtures.Keep(EnforceFixtures.Offender());
|
|
Pawn w1 = Fixtures.Keep(EnforceFixtures.Warden(EnforceFixtures.CellNear(o1.Position, 2f, 5f)));
|
|
Pawn o2 = Fixtures.Keep(EnforceFixtures.Offender(EnforceFixtures.CellNear(o1.Position, 10f, 20f)));
|
|
Pawn w2 = Fixtures.Keep(EnforceFixtures.Warden(EnforceFixtures.CellNear(o2.Position, 2f, 5f)));
|
|
EnforceFixtures.ForceBreak(o1, EnforceFixtures.DrugBinge);
|
|
EnforceFixtures.ForceBreak(o2, EnforceFixtures.DrugBinge);
|
|
LawCase c1 = StartSubdue(o1, w1, keep: true);
|
|
LawCase c2 = StartSubdue(o2, w2, keep: true);
|
|
bool running1 = SubdueFlow.Runs(c1);
|
|
bool running2 = SubdueFlow.Runs(c2);
|
|
w2.jobs.StartJob(JobMaker.MakeJob(JobDefOf.Vomit), JobCondition.InterruptForced, null, resumeCurJobAfterwards: true);
|
|
bool queued = EnforcerJobs.Queued(w2, BlaxLawsDefOf.BlaxLaws_Subdue, o2);
|
|
return string.Join("|", c1.id, c2.id, w1.ThingID, w2.ThingID, running1, running2, w2.CurJobDef?.defName ?? "none", queued);
|
|
}
|
|
|
|
private static LawCase StartSubdue(Pawn offender, Pawn enforcer, bool keep = false)
|
|
{
|
|
LawCase c = EnforceFixtures.BreakCase(offender, "Subdue", LawStage.Planning, 3);
|
|
if (keep)
|
|
Fixtures.KeepLaw(c.LawFor(LawStage.Planning));
|
|
c.MarkPunished(LawStage.Planning);
|
|
c.activePunishment = "Subdue";
|
|
c.activeStage = LawStage.Planning;
|
|
SubdueFlow.TryStartWith(c, enforcer);
|
|
return c;
|
|
}
|
|
|
|
private const string InPlaceSaveName = "BlaxLawsTestInPlace";
|
|
|
|
[BlaxTest("subdue save: a save in play puts the running subdue, its driver and the queue back at once; the save holds no subdue")]
|
|
public static void SubdueSurvivesSaveInPlay()
|
|
{
|
|
Pawn offender = EnforceFixtures.Offender();
|
|
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f));
|
|
EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge);
|
|
LawCase c = StartSubdue(offender, warden);
|
|
T.Check(SubdueFlow.Runs(c), "the subdue didn't start; case " + c + ", wait " + c.waitReason);
|
|
// Vanilla never queues the subdue (its JobDef isn't suspendable), so the queue backstop is exercised by hand:
|
|
// one subdue entry and one other entry the filter keeps.
|
|
warden.jobs.jobQueue.EnqueueLast(JobMaker.MakeJob(BlaxLawsDefOf.BlaxLaws_Subdue, offender));
|
|
warden.jobs.jobQueue.EnqueueLast(JobMaker.MakeJob(JobDefOf.Wait, 60));
|
|
Job job = warden.CurJob;
|
|
JobDriver driver = warden.jobs.curDriver;
|
|
JobQueue queue = warden.jobs.jobQueue;
|
|
string path = GenFilePaths.FilePathForSavedGame(InPlaceSaveName);
|
|
try
|
|
{
|
|
// The same synchronous full save the autosave makes; it goes to the -DataDir save folder.
|
|
GameDataSaveLoader.SaveGame(InPlaceSaveName);
|
|
T.Check(File.Exists(path), "the in-play save wasn't written");
|
|
T.Check(!File.ReadAllText(path).Contains("BlaxLaws_Subdue"), "the in-play save holds a BlaxLaws_Subdue job");
|
|
T.Check(warden.CurJob == job, "the enforcer's job after the save: " + (warden.CurJobDef?.defName ?? "none"));
|
|
T.Check(warden.jobs.curDriver == driver, "the enforcer's job driver wasn't put back after the save");
|
|
T.Check(ReferenceEquals(warden.jobs.jobQueue, queue), "the enforcer's job queue wasn't put back after the save");
|
|
T.Equal(2, warden.jobs.jobQueue.Count, "queued jobs after the save");
|
|
T.Check(EnforcerJobs.Queued(warden, BlaxLawsDefOf.BlaxLaws_Subdue, offender), "the queued subdue is gone after the save");
|
|
T.Check(SubdueFlow.Runs(c), "the subdue doesn't run right after the save");
|
|
Fixtures.Tick(1);
|
|
T.Check(warden.CurJob == job && warden.jobs.curDriver == driver, "the enforcer lost its subdue one tick after the save: " + (warden.CurJobDef?.defName ?? "none"));
|
|
T.Check(SubdueFlow.Runs(c), "the subdue doesn't run one tick after the save");
|
|
}
|
|
finally
|
|
{
|
|
warden.jobs?.ClearQueuedJobs();
|
|
try
|
|
{
|
|
if (File.Exists(path))
|
|
File.Delete(path);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
}
|
|
}
|
|
}
|
|
|
|
[BlaxTest("subdue save: the save holds no subdue job and no queued one; after the reload the sweep subdues again within 250 ticks", phase: 2)]
|
|
public static void SubdueSaveRoundTrip()
|
|
{
|
|
T.Check(T.Carry.TryGetValue(SubdueSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 save setup did not run");
|
|
string[] parts = carry.Split('|');
|
|
T.Check(parts.Length == 8, "carry: " + carry);
|
|
T.Check(parts[4] == "True" && parts[5] == "True", "the subdues didn't run at the save: " + carry);
|
|
T.Equal("Vomit", parts[6], "the second enforcer's job at the save");
|
|
T.Equal("False", parts[7], "the vomiting enforcer queued its subdue");
|
|
|
|
string xml = File.ReadAllText(GenFilePaths.FilePathForSavedGame(TestRunner.SaveName));
|
|
T.Check(!xml.Contains("BlaxLaws_Subdue"), "the save holds a BlaxLaws_Subdue job");
|
|
|
|
foreach (Pawn p in EnforceFixtures.Map.mapPawns.AllPawnsSpawned)
|
|
{
|
|
JobQueue q = p.jobs?.jobQueue;
|
|
for (int i = 0; q != null && i < q.Count; i++)
|
|
T.Check(q[i]?.job?.def != BlaxLawsDefOf.BlaxLaws_Subdue, p.LabelShort + " has a queued subdue after the reload");
|
|
}
|
|
LawCase c1 = Fixtures.Comp.CaseById(int.Parse(parts[0]));
|
|
T.NotNull(c1, "the first subdue case after the reload");
|
|
T.NotNull(c1.offender, "the first case's offender after the reload");
|
|
bool again = EnforceFixtures.RunUntil(() => SubdueFlow.Runs(c1) || c1.outcome == CaseOutcomes.Subdued, Enforcement.SweepInterval + 5);
|
|
T.Check(again, "no new subdue within a sweep after the reload; case " + c1 + ", wait " + c1.waitReason);
|
|
}
|
|
|
|
[BlaxTest("removal: no pawn runs or queues a Blax Laws job after the component was removed", phase: 3)]
|
|
public static void NoLawsJobsAfterRemoval()
|
|
{
|
|
foreach (Map map in Find.Maps)
|
|
{
|
|
foreach (Pawn p in map.mapPawns.AllPawnsSpawned)
|
|
{
|
|
T.Check(p.CurJobDef?.defName?.StartsWith("BlaxLaws") != true, p.LabelShort + " runs " + p.CurJobDef?.defName);
|
|
JobQueue q = p.jobs?.jobQueue;
|
|
for (int i = 0; q != null && i < q.Count; i++)
|
|
T.Check(q[i]?.job?.def?.defName?.StartsWith("BlaxLaws") != true, p.LabelShort + " has queued " + q[i]?.job?.def?.defName);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static BlaxLawsSettings Settings => Fixtures.Settings;
|
|
}
|
|
}
|