using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using BlaxLaws; using HarmonyLib; using RimWorld; using RimWorld.Planet; using Verse; using Verse.AI; using Verse.AI.Group; namespace BlaxLawsTests { /// /// Shared helpers for tests. Pawns and things made here are removed after each test unless passed to /// Keep(). Mod settings are restored after each test, and lawbook rows a test added are deleted unless /// passed to KeepLaw(), so tests may change both freely. /// public static partial class Fixtures { private static readonly List made = new List(); private static readonly HashSet kept = new HashSet(); private static readonly List madeThings = new List(); private static readonly HashSet keptThings = new HashSet(); private static readonly HashSet keptLaws = new HashSet(); private static readonly List cleanups = new List(); public static Map Map => Find.CurrentMap; public static BlaxLawsSettings Settings => BlaxLawsMod.Settings; public static GameComponent_BlaxLaws Comp => GameComponent_BlaxLaws.Instance; // ---- factions -------------------------------------------------------------------- /// A visible, non-player, humanlike faction that is not hostile to the player. public static Faction FriendlyFaction() => Find.FactionManager.AllFactionsVisible .Where(f => !f.IsPlayer && !f.defeated && f.def.humanlikeFaction && !f.HostileTo(Faction.OfPlayer)) .OrderBy(f => f.loadID).FirstOrDefault(); /// A visible, non-player, humanlike faction hostile to the player. public static Faction HostileFaction() => Find.FactionManager.AllFactionsVisible .Where(f => !f.IsPlayer && !f.defeated && f.def.humanlikeFaction && f.HostileTo(Faction.OfPlayer)) .OrderBy(f => f.loadID).FirstOrDefault(); // ---- pawns ----------------------------------------------------------------------- /// A fresh pawn, not spawned. Relations off so no accidental family ties. public static Pawn Generate(PawnKindDef kind, Faction faction, DevelopmentalStage stage = DevelopmentalStage.Adult) { var req = new PawnGenerationRequest(kind, faction, PawnGenerationContext.NonPlayer, forceGenerateNewPawn: true, allowDowned: stage.Baby(), canGeneratePawnRelations: false, colonistRelationChanceFactor: 0f, developmentalStages: stage); Pawn p = PawnGenerator.GeneratePawn(req); made.Add(p); return p; } /// /// A standable, unfogged cell near the map center that belongs to a district, so pawns spawned there /// path, find beds and count as in a room like any colonist. The district reaches the map edge: never /// the inside of a room a fixture built, such as a prison cell, where no other pawn fits beside it. /// public static IntVec3 PawnCell() { Map map = Map; if (CellFinder.TryFindRandomCellNear(map.Center, map, 20, c => c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) is District d && d.TouchesMapEdge && c.GetFirstPawn(map) == null, out IntVec3 cell)) return cell; if (CellFinder.TryFindRandomCellNear(map.Center, map, 60, c => c.Standable(map) && c.GetDistrict(map) != null, out cell)) return cell; T.Fail("no standable cell with a district near the map center"); return IntVec3.Invalid; } /// Spawns the pawn at the cell, or on PawnCell() when none is given. public static Pawn Spawn(Pawn p, IntVec3? at = null) { IntVec3 cell = at ?? PawnCell(); T.Check(cell.GetDistrict(Map) != null, "spawn cell " + cell + " has no district"); GenSpawn.Spawn(p, cell, Map); return p; } /// A spawned free adult colonist. public static Pawn Colonist() => Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer)); /// A spawned slave of the colony. Skips the test without Ideology. public static Pawn ColonySlave(Faction origin = null) { T.NeedsDlc("Ideology", ModsConfig.IdeologyActive); Pawn p = Generate(PawnKindDefOf.Slave, origin ?? FriendlyFaction()); Spawn(p); p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave); T.Check(p.IsSlaveOfColony, "slave fixture is not a slave of the colony"); return p; } /// A spawned prisoner of the colony, from a hostile faction when there is one. public static Pawn Prisoner() { Faction from = HostileFaction() ?? FriendlyFaction(); Pawn p = Spawn(Generate(PawnKindDefOf.Slave, from)); p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner); T.Check(p.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony"); return p; } /// A spawned child of the colony. Skips the test without Biotech. public static Pawn Child() { T.NeedsDlc("Biotech", ModsConfig.BiotechActive); Pawn p = Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer, DevelopmentalStage.Child)); T.Check(p.DevelopmentalStage.Child(), "child fixture is " + p.DevelopmentalStage + ", not a child"); return p; } /// Exclude a pawn from the per-test cleanup (phase-1 setup for phase-2 checks). public static Pawn Keep(Pawn p) { kept.Add(p); return p; } public static Pawn FindPawnById(string thingId) { if (thingId == null) return null; foreach (Map m in Find.Maps) foreach (Pawn p in m.mapPawns.AllPawns) if (p.ThingID == thingId) return p; foreach (Pawn p in Find.WorldPawns.AllPawnsAliveOrDead) if (p.ThingID == thingId) return p; return null; } // ---- things ---------------------------------------------------------------------- /// Destroy this thing after the test unless kept. public static TT Track(TT thing) where TT : Thing { madeThings.Add(thing); return thing; } public static TT Keep(TT thing) where TT : Thing { keptThings.Add(thing); return thing; } /// A thing a test made or kept, so a fixture never clears it away. public static bool IsFixtureThing(Thing t) => madeThings.Contains(t) || keptThings.Contains(t); /// /// Ground a fixture building may go on once cleared, as a player clears a building site: walkable terrain /// that is not water, unfogged, in the district, with no building and no pawn, and nothing on it but plants, /// filth and items no test made. A wild map (a dense jungle) has few cells free of trees and starting items. /// public static bool Buildable(IntVec3 c, Map map, District district) { if (!c.InBounds(map) || c.Fogged(map) || c.GetDistrict(map) != district) return false; TerrainDef terrain = c.GetTerrain(map); if (terrain.IsWater || terrain.passability != Traversability.Standable) return false; List things = c.GetThingList(map); for (int i = 0; i < things.Count; i++) { Thing t = things[i]; if (t is Plant || t.def.category == ThingCategory.Filth || t.def.category == ThingCategory.Mote) continue; if (t.def.category == ThingCategory.Item && !IsFixtureThing(t)) continue; return false; } return true; } /// Removes the plants and items on the cells, so a building fits (see Buildable). public static void ClearGround(IEnumerable cells, Map map) { foreach (IntVec3 c in cells) { if (!c.InBounds(map)) continue; foreach (Thing t in c.GetThingList(map).ToList()) { if ((t is Plant || t.def.category == ThingCategory.Item) && !IsFixtureThing(t) && !t.Destroyed) t.Destroy(DestroyMode.Vanish); } } } // ---- lawbook --------------------------------------------------------------------- /// /// Adds a row through Lawbook.TryAdd and returns it; fails the test when a row with the key exists. /// Deleted after the test unless passed to KeepLaw. /// public static Law LawRow(string actKey, string option, LawStage stage, LawSeverity severity, string punishment, int days, string savedMod = null, string savedPackageId = null) { var law = new Law { actKey = actKey, option = option, stage = stage, severity = severity, punishment = punishment, days = days, enabled = true, savedLabel = ActKey.NameOf(actKey), savedMod = savedMod, savedPackageId = savedPackageId, }; T.Check(Lawbook.TryAdd(law, out Law existing), "LawRow " + actKey + ": refused, existing " + existing); return law; } public static Law KeepLaw(Law law) { keptLaws.Add(law.id); return law; } /// The ids of the rows before a test (used by the runner). public static HashSet SnapshotLawbook() => new HashSet(Lawbook.Laws.Select(l => l.id)); /// Deletes every row a test added that it didn't keep (used by the runner). public static void RestoreLawbook(HashSet before) { foreach (Law l in Lawbook.Laws.ToList()) { if (!before.Contains(l.id) && !keptLaws.Contains(l.id)) Lawbook.Delete(l); } } /// Runs after the test, before things are removed (undo a test-only patch, for example). public static void OnCleanup(Action action) => cleanups.Add(action); // ---- time ------------------------------------------------------------------------ public static void Tick(int ticks) { for (int i = 0; i < ticks; i++) Find.TickManager.DoSingleTick(); } /// /// No incidents, and no mental break a test didn't start: the quick test's own colonists sleep on the /// ground, eat what they find and hear of every fixture colonist that dies, so over the suite's /// simulated days their mood sinks and they would break (MentalBreaker checks /// DebugSettings.enableRandomMentalStates first). Tests start breaks with forced: true, which ignores it. /// public static void QuietStoryteller() { Find.Storyteller.incidentQueue.Clear(); Find.Storyteller.storytellerComps.Clear(); DebugSettings.enableRandomMentalStates = false; } /// /// Before each phase-1 test: the pawns no test made stay out of the next test's way. The quick test's /// colonists are fed and taken out of any break, and an animal in a manhunter state calms down. A /// starving or breaking colonist wanders off and can turn an animal manhunter, and a manhunter is an /// active threat that keeps every later enforcement waiting for the danger to pass /// (Enforcers.DangerBlocks; RimWorld/GenHostility.cs:227). Each such fix is noted in the results. /// /// The injuries of the map's colonists that no test made, keyed by pawn (for BystanderHarm). public static Dictionary> BystanderInjuries() { var result = new Dictionary>(); Map map = Map; if (map == null) return result; foreach (Pawn p in map.mapPawns.FreeColonistsSpawned) { if (p != null && !kept.Contains(p) && !made.Contains(p) && p.health?.hediffSet != null) result[p] = new HashSet(p.health.hediffSet.hediffs.Where(h => h is Hediff_Injury)); } return result; } /// /// What a test did to the colonists it didn't make: new injuries (with their source) and downs, for a note /// that names the test, so a later test that finds a downed bystander can be traced back. /// public static string BystanderHarm(Dictionary> before) { var parts = new List(); foreach (var kv in before) { Pawn p = kv.Key; if (p.Destroyed) continue; if (p.Dead) { parts.Add(p.LabelShort + " (" + p.ThingID + ") died"); continue; } var fresh = p.health.hediffSet.hediffs.Where(h => h is Hediff_Injury && !kv.Value.Contains(h)).ToList(); if (fresh.Count == 0 && !p.Downed) continue; parts.Add(p.LabelShort + " (" + p.ThingID + ")" + (p.Downed ? " downed" : "") + ", " + fresh.Count + " new injuries: " + string.Join(" ", fresh.Take(8).Select(h => h.def.defName + "/" + (h.sourceLabel ?? h.sourceDef?.defName ?? "?"))) + ", job " + (p.CurJobDef?.defName ?? "none")); } return string.Join("; ", parts); } public static void CalmBystanders() { Map map = Map; if (map == null) return; // A colonist no test made that some earlier test left downed draws doctors and rescuers, the fixture // wardens included, onto jobs Laws never pulls them off; heal it so every test starts on the same map. foreach (Pawn p in map.mapPawns.FreeColonistsSpawned.ToList()) { if (p == null || kept.Contains(p) || made.Contains(p) || !p.Downed || p.Dead) continue; var injuries = p.health.hediffSet.hediffs.Where(h => h is Hediff_Injury && !h.IsPermanent()).ToList(); TestRunner.Note("healed " + p.LabelShort + " (" + p.ThingID + "), downed before the test, of " + injuries.Count + " injuries"); foreach (Hediff h in injuries) p.health.RemoveHediff(h); } foreach (Pawn p in map.mapPawns.AllPawnsSpawned.ToList()) { if (p == null || p.Dead || kept.Contains(p) || made.Contains(p)) continue; if (p.IsFreeColonist) { 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.IsFreeColonist || p.RaceProps.Animal) && p.InMentalState) { TestRunner.Note("calmed " + p.LabelShort + " out of " + p.MentalStateDef.defName + " before the test" + (p.RaceProps.Animal ? "; " + BondStory(p) : "")); p.MentalState.RecoverFromState(); } if (p.RaceProps.Animal) DropFixtureBonds(p); } // A party or another gathering takes colonists into its lord, and a pawn in a lord is never sent // (Enforcers.IsFree), so a random party during a test leaves its cases waiting as busy. None starts // for 600000 ticks after the last one (RimWorld/VoluntarilyJoinableLordsStarter.cs:76-86), and the // ones running end before the test. if (map.lordsStarter != null) { AccessTools.Field(typeof(VoluntarilyJoinableLordsStarter), "lastLordStartTick").SetValue(map.lordsStarter, Find.TickManager.TicksGame); AccessTools.Field(typeof(VoluntarilyJoinableLordsStarter), "startRandomGatheringASAP").SetValue(map.lordsStarter, false); } foreach (Lord lord in map.lordManager.lords.ToList()) { if (lord?.LordJob is LordJob_VoluntarilyJoinable && !lord.ownedPawns.Any(p => kept.Contains(p) || made.Contains(p))) { TestRunner.Note("ended the gathering " + lord.LordJob.GetType().Name + " before the test"); map.lordManager.RemoveLord(lord); } } } // ---- settings and cleanup (used by the runner) ----------------------------------- public static Dictionary SnapshotSettings() { var d = new Dictionary(); if (Settings == null) return d; foreach (FieldInfo f in typeof(BlaxLawsSettings).GetFields(BindingFlags.Public | BindingFlags.Instance)) d[f] = f.GetValue(Settings); return d; } public static void RestoreSettings(Dictionary snapshot) { if (Settings == null) return; foreach (var kv in snapshot) kv.Key.SetValue(Settings, kv.Value); BlaxLawsMod.ApplyTabVisibility(); } public static void Cleanup() { List actions = cleanups.ToList(); cleanups.Clear(); foreach (Action a in actions) { try { a(); } catch (Exception e) { TestRunner.Note("cleanup action threw: " + e.Message); } } Find.Selector?.ClearSelection(); foreach (Thing t in madeThings) { if (t == null || keptThings.Contains(t) || t.Destroyed) continue; if (t.Spawned || t.holdingOwner != null) t.Destroy(DestroyMode.Vanish); } madeThings.Clear(); // Two passes: a pawn another fixture pawn carries (an arrest or capture cut off by the test's end) is // held, not spawned, and destroying the carrier drops it onto the map, where it would stay as a // prisoner that claims the next test's prisoner bed. for (int pass = 0; pass < 2; pass++) { foreach (Pawn p in made) { if (p == null || kept.Contains(p) || p.Destroyed) continue; if (pass == 0) DropRitualObligations(p); if (p.Corpse != null && (p.Corpse.Spawned || p.Corpse.holdingOwner != null)) p.Corpse.Destroy(DestroyMode.Vanish); else if (p.Spawned || p.holdingOwner != null) p.Destroy(DestroyMode.Vanish); else if (p.IsWorldPawn()) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p); } } made.Clear(); } /// /// A fixture colonist that died gets a funeral obligation, and a living one can get a scarification or /// blinding obligation when it joins or changes status (Ideology). The cleanup destroys the pawn or its /// corpse, so drop those obligations too, or the save warns about a reference to a discarded pawn. /// private static void DropRitualObligations(Pawn p) { if (!ModsConfig.IdeologyActive || Find.IdeoManager == null) return; Corpse corpse = p.Corpse; bool Hits(TargetInfo t) => t.HasThing && (t.Thing == p || (corpse != null && t.Thing == corpse)); foreach (Ideo ideo in Find.IdeoManager.IdeosListForReading) { foreach (Precept precept in ideo.PreceptsListForReading) { if (!(precept is Precept_Ritual ritual) || ritual.activeObligations == null) continue; foreach (RitualObligation o in ritual.activeObligations.ToList()) { if (o != null && (Hits(o.targetA) || Hits(o.targetB) || Hits(o.targetC))) ritual.RemoveObligation(o); } } } } } }