rimworld-blax-slaves/Tests/BlaxSlavesTests/Source/Fixtures.cs

307 lines
13 KiB
C#

using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxSlaves;
using RimWorld;
using RimWorld.Planet;
using Verse;
namespace BlaxSlavesTests
{
/// <summary>
/// Shared helpers for tests. Pawns made here are destroyed after each test unless passed to
/// Keep(). Mod settings are restored after each test, so tests may change them freely.
/// </summary>
public static class Fixtures
{
private static readonly List<Pawn> made = new List<Pawn>();
private static readonly HashSet<Pawn> kept = new HashSet<Pawn>();
public static Map Map => Find.CurrentMap;
public static BlaxSlavesSettings Settings => BlaxSlavesMod.Settings;
// ---- factions --------------------------------------------------------------------
/// <summary>A visible, non-player, humanlike faction that is not hostile to the player.</summary>
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();
/// <summary>A visible, non-player, humanlike faction hostile to the player.</summary>
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 -----------------------------------------------------------------------
/// <summary>A fresh adult pawn, not spawned. Relations off so no accidental family ties.</summary>
public static Pawn Generate(PawnKindDef kind, Faction faction)
{
var req = new PawnGenerationRequest(kind, faction, PawnGenerationContext.NonPlayer,
forceGenerateNewPawn: true, canGeneratePawnRelations: false,
colonistRelationChanceFactor: 0f, developmentalStages: DevelopmentalStage.Adult);
Pawn p = PawnGenerator.GeneratePawn(req);
made.Add(p);
return p;
}
/// <summary>
/// Spawns the pawn on a random open cell near the map's anchor. Vanilla's RandomClosewalkCellNear
/// falls back to its root when it finds nothing, so on a map whose center lies in rock the pawn
/// would stand inside the rock with no district: vanilla AI then throws (a prisoner's escape check
/// reads the district) and the mood gate scenes find no room around the victim.
/// </summary>
public static Pawn Spawn(Pawn p)
{
Map map = Map;
IntVec3 root = Anchor(map);
if (!CellFinder.TryRandomClosewalkCellNear(root, map, 12, out IntVec3 cell, c => IsOpen(c, map)))
cell = root;
GenSpawn.Spawn(p, cell, map);
return p;
}
private static Map anchorMap;
private static IntVec3 anchor = IntVec3.Invalid;
/// <summary>Standable, not fogged and inside a district: a cell vanilla AI and the scenes can work with.</summary>
public static bool IsOpen(IntVec3 c, Map map) =>
c.InBounds(map) && c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) != null;
/// <summary>The map center when it is open, else the open cell closest to it. Skips the test when the map has none.</summary>
private static IntVec3 Anchor(Map map)
{
IntVec3 center = map.Center;
if (IsOpen(center, map))
return center;
if (map == anchorMap && anchor.IsValid && IsOpen(anchor, map))
return anchor;
IntVec3 best = IntVec3.Invalid;
int bestDist = int.MaxValue;
foreach (IntVec3 c in map.AllCells)
{
int dist = (c - center).LengthHorizontalSquared;
if (dist < bestDist && IsOpen(c, map))
{
best = c;
bestDist = dist;
}
}
if (!best.IsValid)
T.Skip("setup: no standable, unfogged cell on the map to spawn test pawns on");
T.Info("map center " + center + " is not open (rock, fog or no district), test pawns spawn near " + best);
anchorMap = map;
anchor = best;
return best;
}
/// <summary>A spawned free colonist. pacifist = has the Kind trait; otherwise Kind is removed.</summary>
public static Pawn Colonist(bool pacifist = false)
{
Pawn p = Generate(PawnKindDefOf.Colonist, Faction.OfPlayer);
Trait kind = p.story.traits.GetTrait(TraitDefOf.Kind);
if (pacifist && kind == null) p.story.traits.GainTrait(new Trait(TraitDefOf.Kind));
if (!pacifist && kind != null) p.story.traits.RemoveTrait(kind);
return Spawn(p);
}
/// <summary>A spawned slave of the colony, enslaved from origin (default: a friendly faction). Skips the test without Ideology.</summary>
public static Pawn ColonySlave(Faction origin = null)
{
RequireIdeology();
Pawn p = Generate(PawnKindDefOf.Slave, origin ?? FriendlyFaction());
Spawn(p);
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
return p;
}
/// <summary>A spawned prisoner of the colony, from a hostile faction when there is one.</summary>
public static Pawn ColonyPrisoner(Faction from = null)
{
Pawn p = Spawn(Generate(PawnKindDefOf.Slave, from ?? HostileFaction() ?? FriendlyFaction()));
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner);
T.Check(p.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony");
return p;
}
/// <summary>
/// A spawned colony slave even without Ideology, as a save made with Ideology and loaded without it
/// leaves one: vanilla keeps the slave status, but there is no suppression and no interaction mode.
/// With Ideology it is a normal colony slave.
/// </summary>
public static Pawn LeftoverSlave()
{
if (ModsConfig.IdeologyActive)
return ColonySlave();
Pawn p = Spawn(Generate(PawnKindDefOf.Slave, FriendlyFaction()));
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
T.Check(p.IsSlaveOfColony, "setup: vanilla refused to make a colony slave without Ideology");
return p;
}
// ---- DLCs ------------------------------------------------------------------------
/// <summary>Skips the test without Ideology: slaves, brands and everything that acts on them need it.</summary>
public static void RequireIdeology()
{
if (!ModsConfig.IdeologyActive)
T.Skip("needs Ideology");
}
/// <summary>The active DLCs for the DLCS line of the results file, "none" for core only.</summary>
public static string ActiveDlcs()
{
var dlcs = new List<string>();
if (ModsConfig.RoyaltyActive) dlcs.Add("Royalty");
if (ModsConfig.IdeologyActive) dlcs.Add("Ideology");
if (ModsConfig.BiotechActive) dlcs.Add("Biotech");
if (ModsConfig.AnomalyActive) dlcs.Add("Anomaly");
if (ModsConfig.OdysseyActive) dlcs.Add("Odyssey");
return dlcs.Count == 0 ? "none" : string.Join(",", dlcs);
}
private static readonly FieldInfo IdeologyActiveField = typeof(ModsConfig).GetField("ideologyActive", BindingFlags.NonPublic | BindingFlags.Static);
/// <summary>
/// Runs a DLC-off check. Without Ideology it simply runs. With Ideology loaded, ModsConfig.IdeologyActive
/// reads false for the body only, so the same check also guards the mod's own Ideology gates in a
/// full run (a real -NoDlc run is still what proves the game loads and plays without it). Keep the body
/// to direct calls into Blax Slaves and plain reads: never tick the game or run vanilla systems inside.
/// </summary>
public static void AsIfIdeologyOff(System.Action body)
{
if (!ModsConfig.IdeologyActive)
{
body();
return;
}
if (IdeologyActiveField == null || IdeologyActiveField.FieldType != typeof(bool))
T.Skip("ModsConfig.ideologyActive not found (renamed in this game version?), so Ideology can't be switched off for this check; a -NoDlc run covers it");
IdeologyActiveField.SetValue(null, false);
try
{
T.Check(!ModsConfig.IdeologyActive, "setup: ModsConfig.IdeologyActive still true after switching ideologyActive off");
body();
}
finally
{
IdeologyActiveField.SetValue(null, true);
}
}
/// <summary>Errors and warnings the game logs while the body runs (any source), one line each.</summary>
public static List<string> LoggedProblems(System.Action body)
{
var found = new List<string>();
UnityEngine.Application.LogCallback handler = (text, stack, type) =>
{
if (type == UnityEngine.LogType.Error || type == UnityEngine.LogType.Exception || type == UnityEngine.LogType.Warning)
lock (found) found.Add(type + ": " + text);
};
UnityEngine.Application.logMessageReceivedThreaded += handler;
try
{
body();
}
finally
{
UnityEngine.Application.logMessageReceivedThreaded -= handler;
}
return found;
}
/// <summary>Exclude a pawn from the per-test cleanup (phase-1 setup for phase-2 checks).</summary>
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;
}
// ---- time ------------------------------------------------------------------------
public static void Tick(int ticks)
{
for (int i = 0; i < ticks; i++) Find.TickManager.DoSingleTick();
}
public static void QuietStoryteller()
{
Find.Storyteller.incidentQueue.Clear();
Find.Storyteller.storytellerComps.Clear();
}
// ---- thoughts --------------------------------------------------------------------
/// <summary>Snapshot of a pawn's memories with their age, to spot new or renewed ones.</summary>
public static Dictionary<Thought_Memory, int> Memories(Pawn p)
{
var d = new Dictionary<Thought_Memory, int>();
var list = p.needs?.mood?.thoughts?.memories?.Memories;
if (list != null) foreach (Thought_Memory m in list) d[m] = m.age;
return d;
}
/// <summary>Memories added or renewed since the snapshot that lower mood or opinion.</summary>
public static List<Thought_Memory> NewBadMemories(Pawn p, Dictionary<Thought_Memory, int> before)
{
var result = new List<Thought_Memory>();
var list = p.needs?.mood?.thoughts?.memories?.Memories;
if (list == null) return result;
foreach (Thought_Memory m in list)
{
bool fresh = !before.TryGetValue(m, out int oldAge) || m.age < oldAge;
if (!fresh) continue;
bool bad = m.MoodOffset() < 0f || (m is ISocialThought s && s.OpinionOffset() < 0f);
if (bad) result.Add(m);
}
return result;
}
public static string Describe(IEnumerable<Thought_Memory> memories) =>
string.Join(", ", memories.Select(m => m.def.defName + (m.otherPawn != null ? "(" + m.otherPawn.LabelShort + ")" : "")));
// ---- settings and cleanup (used by the runner) -----------------------------------
public static Dictionary<FieldInfo, object> SnapshotSettings()
{
var d = new Dictionary<FieldInfo, object>();
if (Settings == null) return d;
foreach (FieldInfo f in typeof(BlaxSlavesSettings).GetFields(BindingFlags.Public | BindingFlags.Instance))
d[f] = f.GetValue(Settings);
return d;
}
public static void RestoreSettings(Dictionary<FieldInfo, object> snapshot)
{
if (Settings == null) return;
foreach (var kv in snapshot) kv.Key.SetValue(Settings, kv.Value);
}
public static void Cleanup()
{
foreach (Pawn p in made)
{
if (p == null || kept.Contains(p)) continue;
if (p.Corpse != null && p.Corpse.Spawned) p.Corpse.Destroy(DestroyMode.Vanish);
else if (p.Spawned) p.Destroy(DestroyMode.Vanish);
else if (p.IsWorldPawn()) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p);
}
made.Clear();
}
}
}