rimworld-blax-zones/Tests/BlaxZonesTests/Source/OrbitalTests.cs

479 lines
24 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxZones;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxZonesTests
{
/// <summary>
/// Package Orbital. Design: 1.0 "Orbital purchases land in the zone" > Tests.
/// Tests: [BlaxTest("orbital: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped.
/// Nothing is saved by this feature, so every test is phase 1. Each test turns the orbital checkbox off on
/// delivery zones other tests left on the map (restored afterwards), so only its own zones can receive.
/// </summary>
public static class OrbitalTests
{
/// <summary>Cells between a zone and the beacon ZoneRectWithBeacon places. TradeDropSpot looks within 5 of the beacon first.</summary>
private const int BeaconGap = 8;
/// <summary>A fixed vanilla spot at least this far from the test's zones, so overflow and vanilla can't be confused.</summary>
private const int FarSpotDistance = 40;
// ---- tests -----------------------------------------------------------------------
[BlaxTest("orbital: bought steel falls in a drop pod onto a zone cell, right after the call")]
public static void SteelLandsInZone()
{
OnlyThisTestsZones();
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3));
TradeShip ship = OrbitalTrader();
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
DropPodIncoming pod = Buy(ship, steel);
T.Check(zone.ContainsCell(pod.Position), "the pod falls on " + pod.Position + ", not on a zone cell");
}
[BlaxTest("orbital: medicine goes to a medicine-only zone at Important, steel to the general zone")]
public static void FilterAndPriority()
{
OnlyThisTestsZones();
CellRect area = Fixtures.TestArea(7, 2);
// The general zone is made first, so a lower ID can't be why medicine picks the other one.
Zone_Delivery general = Fixtures.DeliveryZone(new CellRect(area.minX, area.minZ, 2, 2));
Zone_Delivery medical = Fixtures.DeliveryZone(new CellRect(area.maxX - 1, area.minZ, 2, 2),
Fixtures.FilterOf(ThingDefOf.MedicineIndustrial), StoragePriority.Important);
TradeShip ship = OrbitalTrader();
DropPodIncoming medPod = Buy(ship, Fixtures.Stack(ThingDefOf.MedicineIndustrial, 10));
DropPodIncoming steelPod = Buy(ship, Fixtures.Stack(ThingDefOf.Steel, 50));
T.Check(medical.ContainsCell(medPod.Position), "medicine falls on " + medPod.Position + ", not in the medicine zone");
T.Check(general.ContainsCell(steelPod.Position), "steel falls on " + steelPod.Position + ", not in the general zone");
}
[BlaxTest("orbital: a fully roofed medicine zone sends medicine to the general zone")]
public static void RoofedZoneSkipped()
{
OnlyThisTestsZones();
CellRect area = Fixtures.TestArea(7, 2);
Zone_Delivery general = Fixtures.DeliveryZone(new CellRect(area.minX, area.minZ, 2, 2));
var medRect = new CellRect(area.maxX - 1, area.minZ, 2, 2);
Zone_Delivery medical = Fixtures.DeliveryZone(medRect, Fixtures.FilterOf(ThingDefOf.MedicineIndustrial), StoragePriority.Important);
Fixtures.Roof(medRect);
TradeShip ship = OrbitalTrader();
DropPodIncoming pod = Buy(ship, Fixtures.Stack(ThingDefOf.MedicineIndustrial, 10));
T.Check(!medical.ContainsCell(pod.Position), "medicine falls into the roofed medicine zone at " + pod.Position);
T.Check(general.ContainsCell(pod.Position), "medicine falls on " + pod.Position + ", not in the general zone");
}
[BlaxTest("orbital: a 1-cell zone with 5 stacks gets 1 pod, the other 4 land within 16 cells")]
public static void OneCellOverflow()
{
OnlyThisTestsZones();
Fixtures.Settings.overflowNearZone = true;
Fixtures.Settings.overflowRadius = BlaxZonesSettings.DefaultOverflowRadius;
CellRect area = Fixtures.TestArea(1, 1);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
IntVec3 vanilla = FixVanillaSpot(FarCell(area));
TradeShip ship = OrbitalTrader();
var pods = new List<DropPodIncoming>();
for (int i = 0; i < 5; i++)
pods.Add(Buy(ship, Fixtures.Stack(ThingDefOf.Steel, 50)));
T.Equal(1, pods.Count(p => zone.ContainsCell(p.Position)), "pods on the zone cell");
foreach (DropPodIncoming p in pods.Where(p => !zone.ContainsCell(p.Position)))
{
T.Check(p.Position != vanilla, "an overflow pod went to the vanilla spot " + vanilla);
int d = DistanceToZone(zone, p.Position);
T.Check(d <= BlaxZonesSettings.DefaultOverflowRadius, "an overflow pod falls " + d + " cells from the zone, at " + p.Position);
}
}
[BlaxTest("orbital: an L-shaped zone whose centroid is a wall still overflows next to the zone")]
public static void LShapeOverflow()
{
OnlyThisTestsZones();
Fixtures.Settings.overflowNearZone = true;
Fixtures.Settings.overflowRadius = BlaxZonesSettings.DefaultOverflowRadius;
CellRect area = Fixtures.TestArea(5, 5);
// Bottom row and left column: 9 cells, centroid (1.1, 1.1) from the corner, outside the L.
Zone_Delivery zone = Fixtures.DeliveryZone(new CellRect(area.minX, area.minZ, 5, 1));
for (int dz = 1; dz < 5; dz++)
zone.AddCell(new IntVec3(area.minX, 0, area.minZ + dz));
T.Equal(9, zone.CellCount, "L-shaped zone cells");
IntVec3 centroid = new IntVec3((int)Math.Round(zone.Cells.Average(c => c.x)), 0, (int)Math.Round(zone.Cells.Average(c => c.z)));
T.Check(!zone.ContainsCell(centroid), "the L's centroid " + centroid + " is a zone cell; the test needs it outside");
Fixtures.Wall(centroid);
T.Equal(9, zone.CellCount, "zone cells after the wall on the centroid");
IntVec3 vanilla = FixVanillaSpot(FarCell(area));
TradeShip ship = OrbitalTrader();
var pods = new List<DropPodIncoming>();
for (int i = 0; i < zone.CellCount + 1; i++)
pods.Add(Buy(ship, Fixtures.Stack(ThingDefOf.Steel, 50)));
T.Equal(zone.CellCount, pods.Count(p => zone.ContainsCell(p.Position)), "pods on zone cells");
DropPodIncoming overflow = pods.Last();
T.Check(!zone.ContainsCell(overflow.Position), "the last pod falls on a zone cell that already had one");
T.Check(overflow.Position != vanilla, "the overflow pod went to the vanilla spot " + vanilla);
int d = DistanceToZone(zone, overflow.Position);
T.Check(d <= BlaxZonesSettings.DefaultOverflowRadius, "the overflow pod falls " + d + " cells from the zone, at " + overflow.Position);
}
[BlaxTest("orbital: with no zones the pod lands at vanilla's TradeDropSpot")]
public static void NoZonesVanilla()
{
OnlyThisTestsZones();
IntVec3 beacon;
ZoneRectWithBeacon(3, 3, out beacon);
ObserveVanillaSpot();
TradeShip ship = OrbitalTrader();
DropPodIncoming pod = Buy(ship, Fixtures.Stack(ThingDefOf.Steel, 50));
T.Check(VanillaSpot.Last.IsValid, "TradeDropSpot did not run");
T.Equal(VanillaSpot.Last, pod.Position, "pod cell vs vanilla TradeDropSpot");
T.Info("vanilla spot " + VanillaSpot.Last + " lies " + Chebyshev(VanillaSpot.Last, beacon) + " cells from the test beacon");
}
[BlaxTest("orbital: a bought animal is not routed")]
public static void AnimalNotRouted()
{
OnlyThisTestsZones();
Zone_Delivery zone = Fixtures.DeliveryZone(ZoneRectWithBeacon(3, 3, out _));
ObserveVanillaSpot();
TradeShip ship = OrbitalTrader();
Pawn chicken = Fixtures.Animal(ThingDefOf.Chicken, tamed: false);
DropPodIncoming pod = Buy(ship, chicken);
T.Check(!zone.ContainsCell(pod.Position), "the chicken's pod falls into the zone at " + pod.Position);
T.Equal(VanillaSpot.Last, pod.Position, "chicken pod cell vs vanilla TradeDropSpot");
}
[BlaxTest("orbital: with zones away from every beacon, 20 center-drop raid spawn centers never land in a zone")]
public static void RaidsNeverTargetZones()
{
Map map = Fixtures.Map;
Fixtures.DeliveryZone(ZoneRectWithBeacon(4, 4, out _));
Fixtures.DeliveryZone(Fixtures.TestArea(4, 4));
T.Check(map.listerBuildings.ColonistsHaveBuildingWithPowerOn(ThingDefOf.OrbitalTradeBeacon), "no powered trade beacon");
ObserveVanillaSpot();
Faction raiders = Fixtures.HostileFaction();
var worker = (PawnsArrivalModeWorker_CenterDrop)PawnsArrivalModeDefOf.CenterDrop.Worker;
int beaconCalls = 0, vanillaCloseHits = 0;
Rand.PushState(20261129);
try
{
for (int i = 0; i < 20; i++)
{
VanillaSpot.Calls = 0;
var parms = new IncidentParms { target = map, faction = raiders, raidArrivalMode = PawnsArrivalModeDefOf.CenterDrop };
T.Check(worker.TryResolveRaidSpawnCenter(parms), "TryResolveRaidSpawnCenter failed on call " + (i + 1));
IntVec3 center = parms.spawnCenter;
bool inZone = center.IsValid && center.InBounds(map) && map.zoneManager.ZoneAt(center) is Zone_Delivery;
if (VanillaSpot.Calls > 0)
{
beaconCalls++;
T.Check(!inZone, "raid spawn center " + parms.spawnCenter + " from the beacon is a delivery zone cell (call " + (i + 1) + ")");
}
else if (inZone)
{
vanillaCloseHits++;
}
}
}
finally
{
Rand.PopState();
}
T.Check(beaconCalls > 0, "none of the 20 calls took the beacon branch (40% each)");
T.Info(beaconCalls + " of 20 centers came from TradeDropSpot");
if (vanillaCloseHits > 0)
T.Info(vanillaCloseHits + " centers from vanilla's close drop near a colonist fell in a zone; Zones does not touch that path");
}
[BlaxTest("orbital: another mod's TradeDropSpot is the fallback, and a zone still wins")]
public static void ComposesWithTradeDropSpotPrefix()
{
OnlyThisTestsZones();
CellRect area = Fixtures.TestArea(3, 3);
IntVec3 fixedSpot = FixVanillaSpot(FarCell(area));
TradeShip ship = OrbitalTrader();
DropPodIncoming noZone = Buy(ship, Fixtures.Stack(ThingDefOf.Steel, 50));
T.Equal(fixedSpot, noZone.Position, "pod cell with no zone vs the prefix's spot");
Zone_Delivery zone = Fixtures.DeliveryZone(area);
DropPodIncoming withZone = Buy(ship, Fixtures.Stack(ThingDefOf.Steel, 50));
T.Check(zone.ContainsCell(withZone.Position), "with a zone the pod falls on " + withZone.Position + ", not in the zone");
}
[BlaxTest("orbital: after 300 ticks the item lies within 1 cell of the zone")]
public static void ItemLandsAfterTicks()
{
OnlyThisTestsZones();
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3));
TradeShip ship = OrbitalTrader();
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
steel.SetForbidden(true, warnOnFail: false); // keeps haulers away while the game ticks
DropPodIncoming pod = Buy(ship, steel);
// Impact after 120 to 200 ticks (SkyfallerProperties.ticksToImpactRange), then the pod opens after 110 (ActiveTransporterInfo.openDelay).
int needed = pod.ticksToImpact + 110 + 2;
Fixtures.Tick(300);
int extra = 0;
while (!steel.Spawned && !steel.Destroyed && 300 + extra < needed + 20)
{
Fixtures.Tick(1);
extra++;
}
if (extra > 0)
T.Info("the pod needed " + extra + " ticks past 300 (impact in " + (needed - 112) + " ticks, then the 110-tick open delay)");
T.Check(!steel.Destroyed, "the steel was destroyed or merged away");
T.Check(steel.Spawned, "the steel is not on the map after " + (300 + extra) + " ticks; it is in " + steel.ParentHolder);
int d = DistanceToZone(zone, steel.Position);
T.Check(d <= 1, "the steel lies " + d + " cells from the zone, at " + steel.Position);
}
[BlaxTest("orbital: when the router throws, the steel lands at the vanilla spot and Zones logs one error")]
public static void RouterThrowsFallsBack()
{
OnlyThisTestsZones();
Zone_Delivery zone = Fixtures.DeliveryZone(ZoneRectWithBeacon(3, 3, out _));
ObserveVanillaSpot();
TradeShip ship = OrbitalTrader();
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
ZonesLog.ResetOnce(); // the error is logged once per game; an earlier failure must not hide it
ZonesTestHooks.RouterThrows = true;
T.ExpectErrors("[Blax Zones]", 1);
DropPodIncoming pod = Buy(ship, steel);
T.Check(VanillaSpot.Last.IsValid, "TradeDropSpot did not run");
T.Check(!zone.ContainsCell(VanillaSpot.Last), "vanilla's spot " + VanillaSpot.Last + " is a zone cell, so the test can't tell");
T.Equal(VanillaSpot.Last, pod.Position, "pod cell vs vanilla TradeDropSpot");
}
[BlaxTest("orbital: the transpiler replaced exactly one SpawnDropPod call and logged no unexpected call count")]
public static void TranspilerCount()
{
T.Equal(1, Patch_TradeShip_GiveSoldThingToPlayer.LastCallCount, "Patch_TradeShip_GiveSoldThingToPlayer.LastCallCount");
// Errors only: the runner logs test names as messages, and a name may contain the phrase.
bool logged = Log.Messages.Any(m => m.type == LogMessageType.Error && m.text != null && m.text.Contains("[Blax Zones]") && m.text.Contains("unexpected call count"));
T.Check(!logged, "the log has an 'unexpected call count' error");
MethodInfo give = AccessTools.Method(typeof(TradeShip), nameof(TradeShip.GiveSoldThingToPlayer));
Patches info = Harmony.GetPatchInfo(give);
T.Check(info != null && info.Transpilers.Any(p => p.owner == BlaxZonesStartup.HarmonyId), "no Blax Zones transpiler on TradeShip.GiveSoldThingToPlayer");
Patches spot = Harmony.GetPatchInfo(VanillaSpot.Target);
bool ours = spot != null && spot.Prefixes.Concat(spot.Postfixes).Concat(spot.Transpilers).Concat(spot.Finalizers)
.Any(p => p.owner == BlaxZonesStartup.HarmonyId);
T.Check(!ours, "Blax Zones patches DropCellFinder.TradeDropSpot");
}
[BlaxTest("orbital: with Route orbital trade off the pod lands at the vanilla spot")]
public static void RouteOrbitalOff()
{
OnlyThisTestsZones();
Zone_Delivery zone = Fixtures.DeliveryZone(ZoneRectWithBeacon(3, 3, out _));
ObserveVanillaSpot();
Fixtures.Settings.routeOrbital = false;
TradeShip ship = OrbitalTrader();
DropPodIncoming pod = Buy(ship, Fixtures.Stack(ThingDefOf.Steel, 50));
T.Check(!zone.ContainsCell(pod.Position), "the pod falls into the zone at " + pod.Position + " with routing off");
T.Equal(VanillaSpot.Last, pod.Position, "pod cell vs vanilla TradeDropSpot");
}
// ---- helpers ---------------------------------------------------------------------
/// <summary>
/// An orbital trade ship of the kind (default: the first orbital kind without a faction, by defName),
/// on the current map's passing ships. Its stock is not generated; tests hand it the things to sell.
/// Removed from the map after the test.
/// </summary>
private static TradeShip OrbitalTrader(TraderKindDef kind = null)
{
kind ??= DefDatabase<TraderKindDef>.AllDefsListForReading
.Where(k => k.orbital && k.faction == null).OrderBy(k => k.defName).FirstOrDefault();
T.NotNull(kind, "an orbital TraderKindDef");
T.Check(kind.orbital, kind.defName + " is not an orbital trader");
var ship = new TradeShip(kind);
Map map = Fixtures.Map;
map.passingShipManager.AddShip(ship);
Fixtures.OnCleanup(() =>
{
ship.passingShipManager?.RemoveShip(ship);
ship.GetDirectlyHeldThings()?.ClearAndDestroyContents();
});
T.Check(ship.Map == map, "trade ship is not on the current map");
return ship;
}
/// <summary>
/// The player buys the whole stack from the ship, as the trade dialog does (Tradeable.cs:472-478).
/// Returns the incoming drop pod that holds it, tracked for cleanup. Never ticks.
/// </summary>
private static DropPodIncoming Buy(TradeShip ship, Thing thing)
{
if (!(thing is Pawn))
Fixtures.Track(thing); // fixture pawns are cleaned up by Fixtures; the pod's cleanup takes them too
ship.GiveSoldThingToPlayer(thing, thing.stackCount, Negotiator());
Thing holder = thing.SpawnedParentOrMe;
T.Check(holder is DropPodIncoming, thing.LabelShort + " is not in an incoming drop pod but in " + (holder?.ToString() ?? "nothing spawned"));
return Fixtures.Track((DropPodIncoming)holder);
}
/// <summary>A free colonist already on the map, or a fixture one.</summary>
private static Pawn Negotiator() =>
Fixtures.Map.mapPawns.FreeColonistsSpawned.Where(p => !p.Dead).OrderBy(p => p.thingIDNumber).FirstOrDefault() ?? Fixtures.Colonist();
/// <summary>
/// Turns the orbital 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.
/// </summary>
private static void OnlyThisTestsZones()
{
var off = new List<Zone_Delivery>();
foreach (Zone z in Fixtures.Map.zoneManager.AllZones)
{
if (z is Zone_Delivery d && d.acceptOrbital)
{
d.acceptOrbital = false;
off.Add(d);
}
}
Fixtures.OnCleanup(() =>
{
foreach (Zone_Delivery d in off)
d.acceptOrbital = true;
});
}
/// <summary>
/// A w x h zone rect at the west end of a test area, with a powered trade beacon BeaconGap cells
/// east of it. Vanilla's TradeDropSpot takes the first unroofed beacon and looks within 5 cells of
/// it first (DropCellFinder.cs:30-40, 270-276), so its spot stays off the zone.
/// </summary>
private static CellRect ZoneRectWithBeacon(int w, int h, out IntVec3 beacon)
{
CellRect area = Fixtures.TestArea(w + BeaconGap, h);
beacon = new IntVec3(area.maxX, 0, area.minZ + h / 2);
Fixtures.PoweredBeacon(beacon);
return new CellRect(area.minX, area.minZ, w, h);
}
/// <summary>A good drop spot, outside every zone, at least FarSpotDistance cells from the rect. Scans in a fixed order.</summary>
private static IntVec3 FarCell(CellRect awayFrom)
{
Map map = Fixtures.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)
continue;
if (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;
}
/// <summary>A test-only prefix makes TradeDropSpot return the cell, as Trade Ships Drop Spot or Trading Control would. Unpatched after the test.</summary>
private static IntVec3 FixVanillaSpot(IntVec3 cell)
{
VanillaSpot.Install(cell);
return cell;
}
/// <summary>A test-only postfix records what vanilla's TradeDropSpot returned. Unpatched after the test.</summary>
private static void ObserveVanillaSpot() => VanillaSpot.Install(null);
private static int Chebyshev(IntVec3 a, IntVec3 b) => Math.Max(Math.Abs(a.x - b.x), Math.Abs(a.z - b.z));
private 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);
}
/// <summary>Cells from the nearest zone cell, as the overflow search measures it (a square radius, CellFinder.cs:351-357).</summary>
private static int DistanceToZone(Zone zone, IntVec3 c) => zone.Cells.Count == 0 ? int.MaxValue : zone.Cells.Min(z => Chebyshev(z, c));
/// <summary>
/// Test-only patches on DropCellFinder.TradeDropSpot: a prefix that returns Fixed when set, and a
/// postfix that records every result. Blax Zones itself never patches this method.
/// </summary>
internal static class VanillaSpot
{
private const string HarmonyId = "blax.zones.tests.orbital";
private static Harmony harmony;
private static bool patched;
public static readonly MethodInfo Target = AccessTools.Method(typeof(DropCellFinder), nameof(DropCellFinder.TradeDropSpot), new[] { typeof(Map) });
public static IntVec3? Fixed;
public static IntVec3 Last = IntVec3.Invalid;
public static int Calls;
public static void Install(IntVec3? fixedCell)
{
T.NotNull(Target, "DropCellFinder.TradeDropSpot(Map)");
Fixed = fixedCell;
Last = IntVec3.Invalid;
Calls = 0;
if (patched)
return;
harmony ??= new Harmony(HarmonyId);
harmony.Patch(Target,
prefix: new HarmonyMethod(AccessTools.Method(typeof(VanillaSpot), nameof(Prefix))),
postfix: new HarmonyMethod(AccessTools.Method(typeof(VanillaSpot), nameof(Postfix))));
patched = true;
Fixtures.OnCleanup(Uninstall);
}
private static void Uninstall()
{
Fixed = null;
if (!patched)
return;
patched = false;
harmony.Unpatch(Target, HarmonyPatchType.All, HarmonyId);
}
public static bool Prefix(ref IntVec3 __result)
{
if (!Fixed.HasValue)
return true;
__result = Fixed.Value;
return false;
}
public static void Postfix(IntVec3 __result)
{
Last = __result;
Calls++;
}
}
}
}