Blax Laws 1.0.0: escapee that dies off the map, gift and map-loss tests, steadier perf test

- A jailed colonist that escapes and then dies off the map closes as
  escaped, not "died in jail", also when the world deletes it first.
- Tests for a prisoner given away by pod and one lost with its map.
- The subdue tests keep predators off colonists: a wild wolf killed a
  subdued binger once, which the test read as subdue damage.
- The performance test takes up to five rounds and decides from the
  spread of its samples, so a busy machine no longer fails it while a
  slow hook still does.
This commit is contained in:
Fabian @ Blax Software 2026-12-03 16:32:47 +01:00
parent 2cc552b31f
commit 198093e715
9 changed files with 261 additions and 21 deletions

Binary file not shown.

Binary file not shown.

View File

@ -59,8 +59,9 @@ namespace BlaxLaws
// WorldPawnGC.cs:20, 28-30) before this check saw it off the map. A save in between nulls the // WorldPawnGC.cs:20, 28-30) before this check saw it off the map. A save in between nulls the
// reference (LawCase.DropGoneReferences), so only the saved note counts. A pawn destroyed in place // reference (LawCase.DropGoneReferences), so only the saved note counts. A pawn destroyed in place
// (another mod, a dev tool) passes to the world too (Pawn.Destroy, Pawn.cs:2349-2397) and the GC may // (another mod, a dev tool) passes to the world too (Pawn.Destroy, Pawn.cs:2349-2397) and the GC may
// discard it just the same, but it never escaped: offender gone. // discard it just the same, but it never escaped: offender gone. A discarded pawn is on no map, so an
if (c.escapedTick >= 0 && (p == null || !p.Dead)) // escapee that died off the map before the GC took it closes as escaped too, as below.
if (c.escapedTick >= 0)
{ {
CloseEscaped(c, comp); CloseEscaped(c, comp);
return; return;
@ -70,6 +71,15 @@ namespace BlaxLaws
} }
if (p.Dead) if (p.Dead)
{ {
// An escapee stays a prisoner of the colony off the map (Pawn.ExitMap clears the guest status only for
// a released prisoner, Pawn.cs:2556-2589) and world pawns keep ticking (WorldPawns.cs:73-101), so it can
// bleed out there before this sweep. A world pawn dies with no corpse (Pawn.cs:2221-2224): the escape
// ended the sentence, and the death came after it. A corpse on a map means it came back and died there.
if (c.escapedTick >= 0 && !p.SpawnedOrAnyParentSpawned)
{
CloseEscaped(c, comp);
return;
}
CaseMessages.Post(c, "BlaxLaws_MsgDiedInJail".Translate(c.OffenderLabel)); CaseMessages.Post(c, "BlaxLaws_MsgDiedInJail".Translate(c.OffenderLabel));
comp.CloseCase(c, EnforcementOutcomes.Died); comp.CloseCase(c, EnforcementOutcomes.Died);
return; return;

View File

@ -51,8 +51,9 @@ namespace BlaxLawsTests
s.enforcers = EnforcerMode.WardensFirst; s.enforcers = EnforcerMode.WardensFirst;
s.caseMessages = true; s.caseMessages = true;
s.subdueRemovesCatharsis = true; s.subdueRemovesCatharsis = true;
// Only the subdue hits the binger (no social fight), and the binge has no drug to reach. // Only the subdue hits the binger (no social fight, no predator), and the binge has no drug to reach.
DetectionKit.QuietSocialFights(); DetectionKit.QuietSocialFights();
EnforceFixtures.NoPredatorsHuntColonists();
DetectionKit.ClearDrugsOnMap(); DetectionKit.ClearDrugsOnMap();
Pawn offender = EnforceFixtures.Offender(); Pawn offender = EnforceFixtures.Offender();

View File

@ -572,12 +572,32 @@ namespace BlaxLawsTests
string.Join(" ", p.health.hediffSet.hediffs.Where(h => !h.IsPermanent()).Select(h => h.def.defName)); 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, the pain, and what both pawns do.</summary> /// <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) public static string SubdueStory(LawCase c, Pawn offender, HashSet<Hediff_Injury> before)
{ {
List<Hediff_Injury> fresh = NewInjuries(offender, before); List<Hediff_Injury> fresh = NewInjuries(offender, before);
Pawn e = c.enforcer; Pawn e = c.enforcer;
return "case " + c + ", wait " + c.waitReason + "; " + fresh.Count + " hits (" + fresh.Sum(h => h.Severity).ToString("0") + " points), pain " + 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") + offender.health.hediffSet.PainTotal.ToString("0.00") + " of " + offender.GetStatValue(StatDefOf.PainShockThreshold).ToString("0.00") +
", room left " + SubdueHits.RoomToLive(offender).ToString("0") + ", drugs " + ", 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") + (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") +
@ -586,6 +606,28 @@ namespace BlaxLawsTests
e.Position.DistanceTo(offender.Position).ToString("0") + " cells off, speed " + e.GetStatValue(StatDefOf.MoveSpeed).ToString("0.0")); 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> /// <summary>An injury for a message: def, part, severity and what made it.</summary>
public static string Describe(Hediff_Injury h) => public static string Describe(Hediff_Injury h) =>
h.def.defName + " on " + (h.Part?.Label ?? "the whole body") + " " + h.Severity.ToString("0.###") + " from " + h.def.defName + " on " + (h.Part?.Label ?? "the whole body") + " " + h.Severity.ToString("0.###") + " from " +
@ -1311,8 +1353,9 @@ namespace BlaxLawsTests
private static LawCase SubdueBinge(Pawn offender, out HashSet<Hediff_Injury> before, string punishment = "Subdue", LawStage stage = LawStage.Planning, int ticks = EnforceFixtures.SubdueTicks) 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) // 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 random break of a bystander, and no predator hunts it (a hunt is danger, which calls off the subdue).
DetectionKit.QuietSocialFights(); DetectionKit.QuietSocialFights();
EnforceFixtures.NoPredatorsHuntColonists();
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f)); EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f));
before = EnforceFixtures.Injuries(offender); before = EnforceFixtures.Injuries(offender);
EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge, causedByMood: true); EnforceFixtures.ForceBreak(offender, EnforceFixtures.DrugBinge, causedByMood: true);
@ -1506,6 +1549,7 @@ namespace BlaxLawsTests
[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")] [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() public static void SubdueThenJail()
{ {
EnforceFixtures.NoPredatorsHuntColonists();
PrisonRoom room = EnforceFixtures.PrisonCell(); PrisonRoom room = EnforceFixtures.PrisonCell();
Pawn offender = EnforceFixtures.Offender(); Pawn offender = EnforceFixtures.Offender();
Pawn doctor = EnforceFixtures.Offender(EnforceFixtures.CellNear(offender.Position, 3f, 8f)); Pawn doctor = EnforceFixtures.Offender(EnforceFixtures.CellNear(offender.Position, 3f, 8f));
@ -1535,6 +1579,7 @@ namespace BlaxLawsTests
[BlaxTest("subdue: a forced tantrum goes down and never attacks the enforcer")] [BlaxTest("subdue: a forced tantrum goes down and never attacks the enforcer")]
public static void SubdueTantrum() public static void SubdueTantrum()
{ {
EnforceFixtures.NoPredatorsHuntColonists();
Pawn offender = EnforceFixtures.Offender(); Pawn offender = EnforceFixtures.Offender();
EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f)); EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f));
HashSet<Hediff_Injury> offenderBefore = EnforceFixtures.Injuries(offender); HashSet<Hediff_Injury> offenderBefore = EnforceFixtures.Injuries(offender);
@ -1552,6 +1597,7 @@ namespace BlaxLawsTests
[BlaxTest("subdue: a forced murderous rage goes down; its named victim is never the enforcer, and the enforcer is never attacked")] [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() public static void SubdueMurderousRage()
{ {
EnforceFixtures.NoPredatorsHuntColonists();
Pawn offender = EnforceFixtures.Offender(); Pawn offender = EnforceFixtures.Offender();
Pawn victim = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 1f, 2f)); Pawn victim = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 1f, 2f));
Pawn other = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 4f, 8f)); Pawn other = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 4f, 8f));

