using System; using System.Collections.Generic; using System.Linq; using BlaxZones; using RimWorld; using Verse; using Verse.AI.Group; namespace BlaxZonesTests { /// /// Fixtures added in 1.1 (design: "Headless tests in 1.1"): quest drop parts, trader caravans, a fixed /// vanilla trade spot far from the test's zones, and the source switch that keeps other tests' zones /// out of a test. /// public static partial class Fixtures { /// The in-signal QuestDropPods parts listen to. public const string QuestSignal = "blax.test"; /// A fixed vanilla spot at least this far from the test's zones, so routed and vanilla drops can't be confused. public const int FarSpotDistance = 40; // ---- zones ------------------------------------------------------------------------ /// /// Turns the source's checkbox off on every delivery zone on the map until the test ends, so zones /// other tests kept can't receive. Call before making the test's own zones. /// public static void OnlyThisTestsZones(DeliverySource source) { var off = new List(); foreach (Zone z in Map.zoneManager.AllZones) { if (z is Zone_Delivery d && d.AcceptsSource(source)) { SetSource(d, source, false); off.Add(d); } } OnCleanup(() => { foreach (Zone_Delivery d in off) SetSource(d, source, true); }); } private static void SetSource(Zone_Delivery zone, DeliverySource source, bool on) { switch (source) { case DeliverySource.Orbital: zone.acceptOrbital = on; break; case DeliverySource.Rewards: zone.acceptRewards = on; break; case DeliverySource.Caravan: zone.acceptCaravan = on; break; } } // ---- spots and distances ------------------------------------------------------------ /// A good drop spot, outside every zone, at least FarSpotDistance cells from the rect. Scans in a fixed order. public static IntVec3 FarCell(CellRect awayFrom) { Map map = Map; for (int x = 10; x < map.Size.x - 10; x += 3) { for (int z = 10; z < map.Size.z - 10; z += 3) { var c = new IntVec3(x, 0, z); if (ChebyshevToRect(awayFrom, c) < FarSpotDistance || map.zoneManager.ZoneAt(c) != null) continue; if (DropCellFinder.IsGoodDropSpot(c, map, allowFogged: false, canRoofPunch: false)) return c; } } T.Fail("no good drop spot " + FarSpotDistance + " cells from " + awayFrom); return IntVec3.Invalid; } /// Makes DropCellFinder.TradeDropSpot return a far cell until the test ends (a test-only prefix). Returns the cell. public static IntVec3 FixTradeDropSpotAwayFrom(CellRect area) { IntVec3 cell = FarCell(area); OrbitalTests.VanillaSpot.Install(cell); return cell; } public static int Chebyshev(IntVec3 a, IntVec3 b) => Math.Max(Math.Abs(a.x - b.x), Math.Abs(a.z - b.z)); public static int ChebyshevToRect(CellRect r, IntVec3 c) { int dx = c.x < r.minX ? r.minX - c.x : (c.x > r.maxX ? c.x - r.maxX : 0); int dz = c.z < r.minZ ? r.minZ - c.z : (c.z > r.maxZ ? c.z - r.maxZ : 0); return Math.Max(dx, dz); } /// Cells from the nearest zone cell (a square radius). public static int DistanceToZone(Zone zone, IntVec3 c) => zone.Cells.Count == 0 ? int.MaxValue : zone.Cells.Min(z => Chebyshev(z, c)); /// True when the cell lies in any delivery zone of the current map. public static bool InDeliveryZone(IntVec3 c) => c.InBounds(Map) && Map.zoneManager.ZoneAt(c) is Zone_Delivery; // ---- drop pods and letters -------------------------------------------------------------- /// The incoming drop pod (any skin) the thing sits in, tracked for cleanup; fails when it is in none. public static Skyfaller PodOf(Thing thing) { Thing holder = thing.SpawnedParentOrMe; T.Check(holder is Skyfaller, thing.LabelShort + " is not in an incoming drop pod but in " + (holder?.ToString() ?? "nothing spawned")); return Track((Skyfaller)holder); } /// /// After the test, removes the letters that arrive from now on, from the letter stack and from the /// archive (a saved letter naming a test quest that was never in the quest manager warns on load). /// Returns the letters there now. /// public static HashSet DropLettersAfterTest() { var letters = new HashSet(Find.LetterStack.LettersListForReading); var archived = new HashSet(Find.Archive.ArchivablesListForReading); OnCleanup(() => { foreach (Letter l in Find.LetterStack.LettersListForReading.Where(l => !letters.Contains(l)).ToList()) Find.LetterStack.RemoveLetter(l); foreach (IArchivable a in Find.Archive.ArchivablesListForReading.Where(a => a is Letter && !archived.Contains(a)).ToList()) Find.Archive.Remove(a); }); return letters; } // ---- quests ------------------------------------------------------------------------------ /// /// A raw quest that isn't in the quest manager, with a root that allows every surface map (Quest.MakeRaw /// sets none, and QuestPart_DropPods asks it, QuestScriptDef.cs:247). Registered as a signal receiver /// until the test ends, so chained parts get their signals. /// public static Quest TestQuest() { Quest quest = Quest.MakeRaw(); quest.root = new QuestScriptDef { defName = "BlaxZonesTestQuest" }; Find.SignalManager.RegisterReceiver(quest); OnCleanup(() => Find.SignalManager.DeregisterReceiver(quest)); return quest; } /// /// A QuestPart_DropPods on the current map listening to QuestSignal, holding the things (items and /// pawns), with useTradeDropSpot as given, added to the quest (a new TestQuest when none is given). /// Fire it with part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)). /// public static QuestPart_DropPods QuestDropPods(IEnumerable things, bool useTradeDropSpot, Quest quest = null) { quest ??= TestQuest(); var part = new QuestPart_DropPods { inSignal = QuestSignal, useTradeDropSpot = useTradeDropSpot, mapParent = Map.Parent, }; part.Things = things; quest.AddPart(part); return part; } /// /// QuestDropPods plus a chained second part: the first part's outSignalResult fires the second, which /// holds secondThings, uses no trade spot and drops at secondSpot. The second part listens in every /// quest state, since the raw quest is never accepted. /// public static QuestPart_DropPods QuestDropPods(IEnumerable things, bool useTradeDropSpot, IEnumerable secondThings, IntVec3 secondSpot, out QuestPart_DropPods second) { Quest quest = TestQuest(); QuestPart_DropPods first = QuestDropPods(things, useTradeDropSpot, quest); string chained = "Quest" + quest.id + ".blax.chained"; first.outSignalResult = chained; second = new QuestPart_DropPods { inSignal = chained, useTradeDropSpot = false, dropSpot = secondSpot, mapParent = Map.Parent, signalListenMode = QuestPart.SignalListenMode.Always, }; second.Things = secondThings; quest.AddPart(second); return first; } // ---- trader caravans ------------------------------------------------------------------ /// /// Forces IncidentDefOf.TraderCaravanArrival on the current map with the first friendly faction that /// can send one and returns its lord (LordJob_TradeWithColony). The lord, its pawns and the letter /// leave after the test. Skips when no faction in this world can send a caravan. /// public static Lord TraderCaravan() { IncidentWorker worker = IncidentDefOf.TraderCaravanArrival.Worker; var parms = new IncidentParms { target = Map, forced = true }; var arrive = worker as IncidentWorker_PawnsArrive; T.NotNull(arrive, worker.GetType().FullName + " as IncidentWorker_PawnsArrive"); parms.faction = Find.FactionManager.AllFactionsListForReading .Where(f => !f.IsPlayer && !f.defeated && !f.Hidden && f.def.humanlikeFaction && !f.HostileTo(Faction.OfPlayer) && arrive.FactionCanBeGroupSource(f, parms)) .OrderBy(f => f.loadID) .FirstOrDefault(); if (parms.faction == null) T.Skip("no friendly faction in this world can send a trader caravan"); return Arrive(worker, parms, "trader caravan"); } /// Fires the worker and returns the one lord it made. Everything it brings leaves after the test. public static Lord Arrive(IncidentWorker worker, IncidentParms parms, string what) { HashSet before = LeaveAfterTest(); T.Check(worker.TryExecute(parms), what + " did not fire"); List made = Map.lordManager.lords.Where(l => !before.Contains(l)).ToList(); T.Equal(1, made.Count, "lords made by the " + what); return made[0]; } /// /// After the test, removes the lords, sends off the pawns and drops the letters that appear on the /// current map from now on. Returns the lords there now. /// public static HashSet LeaveAfterTest() { Map map = Map; var lords = new HashSet(map.lordManager.lords); var pawns = new HashSet(map.mapPawns.AllPawnsSpawned); DropLettersAfterTest(); OnCleanup(() => { foreach (Lord l in map.lordManager.lords.Where(l => !lords.Contains(l)).ToList()) map.lordManager.RemoveLord(l); foreach (Pawn p in map.mapPawns.AllPawnsSpawned.Where(p => !pawns.Contains(p)).ToList()) { if (p.Spawned) p.ExitMap(false, Rot4.Invalid); } }); return lords; } /// The caravan's trader (TraderCaravanUtility.FindTrader), with a trader tracker. public static Pawn TraderOf(Lord lord) { Pawn trader = TraderCaravanUtility.FindTrader(lord); T.NotNull(trader, "the caravan's trader"); T.NotNull(trader.trader, "the trader's Pawn_TraderTracker"); return trader; } /// The caravan's first pack animal carrying goods (TraderCaravanRole.Carrier). public static Pawn CarrierOf(Lord lord) { Pawn carrier = lord.ownedPawns.Where(p => p.GetTraderCaravanRole() == TraderCaravanRole.Carrier).OrderBy(p => p.thingIDNumber).FirstOrDefault(); if (carrier == null) T.Skip("the caravan has no pack animal with goods"); return carrier; } /// /// A stack of the def put into the carrier's inventory, so it is one of the trader's goods. Tracked /// for cleanup wherever it ends up. /// public static Thing GoodsOnCarrier(Pawn carrier, ThingDef def, int count) { Thing stack = Stack(def, count); T.Check(carrier.inventory.innerContainer.TryAdd(stack, canMergeWithExistingStacks: false), "could not put " + def.defName + " on " + carrier.LabelShort); return stack; } /// A free colonist already on the map, or a fixture one. public static Pawn Negotiator() => Map.mapPawns.FreeColonistsSpawned.Where(p => !p.Dead && !p.Downed).OrderBy(p => p.thingIDNumber).FirstOrDefault() ?? Colonist(); } }