View File

@ -26,12 +26,17 @@ namespace BlaxLawsTests
/// 250 ticks hold exactly one rare tick, so every block carries the same periodic work. /// 250 ticks hold exactly one rare tick, so every block carries the same periodic work.
/// - A full collection before each block, outside the timing, so garbage of one block isn't paid by the next. /// - A full collection before each block, outside the timing, so garbage of one block isn't paid by the next.
/// - The decision is the time inside Laws' own code (LawsClock: every patch method of Laws and its component /// - The decision is the time inside Laws' own code (LawsClock: every patch method of Laws and its component
/// tick, timed per call) over the rest of the tick, under 2% in one of up to 3 rounds. A round counts only if /// tick, timed per call) over the rest of the tick, under 2% in one of up to 5 rounds. A round counts only if
/// hook C (meals) and the record hooks were timed in it, and every block with Laws timed hook calls, not only /// hook C (meals) and the record hooks were timed in it, and every block with Laws timed hook calls, not only
/// the component tick. The time in patch bodies leaves out Harmony's dispatch into the patched game methods, /// the component tick.
/// so the median of all paired ratios (with / without) so far, minus 1, must also stay under a coarse 10%: /// - The time in patch bodies leaves out Harmony's dispatch into the patched game methods, so the median of all
/// single pairs scatter by 20 to 70% with the game's workload and the desktop, so that median moves a few % /// paired ratios (with / without) so far, minus 1, must also stay under a coarse 10%. Single pairs scatter by 20
/// either way and can't decide a 2% budget, but it catches a gross dispatch cost. /// to 70% on a quiet desktop and by -66% to +334% on a busy one, where the plain median of 10 to 30 pairs moves
/// by 10 to 15%. So the median's one-sided 95% sign-test bounds decide: over 10% when even the lower bound is,
/// under when the upper bound is. While neither holds, rounds are added. Still undecided after the last round,
/// a quiet machine (interquartile range of the pairs under 30%) is judged on the plain median as before, and a
/// busy one ends as a SKIP that carries the numbers: load alone never fails the run, and a real dispatch cost
/// still does.
/// Every round's numbers go into the results as INFO lines and into the failure message. /// Every round's numbers go into the results as INFO lines and into the failure message.
/// </summary> /// </summary>
public static class PerfTests public static class PerfTests
@ -40,16 +45,20 @@ namespace BlaxLawsTests
private const int BlockTicks = 250; private const int BlockTicks = 250;
private const int PairsPerRound = 10; // 2500 ticks per arm and round private const int PairsPerRound = 10; // 2500 ticks per arm and round
private const int WarmupPairs = 2; private const int WarmupPairs = 2;
private const int MaxRounds = 3; private const int MaxRounds = 5; // up to 50 pairs; a round takes about 10 to 20 s under load
private const double Budget = 0.02; private const double Budget = 0.02;
// A coarse bound on the pooled median of the paired ratios (with / without): it includes what LawsClock // A coarse bound on the pooled median of the paired ratios (with / without): it includes what LawsClock
// can't see, Harmony's dispatch into the patched game methods. Loose, so the desktop can't make it flaky. // can't see, Harmony's dispatch into the patched game methods. Loose, so the desktop can't make it flaky.
private const double DispatchBound = 0.10; private const double DispatchBound = 0.10;
// Interquartile range of the pooled paired ratios under which the machine counts as quiet: an undecided
// dispatch bound is then judged on the plain median, as before.
private const double QuietSpread = 0.30;
private enum Verdict { Under, Over, Open }
private const int HungryPerBlock = 3; private const int HungryPerBlock = 3;
private const int HaulItemsPerBlock = 30; private const int HaulItemsPerBlock = 30;
private const int ZoneSize = 10; private const int ZoneSize = 10;
[BlaxTest("perf: 60 colonists with the starter lawbook over 2500 ticks: the time in Laws' code stays under 2% of the tick (10 alternating 250-tick pairs with and without Laws, up to 3 rounds)")] [BlaxTest("perf: 60 colonists with the starter lawbook over 2500 ticks: the time in Laws' code stays under 2% of the tick (10 alternating 250-tick pairs with and without Laws, up to 5 rounds)")]
public static void StarterLawbook() public static void StarterLawbook()
{ {
Work w = Build(); Work w = Build();
@ -102,8 +111,9 @@ namespace BlaxLawsTests
var report = new List<string>(); var report = new List<string>();
var pooledRatios = new List<double>(); var pooledRatios = new List<double>();
bool passed = false; bool shareOk = false;
for (int round = 1; round <= MaxRounds && !passed; round++) Verdict dispatch = Verdict.Open;
for (int round = 1; round <= MaxRounds; round++)
{ {
var ratios = new List<double>(); var ratios = new List<double>();
var with = new List<double>(); var with = new List<double>();
@ -133,6 +143,9 @@ namespace BlaxLawsTests
ratios.Add(off.ticks > 0 ? (double)on.ticks / off.ticks : 1.0); ratios.Add(off.ticks > 0 ? (double)on.ticks / off.ticks : 1.0);
} }
pooledRatios.AddRange(ratios); pooledRatios.AddRange(ratios);
var (lo, hi) = MedianBounds(pooledRatios);
double spread = Quantile(pooledRatios, 0.75) - Quantile(pooledRatios, 0.25);
dispatch = lo - 1.0 > DispatchBound ? Verdict.Over : hi - 1.0 < DispatchBound ? Verdict.Under : Verdict.Open;
// The decision: the time spent inside Laws' own code (every Harmony patch method of Laws and its // The decision: the time spent inside Laws' own code (every Harmony patch method of Laws and its
// component tick, timed by LawsClock) over the rest of the tick. It doesn't move with the game's // component tick, timed by LawsClock) over the rest of the tick. It doesn't move with the game's
// workload or the desktop the way the paired arms do, whose single pairs scatter by 20 to 70%. // workload or the desktop the way the paired arms do, whose single pairs scatter by 20 to 70%.
@ -150,14 +163,17 @@ namespace BlaxLawsTests
"pooled paired median of " + pooledRatios.Count + " pairs " + Pct(pooled) + " (bound " + Pct(DispatchBound) + "), " + "pooled paired median of " + pooledRatios.Count + " pairs " + Pct(pooled) + " (bound " + Pct(DispatchBound) + "), " +
"arm medians " + Pct(armOverhead) + "; budget " + Pct(Budget) + " = " + "arm medians " + Pct(armOverhead) + "; budget " + Pct(Budget) + " = " +
(Median(without) * Budget * 1e6 / Stopwatch.Frequency / BlockTicks).ToString("0.0") + " us/tick; " + (Median(without) * Budget * 1e6 / Stopwatch.Frequency / BlockTicks).ToString("0.0") + " us/tick; " +
"allocated bytes/tick with " + (bytesWith / armTicks) + ", without " + (bytesWithout / armTicks); "allocated bytes/tick with " + (bytesWith / armTicks) + ", without " + (bytesWithout / armTicks) + "; " +
"95% bounds of the pooled median " + Pct(lo - 1.0) + " to " + Pct(hi - 1.0) + ", spread (IQR) " + Pct(spread) + ", dispatch " + dispatch;
T.Info(line); T.Info(line);
report.Add(line); report.Add(line);
// Without Laws only the component's suspended tick runs (one early return a tick, LawsTestHooks.TickSuspended). // Without Laws only the component's suspended tick runs (one early return a tick, LawsTestHooks.TickSuspended).
T.Check(lawsCallsWithout <= armTicks, "calls into Laws' code without Laws: " + lawsCallsWithout + " in " + armTicks + " ticks"); T.Check(lawsCallsWithout <= armTicks, "calls into Laws' code without Laws: " + lawsCallsWithout + " in " + armTicks + " ticks");
// A round counts only if the two busiest hooks were timed in it: meals eaten (hook C) and records // A round counts only if the two busiest hooks were timed in it: meals eaten (hook C) and records
// counted (the record hooks). A round without them would measure a lighter workload. // counted (the record hooks). A round without them would measure a lighter workload.
passed = share < Budget && pooled < DispatchBound && ingestedCalls > 0 && recordCalls > 0; shareOk |= share < Budget && ingestedCalls > 0 && recordCalls > 0;
if (dispatch == Verdict.Over || (shareOk && dispatch == Verdict.Under))
break;
} }
for (int i = 0; i < rows.Count; i++) for (int i = 0; i < rows.Count; i++)
@ -169,8 +185,17 @@ namespace BlaxLawsTests
for (int i = 0; i < rows.Count; i++) for (int i = 0; i < rows.Count; i++)
T.Check(growthWith[i] > 0, "fixture: the '" + rows[i].name + "' row counted no act while watching, so the run measured no filing. " + T.Check(growthWith[i] > 0, "fixture: the '" + rows[i].name + "' row counted no act while watching, so the run measured no filing. " +
string.Join(" | ", report)); string.Join(" | ", report));
T.Check(passed, "in none of " + MaxRounds + " rounds did Laws' code stay under " + Pct(Budget) + " of the tick with the pooled paired median under " + string all = string.Join(" | ", report);
Pct(DispatchBound) + " and both hook C and the record hooks timed: " + string.Join(" | ", report)); T.Check(shareOk, "in none of " + report.Count + " rounds did Laws' code stay under " + Pct(Budget) + " of the tick with both hook C and the record hooks timed: " + all);
T.Check(dispatch != Verdict.Over, "with Laws the tick is slower by more than " + Pct(DispatchBound) + " even at the 95% lower bound of the pooled paired median (Harmony dispatch or hook cost): " + all);
if (dispatch == Verdict.Open)
{
double pooledSpread = Quantile(pooledRatios, 0.75) - Quantile(pooledRatios, 0.25);
if (pooledSpread < QuietSpread)
T.Check(Median(pooledRatios) - 1.0 < DispatchBound, "on a quiet machine (spread " + Pct(pooledSpread) + ") the pooled paired median stays over " + Pct(DispatchBound) + ": " + all);
else
T.Skip("Laws' own time passed, but the machine is too busy (spread " + Pct(pooledSpread) + ", over " + Pct(QuietSpread) + ") to bound Harmony's dispatch to " + Pct(DispatchBound) + ": " + all);
}
} }
/// <summary> /// <summary>
@ -379,6 +404,38 @@ namespace BlaxLawsTests
return s.Count % 2 == 1 ? s[m] : (s[m - 1] + s[m]) / 2.0; return s.Count % 2 == 1 ? s[m] : (s[m - 1] + s[m]) / 2.0;
} }
/// <summary>
/// One-sided 95% sign-test bounds of the median: the k-th smallest and the k-th largest value, with k the
/// largest count for which P(Binomial(n, 1/2) <= k - 1) <= 0.05 (n=10: k=2, n=20: k=6, n=30: k=11, n=50: k=19).
/// No bound (infinite) when n is too small for any k.
/// </summary>
private static (double lo, double hi) MedianBounds(List<double> values)
{
List<double> s = values.OrderBy(v => v).ToList();
int n = s.Count, k = 0;
double c = 1.0, p = Math.Pow(0.5, n), cum = 0.0;
for (int i = 0; i < n; i++)
{
cum += c * p;
if (cum > 0.05)
break;
k = i + 1;
c = c * (n - i) / (i + 1);
}
return k == 0 ? (double.NegativeInfinity, double.PositiveInfinity) : (s[k - 1], s[n - k]);
}
/// <summary>The q-quantile, linear between the two nearest values.</summary>
private static double Quantile(List<double> values, double q)
{
List<double> s = values.OrderBy(v => v).ToList();
if (s.Count == 0)
return 0.0;
double pos = q * (s.Count - 1);
int i = (int)Math.Floor(pos);
return i + 1 < s.Count ? s[i] + (s[i + 1] - s[i]) * (pos - i) : s[i];
}
private static string MsPerTick(double blockTicks) => (blockTicks * 1000.0 / Stopwatch.Frequency / BlockTicks).ToString("0.000"); private static string MsPerTick(double blockTicks) => (blockTicks * 1000.0 / Stopwatch.Frequency / BlockTicks).ToString("0.000");
private static string Pct(double fraction) => (fraction * 100.0).ToString("0.00") + "%"; private static string Pct(double fraction) => (fraction * 100.0).ToString("0.00") + "%";

View File

@ -104,6 +104,50 @@ namespace BlaxLawsTests
T.Equal(1, EnforceFixtures.MessagesWith(text) - messages, "escape messages"); T.Equal(1, EnforceFixtures.MessagesWith(text) - messages, "escape messages");
} }
[BlaxTest("jail end: a jailed colonist that escapes and dies off the map before the next sentence sweep closes as escaped with one escape message and no died-in-jail message")]
public static void EscapeeDiesOffMap()
{
EscapeeDiesOffMap(discard: false);
}
[BlaxTest("jail end: a jailed colonist that escapes, dies off the map and is discarded by the world before the next sentence sweep closes as escaped with one escape message, not as offender gone or died in jail")]
public static void EscapeeDiesOffMapDiscarded()
{
EscapeeDiesOffMap(discard: true);
}
/// <summary>
/// An escapee stays a prisoner of the colony off the map (Pawn.ExitMap clears the guest status only for a
/// released prisoner, Verse/Pawn.cs:2556-2589), and world pawns keep ticking (RimWorld.Planet/WorldPawns.cs:73-101),
/// so a bleeding escapee can die there before the sweep. A world pawn dies with no corpse
/// (Verse/Pawn.cs:2221-2224) and stays a world pawn among the dead.
/// </summary>
private static void EscapeeDiesOffMap(bool discard)
{
LawCase c = JailInCell(out Pawn o, out _);
NoWorldPawnGcBeforeNextSweep();
string escaped = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
string died = "BlaxLaws_MsgDiedInJail".Translate(c.OffenderLabel).Resolve();
int escapedBefore = EnforceFixtures.MessagesWith(escaped);
int diedBefore = EnforceFixtures.MessagesWith(died);
o.ExitMap(true, CellRect.WholeMap(o.Map).GetClosestEdge(o.Position));
T.Check(!o.Spawned && o.IsWorldPawn() && c.escapedTick >= 0, "fixture: the escape isn't noted off the map: spawned " + o.Spawned +
", world pawn " + o.IsWorldPawn() + ", note " + c.escapedTick);
o.Kill(null);
T.Check(o.Dead && o.Corpse == null && o.IsWorldPawn(), "fixture: " + o.LabelShort + " isn't a dead world pawn without a corpse: dead " + o.Dead +
", corpse " + o.Corpse + ", world pawn " + o.IsWorldPawn());
if (discard)
{
Find.WorldPawns.RemoveAndDiscardPawnViaGC(o);
T.Check(o.Discarded, "fixture: the dead escapee wasn't discarded");
}
EnforceFixtures.TickPastSentenceSweep();
T.Check(c.IsClosed, "the case of the escapee that died off the map isn't closed: " + c);
T.Equal(EnforcementOutcomes.Escaped, c.outcome, "the outcome of an escapee that died off the map, discarded " + discard);
T.Equal(1, EnforceFixtures.MessagesWith(escaped) - escapedBefore, "escape messages");
T.Equal(0, EnforceFixtures.MessagesWith(died) - diedBefore, "died-in-jail messages");
}
[BlaxTest("jail end: a jailed colonist destroyed in its cell alive (another mod, a dev tool), not escaped, closes as offender gone at the next sentence sweep with no escape message, also when the world discards it before that sweep")] [BlaxTest("jail end: a jailed colonist destroyed in its cell alive (another mod, a dev tool), not escaped, closes as offender gone at the next sentence sweep with no escape message, also when the world discards it before that sweep")]
public static void DestroyedInCellIsGone() public static void DestroyedInCellIsGone()
{ {
@ -262,6 +306,86 @@ namespace BlaxLawsTests
T.Equal(1, EnforceFixtures.MessagesWith(left) - leftBefore, "left-custody messages"); T.Equal(1, EnforceFixtures.MessagesWith(left) - leftBefore, "left-custody messages");
} }
[BlaxTest("jail end: a jailed colonist given away by transport pod to another faction's settlement stays jailed in the pod, then closes as offender gone with a left-custody message and no escape or released-early message")]
public static void GivenAwayByPodIsGone()
{
LawCase c = JailInCell(out Pawn o, out _);
Settlement s = Find.WorldObjects.Settlements.FirstOrDefault(x => x.Faction != null && !x.Faction.IsPlayer && x.Faction.def.humanlikeFaction);
if (s == null)
T.Skip("this world has no other faction's settlement");
Faction f = s.Faction;
// The gift raises goodwill (FactionGiftUtility.cs:63, HistoryEventDefOf.GaveGift, which Laws records no
// act for: CatalogueRules). Put the relation back after the test.
FactionRelation theirs = f.RelationWith(Faction.OfPlayer);
FactionRelation ours = Faction.OfPlayer.RelationWith(f);
int goodwill = theirs.baseGoodwill;
FactionRelationKind kind = theirs.kind;
Fixtures.OnCleanup(() =>
{
theirs.baseGoodwill = ours.baseGoodwill = goodwill;
theirs.kind = ours.kind = kind;
});
Fixtures.OnCleanup(() => DropTales(o));
string escaped = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
string left = "BlaxLaws_MsgLeftCustody".Translate(c.OffenderLabel).Resolve();
string early = "BlaxLaws_MsgReleasedEarly".Translate(c.OffenderLabel).Resolve();
int escapedBefore = EnforceFixtures.MessagesWith(escaped);
int leftBefore = EnforceFixtures.MessagesWith(left);
int earlyBefore = EnforceFixtures.MessagesWith(early);
// Loaded into a pod: still the colony's prisoner, in flight.
o.DeSpawnOrDeselect();
var pod = new ActiveTransporterInfo();
T.Check(pod.innerContainer.TryAdd(o), "fixture: the prisoner didn't go into the pod");
T.Check(o.IsPrisonerOfColony && !o.Spawned, "fixture: " + o.LabelShort + " isn't a prisoner in the pod");
Sentences.Check(c);
T.Check(!c.IsClosed && c.status == CaseStatus.Jailed, "the case of the prisoner in the pod in flight: " + c);
// What the pod's arrival as a gift does (RimWorld.Planet/FactionGiftUtility.cs:46-76): SplitOff,
// SetFaction (which ends the guest status, Verse/Pawn.cs:2702-2710), then DestroyOrPassToWorld.
FactionGiftUtility.GiveGift(new List<ActiveTransporterInfo> { pod }, s);
T.Check(o.Faction == f && !o.IsPrisonerOfColony && o.IsWorldPawn() && !o.Spawned,
"fixture: the gift isn't a world pawn of " + f + ": faction " + o.Faction + ", prisoner " + o.IsPrisonerOfColony + ", world pawn " + o.IsWorldPawn() + ", spawned " + o.Spawned);
T.Equal(-1, c.escapedTick, "the escape note after the gift");
Sentences.Check(c);
T.Check(c.IsClosed, "the case of the colonist given away isn't closed: " + c);
T.Equal(CaseOutcomes.OffenderGone, c.outcome, "the outcome after the gift");
T.Equal(1, EnforceFixtures.MessagesWith(left) - leftBefore, "left-custody messages");
T.Equal(0, EnforceFixtures.MessagesWith(escaped) - escapedBefore, "escape messages");
T.Equal(0, EnforceFixtures.MessagesWith(early) - earlyBefore, "released-early messages");
}
[BlaxTest("jail end: a jailed colonist lost with an abandoned or closed map closes as offender gone with a left-custody message and no escape or released-early message")]
public static void LostWithMapIsGone()
{
LawCase c = JailInCell(out Pawn o, out _);
// Vanilla's own per-pawn step of a map's deinit (Verse/MapDeiniter.cs:218-237, reached from
// Game.DeinitAndRemoveMap through PassPawnsToWorld, :142), run on the one prisoner: no second map needed.
MethodInfo cleanUp = typeof(MapDeiniter).GetMethod("CleanUpAndPassToWorld", BindingFlags.NonPublic | BindingFlags.Static);
T.NotNull(cleanUp, "fixture: MapDeiniter.CleanUpAndPassToWorld");
Fixtures.OnCleanup(() => DropTales(o));
string escaped = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
string left = "BlaxLaws_MsgLeftCustody".Translate(c.OffenderLabel).Resolve();
string early = "BlaxLaws_MsgReleasedEarly".Translate(c.OffenderLabel).Resolve();
int escapedBefore = EnforceFixtures.MessagesWith(escaped);
int leftBefore = EnforceFixtures.MessagesWith(left);
int earlyBefore = EnforceFixtures.MessagesWith(early);
o.DeSpawnOrDeselect();
cleanUp.Invoke(null, new object[] { o });
T.Check(o.IsWorldPawn() && !o.IsPrisonerOfColony && !o.Spawned, "fixture: the prisoner isn't a free world pawn after the deinit: world pawn " + o.IsWorldPawn() +
", prisoner " + o.IsPrisonerOfColony + ", spawned " + o.Spawned);
T.Equal(-1, c.escapedTick, "the escape note after the map loss");
// Pawn.Notify_PassedToWorld (Verse/Pawn.cs:1859-1888) gives a free colonist a random other faction, or none.
T.Info("the faction after the map loss: " + (o.Faction?.Name ?? "none"));
Sentences.Check(c);
T.Check(c.IsClosed, "the case of the colonist lost with the map isn't closed: " + c);
T.Equal(CaseOutcomes.OffenderGone, c.outcome, "the outcome after the map loss");
T.Equal(1, EnforceFixtures.MessagesWith(left) - leftBefore, "left-custody messages");
T.Equal(0, EnforceFixtures.MessagesWith(escaped) - escapedBefore, "escape messages");
T.Equal(0, EnforceFixtures.MessagesWith(early) - earlyBefore, "released-early messages");
}
private const string InPlaySaveName = "BlaxLawsTestEscapeSave"; private const string InPlaySaveName = "BlaxLawsTestEscapeSave";
[BlaxTest("jail end: an escapee discarded by the world and then saved before the next sentence sweep (the save drops the reference) still closes as escaped with one message")] [BlaxTest("jail end: an escapee discarded by the world and then saved before the next sentence sweep (the save drops the reference) still closes as escaped with one message")]

View File

@ -269,8 +269,10 @@ namespace BlaxLawsTests
{ {
// Only the subdue hits the offenders: no social fight and no random break of a bystander. No drug to // Only the subdue hits the offenders: no social fight and no random break of a bystander. No drug to
// binge on either: a smokeleaf dose cuts the halved pawn's pain to 0.45, which needs more points than the cap. // binge on either: a smokeleaf dose cuts the halved pawn's pain to 0.45, which needs more points than the cap.
// A binger once died during the run (case closed as offender gone, bruises past the cap): note every kill. // No predator hunts a colonist: a wild arctic wolf once hunted the binger, the danger rightly called off the
// subdue, and the wolf killed it. Every kill is noted, and SubdueStory names injuries the subdue didn't make.
Fixtures.LogKillsDuringTest(); Fixtures.LogKillsDuringTest();
EnforceFixtures.NoPredatorsHuntColonists();
DetectionKit.QuietSocialFights(); DetectionKit.QuietSocialFights();
DetectionKit.ClearDrugsOnMap(); DetectionKit.ClearDrugsOnMap();
BingeRun n = SubduedInPainShock(() => Unhurt(), EnforceFixtures.SubdueTicks, "normal pain", out Pawn normal); BingeRun n = SubduedInPainShock(() => Unhurt(), EnforceFixtures.SubdueTicks, "normal pain", out Pawn normal);

View File

@ -785,7 +785,7 @@ Not specced yet: the jury (see `docs/features.md`). Needs court sessions and the
- **Phase 3:** after phase 2 the runner saves as `BlaxLawsTest3`, replaces `Class="BlaxLaws.GameComponent_BlaxLaws"` with a type that doesn't exist, loads, and runs the phase 3 tests: exactly the 2 expected errors, a jailed colonist still a prisoner of the colony, no "BlaxLaws" in any pawn's job or queue. Phase 2 saves while an enforcer vomits mid-subdue (`Vomit` started with `resumeCurJobAfterwards`), so phase 3 also proves a queued subdue never reaches the file. - **Phase 3:** after phase 2 the runner saves as `BlaxLawsTest3`, replaces `Class="BlaxLaws.GameComponent_BlaxLaws"` with a type that doesn't exist, loads, and runs the phase 3 tests: exactly the 2 expected errors, a jailed colonist still a prisoner of the colony, no "BlaxLaws" in any pawn's job or queue. Phase 2 saves while an enforcer vomits mid-subdue (`Vomit` started with `resumeCurJobAfterwards`), so phase 3 also proves a queued subdue never reaches the file.
- **Fixtures:** Colonist, ColonySlave (Ideology), Child (Biotech), Prisoner, `Tick`, `QuietStoryteller`, `SnapshotSettings` from Castes; new: `PrisonerBed(cell)`, `Drug(def, cell)`, `Table(cell)`, `Corpse(cell)`, `ForceBreak(pawn, def, chemical)`, `LawRow(actKey, option, stage, severity, punishment, days)`. The test mod ships its own defs for the catalogue tests: a drug ThingDef, an InteractionDef, a RecipeDef and a MentalStateDef plus MentalBreakDef that reuse `MentalState_FireStartingSpree`. - **Fixtures:** Colonist, ColonySlave (Ideology), Child (Biotech), Prisoner, `Tick`, `QuietStoryteller`, `SnapshotSettings` from Castes; new: `PrisonerBed(cell)`, `Drug(def, cell)`, `Table(cell)`, `Corpse(cell)`, `ForceBreak(pawn, def, chemical)`, `LawRow(actKey, option, stage, severity, punishment, days)`. The test mod ships its own defs for the catalogue tests: a drug ThingDef, an InteractionDef, a RecipeDef and a MentalStateDef plus MentalBreakDef that reuse `MentalState_FireStartingSpree`.
- **Compat runs:** `-Compat` adds Prison Labor, Prisoner Realism, Custom Prisoner Interactions, Hospitality, Vanilla Social Interactions Expanded, Humanoid Alien Races if installed (Law and Order's tab never showed for its pawns), Blax Castes, Blax Slaves, Blax Zones and Blax Defaults. Package ids are read from each installed About.xml and recorded in Compat.cs with their source, as Castes does. Prisoner Sentencing and Prison Expanded aren't installed; their early release is simulated with a direct `GenGuest.PrisonerRelease`. The catalogue tests run there too: the compat mods' defs must appear under their mod names. - **Compat runs:** `-Compat` adds Prison Labor, Prisoner Realism, Custom Prisoner Interactions, Hospitality, Vanilla Social Interactions Expanded, Humanoid Alien Races if installed (Law and Order's tab never showed for its pawns), Blax Castes, Blax Slaves, Blax Zones and Blax Defaults. Package ids are read from each installed About.xml and recorded in Compat.cs with their source, as Castes does. Prisoner Sentencing and Prison Expanded aren't installed; their early release is simulated with a direct `GenGuest.PrisonerRelease`. The catalogue tests run there too: the compat mods' defs must appear under their mod names.
- **Performance:** 60 colonists and the starter lawbook, 10 alternating 250-tick blocks with and without Laws (patches removed and the component tick skipped), up to three rounds: the time inside Laws' own code (its patch bodies and component tick, timed per call) stays under 2% of the rest of the tick in one round, and the median of all paired with/without ratios stays under a coarse 10%, which also holds Harmony's dispatch into the patched methods. A round counts only with meals eaten and records counted in it. The same with a "Records: things hauled" row and an "Ate: any meal" row, the two busiest hooks. - **Performance:** 60 colonists and the starter lawbook, 10 alternating 250-tick blocks with and without Laws (patches removed and the component tick skipped), up to five rounds: the time inside Laws' own code (its patch bodies and component tick, timed per call) stays under 2% of the rest of the tick in one round, and the median of all paired with/without ratios stays under a coarse 10%, which also holds Harmony's dispatch into the patched methods. The median's one-sided 95% sign-test bounds decide that: it fails when even the lower bound is over 10% and passes when the upper bound is under; rounds are added while neither holds. Still undecided after five rounds, a quiet machine (interquartile range of the pairs under 30%) is judged on the plain median, and a busy one ends as a SKIP with the numbers, so load alone never fails the run. A round counts only with meals eaten and records counted in it. The same with a "Records: things hauled" row and an "Ate: any meal" row, the two busiest hooks.
- **Phase 2:** phase 3 still expects exactly 2 errors. All 8 DLC combinations. - **Phase 2:** phase 3 still expects exactly 2 errors. All 8 DLC combinations.
- **Effort:** S plus S for the harness copy, the compat and performance runs, plus S for the scaffold (csproj, startup, LawsLog, Compat, DlcSupport, the Tools copy, the art with a "scale" badge). - **Effort:** S plus S for the harness copy, the compat and performance runs, plus S for the scaffold (csproj, startup, LawsLog, Compat, DlcSupport, the Tools copy, the art with a "scale" badge).