feat: Blax Zones 1.0: delivery zones, orbital purchases, caravan camps

Orbital purchases land in a delivery zone picked by item filter and priority, with overflow only to cells colonists can reach. Caravans and tribute collectors camp next to a chosen zone. ZonesApi lets other mods request drop spots. Works with any DLC combination; tested on core only, every Royalty/Ideology/Biotech combination and with the compat mod set.
This commit is contained in:
Fabian @ Blax Software 2026-11-29 19:27:08 +01:00
parent 09a1bc6c52
commit d8d7e3d3c0
53 changed files with 6852 additions and 4 deletions

9
.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
Source/**/bin/
Source/**/obj/
.vs/
*.user
Tests/**/1.7/
Tests/**/bin/
Tests/**/obj/
Tools/**/bin/
Tools/**/obj/

Binary file not shown.

Binary file not shown.

39
About/About.xml Normal file
View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<ModMetaData>
<name>Blax Zones</name>
<author>Blax Gaming</author>
<packageId>blax.zones</packageId>
<modVersion>1.0.0</modVersion>
<supportedVersions>
<li>1.7</li>
</supportedVersions>
<modDependencies>
<li>
<packageId>brrainz.harmony</packageId>
<displayName>Harmony</displayName>
<steamWorkshopUrl>steam://url/CommunityFilePage/2009463077</steamWorkshopUrl>
<downloadUrl>https://github.com/pardeike/HarmonyRimWorld/releases/latest</downloadUrl>
</li>
</modDependencies>
<loadAfter>
<li>brrainz.harmony</li>
<li>blax.castes</li>
</loadAfter>
<description>Delivery zones and caravan camps. Works with any DLC combination, core only included.
&lt;color=#19C63C&gt;Delivery zones&lt;/color&gt;
- Drag a delivery zone like a stockpile. What you buy from orbital traders lands in it, sorted by item filter and priority: medicine by the hospital, steel by the workshop.
- When every cell is taken, pods land next to the zone. With no fitting zone they land where they always did.
- While the zone is selected, red outlines mark cells drop pods can't use: roofed, water, inside an enclosed pen, blocked or unreachable.
&lt;color=#19C63C&gt;Caravan camps&lt;/color&gt;
- Tick "Caravans camp here" on a delivery zone, and visiting trader caravans and tribute collectors (Royalty) camp next to it.
&lt;color=#19C63C&gt;Safe to remove&lt;/color&gt;
- Blax zones live in their own save data. Unsubscribe and the save still loads: the delivery zones are gone, vanilla zones stay.
Multiplayer: not supported yet.
&lt;color=#19C63C&gt;Made by Blax&lt;/color&gt;
Blax Gaming is a project of Blax Software, an Austrian software practice. We write Austrian-quality code in many fields: web platforms, mobile apps, backends, infrastructure, and the mods we play in our own colonies. www.blax.at</description>
</ModMetaData>

15
CHANGELOG.md Normal file
View File

@ -0,0 +1,15 @@
# Changelog
## 1.0.0
- Delivery zones: "Delivery zone" sits in the Zone menu right after "Growing zone" and is dragged like a stockpile. It draws amber and has an Expand gizmo. Like every zone, it extends the home area 4 cells around itself while auto home area is on.
- Delivery tab: a priority from Low to Critical, "Orbital trade lands here" (on), "Caravans camp here" (off) and an item filter that allows every item. Corpses and, with Biotech, Wastepack never land in a zone and are hidden from the filter. Copy settings and Paste settings move the filter, the priority and both checkboxes from one delivery zone to another.
- While a delivery zone is selected, red outlines mark the cells drop pods can't use: roofed, water, inside an enclosed animal pen, blocked by a building, fogged, or out of your colonists' reach. The inspect pane counts them.
- Orbital purchases land in the zone: everything bought from an orbital trader, plus the silver from selling, drops into the best matching delivery zone instead of next to the trade beacon. The zone's filter decides what fits, then the highest priority wins, then the oldest zone. Pods spread over the free cells, nearest the zone's middle first, and join a matching stack once every free cell is taken.
- When every cell of the top zone is taken, pods land next to it on a cell your colonists can reach, within 16 cells by default (5 to 30). Overflow from a zone your colonists can't reach lands at the vanilla spot. With "Overflow lands next to the zone" off, they land at the vanilla spot.
- Bought people and animals, raids, ransom payments and returning lent colonists land as before. With no fitting zone the pod lands at the vanilla spot, and so does it if anything in Blax Zones goes wrong, so no item is ever lost. Another mod that moves the vanilla drop spot keeps working as the fallback.
- Trader caravans camp at a zone: with "Caravans camp here" ticked, visiting trader caravans and, with Royalty, tribute collectors gather within 6 cells of the zone, on open ground they can all reach. Goods bought from them drop at their pack animals' feet, right beside the zone. Visitor groups and Hospitality guests pick their own spot. Camping stands down, with one log line, while Trading Spot Rewritten, [KV] Trading Spot, [GMT] Trading Spot or Trading Control is active.
- Save-safe zone storage: delivery zones are saved with Blax Zones' own map data, never in the game's zone list. Unsubscribing leaves a save that loads: the delivery zones are gone, vanilla zones stay, and the log shows two errors per map. Blax Zones can be added to a running save.
- Settings: Delivery zones (hides the designator; existing zones stay), Route orbital trade, Overflow lands next to the zone with its radius, Caravans may camp at zones, Reset to defaults.
- Works with any DLC combination, core only included.
- For other mods: `BlaxZones.ZonesApi` version 1, `TryFindDropSpot(Map, Thing, out IntVec3)`, returns the delivery zone cell a drop pod with that thing should land on, by the same rules as orbital trade.

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Shared keys (integrator). Each work package keeps its own keys in BlaxZones_<package>.xml. -->
<!-- Zones -->
<BlaxZones_DeliveryZone>Delivery zone</BlaxZones_DeliveryZone>
<BlaxZones_NeedsDlc>Needs {0}</BlaxZones_NeedsDlc>
<!-- Settings -->
<BlaxZones_SettingDeliveryZones>Delivery zones</BlaxZones_SettingDeliveryZones>
<BlaxZones_SettingDeliveryZonesTip>Shows "Delivery zone" in the Zone menu. Off hides it; existing delivery zones stay and still receive deliveries.</BlaxZones_SettingDeliveryZonesTip>
<BlaxZones_SettingRouteOrbital>Route orbital trade</BlaxZones_SettingRouteOrbital>
<BlaxZones_SettingRouteOrbitalTip>What you buy from orbital traders, and the silver from selling, lands in the best matching delivery zone instead of next to a trade beacon. Off: pods land where they always did.</BlaxZones_SettingRouteOrbitalTip>
<BlaxZones_SettingOverflowNearZone>Overflow lands next to the zone</BlaxZones_SettingOverflowNearZone>
<BlaxZones_SettingOverflowNearZoneTip>When every cell of the zone is taken, pods land near the top zone. Off: they land where they always did.</BlaxZones_SettingOverflowNearZoneTip>
<BlaxZones_SettingOverflowRadius>Overflow radius: {0} cells</BlaxZones_SettingOverflowRadius>
<BlaxZones_SettingOverflowRadiusTip>How far from the zone overflow pods may land, from 5 to 30.</BlaxZones_SettingOverflowRadiusTip>
<BlaxZones_SettingCampAtZones>Caravans may camp at zones</BlaxZones_SettingCampAtZones>
<BlaxZones_SettingCampAtZonesTip>Trader caravans and tribute collectors camp next to a delivery zone that has "Caravans camp here" ticked. Visitor groups don't.</BlaxZones_SettingCampAtZonesTip>
<BlaxZones_SettingsReset>Reset to defaults</BlaxZones_SettingsReset>
</LanguageData>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Package Camp: its own keys only, prefixed BlaxZones_. -->
</LanguageData>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Package Designators: its own keys only, prefixed BlaxZones_. -->
<BlaxZones_DesignatorDeliveryZoneDesc>Mark a landing area for drop pods. What you buy from orbital traders, and the silver from selling, lands here. Each zone's tab sets what may land there and its priority.\n\nLike every zone, it extends the home area 4 cells around itself while auto home area is on.</BlaxZones_DesignatorDeliveryZoneDesc>
</LanguageData>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Package Orbital: its own keys only, prefixed BlaxZones_. -->
</LanguageData>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Package Router: its own keys only, prefixed BlaxZones_. -->
</LanguageData>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Package Rules: its own keys only, prefixed BlaxZones_. -->
<!-- Delivery zone inspect pane: cells failing the drop pod rule (roof, pen, water, building, fog, unreachable). -->
<BlaxZones_UnusableCells>{0} cells drop pods can't use</BlaxZones_UnusableCells>
<BlaxZones_UnusableCell>1 cell drop pods can't use</BlaxZones_UnusableCell>
</LanguageData>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Package Store: its own keys only, prefixed BlaxZones_. -->
</LanguageData>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Package Tab: its own keys only, prefixed BlaxZones_. -->
<!-- Tab -->
<BlaxZones_TabDelivery>Delivery</BlaxZones_TabDelivery>
<BlaxZones_PriorityTip>Deliveries try the zone with the highest priority first. Zones with the same priority go oldest first.</BlaxZones_PriorityTip>
<BlaxZones_AcceptOrbital>Orbital trade lands here</BlaxZones_AcceptOrbital>
<BlaxZones_AcceptOrbitalTip>What you buy from orbital traders, and the silver from selling, lands here when the item filter allows it.</BlaxZones_AcceptOrbitalTip>
<BlaxZones_AcceptOrbitalSlavesTip>Also Blax Slaves payouts (ransom, buy-back, wages).</BlaxZones_AcceptOrbitalSlavesTip>
<BlaxZones_AcceptOrbitalOffTip>"Route orbital trade" is off in the mod settings, so nothing lands here now.</BlaxZones_AcceptOrbitalOffTip>
<BlaxZones_AcceptOrbitalOffSlavesTip>"Route orbital trade" is off in the mod settings, so orbital trade doesn't land here now. Blax Slaves payouts still do.</BlaxZones_AcceptOrbitalOffSlavesTip>
<BlaxZones_CampHere>Caravans camp here</BlaxZones_CampHere>
<BlaxZones_CampHereTip>Trader caravans and tribute collectors camp next to this zone instead of a random spot outside the colony. Visitor groups don't.</BlaxZones_CampHereTip>
<BlaxZones_CampHereOffTip>"Caravans may camp at zones" is off in the mod settings, so no caravan camps here now.</BlaxZones_CampHereOffTip>
<BlaxZones_CampHereStandDownTip>{0} is active and places caravans itself, so no caravan camps here.</BlaxZones_CampHereStandDownTip>
<!-- Copy and paste -->
<BlaxZones_CopySettings>Copy settings</BlaxZones_CopySettings>
<BlaxZones_CopySettingsDesc>Copy this delivery zone's item filter, priority and checkboxes.</BlaxZones_CopySettingsDesc>
<BlaxZones_PasteSettings>Paste settings</BlaxZones_PasteSettings>
<BlaxZones_PasteSettingsDesc>Paste the copied item filter, priority and checkboxes into this delivery zone. Its cells stay as they are.</BlaxZones_PasteSettingsDesc>
<BlaxZones_SettingsCopied>Copied delivery zone settings.</BlaxZones_SettingsCopied>
<BlaxZones_SettingsPasted>Pasted delivery zone settings.</BlaxZones_SettingsPasted>
<BlaxZones_NothingCopied>Copy a delivery zone's settings first.</BlaxZones_NothingCopied>
</LanguageData>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Package Designators: insert BlaxZones.Designator_ZoneAdd_Delivery after Designator_ZoneAdd_Growing in the Zone category.
Anchored on Growing (Core Misc/Designations/DesignationCategories.xml:40), not on Fishing, whose entry carries MayRequire Odyssey. -->
<Patch>
<Operation Class="PatchOperationInsert">
<xpath>Defs/DesignationCategoryDef[defName="Zone"]/specialDesignatorClasses/li[text()="Designator_ZoneAdd_Growing"]</xpath>
<order>Append</order>
<value>
<li>BlaxZones.Designator_ZoneAdd_Delivery</li>
</value>
</Operation>
</Patch>

View File

@ -1,12 +1,25 @@
# Blax Zones
[![RimWorld 1.7](https://img.shields.io/badge/RimWorld-1.7-19C63C)](https://rimworldgame.com)
[![Status: planned](https://img.shields.io/badge/status-planned-5a6b5d)](docs/design.md)
[![Status: 1.0 in progress](https://img.shields.io/badge/status-1.0_in_progress-CDCDCD)](docs/design.md)
RimWorld 1.7 mod, planned (Blax Gaming). No code yet.
Drag a zone and bought goods land where you want them; drag another over the barn and every animal has a bed. A RimWorld 1.7 mod by Blax Gaming. Version 1.0 (delivery zones, orbital purchases and caravan camps) is built and in testing; each feature names the release it comes in. Needs Harmony.
- 📦 **Delivery zones.** What you buy from orbital or caravan traders, plus quest and royal rewards, lands in a zone you drag, sorted by item filter: medicine by the hospital, steel by the workshop.
- 🛏️ **Sleeping zones.** Every cell is a sleeping spot for colonists, slaves, prisoners or animals. Drag one over the barn and every chicken has a bed.
- 📦 **Delivery zones (1.0).** What you buy from orbital traders lands in a zone you drag, sorted by item filter and priority: medicine by the hospital, steel by the workshop.
- 🐪 **Caravan camps (1.0).** Trader caravans and tribute collectors camp next to a zone you pick.
- 🎁 **Quest rewards (1.1).** Item rewards from quests drop into the zone too.
- 🛒 **Caravan purchases (1.1).** Goods bought from trader caravans and Hospitality guests appear in the zone, even a roofed one.
- 🐔 **Animal sleeping zones (1.2).** Every cell is a sleeping spot. Drag one over the barn and every chicken has a bed.
- 🐄 **Which animals sleep where (1.2).** Species and body-size filters, so big stalls stay free of chickens.
- 🧹 **Safe to remove (1.2).** A button in the mod settings strips everything from a save first. Without it, a save still loads after you unsubscribe.
- 🗄️ **Straight into storage (1.3).** Stockpiles, shelves, racks and fridges can receive deliveries directly. Optional, off by default: goods appear under a roof without a drop pod.
- 💰 **Sell zones (1.3).** Optional, off by default, needs a powered trade beacon: orbital traders buy from flagged storage, no hauling to the beacon.
- 🪂 **Cargo pods (1.3).** Optional, off by default: random cargo pod events land in a zone you pick.
- 🛏️ **People sleeping zones (1.4).** Dorms and prisons for colonists, slaves and prisoners, one cell per sleeper.
- 🏥 **Medical and shared zones (1.4).** A whole zone as an infirmary, or cells nobody keeps.
- 🏷️ **Castes (1.5).** With Blax Castes, people sleeping zones can be limited by caste.
Works with any DLC combination, core only included. Only slave sleeping zones need a DLC (Ideology); tribute collectors and Empire quest rewards arrive only with Royalty.
Design and roadmap: `docs/design.md`.

View File

@ -0,0 +1,46 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- RimWorld 1.7 runs on .NET 10 (CoreCLR). Build: dotnet build -c Release -->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<AssemblyName>BlaxZones</AssemblyName>
<RootNamespace>BlaxZones</RootNamespace>
<LangVersion>latest</LangVersion>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<OutputPath>..\..\1.7\Assemblies\</OutputPath>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
<GenerateDependencyFile>false</GenerateDependencyFile>
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
<DebugType>portable</DebugType>
<Deterministic>true</Deterministic>
<!-- The SDK appends the git commit to the informational version, so every commit would change the
next build and the committed DLL could never match HEAD. Same source, same bytes. -->
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<!-- Keep local paths out of the shipped DLL/PDB. -->
<PathMap>$(MSBuildProjectDirectory)=Source/BlaxZones</PathMap>
</PropertyGroup>
<!-- Override on the command line if the game or the Harmony mod live elsewhere. -->
<PropertyGroup>
<RimWorldDir Condition="'$(RimWorldDir)' == ''">E:\SteamLibrary\steamapps\common\RimWorld</RimWorldDir>
<HarmonyDir Condition="'$(HarmonyDir)' == ''">E:\SteamLibrary\steamapps\workshop\content\294100\2009463077\1.7\Assemblies</HarmonyDir>
</PropertyGroup>
<ItemGroup>
<Reference Include="Assembly-CSharp">
<HintPath>$(RimWorldDir)\Assembly-CSharp.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="UnityStubs">
<HintPath>$(RimWorldDir)\UnityStubs.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="0Harmony">
<HintPath>$(HarmonyDir)\0Harmony.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
</Project>

View File

@ -0,0 +1,132 @@
using System;
using HarmonyLib;
using UnityEngine;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Global settings. Every feature has a toggle; zone storage has none, it is the save format.
/// Per-zone choices live on the zone (Zone_Delivery), not here.
/// </summary>
public class BlaxZonesSettings : ModSettings
{
/// <summary>The delivery zone designators show in the Zone menu. Off hides them; existing zones stay and still route.</summary>
public bool deliveryZones = true;
/// <summary>What the player buys from orbital traders, and the silver from selling, lands in delivery zones.</summary>
public bool routeOrbital = true;
/// <summary>When every zone cell is taken, pods land next to the top zone. Off: overflow goes to the vanilla spot.</summary>
public bool overflowNearZone = true;
/// <summary>How far from the top zone overflow pods may land. Never below 5: the vanilla search can hang below it.</summary>
public int overflowRadius = DefaultOverflowRadius;
/// <summary>Trader caravans and tribute collectors camp next to a zone with "Caravans camp here" ticked.</summary>
public bool campAtZones = true;
public const int DefaultOverflowRadius = 16;
public const int MinOverflowRadius = 5;
public const int MaxOverflowRadius = 30;
/// <summary>The overflow radius as the router must use it, clamped to 5..30 whatever the file says.</summary>
public int OverflowRadiusClamped => Mathf.Clamp(overflowRadius, MinOverflowRadius, MaxOverflowRadius);
public override void ExposeData()
{
base.ExposeData();
Scribe_Values.Look(ref deliveryZones, "deliveryZones", true);
Scribe_Values.Look(ref routeOrbital, "routeOrbital", true);
Scribe_Values.Look(ref overflowNearZone, "overflowNearZone", true);
Scribe_Values.Look(ref overflowRadius, "overflowRadius", DefaultOverflowRadius);
Scribe_Values.Look(ref campAtZones, "campAtZones", true);
if (Scribe.mode == LoadSaveMode.PostLoadInit || Scribe.mode == LoadSaveMode.LoadingVars)
overflowRadius = Mathf.Clamp(overflowRadius, MinOverflowRadius, MaxOverflowRadius);
}
public void Reset()
{
var d = new BlaxZonesSettings();
deliveryZones = d.deliveryZones;
routeOrbital = d.routeOrbital;
overflowNearZone = d.overflowNearZone;
overflowRadius = d.overflowRadius;
campAtZones = d.campAtZones;
}
}
public class BlaxZonesMod : Mod
{
public static BlaxZonesSettings Settings;
/// <summary>The settings, or defaults before the mod class exists, so nothing reads null while loading.</summary>
public static BlaxZonesSettings S => Settings ?? (fallback ??= new BlaxZonesSettings());
private static BlaxZonesSettings fallback;
public BlaxZonesMod(ModContentPack content) : base(content)
{
Settings = GetSettings<BlaxZonesSettings>();
}
public override string SettingsCategory() => "Blax Zones";
public override void DoSettingsWindowContents(Rect inRect)
{
BlaxZonesSettings s = Settings;
var l = new Listing_Standard();
l.maxOneColumn = true;
l.Begin(inRect);
l.CheckboxLabeled("BlaxZones_SettingDeliveryZones".Translate(), ref s.deliveryZones, "BlaxZones_SettingDeliveryZonesTip".Translate());
l.CheckboxLabeled("BlaxZones_SettingRouteOrbital".Translate(), ref s.routeOrbital, "BlaxZones_SettingRouteOrbitalTip".Translate());
l.CheckboxLabeled("BlaxZones_SettingOverflowNearZone".Translate(), ref s.overflowNearZone, "BlaxZones_SettingOverflowNearZoneTip".Translate());
if (s.overflowNearZone)
{
s.overflowRadius = Mathf.RoundToInt(l.SliderLabeled("BlaxZones_SettingOverflowRadius".Translate(s.OverflowRadiusClamped),
s.OverflowRadiusClamped, BlaxZonesSettings.MinOverflowRadius, BlaxZonesSettings.MaxOverflowRadius, 0.6f,
"BlaxZones_SettingOverflowRadiusTip".Translate()));
s.overflowRadius = Mathf.Clamp(s.overflowRadius, BlaxZonesSettings.MinOverflowRadius, BlaxZonesSettings.MaxOverflowRadius);
}
l.GapLine();
l.CheckboxLabeled("BlaxZones_SettingCampAtZones".Translate(), ref s.campAtZones, "BlaxZones_SettingCampAtZonesTip".Translate());
l.Gap();
if (l.ButtonText("BlaxZones_SettingsReset".Translate()))
s.Reset();
l.End();
}
}
/// <summary>
/// Applies the Harmony patches after every Mod class exists (so the Harmony mod has set up
/// its 1.7 backend), one class at a time so a single broken target can't take the rest down.
/// </summary>
[StaticConstructorOnStartup]
public static class BlaxZonesStartup
{
public const string HarmonyId = "blax.zones";
public static readonly Harmony Harmony = new Harmony(HarmonyId);
/// <summary>Patch classes that failed to apply, by type name. Read by the smoke test.</summary>
public static readonly System.Collections.Generic.List<string> FailedPatches = new System.Collections.Generic.List<string>();
static BlaxZonesStartup()
{
int ok = 0;
foreach (Type type in typeof(BlaxZonesStartup).Assembly.GetTypes())
{
if (!type.IsDefined(typeof(HarmonyPatch), false))
continue;
try
{
Harmony.CreateClassProcessor(type).Patch();
ok++;
}
catch (Exception e)
{
FailedPatches.Add(type.Name);
Log.Error("[Blax Zones] Patch " + type.Name + " failed: " + e);
}
}
Log.Message("[Blax Zones] " + ok + " patches applied" + (FailedPatches.Count > 0 ? ", " + FailedPatches.Count + " failed" : ""));
}
}
}

View File

@ -0,0 +1,62 @@
using System;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Camp. Sets CampScope while a trader caravan (or tribute collector, which inherits the
/// method) arrives; the finalizer restores the previous value, even on an exception.
/// IncidentWorker_TraderCaravanArrival.cs:78-129: the one RCellFinder call is at :112, the lord with
/// the chill spot is made at :126-127. IncidentWorker_CaravanArrivalTributeCollector.cs:7 does not
/// override TryExecuteWorker, so the prefix on the base class covers it with no Royalty code.
/// </summary>
[HarmonyPatch(typeof(IncidentWorker_TraderCaravanArrival), "TryExecuteWorker")]
public static class Patch_TraderCaravanArrival_TryExecuteWorker
{
public static void Prefix(out bool __state)
{
__state = CampScope.Active;
CampScope.Active = true;
}
public static Exception Finalizer(bool __state, Exception __exception)
{
CampScope.Active = __state;
return __exception;
}
}
/// <summary>
/// Package Camp. The overload every TryFindRandomSpotJustOutsideColony call ends in
/// (RCellFinder.cs:714). While CampScope is active and a camp zone exists, returns a spot next to the
/// zone; otherwise vanilla runs. Visitor groups reach it too but never set CampScope.
/// </summary>
[HarmonyPatch(typeof(RCellFinder), nameof(RCellFinder.TryFindRandomSpotJustOutsideColony),
new[] { typeof(IntVec3), typeof(Map), typeof(Pawn), typeof(IntVec3), typeof(Predicate<IntVec3>) },
new[] { ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Out, ArgumentType.Normal })]
public static class Patch_RCellFinder_TryFindRandomSpotJustOutsideColony
{
/// <summary>Return false with __result true and result set to skip vanilla; true lets vanilla run.</summary>
public static bool Prefix(IntVec3 root, Map map, Pawn searcher, ref IntVec3 result, Predicate<IntVec3> extraValidator, ref bool __result)
{
if (!CampScope.Active)
return true;
try
{
if (CampScope.TryFindCampSpot(map, extraValidator, out IntVec3 cell))
{
result = cell;
__result = true;
return false;
}
}
catch (Exception e)
{
ZonesLog.Once("Caravan camp spot", e);
}
return true;
}
}
}

View File

@ -0,0 +1,140 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Camp. Design: 1.0 "Trader caravans camp at a zone". Set while
/// IncidentWorker_TraderCaravanArrival.TryExecuteWorker runs (tribute collectors inherit it), so the
/// RCellFinder prefix knows the spot it picks becomes a trader caravan's chill spot.
/// </summary>
public static class CampScope
{
/// <summary>Within 6 cells of the camp zone.</summary>
public const int Radius = 6;
[ThreadStatic] public static bool Active;
/// <summary>
/// A camp spot next to a delivery zone with campHere ticked: standable, unfogged, unroofed, within
/// Radius of the zone, passing the caller's extraValidator, cells outside enclosed rooms first.
/// False (vanilla runs) when no zone is ticked, the setting is off, a trading-spot mod is active
/// (Compat.ActiveTradingSpotMod() != null) or no cell passes.
///
/// Zones are tried by priority (highest first), then zone ID, the router's order. Within a zone the
/// cells come in four groups, each in random order: outside enclosed rooms and off delivery zones,
/// outside enclosed rooms on a delivery zone, then the same two inside enclosed rooms. Off-zone
/// cells come first so the pack animals stand beside the landing pad, not on it. Door cells are
/// never used. A null extraValidator accepts every cell.
/// </summary>
public static bool TryFindCampSpot(Map map, Predicate<IntVec3> extraValidator, out IntVec3 cell)
{
cell = IntVec3.Invalid;
if (map == null || !BlaxZonesMod.S.campAtZones)
return false;
// Zones was removed from this game (removal button): vanilla only.
if (MapComponent_BlaxZones.Of(map) == null || map.zoneManager == null)
return false;
List<Zone_Delivery> zones = CampZones(map);
if (zones.Count == 0)
return false;
string standDown = Compat.ActiveTradingSpotMod();
if (standDown != null)
{
ZonesLog.MessageOnce("camp-standdown:" + standDown, StandDownMessage(standDown));
return false;
}
foreach (Zone_Delivery zone in zones)
{
if (TryFindSpotNear(map, zone, extraValidator, out cell))
return true;
}
cell = IntVec3.Invalid;
return false;
}
/// <summary>The one-time log line when camping stands down for a trading-spot mod (without the "[Blax Zones] " prefix).</summary>
public static string StandDownMessage(string packageId) =>
"Caravan camps are off while " + packageId + " is active, because that mod picks where trader caravans gather.";
/// <summary>Delivery zones with "Caravans camp here" ticked, by priority (highest first), then zone ID.</summary>
public static List<Zone_Delivery> CampZones(Map map) =>
map.zoneManager.AllZones.OfType<Zone_Delivery>()
.Where(z => z.campHere && z.CellCount > 0)
.OrderByDescending(z => z.priority).ThenBy(z => z.ID)
.ToList();
/// <summary>Within Radius (straight-line) of one of the zone's cells.</summary>
public static bool WithinRadius(Zone zone, IntVec3 c)
{
foreach (IntVec3 z in zone.Cells)
{
if (c.InHorDistOf(z, Radius))
return true;
}
return false;
}
private static bool TryFindSpotNear(Map map, Zone_Delivery zone, Predicate<IntVec3> extraValidator, out IntVec3 cell)
{
var groups = new List<IntVec3>[4];
for (int g = 0; g < groups.Length; g++)
groups[g] = new List<IntVec3>();
var seen = new HashSet<IntVec3>();
int radial = GenRadial.NumCellsInRadius(Radius);
foreach (IntVec3 z in zone.Cells)
{
Consider(map, z, seen, groups);
// The zone cell nearest to any outside cell always has a neighbour outside the zone, so
// spreading from edge cells covers every cell within Radius.
if (!IsEdge(map, zone, z))
continue;
for (int i = 0; i < radial; i++)
Consider(map, z + GenRadial.RadialPattern[i], seen, groups);
}
foreach (List<IntVec3> group in groups)
{
group.Shuffle();
foreach (IntVec3 c in group)
{
if (extraValidator == null || extraValidator(c))
{
cell = c;
return true;
}
}
}
cell = IntVec3.Invalid;
return false;
}
private static void Consider(Map map, IntVec3 c, HashSet<IntVec3> seen, List<IntVec3>[] groups)
{
if (!seen.Add(c) || !c.InBounds(map))
return;
if (!c.Standable(map) || c.Fogged(map) || c.Roofed(map) || c.GetDoor(map) != null)
return;
Room room = c.GetRoom(map);
int group = room != null && !room.TouchesMapEdge ? 2 : 0;
if (map.zoneManager.ZoneAt(c) is Zone_Delivery)
group++;
groups[group].Add(c);
}
private static bool IsEdge(Map map, Zone zone, IntVec3 c)
{
for (int i = 0; i < 4; i++)
{
IntVec3 n = c + GenAdj.CardinalDirections[i];
if (!n.InBounds(map) || map.zoneManager.ZoneAt(n) != zone)
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,60 @@
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Camp. Trading-spot mods camping stands down for (design: 1.0 "Trader caravans camp at a
/// zone", Stand-down). Each id read from the mod's own About/About.xml (checked 2026-11-29):
/// - Trading Spot Rewritten (Workshop 3780903689): forge.elsie.cafe/NachoToast/TradingSpot, branch main,
/// the source link on its Workshop page. Supports 1.6 and 1.7.
/// - [KV] Trading Spot (1180719658): github.com/KiameV/rimworld-tradingspot, branch 1.2
/// (About/PublishedFileId.txt 1180719658). The master branch's About.xml carries another mod's
/// metadata ([KV] Change Dresser); Trading Control's About.xml lists the same id in incompatibleWith.
/// - [GMT] Trading Spot (2874517333): github.com/fl-modding/rimworld-TradingSpot, branch main
/// (About/PublishedFileId.txt 2874517333). The Workshop page links no source; this repository's
/// name, author (Grizzlemethis) and file id match it.
/// - Trading Control (2007107588): github.com/Toakan-Network/RW-TradingControl, branch main, the
/// repository its Workshop comments point to (About.xml url names 2007107588).
/// Not confirmed, so not listed: Trading Spot (3507108484, ProgrammerLily) and Trade Caravan Spot
/// (3733234194, Clown) publish no source, and reading their Workshop files needs a download.
/// None of these mods is installed on the test machine; the stand-down is tested with SimulatedActive.
/// </summary>
public static partial class Compat
{
public const string TradingSpotRewritten = "NachoToast.TradingSpot";
public const string TradingSpotKV = "tradingspot.kv.rw";
public const string TradingSpotGMT = "Grizzlemethis.TradingSpot.RW";
public const string TradingControl = "TradingControl.Tad.Rimworld.Core";
/// <summary>Every trading-spot mod camping stands down for.</summary>
public static readonly string[] TradingSpotMods = { TradingSpotRewritten, TradingSpotKV, TradingSpotGMT, TradingControl };
// The mod list can't change while the game runs, so the real detection runs once per process.
private static bool tradingSpotDetected;
private static string realTradingSpotMod;
/// <summary>The first active trading-spot mod (real or simulated), or null.</summary>
public static string ActiveTradingSpotMod()
{
if (!tradingSpotDetected)
{
realTradingSpotMod = null;
foreach (string id in TradingSpotMods)
{
if (ModLister.GetActiveModWithIdentifier(id, ignorePostfix: true) != null)
{
realTradingSpotMod = id;
break;
}
}
tradingSpotDetected = true;
}
foreach (string id in TradingSpotMods)
{
if (id == realTradingSpotMod || SimulatedActive.Contains(id))
return id;
}
return null;
}
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Shared mod detection. Zones has no hard dependency on any other mod. Package ids of the other
/// Blax mods are listed here; ids of mods a single feature reacts to live in that feature's partial
/// file of this class (Compat.TradingSpots.cs), each with the source it was read from.
/// </summary>
public static partial class Compat
{
public const string BlaxCastes = "blax.castes";
public const string BlaxSlaves = "blax.slaves";
public const string BlaxDefaults = "blax.defaults";
/// <summary>
/// Package ids tests treat as active, the Castes overlap-warning pattern. Only tests write it;
/// the runner clears it after every test.
/// </summary>
public static readonly HashSet<string> SimulatedActive = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Active by packageId, local or Steam copy, or simulated by a test. ModsConfig.IsActive misses a
/// mod that is installed both ways (the Steam copy gets a "_steam" postfix), so nothing in Blax
/// Zones uses it.
/// </summary>
public static bool IsActive(string packageId) =>
SimulatedActive.Contains(packageId) || ModLister.GetActiveModWithIdentifier(packageId, ignorePostfix: true) != null;
/// <summary>Blax Slaves routes its payouts through ZonesApi; the orbital checkbox's tooltip says so.</summary>
public static bool SlavesActive => IsActive(BlaxSlaves);
}
}

View File

@ -0,0 +1,56 @@
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Tab. Copied delivery zone settings for the copy/paste gizmos: a copy of the choices
/// (filter, priority, sources, camp), never a Zone, so no game state sits in a static (design:
/// "Rules every feature follows"). Paste goes through Zone_Delivery.CopySettingsFrom or the same fields.
///
/// Like vanilla's StorageSettingsClipboard (StorageSettingsClipboard.cs:8-27) it keeps a detached
/// ThingFilter: defs only, no settings-changed callback, so it survives loading another game.
/// </summary>
public static class DeliveryClipboard
{
private static ThingFilter filter;
private static StoragePriority priority = StoragePriority.Normal;
private static bool acceptOrbital = true;
private static bool campHere;
private static bool copied;
public static bool HasCopy => copied;
/// <summary>Copies the zone's filter, priority, sources and camp flag. Never the zone, its cells or its label.</summary>
public static void Copy(Zone_Delivery zone)
{
if (zone == null)
return;
filter ??= new ThingFilter();
if (zone.filter != null)
filter.CopyAllowancesFrom(zone.filter);
else
filter.CopyAllowancesFrom(DeliveryFilters.NewDefaultFilter());
priority = zone.priority;
acceptOrbital = zone.acceptOrbital;
campHere = zone.campHere;
copied = true;
}
/// <summary>
/// Writes the copied settings into the zone, the same fields Zone_Delivery.CopySettingsFrom
/// writes. Does nothing before the first copy. The zone's cells and label stay.
/// </summary>
public static void PasteInto(Zone_Delivery zone)
{
if (zone == null || !copied)
return;
zone.filter ??= new ThingFilter();
if (filter != null)
zone.filter.CopyAllowancesFrom(filter);
zone.priority = priority;
zone.acceptOrbital = acceptOrbital;
zone.campHere = campHere;
}
}
}

View File

@ -0,0 +1,65 @@
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>Where a delivery comes from. Each source has a checkbox on the delivery zone.</summary>
public enum DeliverySource
{
/// <summary>Orbital trade purchases and sale silver, and ZonesApi callers (Blax Slaves payouts).</summary>
Orbital,
}
/// <summary>
/// What may ever be routed into a zone, and the parent filter every delivery zone's item filter
/// sits under. Built from defs on first use, so it holds no game state.
/// </summary>
public static class DeliveryFilters
{
private static ThingFilter parent;
/// <summary>
/// Every storable item except corpses and, with Biotech, Wastepack. The zone tab shows only
/// these, and a new zone allows all of them.
/// </summary>
public static ThingFilter Parent
{
get
{
if (parent == null)
{
ThingFilter f = ThingFilter.CreateOnlyEverStorableThingFilter();
if (ThingCategoryDefOf.Corpses != null)
f.SetAllow(ThingCategoryDefOf.Corpses, false);
if (ThingDefOf.Wastepack != null) // Biotech only; null without it
f.SetAllow(ThingDefOf.Wastepack, false);
parent = f;
}
return parent;
}
}
/// <summary>A new zone's filter: everything the parent allows.</summary>
public static ThingFilter NewDefaultFilter()
{
var f = new ThingFilter();
f.SetAllowAll(Parent);
return f;
}
/// <summary>
/// Never routed, whatever a zone's filter says: pawns, corpses and Wastepack (null-checked,
/// Biotech only). A minified thing is judged by what it holds.
/// </summary>
public static bool NeverRouted(Thing thing)
{
if (thing == null)
return true;
Thing inner = thing.GetInnerIfMinified();
if (inner is Pawn || inner is Corpse || thing is Pawn || thing is Corpse)
return true;
ThingDef wastepack = ThingDefOf.Wastepack;
return wastepack != null && inner.def == wastepack;
}
}
}

View File

@ -0,0 +1,63 @@
using System;
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>Package Orbital. Design: 1.0 "Orbital purchases land in the zone".</summary>
public static partial class DeliveryRouter
{
/// <summary>
/// Replaces the single TradeUtility.SpawnDropPod(IntVec3, Map, Thing) call in
/// TradeShip.GiveSoldThingToPlayer (TradeShip.cs:199-207), same signature. With "Route orbital
/// trade" on, picks a cell through TryFindDropSpot(map, t, DeliverySource.Orbital, ...) and calls
/// TradeUtility.SpawnDropPod(cell, map, t); otherwise, when no zone fits or on any exception (logged
/// once), calls TradeUtility.SpawnDropPod(dropSpot, map, t) with the vanilla spot it was given.
/// Bought pawns and sale silver come through here too (Tradeable.cs:472-478, Tradeable_Pawn.cs:59);
/// the router refuses pawns, so they land at the vanilla spot.
/// </summary>
public static void DeliverFromOrbit(IntVec3 dropSpot, Map map, Thing t)
{
try
{
if (BlaxZonesMod.S.routeOrbital
&& TryFindDropSpot(map, t, DeliverySource.Orbital, out IntVec3 cell)
&& cell.IsValid && cell.InBounds(map))
{
TradeUtility.SpawnDropPod(cell, map, t);
return;
}
}
catch (Exception e)
{
ZonesLog.Once("Orbital delivery", e);
if (!FreeForVanillaPod(t))
return;
}
TradeUtility.SpawnDropPod(dropSpot, map, t);
}
/// <summary>
/// After a routed SpawnDropPod threw: true when the thing can go into vanilla's pod. False when
/// a spawned pod already carries it, so it is not lost and must not be dropped twice. A thing
/// left in the contents of a pod that never spawned is taken out first; adding it to a second
/// container while it still has a holder would fail and lose it.
/// </summary>
private static bool FreeForVanillaPod(Thing t)
{
try
{
if (t == null || t.Destroyed)
return true;
if (t.SpawnedOrAnyParentSpawned)
return false;
t.holdingOwner?.Remove(t);
}
catch (Exception e)
{
ZonesLog.Once("Orbital delivery fallback", e);
}
return true;
}
}
}

View File

@ -0,0 +1,308 @@
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxZones
{
/// <summary>
/// Package Router. Design: "DeliveryRouter, shared by every delivery path". One static class every
/// delivery path calls: orbital trade (DeliveryRouter.Orbital.cs, package Orbital), ZonesApi, and
/// from 1.1 rewards, caravans, cargo pods and direct delivery.
///
/// It holds no state: cell orders live in MapComponent_BlaxZones (MapComponent_BlaxZones.Router.cs),
/// cell validity in DeliveryRules. Nothing here catches: every entry point that calls it runs in
/// try/catch and falls back to vanilla.
/// </summary>
public static partial class DeliveryRouter
{
/// <summary>At most this many cell checks per stack.</summary>
public const int MaxChecksPerStack = 400;
/// <summary>
/// The overflow search radius: the setting (5 to 30), never below 5. DropCellFinder.TryFindDropSpotNear
/// grows its search by Min(maxRadius / 5, 1) (DropCellFinder.cs:272), which is 0 below 5, so a
/// failed search with a smaller radius never ends.
/// </summary>
public static int OverflowRadius => Math.Max(BlaxZonesSettings.MinOverflowRadius, BlaxZonesMod.S.OverflowRadiusClamped);
/// <summary>
/// A cell for one pod holding this thing, or false. Refusals (Refuses), then candidates in order,
/// then each candidate's cells (pass 1 empty valid cells, pass 2 cells with a mergeable stack, at
/// most MaxChecksPerStack checks), then overflow next to the top candidate when the setting allows.
/// Throws only when ZonesTestHooks.RouterThrows is set; callers wrap it in try/catch and fall back
/// to vanilla.
/// </summary>
public static bool TryFindDropSpot(Map map, Thing thing, DeliverySource source, out IntVec3 cell)
{
if (ZonesTestHooks.RouterThrows)
throw new System.InvalidOperationException("ZonesTestHooks.RouterThrows");
cell = IntVec3.Invalid;
if (Refuses(map, thing))
return false;
List<Zone_Delivery> candidates = Candidates(map, thing, source);
if (candidates.Count == 0)
return false;
for (int i = 0; i < candidates.Count; i++)
{
if (TryPickCellInZone(candidates[i], thing, out cell))
return true;
}
// Every candidate is full: overflow next to the top one (false when the setting is off).
return TryOverflow(candidates[0], out cell);
}
/// <summary>
/// Never routed: DeliveryFilters.NeverRouted (Pawn, Corpse, Wastepack), a map without
/// MapComponent_BlaxZones (after the removal button), a map with no delivery zones.
/// </summary>
public static bool Refuses(Map map, Thing thing)
{
if (map == null || DeliveryFilters.NeverRouted(thing))
return true;
if (MapComponent_BlaxZones.Of(map) == null)
return true;
return !HasDeliveryZone(map);
}
/// <summary>
/// Delivery zones on the map that accept the source and whose filter accepts the thing, ordered
/// by priority (highest first), then zone ID.
/// </summary>
public static List<Zone_Delivery> Candidates(Map map, Thing thing, DeliverySource source)
{
var result = new List<Zone_Delivery>();
List<Zone> zones = map?.zoneManager?.AllZones;
if (zones == null || thing == null)
return result;
for (int i = 0; i < zones.Count; i++)
{
if (zones[i] is Zone_Delivery zone && zone.cells.Count > 0 && zone.AcceptsSource(source) && zone.Accepts(thing))
result.Add(zone);
}
result.Sort(CompareCandidates);
return result;
}
/// <summary>
/// A pod cell inside one zone: pass 1 empty cells passing DeliveryRules.PodCellOk, pass 2 cells
/// holding a stack the thing can merge into, both in the component's cell order (nearest the
/// centroid first), at most MaxChecksPerStack checks.
/// </summary>
/// <remarks>
/// One walk over the first MaxChecksPerStack cells serves both passes: an empty cell is checked
/// with the pod rule at once (pass 1), a cell with a mergeable stack is remembered and checked
/// only if no empty cell passed (pass 2). A cell holding other items is taken. So each cell costs
/// one pod-rule check at most.
/// </remarks>
public static bool TryPickCellInZone(Zone_Delivery zone, Thing thing, out IntVec3 cell)
{
cell = IntVec3.Invalid;
Map map = zone?.MapOrNull;
if (map == null || thing == null || zone.cells.Count == 0)
return false;
MapComponent_BlaxZones comp = MapComponent_BlaxZones.Of(map);
List<IntVec3> cells = comp != null ? comp.CellsByDistance(zone) : SortedByCentroid(zone.cells);
int checks = Math.Min(cells.Count, MaxChecksPerStack);
List<IntVec3> mergeable = null;
for (int i = 0; i < checks; i++)
{
IntVec3 c = cells[i];
if (!c.InBounds(map))
continue;
switch (Occupancy(map, c, thing))
{
case CellOccupancy.Empty:
if (DeliveryRules.PodCellOk(map, c))
{
cell = c;
return true;
}
break;
case CellOccupancy.Mergeable:
(mergeable ??= new List<IntVec3>()).Add(c);
break;
}
}
if (mergeable != null)
{
for (int i = 0; i < mergeable.Count; i++)
{
if (DeliveryRules.PodCellOk(map, mergeable[i]))
{
cell = mergeable[i];
return true;
}
}
}
return false;
}
/// <summary>The zone's cell nearest its centroid (not the raw centroid, which can be a wall in an L-shaped zone).</summary>
public static IntVec3 OverflowCenter(Zone_Delivery zone)
{
if (zone == null || zone.cells.Count == 0)
return IntVec3.Invalid;
MapComponent_BlaxZones comp = MapComponent_BlaxZones.Of(zone.MapOrNull);
if (comp != null)
return comp.CellsByDistance(zone)[0];
return NearestToCentroid(zone.cells);
}
/// <summary>
/// The search of DropCellFinder.TryFindDropSpotNear(OverflowCenter(top), map, out cell, allowFogged:
/// false, canRoofPunch: false, maxRadius) (DropCellFinder.cs:229-317) plus the reach rule: random
/// cells within a square radius from Min(maxRadius / 2, 5) up to maxRadius, growing by
/// Min(maxRadius / 5, 1), each passing the pod rule (good drop spot and DeliveryRules.ColonyCanReach)
/// and reachable from the center with PassDoors, as vanilla requires. Without the reach rule a zone
/// in a walled-off pocket overflowed into that same pocket. maxRadius is OverflowRadius, never below
/// 5 (the step is 0 below 5: the search never ends). False when the overflow setting is off or no
/// cell fits, so the pod goes to the vanilla spot.
/// </summary>
public static bool TryOverflow(Zone_Delivery top, out IntVec3 cell)
{
cell = IntVec3.Invalid;
if (top == null || !BlaxZonesMod.S.overflowNearZone)
return false;
Map map = top.MapOrNull;
if (map == null)
return false;
IntVec3 center = OverflowCenter(top);
if (!center.IsValid || !center.InBounds(map))
return false;
int maxRadius = OverflowRadius;
int step = Math.Min(maxRadius / 5, 1);
if (step <= 0)
return false;
bool Fits(IntVec3 c) =>
DeliveryRules.PodCellOk(map, c)
&& map.reachability.CanReach(center, c, PathEndMode.OnCell, TraverseMode.PassDoors, Danger.Deadly);
for (int radius = Math.Min(maxRadius / 2, 5); radius <= maxRadius; radius += step)
{
if (CellFinder.TryFindRandomCellNear(center, map, radius, Fits, out IntVec3 found))
{
cell = found;
return true;
}
}
return false;
}
// ---- helpers ---------------------------------------------------------------------
private enum CellOccupancy
{
/// <summary>No item on the cell.</summary>
Empty,
/// <summary>At least one stack the thing can merge into.</summary>
Mergeable,
/// <summary>Items, none the thing can merge into.</summary>
Taken,
}
/// <summary>
/// What items lie on the cell, as the passes see it. A mergeable stack has the same def, accepts
/// the thing (CanStackWith: same stuff, not a relic, comps agree) and has room left.
/// </summary>
private static CellOccupancy Occupancy(Map map, IntVec3 c, Thing thing)
{
List<Thing> things = c.GetThingList(map);
bool anyItem = false;
for (int i = 0; i < things.Count; i++)
{
Thing t = things[i];
if (t.def.category != ThingCategory.Item)
continue;
if (t != thing && t.def == thing.def && t.stackCount < t.def.stackLimit && t.CanStackWith(thing))
return CellOccupancy.Mergeable;
anyItem = true;
}
return anyItem ? CellOccupancy.Taken : CellOccupancy.Empty;
}
/// <summary>Any delivery zone registered on the map. Cheap: one pass over ZoneManager's list.</summary>
private static bool HasDeliveryZone(Map map)
{
List<Zone> zones = map.zoneManager?.AllZones;
if (zones == null)
return false;
for (int i = 0; i < zones.Count; i++)
{
if (zones[i] is Zone_Delivery)
return true;
}
return false;
}
/// <summary>Priority descending, then zone ID ascending. IDs are unique, so the order is total.</summary>
private static int CompareCandidates(Zone_Delivery a, Zone_Delivery b)
{
int byPriority = ((int)b.priority).CompareTo((int)a.priority);
return byPriority != 0 ? byPriority : a.ID.CompareTo(b.ID);
}
/// <summary>
/// A copy of the cells sorted by distance to their centroid, ties by x then z. Exact: distances
/// are compared as (n*x - sumX)^2 + (n*z - sumZ)^2 in integers, so ties never depend on rounding,
/// and no Rand is used (Zone.Cells would shuffle).
/// </summary>
internal static List<IntVec3> SortedByCentroid(List<IntVec3> cells)
{
var sorted = new List<IntVec3>(cells);
if (sorted.Count < 2)
return sorted;
CentroidSums(cells, out long n, out long sumX, out long sumZ);
sorted.Sort((a, b) =>
{
int d = ScaledDistSq(a, n, sumX, sumZ).CompareTo(ScaledDistSq(b, n, sumX, sumZ));
if (d != 0)
return d;
d = a.x.CompareTo(b.x);
return d != 0 ? d : a.z.CompareTo(b.z);
});
return sorted;
}
/// <summary>The first cell SortedByCentroid would return, without sorting.</summary>
internal static IntVec3 NearestToCentroid(List<IntVec3> cells)
{
if (cells == null || cells.Count == 0)
return IntVec3.Invalid;
CentroidSums(cells, out long n, out long sumX, out long sumZ);
IntVec3 best = cells[0];
long bestDist = ScaledDistSq(best, n, sumX, sumZ);
for (int i = 1; i < cells.Count; i++)
{
IntVec3 c = cells[i];
long d = ScaledDistSq(c, n, sumX, sumZ);
if (d < bestDist || (d == bestDist && (c.x < best.x || (c.x == best.x && c.z < best.z))))
{
best = c;
bestDist = d;
}
}
return best;
}
private static void CentroidSums(List<IntVec3> cells, out long n, out long sumX, out long sumZ)
{
n = cells.Count;
sumX = 0;
sumZ = 0;
for (int i = 0; i < cells.Count; i++)
{
sumX += cells[i].x;
sumZ += cells[i].z;
}
}
/// <summary>Squared distance to the centroid, times n squared.</summary>
private static long ScaledDistSq(IntVec3 c, long n, long sumX, long sumZ)
{
long dx = n * c.x - sumX;
long dz = n * c.z - sumZ;
return dx * dx + dz * dz;
}
}
}

View File

@ -0,0 +1,69 @@
using System.Collections.Generic;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxZones
{
/// <summary>
/// Package Rules. Design: "DeliveryRouter, shared by every delivery path" > Reach rule and Pod rule,
/// and 1.0 "Delivery zone" > cell validity and reachability. Which cells a drop pod may use.
/// </summary>
public static class DeliveryRules
{
/// <summary>The router recomputes a cached reach entry older than this.</summary>
public const int ReachMaxAgeTicks = 2500;
/// <summary>While a delivery zone is selected, its unusable cells are recomputed this often.</summary>
public const int SelectedRecheckTicks = 250;
/// <summary>
/// Reach rule: a spawned free colonist (map.mapPawns.FreeColonistsSpawned) can reach the cell
/// with the given PathEndMode (OnCell for pods and placement, Touch for storage). Checked once
/// per district and cached in the component (MapComponent_BlaxZones.Rules.cs). With no free
/// colonist on the map, Reachability.CanReachColony decides. Never CanReachColony first: it is
/// true for any cell that reaches a colony building (Reachability.cs:387-435).
/// </summary>
public static bool ColonyCanReach(Map map, IntVec3 cell, PathEndMode mode = PathEndMode.OnCell)
{
if (map == null || !cell.InBounds(map))
return false;
MapComponent_BlaxZones comp = MapComponent_BlaxZones.Of(map);
// Impassable cells have no district (Touch on a wall fridge): checked every time, never cached.
District district = cell.GetDistrict(map);
if (comp != null && district != null && comp.TryGetCachedReach(district, mode, out bool cached))
return cached;
bool canReach = ComputeReach(map, cell, mode);
if (comp != null && district != null)
comp.StoreReach(district, mode, canReach);
return canReach;
}
/// <summary>The reach rule without the cache.</summary>
internal static bool ComputeReach(Map map, IntVec3 cell, PathEndMode mode)
{
// FreeColonistsSpawned refills one shared list on every call (MapPawns.cs:809), so read it once.
List<Pawn> colonists = map.mapPawns.FreeColonistsSpawned;
if (colonists.Count == 0)
return map.reachability.CanReachColony(cell);
for (int i = 0; i < colonists.Count; i++)
{
Pawn p = colonists[i];
if (p.Spawned && p.Map == map && map.reachability.CanReach(p.Position, cell, mode, TraverseParms.For(p, Danger.Deadly)))
return true;
}
return false;
}
/// <summary>
/// Pod rule: DropCellFinder.IsGoodDropSpot(c, map, allowFogged: false, canRoofPunch: false)
/// (DropCellFinder.cs:319-362) plus the reach rule with OnCell.
/// </summary>
public static bool PodCellOk(Map map, IntVec3 cell)
{
return map != null && cell.InBounds(map)
&& DropCellFinder.IsGoodDropSpot(cell, map, allowFogged: false, canRoofPunch: false)
&& ColonyCanReach(map, cell, PathEndMode.OnCell);
}
}
}

View File

@ -0,0 +1,58 @@
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Designators. "Delivery zone" in the Zone menu, dragged like a stockpile. Inserted after
/// Designator_ZoneAdd_Growing by Patches/BlaxZones_Designators.xml (a namespace-qualified
/// PatchOperationInsert; anchor on Growing, because the Fishing entry carries MayRequire Odyssey).
/// Visible reads BlaxZonesSettings.deliveryZones live.
///
/// Subclasses Designator_ZoneAdd directly, never Designator_ZoneAddStockpile, so Blax Defaults'
/// stockpile hook never reaches it. Designator_ZoneAdd compares the exact zone type and refuses
/// cells in other zones (Designator_ZoneAdd.cs:46, 73, 114, 127), and DesignateMultiCell drops
/// every cell that already has a zone (Designator_ZoneAdd.cs:142), so expanding only adds cells.
/// </summary>
public class Designator_ZoneAdd_Delivery : Designator_ZoneAdd
{
public const string IconPath = "UI/Designators/ZoneCreate_Stockpile";
/// <summary>The tooltip; mentions the 4-cell home area growth (AutoHomeAreaMaker.cs:48-58).</summary>
public const string DescKey = "BlaxZones_DesignatorDeliveryZoneDesc";
public const string TutorTag = "ZoneAdd_Delivery";
protected override string NewZoneLabel => "BlaxZones_DeliveryZone".Translate();
/// <summary>Read live by GizmoGridDrawer (Gizmo.cs:31, GizmoGridDrawer.cs:265), so the toggle needs no restart.</summary>
public override bool Visible => BlaxZonesMod.S.deliveryZones;
public Designator_ZoneAdd_Delivery()
{
zoneTypeToPlace = typeof(Zone_Delivery);
defaultLabel = "BlaxZones_DeliveryZone".Translate();
defaultDesc = DescKey.Translate();
icon = ContentFinder<Texture2D>.Get(IconPath);
defaultIconColor = Zone_Delivery.IconColor;
tutorTag = TutorTag;
// Dragged like a stockpile (Designator_ZoneAdd.cs:36-38, Designator_ZoneAddStockpile.cs:37).
soundDragSustain = SoundDefOf.Designate_DragAreaAdd;
soundDragChanged = SoundDefOf.Designate_DragZone_Changed;
soundSucceeded = SoundDefOf.Designate_ZoneAdd_Stockpile;
}
protected override Zone MakeNewZone() => new Zone_Delivery(Find.CurrentMap.zoneManager);
}
/// <summary>Package Designators. The expand gizmo of a selected delivery zone; only adds new cells.</summary>
public class Designator_ZoneAdd_Delivery_Expand : Designator_ZoneAdd_Delivery
{
public Designator_ZoneAdd_Delivery_Expand()
{
defaultLabel = "DesignatorZoneExpand".Translate();
hotKey = KeyBindingDefOf.Misc6;
}
}
}

View File

@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Tab. The delivery zone tab: priority dropdown (Low to Critical), source checkboxes
/// (orbital in 1.0; its tooltip adds "Also Blax Slaves payouts" while Compat.SlavesActive), the
/// "Caravans camp here" checkbox and ThingFilterUI.DoThingFilterConfigWindow under
/// DeliveryFilters.Parent.
///
/// Layout follows ITab_Storage (ITab_Storage.cs:104-151): the same 300x480 window contracted by 10,
/// the priority button top left, the filter below. Two checkbox rows sit between them.
/// </summary>
public class ITab_Delivery : ITab
{
private static readonly Vector2 WinSize = new Vector2(300f, 480f);
private const float PriorityButtonWidth = 160f;
private const float PriorityButtonHeight = 29f;
private const float RowHeight = 24f;
private const float Gap = 6f;
/// <summary>The filter tree's scroll position and search box. UI state of this shared tab, not game state.</summary>
private readonly ThingFilterUI.UIState thingFilterState = new ThingFilterUI.UIState();
public Zone_Delivery SelZone => SelObject as Zone_Delivery;
public ITab_Delivery()
{
size = WinSize;
labelKey = "BlaxZones_TabDelivery";
}
public override bool IsVisible => SelZone != null;
public override void OnOpen()
{
base.OnOpen();
thingFilterState.quickSearch.Reset();
}
public override void Notify_ClickOutsideWindow()
{
base.Notify_ClickOutsideWindow();
thingFilterState.quickSearch.Unfocus();
}
protected override void FillTab()
{
Zone_Delivery zone = SelZone;
if (zone == null)
return;
zone.filter ??= DeliveryFilters.NewDefaultFilter();
Rect rect = new Rect(0f, 0f, WinSize.x, WinSize.y).ContractedBy(10f);
Widgets.BeginGroup(rect);
try
{
Text.Font = GameFont.Small;
float y = 0f;
// Priority: a button that opens a float menu, as the stockpile tab does.
Rect priorityRect = new Rect(0f, y, PriorityButtonWidth, PriorityButtonHeight);
if (Widgets.ButtonText(priorityRect, PriorityButtonLabel(zone.priority)))
Find.WindowStack.Add(new FloatMenu(PriorityMenuOptions(zone)));
TooltipHandler.TipRegion(priorityRect, "BlaxZones_PriorityTip".Translate());
y += PriorityButtonHeight + Gap;
// Sources. 1.0 has orbital only; 1.1 adds rewards and caravan rows here.
Rect orbitalRect = new Rect(0f, y, rect.width, RowHeight);
Widgets.CheckboxLabeled(orbitalRect, "BlaxZones_AcceptOrbital".Translate(), ref zone.acceptOrbital);
TooltipHandler.TipRegion(orbitalRect, OrbitalTip());
y += RowHeight;
Rect campRect = new Rect(0f, y, rect.width, RowHeight);
Widgets.CheckboxLabeled(campRect, "BlaxZones_CampHere".Translate(), ref zone.campHere);
TooltipHandler.TipRegion(campRect, CampTip());
y += RowHeight + Gap;
Rect filterRect = new Rect(0f, y, rect.width, rect.height - y);
ThingFilterUI.DoThingFilterConfigWindow(filterRect, thingFilterState, zone.filter, DeliveryFilters.Parent, 8,
HiddenDefs(), HiddenSpecialFilters());
}
finally
{
Widgets.EndGroup();
}
}
/// <summary>"Priority: Normal", the stockpile tab's button text (ITab_Storage.cs:114).</summary>
public static string PriorityButtonLabel(StoragePriority p) =>
"Priority".Translate() + ": " + p.Label().CapitalizeFirst();
/// <summary>The dropdown's entries: every StoragePriority from Low to Critical, never Unstored, each setting the zone's priority.</summary>
public static List<FloatMenuOption> PriorityMenuOptions(Zone_Delivery zone)
{
var list = new List<FloatMenuOption>();
foreach (StoragePriority p in Priorities())
{
StoragePriority local = p;
list.Add(new FloatMenuOption(local.Label().CapitalizeFirst(), () =>
{
if (zone != null)
zone.priority = local;
}));
}
return list;
}
/// <summary>Low, Normal, Preferred, Important, Critical: the enum without Unstored, in enum order.</summary>
public static IEnumerable<StoragePriority> Priorities()
{
foreach (StoragePriority p in Enum.GetValues(typeof(StoragePriority)))
{
if (p != StoragePriority.Unstored)
yield return p;
}
}
/// <summary>
/// The orbital checkbox's tooltip. Adds the Blax Slaves line while Slaves is active, and a note while
/// routing is off globally. "Route orbital trade" gates only DeliverFromOrbit; ZonesApi ignores it,
/// so with Slaves active the note says its payouts still land here.
/// </summary>
public static string OrbitalTip()
{
string tip = "BlaxZones_AcceptOrbitalTip".Translate();
bool slaves = Compat.SlavesActive;
if (slaves)
tip += "\n\n" + "BlaxZones_AcceptOrbitalSlavesTip".Translate();
if (!BlaxZonesMod.S.routeOrbital)
tip += "\n\n" + (slaves ? "BlaxZones_AcceptOrbitalOffSlavesTip" : "BlaxZones_AcceptOrbitalOffTip").Translate();
return tip;
}
/// <summary>The camp checkbox's tooltip. Adds a note while camping is off globally or stands down for a trading-spot mod.</summary>
public static string CampTip()
{
string tip = "BlaxZones_CampHereTip".Translate();
if (!BlaxZonesMod.S.campAtZones)
tip += "\n\n" + "BlaxZones_CampHereOffTip".Translate();
string spotMod = Compat.ActiveTradingSpotMod();
if (spotMod != null)
{
string name = ModLister.GetActiveModWithIdentifier(spotMod, ignorePostfix: true)?.Name ?? spotMod;
tip += "\n\n" + "BlaxZones_CampHereStandDownTip".Translate(name);
}
return tip;
}
private static List<ThingDef> hiddenDefs;
/// <summary>
/// Wastepack (Biotech, null-checked) and every corpse def. The parent filter already keeps them
/// out of the tree; passing them here also keeps "Clear all" and category checkboxes from
/// touching them (ThingFilter.SetAllow(ThingCategoryDef, ...) excepts these, ThingFilter.cs:718-730).
/// Built from defs once; no game state.
/// </summary>
public static List<ThingDef> HiddenDefs()
{
if (hiddenDefs == null)
{
var list = new List<ThingDef>();
ThingDef wastepack = ThingDefOf.Wastepack; // Biotech only; null without it
if (wastepack != null)
list.Add(wastepack);
if (ThingCategoryDefOf.Corpses != null)
list.AddRange(ThingCategoryDefOf.Corpses.DescendantThingDefs);
hiddenDefs = list;
}
return hiddenDefs;
}
/// <summary>The meat-source filters the stockpile tab hides with Ideology (ITab_Storage.cs:178-187), null-checked.</summary>
private static IEnumerable<SpecialThingFilterDef> HiddenSpecialFilters()
{
if (!ModsConfig.IdeologyActive)
yield break;
if (SpecialThingFilterDefOf.AllowVegetarian != null) yield return SpecialThingFilterDefOf.AllowVegetarian;
if (SpecialThingFilterDefOf.AllowCarnivore != null) yield return SpecialThingFilterDefOf.AllowCarnivore;
if (SpecialThingFilterDefOf.AllowCannibal != null) yield return SpecialThingFilterDefOf.AllowCannibal;
if (SpecialThingFilterDefOf.AllowInsectMeat != null) yield return SpecialThingFilterDefOf.AllowInsectMeat;
}
}
}

View File

@ -0,0 +1,44 @@
using System.Collections.Generic;
using Verse;
namespace BlaxZones
{
/// <summary>Package Router: each delivery zone's cells sorted by distance to its centroid, rebuilt when its cells change.</summary>
public partial class MapComponent_BlaxZones
{
/// <summary>Cell order per delivery zone of this map. A cache: never saved, dropped on any cell change.</summary>
private readonly Dictionary<Zone_Delivery, List<IntVec3>> cellsByDistance = new Dictionary<Zone_Delivery, List<IntVec3>>();
/// <summary>
/// The zone's cells, nearest its centroid first (ties by x, then z). Cached; rebuilt after
/// AddCell/RemoveCell. The list is shared: read it, never change it. A zone of another map, or
/// one not registered yet, gets a fresh list that is not cached.
/// </summary>
public List<IntVec3> CellsByDistance(Zone_Delivery zone)
{
if (zone == null)
return new List<IntVec3>();
if (zone.MapOrNull != map)
return DeliveryRouter.SortedByCentroid(zone.cells);
// The count check is a backstop for a cell change that bypassed Notify_ZoneCellsChanged.
if (cellsByDistance.TryGetValue(zone, out List<IntVec3> cached) && cached.Count == zone.cells.Count)
return cached;
List<IntVec3> sorted = DeliveryRouter.SortedByCentroid(zone.cells);
cellsByDistance[zone] = sorted;
return sorted;
}
/// <summary>Drops the zone's cell order (its cells changed or it was deregistered).</summary>
private void DropRouterCaches(Zone_Delivery zone)
{
if (zone != null)
cellsByDistance.Remove(zone);
}
/// <summary>Drops every Router cache (FinalizeInit, MapRemoved).</summary>
private void ClearRouterCaches()
{
cellsByDistance.Clear();
}
}
}

View File

@ -0,0 +1,266 @@
using System;
using System.Collections.Generic;
using RimWorld;
using RimWorld.Planet;
using UnityEngine;
using Verse;
using Verse.AI;
namespace BlaxZones
{
/// <summary>
/// Package Rules: the reach cache per district, the unusable cells per delivery zone, the red
/// overlay while a zone is selected and the inspect line "N cells drop pods can't use".
///
/// Reach entries are keyed by the District object and stamped with the tick and the district's
/// lastChangeTick. Vanilla reuses a District when walls go up next to it and stamps it then
/// (RegionAndRoomUpdater.cs:307-314, District.cs:245), so a changed district is never trusted, and
/// any entry is dropped once it is DeliveryRules.ReachMaxAgeTicks old (colonists walled off
/// elsewhere change no district of the zone).
///
/// Unusable cells are cached only for the selected delivery zone, the one the overlay and the
/// inspect pane read every frame. It is recomputed, reach included, when it gets selected and every
/// DeliveryRules.SelectedRecheckTicks while it stays selected. Any other zone is computed on demand.
/// </summary>
public partial class MapComponent_BlaxZones
{
/// <summary>The overlay color: red, like vanilla's invalid-cell outlines.</summary>
private static readonly Color UnusableCellColor = Color.red;
private readonly struct ReachKey : IEquatable<ReachKey>
{
public readonly District district;
public readonly PathEndMode mode;
public ReachKey(District district, PathEndMode mode)
{
this.district = district;
this.mode = mode;
}
// District doesn't override Equals, so this is reference equality: a rebuilt district is a new key.
public bool Equals(ReachKey other) => ReferenceEquals(district, other.district) && mode == other.mode;
public override bool Equals(object obj) => obj is ReachKey other && Equals(other);
public override int GetHashCode() => (district.GetHashCode() * 397) ^ (int)mode;
}
private struct ReachEntry
{
public bool canReach;
public int stamp;
public int districtChangeTick;
}
private sealed class UnusableEntry
{
public readonly List<IntVec3> cells = new List<IntVec3>();
public int stamp;
}
private readonly Dictionary<ReachKey, ReachEntry> reachCache = new Dictionary<ReachKey, ReachEntry>();
private readonly Dictionary<Zone_Delivery, UnusableEntry> unusableCache = new Dictionary<Zone_Delivery, UnusableEntry>();
private readonly HashSet<District> refreshedDistricts = new HashSet<District>();
private readonly List<ReachKey> expiredReach = new List<ReachKey>();
private Zone_Delivery lastSelectedZone;
private static int Now => Find.TickManager?.TicksGame ?? 0;
/// <summary>
/// The cached reach rule result for a district and path end mode, if fresh (younger than
/// DeliveryRules.ReachMaxAgeTicks). False when there is no fresh entry.
/// </summary>
public bool TryGetCachedReach(District district, PathEndMode mode, out bool canReach)
{
canReach = false;
if (district == null)
return false;
var key = new ReachKey(district, mode);
if (!reachCache.TryGetValue(key, out ReachEntry entry))
return false;
if (Now - entry.stamp >= DeliveryRules.ReachMaxAgeTicks || entry.districtChangeTick != district.lastChangeTick)
{
reachCache.Remove(key);
return false;
}
canReach = entry.canReach;
return true;
}
/// <summary>Stores a reach rule result for a district and path end mode, stamped with the current tick.</summary>
public void StoreReach(District district, PathEndMode mode, bool canReach)
{
if (district == null)
return;
reachCache[new ReachKey(district, mode)] = new ReachEntry
{
canReach = canReach,
stamp = Now,
districtChangeTick = district.lastChangeTick,
};
}
/// <summary>
/// The zone's cells drop pods can't use (failing DeliveryRules.PodCellOk), cached per zone,
/// recomputed every DeliveryRules.SelectedRecheckTicks while the zone is selected. The list
/// of the selected zone is the cache itself: read it, never change it.
/// </summary>
public List<IntVec3> UnusableCells(Zone_Delivery zone)
{
if (zone == null || zone.MapOrNull != map)
return new List<IntVec3>();
if (zone != SelectedDeliveryZone())
return ComputeUnusable(zone, refreshReach: false, new List<IntVec3>());
if (!unusableCache.TryGetValue(zone, out UnusableEntry entry) || Now - entry.stamp >= DeliveryRules.ReachMaxAgeTicks)
entry = RefreshUnusable(zone);
return entry.cells;
}
/// <summary>Count of UnusableCells(zone).</summary>
public int UnusableCellCount(Zone_Delivery zone) => UnusableCells(zone).Count;
/// <summary>
/// The Rules line for Zone_Delivery.GetInspectString: "N cells drop pods can't use"
/// (key BlaxZones_UnusableCells in BlaxZones_Rules.xml), or null when every cell is usable.
/// </summary>
public string InspectLineFor(Zone_Delivery zone)
{
int count = UnusableCellCount(zone);
if (count <= 0)
return null;
if (count == 1)
return "BlaxZones_UnusableCell".Translate().Resolve();
return "BlaxZones_UnusableCells".Translate(count).Resolve();
}
/// <summary>Every tick: recompute the selected delivery zone's unusable cells every SelectedRecheckTicks.</summary>
private void TickRules()
{
int now = Now;
if (now % DeliveryRules.ReachMaxAgeTicks == 0)
DropExpiredReach(now);
Zone_Delivery zone = SelectedDeliveryZone();
if (zone == null)
{
lastSelectedZone = null;
return;
}
if (zone != lastSelectedZone || !unusableCache.TryGetValue(zone, out UnusableEntry entry)
|| now - entry.stamp >= DeliveryRules.SelectedRecheckTicks)
{
RefreshUnusable(zone);
}
lastSelectedZone = zone;
}
/// <summary>Every frame: GenDraw.DrawFieldEdges over the selected delivery zone's unusable cells, in red.</summary>
private void UpdateOverlay()
{
// MapComponentUpdate runs for every map, also while the world is shown (Map.cs:1154-1202).
if (!WorldRendererUtility.DrawingMap)
return;
Zone_Delivery zone = SelectedDeliveryZone();
if (zone == null)
{
lastSelectedZone = null;
return;
}
// Selected while paused: no tick comes, so the overlay recomputes on the first frame.
if (zone != lastSelectedZone || !unusableCache.TryGetValue(zone, out UnusableEntry entry))
entry = RefreshUnusable(zone);
lastSelectedZone = zone;
if (entry.cells.Count > 0)
GenDraw.DrawFieldEdges(entry.cells, UnusableCellColor);
}
/// <summary>Drops the zone's unusable-cell cache (its cells changed or it was deregistered).</summary>
private void DropRuleCaches(Zone_Delivery zone)
{
if (zone == null)
return;
unusableCache.Remove(zone);
if (lastSelectedZone == zone)
lastSelectedZone = null;
}
/// <summary>Drops every Rules cache (FinalizeInit, MapRemoved).</summary>
private void ClearRuleCaches()
{
reachCache.Clear();
unusableCache.Clear();
refreshedDistricts.Clear();
expiredReach.Clear();
lastSelectedZone = null;
}
/// <summary>The selected delivery zone if it lies on this map and this map is shown, else null.</summary>
private Zone_Delivery SelectedDeliveryZone()
{
if (Current.ProgramState != ProgramState.Playing || !(Find.UIRoot is UIRoot_Play) || Find.CurrentMap != map)
return null;
Zone_Delivery zone = Find.Selector.SelectedZone as Zone_Delivery;
return zone != null && zone.MapOrNull == map ? zone : null;
}
/// <summary>Recomputes and caches the zone's unusable cells, rechecking the reach of each of its districts once.</summary>
private UnusableEntry RefreshUnusable(Zone_Delivery zone)
{
if (!unusableCache.TryGetValue(zone, out UnusableEntry entry))
{
entry = new UnusableEntry();
unusableCache[zone] = entry;
}
ComputeUnusable(zone, refreshReach: true, entry.cells);
entry.stamp = Now;
return entry;
}
/// <summary>
/// Fills the list with the zone's cells failing the pod rule. With refreshReach, the first cell
/// of each district drops that district's reach entry, so the reach rule runs once per district.
/// </summary>
private List<IntVec3> ComputeUnusable(Zone_Delivery zone, bool refreshReach, List<IntVec3> into)
{
into.Clear();
refreshedDistricts.Clear();
try
{
List<IntVec3> cells = zone.Cells;
for (int i = 0; i < cells.Count; i++)
{
IntVec3 c = cells[i];
if (refreshReach && c.InBounds(map))
{
District district = c.GetDistrict(map);
if (district != null && refreshedDistricts.Add(district))
reachCache.Remove(new ReachKey(district, PathEndMode.OnCell));
}
if (!DeliveryRules.PodCellOk(map, c))
into.Add(c);
}
}
finally
{
refreshedDistricts.Clear();
}
return into;
}
private void DropExpiredReach(int now)
{
if (reachCache.Count == 0)
return;
expiredReach.Clear();
foreach (KeyValuePair<ReachKey, ReachEntry> kv in reachCache)
{
if (now - kv.Value.stamp >= DeliveryRules.ReachMaxAgeTicks)
expiredReach.Add(kv.Key);
}
for (int i = 0; i < expiredReach.Count; i++)
reachCache.Remove(expiredReach[i]);
expiredReach.Clear();
}
}
}

View File

@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using Verse;
namespace BlaxZones
{
/// <summary>Package Store: the component's save data. See ZoneStore.</summary>
public partial class MapComponent_BlaxZones
{
/// <summary>
/// Zones read from the save, held only until the Map.FinalizeLoading prefix registered them,
/// then cleared. Empty at any other time.
/// </summary>
private List<Zone> loadedZones = new List<Zone>();
/// <summary>Zones loaded and not yet registered. Read by tests.</summary>
public IReadOnlyList<Zone> LoadedZones => loadedZones;
/// <summary>
/// Saving: deep-saves the Blax zones found in map.zoneManager.AllZones (the map saves zoneManager
/// before the components, Map.cs:873, 898, and the finalizer has restored the list by then).
/// Loading: reads them into loadedZones. A deleted zone is never saved again.
/// </summary>
private void ExposeStore()
{
if (Scribe.mode == LoadSaveMode.Saving)
{
List<Zone> zones = ZonesToSave();
Scribe_Collections.Look(ref zones, "zones", LookMode.Deep);
return;
}
Scribe_Collections.Look(ref loadedZones, "zones", LookMode.Deep);
if (loadedZones == null)
loadedZones = new List<Zone>(); // no node: a save made before Zones, or an empty component
else if (Scribe.mode == LoadSaveMode.LoadingVars)
loadedZones.RemoveAll(z => z == null); // a zone class that no longer exists logged its own error
}
/// <summary>The Blax zones registered on this map right now, in ZoneManager's order.</summary>
private List<Zone> ZonesToSave()
{
var zones = new List<Zone>();
try
{
List<Zone> all = map?.zoneManager?.AllZones;
if (all != null)
{
foreach (Zone zone in all)
{
if (ZoneStore.IsBlaxZone(zone))
zones.Add(zone);
}
}
}
catch (Exception e)
{
ZonesLog.Once("Collecting zones to save", e);
}
return zones;
}
/// <summary>
/// Called by the Map.FinalizeLoading prefix: registers every loaded zone through
/// ZoneStore.RegisterLoaded, then clears loadedZones. On an exception logs once and leaves the
/// remaining zones out of this load; the zone that threw is taken back out of the manager.
/// </summary>
public void RegisterLoadedZones()
{
List<Zone> zones = loadedZones;
loadedZones = new List<Zone>();
if (zones == null || zones.Count == 0)
return;
Zone current = null;
try
{
foreach (Zone zone in zones)
{
if (zone == null)
continue;
current = zone;
ZoneStore.RegisterLoaded(map, zone);
current = null;
}
}
catch (Exception e)
{
ZonesLog.Once("Registering loaded zones", e);
ZoneStore.UndoRegister(map, current);
}
}
}
}

View File

@ -0,0 +1,117 @@
using System;
using Verse;
namespace BlaxZones
{
/// <summary>
/// All Blax state of one map (design: "Zone store, safe to remove from a save"): our zones while
/// saving and loading, and every cache. No Blax zone or field ever enters a vanilla save list.
/// ZoneManager stays the only zone registry while the game runs; this component keeps no zone list.
///
/// Zones' own code never creates this component: vanilla's Map.FillComponents adds it. Every
/// patch reads it with Of(map) and routes to vanilla on null.
///
/// The class is split by owner. This file (integrator) wires the MapComponent overrides to the
/// package parts:
/// - MapComponent_BlaxZones.Store.cs (Store): ExposeStore, the loaded-zone list, RegisterLoadedZones.
/// - MapComponent_BlaxZones.Rules.cs (Rules): reach cache per district, unusable cells per zone,
/// the red overlay, the inspect line.
/// - MapComponent_BlaxZones.Router.cs (Router): cell order per zone.
/// </summary>
public partial class MapComponent_BlaxZones : MapComponent
{
public MapComponent_BlaxZones(Map map) : base(map)
{
}
/// <summary>The map's component, or null (no map, or Zones was removed from this game).</summary>
public static MapComponent_BlaxZones Of(Map map) => map?.GetComponent<MapComponent_BlaxZones>();
public override void ExposeData()
{
base.ExposeData();
ExposeStore();
}
public override void FinalizeInit()
{
base.FinalizeInit();
ZonesLog.ResetOnce();
try
{
ClearRouterCaches();
ClearRuleCaches();
}
catch (Exception e)
{
ZonesLog.Once("Map init", e);
}
}
public override void MapComponentTick()
{
try
{
TickRules();
}
catch (Exception e)
{
ZonesLog.Once("Map tick", e);
}
}
public override void MapComponentUpdate()
{
try
{
UpdateOverlay();
}
catch (Exception e)
{
ZonesLog.Once("Zone overlay", e);
}
}
/// <summary>Drops caches only. Never deletes or deregisters zones of the removed map; vanilla doesn't either.</summary>
public override void MapRemoved()
{
try
{
ClearRouterCaches();
ClearRuleCaches();
}
catch (Exception e)
{
ZonesLog.Once("Map removal", e);
}
}
/// <summary>Called by Zone_Delivery.AddCell and RemoveCell.</summary>
public void Notify_ZoneCellsChanged(Zone_Delivery zone)
{
try
{
DropRouterCaches(zone);
DropRuleCaches(zone);
}
catch (Exception e)
{
ZonesLog.Once("Zone cell change", e);
}
}
/// <summary>Called by Zone_Delivery.PostDeregister: the zone left ZoneManager, drop everything keyed by it.</summary>
public void Notify_ZoneRemoved(Zone_Delivery zone)
{
try
{
DropRouterCaches(zone);
DropRuleCaches(zone);
}
catch (Exception e)
{
ZonesLog.Once("Zone removal", e);
}
}
}
}

View File

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Orbital. A caller-scoped transpiler on TradeShip.GiveSoldThingToPlayer replaces its one
/// TradeUtility.SpawnDropPod call with DeliveryRouter.DeliverFromOrbit. DropCellFinder.TradeDropSpot
/// is never patched (center-drop raids, ransom and lent colonists use it too).
/// </summary>
[HarmonyPatch(typeof(TradeShip), nameof(TradeShip.GiveSoldThingToPlayer))]
public static class Patch_TradeShip_GiveSoldThingToPlayer
{
public static readonly MethodInfo SpawnDropPod =
AccessTools.Method(typeof(TradeUtility), nameof(TradeUtility.SpawnDropPod), new[] { typeof(IntVec3), typeof(Map), typeof(Thing) });
public static readonly MethodInfo DeliverFromOrbit =
AccessTools.Method(typeof(DeliveryRouter), nameof(DeliveryRouter.DeliverFromOrbit), new[] { typeof(IntVec3), typeof(Map), typeof(Thing) });
/// <summary>Calls of SpawnDropPod the last transpiler run found. The test checks it is exactly 1.</summary>
public static int LastCallCount = -1;
/// <summary>
/// Exactly one SpawnDropPod call: replace it. Any other count: log an error ("unexpected call
/// count") and return the instructions unchanged.
/// </summary>
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
List<CodeInstruction> list = instructions.ToList();
try
{
if (SpawnDropPod == null || DeliverFromOrbit == null)
{
LastCallCount = -1;
Log.Error("[Blax Zones] Orbital routing is off: TradeUtility.SpawnDropPod or DeliveryRouter.DeliverFromOrbit not found. Orbital purchases land at the vanilla drop spot.");
return list;
}
int count = 0;
int at = -1;
for (int i = 0; i < list.Count; i++)
{
if (list[i].Calls(SpawnDropPod))
{
count++;
at = i;
}
}
LastCallCount = count;
if (count != 1)
{
Log.Error("[Blax Zones] Orbital routing is off: unexpected call count " + count + " of TradeUtility.SpawnDropPod in TradeShip.GiveSoldThingToPlayer, expected 1. Orbital purchases land at the vanilla drop spot.");
return list;
}
// Same signature, static: only the target changes. Labels and exception blocks stay on the instruction.
list[at].opcode = OpCodes.Call;
list[at].operand = DeliverFromOrbit;
return list;
}
catch (Exception e)
{
Log.Error("[Blax Zones] Orbital routing is off: the TradeShip.GiveSoldThingToPlayer transpiler failed: " + e);
return instructions;
}
}
}
}

View File

@ -0,0 +1,277 @@
using System;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Store. Design: "Zone store, safe to remove from a save" and 1.0 "Save-safe zone storage".
/// Blax zones never enter ZoneManager's save list: the save prefix swaps allZones for a filtered
/// copy and the finalizer puts the original list object back, even if saving throws. On load the
/// Map.FinalizeLoading prefix re-registers the zones the component loaded.
/// </summary>
/// <remarks>
/// No static field here has an initializer, so the class has no type initializer: a reflection bind
/// that fails can never make ZoneStore.Loading throw TypeInitializationException in the load hook.
/// Every bind happens on first use, inside the callers' try/catch.
/// </remarks>
public static class ZoneStore
{
private static AccessTools.FieldRef<ZoneManager, List<Zone>> allZonesRef;
private static bool allZonesBindFailed;
/// <summary>
/// ZoneManager's private allZones (ZoneManager.cs:9), bound on first use. Null when the field can't
/// be bound (logged once); the save filter then filters the public AllZones list in place.
/// </summary>
public static AccessTools.FieldRef<ZoneManager, List<Zone>> AllZonesRef
{
get
{
if (ZonesTestHooks.AllZonesUnbound)
return null;
if (allZonesRef == null && !allZonesBindFailed)
{
try
{
allZonesRef = AccessTools.FieldRefAccess<ZoneManager, List<Zone>>("allZones");
}
catch (Exception e)
{
ZonesLog.Once("Binding ZoneManager.allZones", e);
}
allZonesBindFailed = allZonesRef == null;
}
return allZonesRef;
}
}
/// <summary>
/// True while the Map.FinalizeLoading prefix registers loaded zones, set in the prefix and cleared
/// in its finalizer. RemoveCell must not unclaim or destroy beds (1.2) while it is set.
/// </summary>
[ThreadStatic] public static bool Loading;
// The internal grid setters (ZoneManager.cs:68, 73). Bound on first use, so a renamed method
// breaks loading only, never the save filter.
private static Action<ZoneManager, Zone, IntVec3> addZoneGridCell;
private static Action<ZoneManager, IntVec3> clearZoneGridCell;
private static Action<ZoneManager, Zone, IntVec3> AddZoneGridCell =>
addZoneGridCell ??= AccessTools.MethodDelegate<Action<ZoneManager, Zone, IntVec3>>(
AccessTools.Method(typeof(ZoneManager), "AddZoneGridCell", new[] { typeof(Zone), typeof(IntVec3) }));
private static Action<ZoneManager, IntVec3> ClearZoneGridCell =>
clearZoneGridCell ??= AccessTools.MethodDelegate<Action<ZoneManager, IntVec3>>(
AccessTools.Method(typeof(ZoneManager), "ClearZoneGridCell", new[] { typeof(IntVec3) }));
/// <summary>
/// Is this one of ours: a zone whose class, or a base class below Zone, comes from this assembly.
/// A subclass another mod derives from a Blax zone needs Blax Zones to load just the same, so it
/// is saved with ours.
/// </summary>
public static bool IsBlaxZone(Zone zone)
{
if (zone == null)
return false;
for (Type t = zone.GetType(); t != null && t != typeof(Zone); t = t.BaseType)
{
if (t.Assembly == typeof(ZoneStore).Assembly)
return true;
}
return false;
}
/// <summary>
/// Registers one loaded zone with the map: sets zone.zoneManager, calls the public
/// ZoneManager.RegisterZone (ZoneManager.cs:52), then the internal AddZoneGridCell
/// (ZoneManager.cs:68) per cell through an AccessTools delegate, and marks the zone mesh dirty.
/// Cells outside the map or already held by another zone are dropped first, so the grid keeps
/// one zone per cell; a zone left with no cells is not registered and is never saved again.
/// Things are not checked here: the thingGrid is still empty, and vanilla's spawn loop trims
/// our zones as it trims stockpiles (ZoneManager.cs:97-112).
/// </summary>
public static void RegisterLoaded(Map map, Zone zone)
{
if (map == null || zone == null)
return;
ZoneManager manager = map.zoneManager;
if (manager == null)
throw new InvalidOperationException("map " + map + " has no zoneManager");
if (manager.AllZones.Contains(zone))
return;
zone.cells ??= new List<IntVec3>();
zone.cells.RemoveAll(c => !c.InBounds(map) || (manager.ZoneAt(c) != null && manager.ZoneAt(c) != zone));
if (zone.cells.Count == 0)
return;
zone.zoneManager = manager;
manager.RegisterZone(zone);
Action<ZoneManager, Zone, IntVec3> add = AddZoneGridCell;
List<IntVec3> cells = zone.cells;
for (int i = 0; i < cells.Count; i++)
add(manager, zone, cells[i]);
// A no-op while loading (MapDrawer.cs:68); Map.FinalizeInit regenerates every mesh anyway (Map.cs:834-837).
if (map.mapDrawer != null)
{
for (int i = 0; i < cells.Count; i++)
map.mapDrawer.MapMeshDirty(cells[i], MapMeshFlagDefOf.Zone);
}
}
/// <summary>
/// Takes a zone whose registration threw back out of the manager and the grid, so a half-registered
/// zone is never saved or drawn. Never throws.
/// </summary>
internal static void UndoRegister(Map map, Zone zone)
{
if (map?.zoneManager == null || zone == null)
return;
try
{
ZoneManager manager = map.zoneManager;
// AllZones is allZones itself (ZoneManager.cs:13); DeregisterZone would run PostDeregister.
manager.AllZones?.Remove(zone);
if (zone.cells != null)
{
foreach (IntVec3 c in zone.cells)
{
if (c.InBounds(map) && manager.ZoneAt(c) == zone)
ClearZoneGridCell(manager, c);
}
}
}
catch
{
// Best effort inside a catch that already logged.
}
}
}
/// <summary>What the save prefix changed in one ZoneManager, so the finalizer undoes exactly that.</summary>
public sealed class ZoneSaveState
{
/// <summary>The list object allZones held before the save.</summary>
public List<Zone> list;
/// <summary>The bound field the prefix swapped a filtered copy into; null when it filtered list in place.</summary>
public AccessTools.FieldRef<ZoneManager, List<Zone>> swappedVia;
/// <summary>The list's full contents before an in-place filter; null after a swap.</summary>
public List<Zone> contents;
public void Restore(ZoneManager manager)
{
if (swappedVia != null)
{
swappedVia(manager) = list;
return;
}
list.Clear();
list.AddRange(contents);
}
}
/// <summary>Save: drop Blax zones from ZoneManager's list while it is written, restore it after.</summary>
[HarmonyPatch(typeof(ZoneManager), nameof(ZoneManager.ExposeData))]
public static class Patch_ZoneManager_ExposeData
{
/// <summary>
/// Only when Scribe.mode == Saving: swap allZones for a copy without Blax zones; __state keeps the
/// original. When allZones can't be bound, the public AllZones list (the same object) is filtered
/// in place instead, so a failed bind never writes Blax zones into the vanilla list.
/// </summary>
public static void Prefix(ZoneManager __instance, out ZoneSaveState __state)
{
__state = null;
try
{
if (Scribe.mode != LoadSaveMode.Saving || __instance == null)
return;
AccessTools.FieldRef<ZoneManager, List<Zone>> field = ZoneStore.AllZonesRef;
List<Zone> all = field != null ? field(__instance) : __instance.AllZones;
if (all == null)
return;
var vanilla = new List<Zone>(all.Count);
for (int i = 0; i < all.Count; i++)
{
if (!ZoneStore.IsBlaxZone(all[i]))
vanilla.Add(all[i]);
}
if (field != null)
{
__state = new ZoneSaveState { list = all, swappedVia = field };
field(__instance) = vanilla;
}
else if (vanilla.Count != all.Count)
{
__state = new ZoneSaveState { list = all, contents = new List<Zone>(all) };
all.Clear();
all.AddRange(vanilla);
}
}
catch (Exception e)
{
ZonesLog.Once("Zone save filter", e);
}
}
/// <summary>Puts the original list object, or its contents, back, even when saving threw.</summary>
public static Exception Finalizer(ZoneManager __instance, ZoneSaveState __state, Exception __exception)
{
if (__state != null)
{
try
{
__state.Restore(__instance);
}
catch (Exception e)
{
ZonesLog.Once("Zone save restore", e);
}
}
return __exception;
}
}
/// <summary>
/// Load: Map.FinalizeLoading (Map.cs:750) runs while zoneGrid exists and nothing has spawned. The
/// prefix registers the component's loaded zones so vanilla's spawn loop trims them like stockpiles.
/// Its whole body sits in try/catch: vanilla catches an exception there and skips the rest of the
/// map's load (Game.cs:619-623). The finalizer never throws either.
/// </summary>
[HarmonyPatch(typeof(Map), nameof(Map.FinalizeLoading))]
public static class Patch_Map_FinalizeLoading
{
public static void Prefix(Map __instance, out bool __state)
{
__state = false;
try
{
__state = ZoneStore.Loading;
ZoneStore.Loading = true;
MapComponent_BlaxZones.Of(__instance)?.RegisterLoadedZones();
}
catch (Exception e)
{
ZonesLog.Once("Registering loaded zones", e);
}
}
public static Exception Finalizer(bool __state, Exception __exception)
{
try
{
ZoneStore.Loading = __state;
}
catch (Exception e)
{
ZonesLog.Once("Clearing the zone load flag", e);
}
return __exception;
}
}
}

View File

@ -0,0 +1,19 @@
using System.Collections.Generic;
using Verse;
namespace BlaxZones
{
/// <summary>Package Designators. Design: 1.0 "Delivery zone" > Designators. The expand gizmo of a selected delivery zone.</summary>
public partial class Zone_Delivery
{
/// <summary>
/// DesignatorUtility.FindAllowedDesignator&lt;Designator_ZoneAdd_Delivery_Expand&gt;(), as Zone_Fishing does
/// (Zone_Fishing.cs:196-199). The expand designator is in no menu, so this returns one standalone instance
/// (DesignatorUtility.cs:40-46). Zone.GetGizmos yields it first (Zone.cs:319-324).
/// </summary>
public override IEnumerable<Gizmo> GetZoneAddGizmos()
{
yield return DesignatorUtility.FindAllowedDesignator<Designator_ZoneAdd_Delivery_Expand>();
}
}
}

View File

@ -0,0 +1,66 @@
using System.Collections.Generic;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.Sound;
namespace BlaxZones
{
/// <summary>Package Tab. Design: 1.0 "Delivery zone" > Tab. The delivery zone's tab and its copy/paste gizmos.</summary>
public partial class Zone_Delivery
{
/// <summary>Vanilla's copy and paste icons (StorageSettingsClipboard.cs:32, 43), loaded on first use on the main thread.</summary>
private static Texture2D copyIcon, pasteIcon;
private static Texture2D CopyIcon => copyIcon ??= ContentFinder<Texture2D>.Get("UI/Commands/CopySettings", reportFailure: false);
private static Texture2D PasteIcon => pasteIcon ??= ContentFinder<Texture2D>.Get("UI/Commands/PasteSettings", reportFailure: false);
/// <summary>The shared tab in an array, as Zone_Stockpile keeps its ITabs (Zone_Stockpile.cs:13-16, 70-73): the inspect pane asks every frame.</summary>
private static InspectTabBase[] inspectTabs;
/// <summary>ITab_Delivery, through InspectTabManager.GetSharedInstance.</summary>
public override IEnumerable<InspectTabBase> GetInspectTabs()
{
return inspectTabs ??= new[] { InspectTabManager.GetSharedInstance(typeof(ITab_Delivery)) };
}
/// <summary>The base zone gizmos plus copy and paste of the zone's settings (DeliveryClipboard).</summary>
public override IEnumerable<Gizmo> GetGizmos()
{
foreach (Gizmo g in base.GetGizmos())
yield return g;
yield return new Command_Action
{
icon = CopyIcon,
defaultLabel = "BlaxZones_CopySettings".Translate(),
defaultDesc = "BlaxZones_CopySettingsDesc".Translate(),
hotKey = KeyBindingDefOf.Misc4,
action = () =>
{
SoundDefOf.Tick_High.PlayOneShotOnCamera();
DeliveryClipboard.Copy(this);
Messages.Message("BlaxZones_SettingsCopied".Translate(), MessageTypeDefOf.NeutralEvent, historical: false);
},
};
var paste = new Command_Action
{
icon = PasteIcon,
defaultLabel = "BlaxZones_PasteSettings".Translate(),
defaultDesc = "BlaxZones_PasteSettingsDesc".Translate(),
hotKey = KeyBindingDefOf.Misc5,
action = () =>
{
SoundDefOf.Tick_High.PlayOneShotOnCamera();
DeliveryClipboard.PasteInto(this);
Messages.Message("BlaxZones_SettingsPasted".Translate(), MessageTypeDefOf.NeutralEvent, historical: false);
},
};
if (!DeliveryClipboard.HasCopy)
paste.Disable("BlaxZones_NothingCopied".Translate());
yield return paste;
}
}
}

View File

@ -0,0 +1,139 @@
using System.Text;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxZones
{
/// <summary>
/// A delivery zone: a landing pad for drop pods (design: "Delivery zone"). Saved inside
/// MapComponent_BlaxZones, never in ZoneManager (design: "Zone store, safe to remove from a save").
///
/// This file holds the data model, saving and the cache notifications (integrator). The tab and
/// copy/paste gizmos are in Zone_Delivery.Tab.cs (package Tab), the expand designator in
/// Zone_Delivery.Designators.cs (package Designators).
/// </summary>
public partial class Zone_Delivery : Zone
{
/// <summary>Amber at the vanilla zone opacity (ZoneColorUtility.ZoneOpacity, 0.09).</summary>
public static readonly Color ZoneColor = new Color(1f, 0.70f, 0.10f, 0.09f);
/// <summary>The designator icon tint (defaultIconColor), amber at full opacity.</summary>
public static readonly Color IconColor = new Color(1f, 0.70f, 0.10f, 1f);
/// <summary>What may land here. Always a child of DeliveryFilters.Parent.</summary>
public ThingFilter filter;
/// <summary>Higher priority zones are tried first; ties go to the lower zone ID.</summary>
public StoragePriority priority = StoragePriority.Normal;
/// <summary>Orbital trade purchases, sale silver and ZonesApi callers (Blax Slaves payouts) may land here.</summary>
public bool acceptOrbital = true;
/// <summary>Trader caravans and tribute collectors camp next to this zone.</summary>
public bool campHere;
protected override Color NextZoneColor => ZoneColor;
/// <summary>The map, or null while the zone is loaded but not yet registered (zoneManager unset).</summary>
public Map MapOrNull => zoneManager?.map;
public Zone_Delivery()
{
}
public Zone_Delivery(ZoneManager zoneManager) : base("BlaxZones_DeliveryZone".Translate(), zoneManager)
{
filter = DeliveryFilters.NewDefaultFilter();
}
public override void ExposeData()
{
base.ExposeData();
Scribe_Deep.Look(ref filter, "filter");
Scribe_Values.Look(ref priority, "priority", StoragePriority.Normal);
Scribe_Values.Look(ref acceptOrbital, "acceptOrbital", true);
Scribe_Values.Look(ref campHere, "campHere", false);
if (Scribe.mode == LoadSaveMode.PostLoadInit)
{
filter ??= DeliveryFilters.NewDefaultFilter();
if (priority == StoragePriority.Unstored)
priority = StoragePriority.Normal;
}
}
/// <summary>Whether this zone takes deliveries from the source (its checkbox).</summary>
public bool AcceptsSource(DeliverySource source)
{
switch (source)
{
case DeliverySource.Orbital:
return acceptOrbital;
default:
return false;
}
}
/// <summary>The zone's own filter plus the never-routed refusals. Not the cell rules.</summary>
public bool Accepts(Thing thing)
{
if (DeliveryFilters.NeverRouted(thing))
return false;
return filter == null || filter.Allows(thing);
}
/// <summary>Copies the player's choices (filter, priority, sources, camp) from another zone. Never the cells.</summary>
public void CopySettingsFrom(Zone_Delivery other)
{
if (other == null || other == this)
return;
filter ??= new ThingFilter();
if (other.filter != null)
filter.CopyAllowancesFrom(other.filter);
priority = other.priority;
acceptOrbital = other.acceptOrbital;
campHere = other.campHere;
}
public override void AddCell(IntVec3 c)
{
base.AddCell(c);
MapComponent_BlaxZones.Of(MapOrNull)?.Notify_ZoneCellsChanged(this);
}
public override void RemoveCell(IntVec3 c)
{
Map map = MapOrNull;
base.RemoveCell(c);
MapComponent_BlaxZones.Of(map)?.Notify_ZoneCellsChanged(this);
}
public override void PostDeregister()
{
Map map = MapOrNull;
base.PostDeregister();
MapComponent_BlaxZones.Of(map)?.Notify_ZoneRemoved(this);
}
public override string GetInspectString()
{
var sb = new StringBuilder(base.GetInspectString() ?? "");
try
{
MapComponent_BlaxZones comp = MapComponent_BlaxZones.Of(MapOrNull);
string rules = comp?.InspectLineFor(this);
if (!rules.NullOrEmpty())
{
if (sb.Length > 0)
sb.AppendLine();
sb.Append(rules);
}
}
catch (System.Exception e)
{
ZonesLog.Once("Delivery zone inspect string", e);
}
return sb.ToString();
}
}
}

View File

@ -0,0 +1,39 @@
using System;
using Verse;
namespace BlaxZones
{
/// <summary>
/// The API other mods bind by reflection (design: "Works with the other Blax mods"). Version 1 is
/// frozen: Blax Slaves binds TryFindDropSpot by exact delegate type and reads Version as a property.
/// Members are only ever added, each with a higher Version.
/// </summary>
public static class ZonesApi
{
public static int Version => 1;
/// <summary>
/// A cell for one drop pod holding exactly this thing, by the orbital rules: the zone's orbital
/// checkbox, its filter and priority, the pod rule and the overflow setting. False when no zone
/// fits, always false for a Pawn, never throws. The caller spawns the pod exactly at the cell
/// (TradeUtility.SpawnDropPod or DropPodUtility.MakeDropPodAt) and calls again per thing after
/// spawning the last pod, because a falling pod is what marks its cell as taken.
/// </summary>
public static bool TryFindDropSpot(Map map, Thing thing, out IntVec3 cell)
{
cell = IntVec3.Invalid;
try
{
if (map == null || thing == null || thing is Pawn)
return false;
return DeliveryRouter.TryFindDropSpot(map, thing, DeliverySource.Orbital, out cell);
}
catch (Exception e)
{
ZonesLog.Once("ZonesApi.TryFindDropSpot", e);
cell = IntVec3.Invalid;
return false;
}
}
}
}

View File

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using Verse;
namespace BlaxZones
{
/// <summary>
/// One-time error logging for hook bodies. Every hook sits in try/catch and logs through here, so
/// a broken hook logs once per game instead of every call. The flags reset in
/// MapComponent_BlaxZones.FinalizeInit, so a failure in a later game logs again.
/// </summary>
public static class ZonesLog
{
private static readonly HashSet<string> logged = new HashSet<string>();
/// <summary>Logs "[Blax Zones] where failed" with the exception, once per key until the next reset.</summary>
public static void Once(string where, Exception e)
{
try
{
if (logged.Add(where))
Log.Error("[Blax Zones] " + where + " failed (logged once per game): " + e);
}
catch
{
// Logging must never throw into a hook.
}
}
/// <summary>A one-time message (stand-downs, hints), not an error.</summary>
public static void MessageOnce(string key, string text)
{
if (logged.Add("msg:" + key))
Log.Message("[Blax Zones] " + text);
}
public static void ResetOnce() => logged.Clear();
}
/// <summary>
/// Switches the test mod flips to force failure paths. Not game state: nothing here is saved and
/// the test runner resets every field after each test.
/// </summary>
public static class ZonesTestHooks
{
/// <summary>DeliveryRouter.TryFindDropSpot throws, to test that every routed path falls back to vanilla.</summary>
public static bool RouterThrows;
/// <summary>ZoneStore.AllZonesRef returns null, as when a game update renames ZoneManager.allZones.</summary>
public static bool AllZonesUnbound;
public static void Reset()
{
RouterThrows = false;
AllZonesUnbound = false;
}
}
}

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<ModMetaData>
<name>Blax Zones Tests</name>
<author>Blax Gaming</author>
<packageId>blax.zones.tests</packageId>
<supportedVersions>
<li>1.7</li>
</supportedVersions>
<!-- No modDependencies: Blax Zones has no download page yet, and the game drops a dependency without one,
with a warning. run-tests.ps1 loads Blax Zones before this mod. -->
<loadAfter>
<li>blax.castes</li>
<li>blax.zones</li>
<li>blax.slaves</li>
</loadAfter>
<description>In-game test suite for Blax Zones. Does nothing unless the game is started with -blaxzonestests (see Tests/run-tests.ps1). Not for players.</description>
</ModMetaData>

View File

@ -0,0 +1,45 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- In-game test suite. Built and run by Tests/run-tests.ps1; the DLL is not committed. -->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<AssemblyName>BlaxZonesTests</AssemblyName>
<RootNamespace>BlaxZonesTests</RootNamespace>
<LangVersion>latest</LangVersion>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<OutputPath>..\1.7\Assemblies\</OutputPath>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
<GenerateDependencyFile>false</GenerateDependencyFile>
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
<DebugType>portable</DebugType>
<PathMap>$(MSBuildProjectDirectory)=Tests/BlaxZonesTests/Source</PathMap>
</PropertyGroup>
<PropertyGroup>
<RimWorldDir Condition="'$(RimWorldDir)' == ''">E:\SteamLibrary\steamapps\common\RimWorld</RimWorldDir>
<HarmonyDir Condition="'$(HarmonyDir)' == ''">E:\SteamLibrary\steamapps\workshop\content\294100\2009463077\1.7\Assemblies</HarmonyDir>
<BlaxZonesDir Condition="'$(BlaxZonesDir)' == ''">$(MSBuildProjectDirectory)\..\..\..\1.7\Assemblies</BlaxZonesDir>
</PropertyGroup>
<ItemGroup>
<Reference Include="Assembly-CSharp">
<HintPath>$(RimWorldDir)\Assembly-CSharp.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="UnityStubs">
<HintPath>$(RimWorldDir)\UnityStubs.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="0Harmony">
<HintPath>$(HarmonyDir)\0Harmony.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="BlaxZones">
<HintPath>$(BlaxZonesDir)\BlaxZones.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
</Project>

View File

@ -0,0 +1,415 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxZones;
using HarmonyLib;
using RimWorld;
using Verse;
using Verse.AI.Group;
namespace BlaxZonesTests
{
/// <summary>
/// Package Camp. Design: 1.0 "Trader caravans camp at a zone" > Tests, and "Headless tests in 1.0" >
/// Stand-down tests (one per trading-spot id in Compat.TradingSpots.cs, through SimulatedActive).
/// Tests: [BlaxTest("camp: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped.
///
/// Arrivals are forced through the incident workers, the way the storyteller fires them. Everything an
/// arrival brings (lords, pawns, letters) leaves the map after the test. Test-only Harmony postfixes on
/// CampScope.TryFindCampSpot and the patched RCellFinder overload count what the camp code saw; they
/// are removed in Fixtures.OnCleanup.
/// </summary>
public static class CampTests
{
/// <summary>The design's radius, written out so the test doesn't just echo CampScope.Radius.</summary>
private const int Radius = 6;
private const string HarmonyId = "blax.zones.tests.camp";
private const string ForcedFailure = "BlaxZonesTests: forced failure inside TryExecuteWorker";
private const string HospitalityId = "Orion.Hospitality";
/// <summary>The ids the stand-down tests below cover; a new id in Compat.TradingSpotMods needs a test here.</summary>
private static readonly string[] StandDownTested =
{
Compat.TradingSpotRewritten, Compat.TradingSpotKV, Compat.TradingSpotGMT, Compat.TradingControl,
};
private static readonly AccessTools.FieldRef<LordJob_TradeWithColony, IntVec3> TradeChillSpot =
AccessTools.FieldRefAccess<LordJob_TradeWithColony, IntVec3>("chillSpot");
private static Harmony harmony;
private static Harmony H => harmony ??= new Harmony(HarmonyId);
// What the observation postfixes saw since Observe().
private static int spotCalls, spotHits, outsideCalls;
private static IntVec3 lastSpot = IntVec3.Invalid;
private static bool scopeAtFailure;
// ---- trader caravans ----------------------------------------------------------------
[BlaxTest("camp: a trader caravan camps within 6 cells of a camp zone")]
public static void CaravanCampsAtZone()
{
Map map = Fixtures.Map;
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: true);
Observe();
IntVec3 spot = TraderCaravan();
T.Check(spotHits == 1, $"camp spots picked: {spotHits} of {spotCalls} calls, expected 1");
T.Equal(lastSpot, spot, "the lord's chill spot against the camp spot CampScope picked");
T.Check(Near(zone, spot), "chill spot " + spot + " is more than " + Radius + " cells from the zone");
T.Check(spot.Standable(map) && !spot.Roofed(map) && !spot.Fogged(map), "chill spot " + spot + " is not standable, unroofed and unfogged");
}
[BlaxTest("camp: a walled-off camp zone keeps the vanilla spot")]
public static void WalledOffZoneKeepsVanillaSpot()
{
CellRect area = Fixtures.TestArea(9, 9);
CellRect ring = area.ExpandedBy(Fixtures.AreaMargin);
foreach (IntVec3 c in ring.EdgeCells)
Fixtures.Wall(c);
Zone_Delivery zone = Fixtures.DeliveryZone(CellRect.SingleCell(area.CenterCell), camp: true);
CellRect inside = ring.ContractedBy(1);
T.Check(GenRadial.RadialCellsAround(area.CenterCell, Radius, true).All(inside.Contains), "the wall ring doesn't enclose every cell within " + Radius);
Observe();
IntVec3 spot = TraderCaravan();
T.Check(spotCalls >= 1, "the caravan never asked CampScope for a spot");
T.Equal(0, spotHits, "camp spots picked for a walled-off zone");
T.Check(!ring.Contains(spot), "chill spot " + spot + " is inside the walls");
T.Check(!Near(zone, spot), "chill spot " + spot + " is within " + Radius + " cells of the walled-off zone");
}
[BlaxTest("camp: without Caravans camp here or with the global setting off the caravan keeps the vanilla spot")]
public static void OptionOffKeepsVanillaSpot()
{
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: false);
Observe();
TraderCaravan();
T.Check(spotCalls >= 1, "zone option off: the caravan never asked CampScope for a spot");
T.Equal(0, spotHits, "zone option off: camp spots picked");
zone.campHere = true;
Fixtures.Settings.campAtZones = false;
Observe();
TraderCaravan();
T.Check(spotCalls >= 1, "global setting off: the caravan never asked CampScope for a spot");
T.Equal(0, spotHits, "global setting off: camp spots picked");
}
[BlaxTest("camp: camp spots are standable, unroofed and within 6 cells, outside enclosed rooms first, and pass the caller's validator")]
public static void CampSpotRules()
{
Map map = Fixtures.Map;
CellRect area = Fixtures.TestArea(9, 9);
IntVec3 center = area.CenterCell;
Zone_Delivery zone = Fixtures.DeliveryZone(CellRect.SingleCell(center), camp: true);
CellRect roofed = CellRect.CenteredOn(center, 1);
Fixtures.Roof(roofed);
// An unroofed walled pocket 3 to 4 cells east of the zone: an enclosed room within the radius.
var pocket = new CellRect(center.x + 3, center.z - 1, 2, 3);
foreach (IntVec3 c in pocket.ExpandedBy(1).EdgeCells)
Fixtures.Wall(c);
Room pocketRoom = pocket.CenterCell.GetRoom(map);
T.Check(pocketRoom != null && !pocketRoom.TouchesMapEdge, "the walled pocket is not an enclosed room");
Room open = area.Min.GetRoom(map);
if (open == null || !open.TouchesMapEdge)
T.Skip("the test area lies in an enclosed room on this map, so nothing is outside one");
for (int i = 0; i < 30; i++)
{
T.Check(CampScope.TryFindCampSpot(map, null, out IntVec3 c), "no camp spot with a null validator (try " + i + ")");
T.Check(Near(zone, c), c + " is more than " + Radius + " cells from the zone");
T.Check(c.Standable(map) && !c.Roofed(map) && !c.Fogged(map), c + " is not standable, unroofed and unfogged");
T.Check(!roofed.Contains(c), c + " is under the roof");
T.Check(!pocket.Contains(c), c + " is in the enclosed pocket although open cells pass");
}
T.Check(!CampScope.TryFindCampSpot(map, c => false, out IntVec3 none), "a camp spot passed a validator that refuses every cell");
T.Check(!none.IsValid, "a refused search still set the cell to " + none);
T.Check(CampScope.TryFindCampSpot(map, pocket.Contains, out IntVec3 inPocket) && pocket.Contains(inPocket),
"the enclosed pocket was not used when only its cells pass");
}
// ---- visitors -----------------------------------------------------------------------
[BlaxTest("camp: a visitor group ignores the camp zone")]
public static void VisitorGroupIgnoresZone()
{
Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: true);
// Vanilla's worker even when Hospitality replaced the def's worker class: this is the path
// that reaches the patched overload (IncidentWorker_VisitorGroup.cs:22-26).
var worker = new IncidentWorker_VisitorGroup { def = IncidentDefOf.VisitorGroup };
IncidentParms parms = Parms(worker, "a visitor group");
Observe();
Lord lord = Arrive(worker, parms, "visitor group");
T.Check(lord.LordJob is LordJob_VisitColony, "visitor lord job is " + lord.LordJob?.GetType().FullName);
T.Check(outsideCalls >= 1, "the visitor group never reached RCellFinder.TryFindRandomSpotJustOutsideColony");
T.Equal(0, spotCalls, "CampScope.TryFindCampSpot calls during a visitor group");
}
[BlaxTest("camp: Hospitality guests ignore the camp zone")]
public static void HospitalityGuestsIgnoreZone()
{
if (!Compat.IsActive(HospitalityId))
T.Skip("needs Hospitality (-Compat)");
Map map = Fixtures.Map;
IncidentWorker worker = IncidentDefOf.VisitorGroup.Worker;
T.Check(worker.GetType().Namespace == "Hospitality", "VisitorGroup's worker is " + worker.GetType().FullName + ", not Hospitality's");
// Welcome guests without the safety dialog or the wait for guest beds; restored after the test.
MapComponent comp = map.components.FirstOrDefault(c => c.GetType().FullName == "Hospitality.Hospitality_MapComponent");
T.NotNull(comp, "Hospitality's map component");
SetForTest(comp, "guestsAreWelcome", true);
SetForTest(comp, "askForSafety", false);
SetForTest(comp, "refuseGuestsUntilWeHaveBeds", false);
Type settings = AccessTools.TypeByName("Hospitality.ModSettings_Hospitality");
if (settings != null)
SetForTest(settings, "disableGuests", false);
Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: true);
IncidentParms parms = Parms(worker, "Hospitality guests");
parms.points = 100f;
Observe();
Lord lord = Arrive(worker, parms, "Hospitality guest group");
T.Check(lord.LordJob.GetType().Namespace == "Hospitality", "guest lord job is " + lord.LordJob.GetType().FullName);
T.Equal(0, spotCalls, "CampScope.TryFindCampSpot calls during Hospitality's guest arrival");
}
// ---- scope ---------------------------------------------------------------------------
[BlaxTest("camp: an exception inside TryExecuteWorker leaves CampScope unset")]
public static void ExceptionLeavesScopeUnset()
{
Fixtures.OnCleanup(() => CampScope.Active = false);
CampScope.Active = false;
IncidentWorker worker = IncidentDefOf.TraderCaravanArrival.Worker;
MethodInfo sendLetter = AccessTools.Method(typeof(IncidentWorker_TraderCaravanArrival), "SendLetter");
MethodInfo thrower = AccessTools.Method(typeof(CampTests), nameof(ThrowInsideIncident));
T.NotNull(sendLetter, "IncidentWorker_TraderCaravanArrival.SendLetter");
H.Patch(sendLetter, prefix: new HarmonyMethod(thrower));
Fixtures.OnCleanup(() => H.Unpatch(sendLetter, thrower));
T.ExpectErrors(ForcedFailure, 1);
IncidentParms parms = Parms(worker, "a trader caravan");
LeaveAfterTest();
scopeAtFailure = false;
try
{
worker.TryExecute(parms);
T.Fail("the forced failure never reached the caller");
}
catch (Exception e) when (Mentions(e, ForcedFailure))
{
// What the game's tick loop does with an incident that throws (TickManager.cs:420-427).
Log.Error(e.ToString());
}
T.Check(scopeAtFailure, "CampScope was not set inside TryExecuteWorker");
T.Check(!CampScope.Active, "CampScope is still set after the exception");
}
// ---- stand-down ----------------------------------------------------------------------
[BlaxTest("camp: every trading-spot id in Compat has a stand-down test")]
public static void StandDownCoverage()
{
List<string> missing = Compat.TradingSpotMods.Except(StandDownTested).ToList();
T.Check(missing.Count == 0, "trading-spot ids without a stand-down test: " + string.Join(", ", missing));
T.Equal(null, Compat.ActiveTradingSpotMod(), "active trading-spot mod with none installed or simulated");
}
[BlaxTest("camp: stands down for Trading Spot Rewritten and logs once")]
public static void StandDownRewritten() => StandsDown(Compat.TradingSpotRewritten);
[BlaxTest("camp: stands down for [KV] Trading Spot and logs once")]
public static void StandDownKV() => StandsDown(Compat.TradingSpotKV);
[BlaxTest("camp: stands down for [GMT] Trading Spot and logs once")]
public static void StandDownGMT() => StandsDown(Compat.TradingSpotGMT);
[BlaxTest("camp: stands down for Trading Control and logs once")]
public static void StandDownTradingControl() => StandsDown(Compat.TradingControl);
// ---- Royalty -------------------------------------------------------------------------
[BlaxTest("camp: with Royalty a tribute collector camps within 6 cells of the zone")]
public static void TributeCollectorCamps()
{
T.NeedsDlc("Royalty", ModsConfig.RoyaltyActive);
IncidentDef def = DefDatabase<IncidentDef>.GetNamedSilentFail("CaravanArrivalTributeCollector");
T.NotNull(def, "IncidentDef CaravanArrivalTributeCollector");
Faction empire = Faction.OfEmpire;
if (empire == null)
T.Skip("no Empire in this world");
if (empire.HostileTo(Faction.OfPlayer))
T.Skip("the Empire is hostile to the colony in this world");
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: true);
var parms = new IncidentParms { target = Fixtures.Map, forced = true, faction = empire };
Observe();
IntVec3 spot = ChillSpot(Arrive(def.Worker, parms, "tribute collector"));
T.Check(spotHits == 1, $"camp spots picked: {spotHits} of {spotCalls} calls, expected 1");
T.Equal(lastSpot, spot, "the tribute collector's chill spot against the camp spot CampScope picked");
T.Check(Near(zone, spot), "chill spot " + spot + " is more than " + Radius + " cells from the zone");
}
// ---- helpers -------------------------------------------------------------------------
private static void StandsDown(string id)
{
Map map = Fixtures.Map;
T.Check(Compat.TradingSpotMods.Contains(id), id + " is not in Compat.TradingSpotMods");
Compat.SimulatedActive.Add(id);
T.Equal(id, Compat.ActiveTradingSpotMod(), "active trading-spot mod");
Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: true);
string message = CampScope.StandDownMessage(id);
int before = Logged(message);
Observe();
TraderCaravan();
T.Check(spotCalls >= 1, "the caravan never asked CampScope for a spot");
T.Equal(0, spotHits, "camp spots picked while " + id + " is active");
T.Check(!CampScope.TryFindCampSpot(map, null, out _), "a second search camped while " + id + " is active");
T.Equal(1, Logged(message) - before, "stand-down messages for " + id);
}
/// <summary>
/// Forces IncidentDefOf.TraderCaravanArrival on the current map with a friendly trader faction and
/// returns the chill spot its LordJob_TradeWithColony was made with. The caravan leaves after the test.
/// </summary>
private static IntVec3 TraderCaravan()
{
IncidentWorker worker = IncidentDefOf.TraderCaravanArrival.Worker;
IncidentParms parms = Parms(worker, "a trader caravan");
return ChillSpot(Arrive(worker, parms, "trader caravan"));
}
private static IntVec3 ChillSpot(Lord lord)
{
var job = lord.LordJob as LordJob_TradeWithColony;
T.NotNull(job, "LordJob_TradeWithColony (the lord has " + lord.LordJob?.GetType().FullName + ")");
return TradeChillSpot(job);
}
/// <summary>Forced parms for the current map with the first friendly faction the worker accepts as the group's source.</summary>
private static IncidentParms Parms(IncidentWorker worker, string what)
{
var parms = new IncidentParms { target = Fixtures.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 " + what);
return parms;
}
/// <summary>Fires the worker and returns the one lord it made.</summary>
private static Lord Arrive(IncidentWorker worker, IncidentParms parms, string what)
{
HashSet<Lord> before = LeaveAfterTest();
T.Check(worker.TryExecute(parms), what + " did not fire");
T.Check(!CampScope.Active, "CampScope is still set after the " + what);
List<Lord> made = Fixtures.Map.lordManager.lords.Where(l => !before.Contains(l)).ToList();
T.Equal(1, made.Count, "lords made by the " + what);
return made[0];
}
/// <summary>
/// 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.
/// </summary>
private static HashSet<Lord> LeaveAfterTest()
{
Map map = Fixtures.Map;
var lords = new HashSet<Lord>(map.lordManager.lords);
var pawns = new HashSet<Pawn>(map.mapPawns.AllPawnsSpawned);
var letters = new HashSet<Letter>(Find.LetterStack.LettersListForReading);
Fixtures.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);
}
foreach (Letter l in Find.LetterStack.LettersListForReading.Where(l => !letters.Contains(l)).ToList())
Find.LetterStack.RemoveLetter(l);
});
return lords;
}
/// <summary>Counts calls of CampScope.TryFindCampSpot and the patched RCellFinder overload until the test ends.</summary>
private static void Observe()
{
spotCalls = spotHits = outsideCalls = 0;
lastSpot = IntVec3.Invalid;
MethodInfo find = AccessTools.Method(typeof(CampScope), nameof(CampScope.TryFindCampSpot));
MethodInfo outside = AccessTools.Method(typeof(RCellFinder), nameof(RCellFinder.TryFindRandomSpotJustOutsideColony),
new[] { typeof(IntVec3), typeof(Map), typeof(Pawn), typeof(IntVec3).MakeByRefType(), typeof(Predicate<IntVec3>) });
MethodInfo onFind = AccessTools.Method(typeof(CampTests), nameof(AfterFindCampSpot));
MethodInfo onOutside = AccessTools.Method(typeof(CampTests), nameof(AfterSpotJustOutsideColony));
T.NotNull(find, "CampScope.TryFindCampSpot");
T.NotNull(outside, "RCellFinder.TryFindRandomSpotJustOutsideColony(IntVec3, Map, Pawn, out IntVec3, Predicate<IntVec3>)");
if (Harmony.GetPatchInfo(find)?.Postfixes.Any(p => p.owner == HarmonyId) != true)
{
H.Patch(find, postfix: new HarmonyMethod(onFind));
Fixtures.OnCleanup(() => H.Unpatch(find, onFind));
}
if (Harmony.GetPatchInfo(outside)?.Postfixes.Any(p => p.owner == HarmonyId) != true)
{
H.Patch(outside, postfix: new HarmonyMethod(onOutside));
Fixtures.OnCleanup(() => H.Unpatch(outside, onOutside));
}
}
private static void AfterFindCampSpot(bool __result, ref IntVec3 cell)
{
spotCalls++;
if (__result)
{
spotHits++;
lastSpot = cell;
}
}
private static void AfterSpotJustOutsideColony() => outsideCalls++;
private static void ThrowInsideIncident()
{
scopeAtFailure = CampScope.Active;
throw new InvalidOperationException(ForcedFailure);
}
private static bool Mentions(Exception e, string text)
{
for (Exception x = e; x != null; x = x.InnerException)
{
if (x.Message != null && x.Message.Contains(text))
return true;
}
return false;
}
private static bool Near(Zone zone, IntVec3 c) => zone.Cells.Any(z => z.InHorDistOf(c, Radius));
/// <summary>Copies of the text in the log, repeats included.</summary>
private static int Logged(string text) =>
Log.Messages.Where(m => m.text != null && m.text.Contains(text)).Sum(m => m.repeats);
/// <summary>Sets a field (instance on an object, static on a Type) and restores it after the test.</summary>
private static void SetForTest(object owner, string field, object value)
{
Type type = owner as Type ?? owner.GetType();
object target = owner is Type ? null : owner;
FieldInfo f = AccessTools.Field(type, field);
T.NotNull(f, type.FullName + "." + field);
object old = f.GetValue(target);
f.SetValue(target, value);
Fixtures.OnCleanup(() => f.SetValue(target, old));
}
}
}

View File

@ -0,0 +1,245 @@
using System.Collections.Generic;
using System.Linq;
using BlaxZones;
using RimWorld;
using Verse;
namespace BlaxZonesTests
{
/// <summary>
/// Package Designators. Design: 1.0 "Delivery zone" > Tests (designating creates a Zone_Delivery, expand only adds cells, refuses stockpile cells, master toggle).
/// Tests: [BlaxTest("designators: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped.
/// </summary>
public static class DesignatorsTests
{
/// <summary>Keys this package adds in Languages/English/Keyed/BlaxZones_Designators.xml.</summary>
private static readonly string[] OwnKeys = { Designator_ZoneAdd_Delivery.DescKey };
/// <summary>
/// Text fragments of errors this package could cause at startup: the failed XML patch names its file, an
/// unresolved type or a throwing constructor names the class ("could not instantiate special designator from
/// class ..."), a missing texture its path.
/// </summary>
private static readonly string[] StartupErrorFragments =
{
"BlaxZones_Designators", "Designator_ZoneAdd_Delivery", Designator_ZoneAdd_Delivery.IconPath,
};
/// <summary>The designator in the Zone menu (exact type, not the expand one), or a failure.</summary>
private static Designator_ZoneAdd_Delivery MenuDesignator()
{
List<Designator> menu = DesignationCategoryDefOf.Zone.AllResolvedDesignators;
Designator_ZoneAdd_Delivery d = menu.FirstOrDefault(x => x.GetType() == typeof(Designator_ZoneAdd_Delivery)) as Designator_ZoneAdd_Delivery;
T.NotNull(d, "Designator_ZoneAdd_Delivery in the Zone menu");
return d;
}
/// <summary>Designates the cells the way a drag does, with nothing selected unless <paramref name="select"/> is given; tracks every new zone.</summary>
private static List<Zone> Designate(Designator_ZoneAdd_Delivery d, IEnumerable<IntVec3> cells, Zone select = null)
{
Map map = Fixtures.Map;
Find.Selector.ClearSelection();
if (select != null)
Find.Selector.Select(select, playSound: false, forceDesignatorDeselect: false);
var before = new HashSet<Zone>(map.zoneManager.AllZones);
d.DesignateMultiCell(cells.ToList());
List<Zone> made = map.zoneManager.AllZones.Where(z => !before.Contains(z)).ToList();
foreach (Zone z in made)
Fixtures.TrackZone(z);
return made;
}
private static string Cells(IEnumerable<IntVec3> cells) => string.Join(" ", cells.Take(6).Select(c => c.ToString()));
[BlaxTest("designators: the Zone menu holds the delivery designator right after Growing, with its label, tooltip, tinted icon and sounds")]
public static void InZoneMenu()
{
List<Designator> menu = DesignationCategoryDefOf.Zone.AllResolvedDesignators;
int growing = menu.FindIndex(x => x.GetType() == typeof(Designator_ZoneAdd_Growing));
T.Check(growing >= 0, "Designator_ZoneAdd_Growing not in the Zone menu");
List<int> ours = Enumerable.Range(0, menu.Count).Where(i => menu[i].GetType() == typeof(Designator_ZoneAdd_Delivery)).ToList();
T.Equal(1, ours.Count, "Designator_ZoneAdd_Delivery entries in the Zone menu");
T.Check(!menu.Any(x => x is Designator_ZoneAdd_Delivery_Expand), "the expand designator is in the Zone menu");
int at = ours[0];
if (at != growing + 1)
{
// A mod loaded after Zones may insert after Growing too; only its own designators may sit between.
List<Designator> between = at > growing ? menu.GetRange(growing + 1, at - growing - 1) : new List<Designator>();
T.Check(at > growing && between.All(x => x.GetType().Assembly != typeof(Designator).Assembly),
"delivery designator at index " + at + ", Growing at " + growing + ": " + string.Join(", ", menu.Select(x => x.GetType().Name)));
T.Info("other mods' designators between Growing and delivery: " + string.Join(", ", between.Select(x => x.GetType().FullName)));
}
var d = (Designator_ZoneAdd_Delivery)menu[at];
T.Equal("BlaxZones_DeliveryZone".Translate().ToString(), d.defaultLabel, "label");
T.Check(!d.defaultDesc.NullOrEmpty() && d.defaultDesc == Designator_ZoneAdd_Delivery.DescKey.Translate().ToString(), "tooltip is not the translated " + Designator_ZoneAdd_Delivery.DescKey);
T.Check(d.defaultDesc.Contains("4"), "tooltip doesn't mention the 4-cell home area growth: " + d.defaultDesc);
T.Check(d.icon != null && d.icon != BaseContent.BadTex, "icon is missing or the bad-texture placeholder");
T.Equal(Zone_Delivery.IconColor, d.defaultIconColor, "icon tint (defaultIconColor)");
T.Equal(Zone_Delivery.IconColor, d.IconDrawColor, "icon draw color");
T.Equal(Designator_ZoneAdd_Delivery.TutorTag, d.tutorTag, "tutorTag");
T.Equal(SoundDefOf.Designate_ZoneAdd_Stockpile, d.soundSucceeded, "soundSucceeded");
T.Equal(SoundDefOf.Designate_DragAreaAdd, d.soundDragSustain, "soundDragSustain");
T.Equal(SoundDefOf.Designate_DragZone_Changed, d.soundDragChanged, "soundDragChanged");
var missing = OwnKeys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
}
[BlaxTest("designators: the patch and the designators load with no error, core only included")]
public static void LoadedWithoutErrors()
{
T.Info("DLCs: Royalty " + ModsConfig.RoyaltyActive + ", Ideology " + ModsConfig.IdeologyActive + ", Biotech " + ModsConfig.BiotechActive +
", Odyssey " + ModsConfig.OdysseyActive);
var errors = Log.Messages
.Where(m => (m.type == LogMessageType.Error) && m.text != null && StartupErrorFragments.Any(f => m.text.Contains(f)))
.ToList();
T.Check(errors.Count == 0, "errors from the designator patch or class: " + string.Join(" | ", errors.Take(3).Select(e => e.text)));
MenuDesignator();
var expand = DesignatorUtility.FindAllowedDesignator<Designator_ZoneAdd_Delivery_Expand>();
T.NotNull(expand, "the expand designator");
T.Equal("DesignatorZoneExpand".Translate().ToString(), expand.defaultLabel, "expand label");
T.Equal(Zone_Delivery.IconColor, expand.defaultIconColor, "expand icon tint");
}
[BlaxTest("designators: Visible follows the delivery zones setting live, menu and expand designator")]
public static void VisibleFollowsSetting()
{
BlaxZonesSettings s = Fixtures.Settings;
Designator_ZoneAdd_Delivery d = MenuDesignator();
var expand = DesignatorUtility.FindAllowedDesignator<Designator_ZoneAdd_Delivery_Expand>();
s.deliveryZones = true;
T.Check(d.Visible && expand.Visible, "hidden with the setting on");
s.deliveryZones = false;
T.Check(!d.Visible, "menu designator visible with the setting off");
T.Check(!expand.Visible, "expand designator visible with the setting off");
s.deliveryZones = true;
T.Check(d.Visible && expand.Visible, "still hidden after turning the setting back on");
}
[BlaxTest("designators: designating unroofed cells creates one delivery zone with exactly those cells and default settings")]
public static void DesignateCreatesZone()
{
Map map = Fixtures.Map;
CellRect area = Fixtures.TestArea(4, 3);
Designator_ZoneAdd_Delivery d = MenuDesignator();
var refused = area.Cells.Where(c => !d.CanDesignateCell(c).Accepted).ToList();
T.Check(refused.Count == 0, "CanDesignateCell refused test-area cells: " + Cells(refused));
T.Check(area.Cells.All(c => !c.Roofed(map)), "test area is roofed");
List<Zone> made = Designate(d, area.Cells);
T.Equal(1, made.Count, "new zones");
var zone = made[0] as Zone_Delivery;
T.Check(zone != null, "the new zone is a " + made[0].GetType().FullName + ", not a Zone_Delivery");
T.Equal(area.Area, zone.CellCount, "zone cells");
var wrong = area.Cells.Where(c => map.zoneManager.ZoneAt(c) != zone).ToList();
T.Check(wrong.Count == 0, "cells not in the new zone: " + Cells(wrong));
T.Check(zone.label != null && zone.label.StartsWith("BlaxZones_DeliveryZone".Translate()), "label '" + zone.label + "'");
T.Check(Find.Selector.SelectedZone == zone, "the new zone is not selected");
T.NotNull(zone.filter, "filter of the designated zone");
T.Equal(StoragePriority.Normal, zone.priority, "priority");
T.Check(zone.acceptOrbital, "orbital checkbox off on a new zone");
T.Check(!zone.campHere, "camp checkbox on on a new zone");
}
[BlaxTest("designators: GetZoneAddGizmos returns the expand designator, which the zone's gizmos include")]
public static void ZoneAddGizmo()
{
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
List<Gizmo> add = zone.GetZoneAddGizmos().ToList();
T.Equal(1, add.Count, "zone-add gizmos");
T.Check(add[0] != null && add[0].GetType() == typeof(Designator_ZoneAdd_Delivery_Expand),
"zone-add gizmo is " + (add[0]?.GetType().FullName ?? "null") + ", not Designator_ZoneAdd_Delivery_Expand");
T.Check(ReferenceEquals(add[0], DesignatorUtility.FindAllowedDesignator<Designator_ZoneAdd_Delivery_Expand>()),
"zone-add gizmo is not the shared expand designator");
T.Check(zone.GetGizmos().Contains(add[0]), "GetGizmos doesn't include the expand designator");
}
[BlaxTest("designators: the expand gizmo grows the selected zone and only adds cells")]
public static void ExpandOnlyAdds()
{
Map map = Fixtures.Map;
CellRect area = Fixtures.TestArea(6, 3);
var first = new CellRect(area.minX, area.minZ, 3, 3);
List<Zone> made = Designate(MenuDesignator(), first.Cells);
T.Equal(1, made.Count, "zones from the first drag");
var zone = (Zone_Delivery)made[0];
var oldCells = new HashSet<IntVec3>(zone.Cells);
T.Equal(9, oldCells.Count, "cells before expanding");
int zoneId = zone.ID;
int deliveryZones = map.zoneManager.AllZones.Count(z => z is Zone_Delivery);
var expand = (Designator_ZoneAdd_Delivery_Expand)zone.GetZoneAddGizmos().Single();
T.Check(area.Cells.All(c => expand.CanDesignateCell(c).Accepted), "expand designator refuses cells of the area or the zone");
// Drag over the whole area: the zone's own cells and the new ones.
List<Zone> extra = Designate(expand, area.Cells, select: zone);
T.Equal(0, extra.Count, "new zones made by expanding");
T.Equal(deliveryZones, map.zoneManager.AllZones.Count(z => z is Zone_Delivery), "delivery zones on the map");
T.Equal(zoneId, zone.ID, "zone ID");
T.Equal(area.Area, zone.CellCount, "cells after expanding");
var lost = oldCells.Where(c => map.zoneManager.ZoneAt(c) != zone).ToList();
T.Check(lost.Count == 0, "expanding dropped cells: " + Cells(lost));
var notAdded = area.Cells.Where(c => map.zoneManager.ZoneAt(c) != zone).ToList();
T.Check(notAdded.Count == 0, "cells not added: " + Cells(notAdded));
// Dragging the zone's own cells again changes nothing.
Designate(expand, first.Cells, select: zone);
T.Equal(area.Area, zone.CellCount, "cells after dragging over the zone's own cells");
}
[BlaxTest("designators: the designator refuses cells in an existing stockpile and leaves it whole")]
public static void RefusesStockpileCells()
{
Map map = Fixtures.Map;
CellRect area = Fixtures.TestArea(4, 3);
var pileRect = new CellRect(area.minX, area.minZ, 2, 3);
Zone_Stockpile pile = Fixtures.Stockpile(pileRect);
Designator_ZoneAdd_Delivery d = MenuDesignator();
var accepted = pileRect.Cells.Where(c => d.CanDesignateCell(c).Accepted).ToList();
T.Check(accepted.Count == 0, "CanDesignateCell accepted stockpile cells: " + Cells(accepted));
var free = area.Cells.Where(c => !pileRect.Contains(c)).ToList();
T.Check(free.All(c => d.CanDesignateCell(c).Accepted), "CanDesignateCell refused free cells next to the stockpile");
// A click on one stockpile cell does nothing, not even select the stockpile.
T.Equal(0, Designate(d, new[] { pileRect.CenterCell }).Count, "zones made by clicking a stockpile cell");
T.Check(Find.Selector.SelectedZone == null, "clicking a stockpile cell selected " + Find.Selector.SelectedZone);
// Even when handed every cell, it takes only the free ones.
List<Zone> made = Designate(d, area.Cells);
T.Equal(1, made.Count, "new zones");
T.Check(made[0] is Zone_Delivery, "new zone is a " + made[0].GetType().FullName);
T.Equal(free.Count, made[0].CellCount, "delivery zone cells");
T.Equal(pileRect.Area, pile.CellCount, "stockpile cells");
var taken = pileRect.Cells.Where(c => map.zoneManager.ZoneAt(c) != pile).ToList();
T.Check(taken.Count == 0, "stockpile cells taken: " + Cells(taken));
}
[BlaxTest("designators: with auto home area on, designated cells mark the 4-cell home border")]
public static void HomeAreaBorder()
{
Map map = Fixtures.Map;
CellRect area = Fixtures.TestArea(3, 3);
CellRect outer = area.ExpandedBy(5).ClipInsideMap(map);
Area_Home home = map.areaManager.Home;
var homeBefore = outer.Cells.ToDictionary(c => c, c => home[c]);
bool autoHomeBefore = Find.PlaySettings.autoHomeArea;
Fixtures.OnCleanup(() =>
{
Find.PlaySettings.autoHomeArea = autoHomeBefore;
foreach (var kv in homeBefore)
map.areaManager.Home[kv.Key] = kv.Value;
});
foreach (IntVec3 c in outer)
home[c] = false;
Find.PlaySettings.autoHomeArea = true;
List<Zone> made = Designate(MenuDesignator(), area.Cells);
T.Equal(1, made.Count, "new zones");
CellRect border = area.ExpandedBy(4).ClipInsideMap(map);
var notHome = border.Cells.Where(c => !home[c]).ToList();
T.Check(notHome.Count == 0, notHome.Count + " cells within 4 of the zone are not home area: " + Cells(notHome));
var beyond = outer.Cells.Where(c => !border.Contains(c) && home[c]).ToList();
T.Check(beyond.Count == 0, beyond.Count + " cells 5 away from the zone became home area: " + Cells(beyond));
}
}
}

View File

@ -0,0 +1,473 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxZones;
using RimWorld;
using RimWorld.Planet;
using Verse;
using Verse.AI;
namespace BlaxZonesTests
{
/// <summary>
/// Shared helpers for tests. Pawns, things and zones made here are removed after each test unless
/// passed to Keep() or KeepZone(). Mod settings are restored after each test, so tests may change
/// them freely. Terrain, roof and fog changes stay: every TestArea is used once and never handed out
/// again in the same run.
/// </summary>
public static class Fixtures
{
private static readonly List<Pawn> made = new List<Pawn>();
private static readonly HashSet<Pawn> kept = new HashSet<Pawn>();
private static readonly List<Thing> madeThings = new List<Thing>();
private static readonly HashSet<Thing> keptThings = new HashSet<Thing>();
private static readonly List<Zone> madeZones = new List<Zone>();
private static readonly HashSet<Zone> keptZones = new HashSet<Zone>();
private static readonly List<Action> cleanups = new List<Action>();
private static readonly List<CellRect> usedAreas = new List<CellRect>();
/// <summary>Cells TestArea clears around the rect it returns, so rings and walls around a zone fit.</summary>
public const int AreaMargin = 3;
public static Map Map => Find.CurrentMap;
public static BlaxZonesSettings Settings => BlaxZonesMod.Settings;
public static MapComponent_BlaxZones Comp => MapComponent_BlaxZones.Of(Map);
// ---- 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 pawn, not spawned. Relations off so no accidental family ties.</summary>
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;
}
/// <summary>Spawns the pawn at the cell, or near the map center when none is given.</summary>
public static Pawn Spawn(Pawn p, IntVec3? at = null)
{
IntVec3 cell = at ?? CellFinder.RandomClosewalkCellNear(Map.Center, Map, 12);
GenSpawn.Spawn(p, cell, Map);
return p;
}
/// <summary>A spawned free adult colonist.</summary>
public static Pawn Colonist() => Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer));
/// <summary>A spawned slave of the colony. Skips the test without Ideology.</summary>
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;
}
/// <summary>A spawned prisoner of the colony, from a hostile faction when there is one.</summary>
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;
}
/// <summary>A spawned baby of the colony. Skips the test without Biotech.</summary>
public static Pawn Baby()
{
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
Pawn p = Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer, DevelopmentalStage.Baby));
T.Check(p.DevelopmentalStage.Baby(), "baby fixture is " + p.DevelopmentalStage + ", not a baby");
return p;
}
/// <summary>
/// An animal of the race (ThingDefOf.Chicken, ThingDefOf.Muffalo, body size 2.4), tamed into the
/// colony or wild, spawned at the cell or near the map center.
/// </summary>
public static Pawn Animal(ThingDef race, bool tamed, IntVec3? at = null)
{
T.NotNull(race, "animal race");
PawnKindDef kind = DefDatabase<PawnKindDef>.AllDefsListForReading.FirstOrDefault(k => k.race == race);
T.NotNull(kind, "pawn kind for " + race.defName);
return Spawn(Generate(kind, tamed ? Faction.OfPlayer : null), at);
}
/// <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;
}
// ---- map areas -------------------------------------------------------------------
/// <summary>
/// A w x h rect on the current map, carved for terrain tests: the rect plus AreaMargin cells
/// around it are cleared of things, set to soil, unroofed and unfogged. It keeps away from map
/// edges, colonists, trade beacons, zones, rock and earlier areas, and a free colonist can walk
/// into it. Quick-test maps vary per run, so tests must not depend on where it lies. Never
/// handed out twice in one run.
/// </summary>
public static CellRect TestArea(int w, int h)
{
Map map = Map;
Rand.PushState(7919 + usedAreas.Count);
try
{
IntVec3 center = map.Center;
var origins = new List<IntVec3>();
for (int x = 10; x + w + 2 * AreaMargin < map.Size.x - 10; x += 6)
for (int z = 10; z + h + 2 * AreaMargin < map.Size.z - 10; z += 6)
origins.Add(new IntVec3(x + AreaMargin, 0, z + AreaMargin));
foreach (IntVec3 o in origins.OrderBy(o => Math.Abs((o.x + w / 2) - center.x) + Math.Abs((o.z + h / 2) - center.z)).ThenBy(o => o.x).ThenBy(o => o.z))
{
var rect = new CellRect(o.x, o.z, w, h);
if (!Usable(map, rect))
continue;
Carve(map, rect.ExpandedBy(AreaMargin));
usedAreas.Add(rect);
return rect;
}
}
finally
{
Rand.PopState();
}
T.Fail("TestArea: no free " + w + "x" + h + " area on this map");
return default;
}
private static bool Usable(Map map, CellRect rect)
{
CellRect carved = rect.ExpandedBy(AreaMargin);
CellRect keepOut = carved.ExpandedBy(3);
if (!keepOut.InBounds(map))
return false;
foreach (CellRect used in usedAreas)
{
if (used.ExpandedBy(AreaMargin + 2).Overlaps(keepOut))
return false;
}
foreach (Pawn p in map.mapPawns.AllPawnsSpawned)
{
if (keepOut.Contains(p.Position))
return false;
}
foreach (Building_OrbitalTradeBeacon b in map.listerBuildings.AllBuildingsColonistOfClass<Building_OrbitalTradeBeacon>())
{
if (b.Position.InHorDistOf(carved.CenterCell, 12f + Math.Max(carved.Width, carved.Height) / 2f))
return false;
}
foreach (IntVec3 c in keepOut)
{
if (map.zoneManager.ZoneAt(c) != null)
return false;
Building ed = c.GetEdifice(map);
if (ed != null && (ed.def.building?.isNaturalRock ?? false))
return false;
RoofDef roof = c.GetRoof(map);
if (roof != null && roof.isThickRoof)
return false;
if (ed != null && ed.Faction == Faction.OfPlayer)
return false;
}
// Carve can't remove a steam geyser or any other non-destroyable thing (Thing.cs:1045-1048 logs an error).
foreach (IntVec3 c in carved)
{
foreach (Thing t in c.GetThingList(map))
{
if (!t.def.destroyable)
return false;
}
}
// A free colonist must reach a standable cell on the ring just outside the carved area.
List<Pawn> colonists = map.mapPawns.FreeColonistsSpawned.ToList();
if (colonists.Count == 0)
return true;
Pawn walker = colonists[0];
foreach (IntVec3 c in carved.ExpandedBy(1).EdgeCells)
{
if (c.Standable(map) && map.reachability.CanReach(walker.Position, c, PathEndMode.OnCell, TraverseParms.For(TraverseMode.PassDoors)))
return true;
}
return false;
}
private static void Carve(Map map, CellRect area)
{
foreach (IntVec3 c in area)
{
foreach (Thing t in c.GetThingList(map).ToList())
{
if (t is Pawn || t.Destroyed)
continue;
t.Destroy(DestroyMode.Vanish);
}
map.terrainGrid.SetTerrain(c, TerrainDefOf.Soil);
map.roofGrid.SetRoof(c, null);
map.snowGrid.SetDepth(c, 0f);
map.fogGrid.Unfog(c);
}
}
/// <summary>Constructed roof over every cell of the rect.</summary>
public static void Roof(CellRect rect)
{
foreach (IntVec3 c in rect)
Map.roofGrid.SetRoof(c, RoofDefOf.RoofConstructed);
}
/// <summary>A player wall on the cell (removes zone cells under it, as vanilla does).</summary>
public static Thing Wall(IntVec3 cell) => SpawnBuilding(ThingDefOf.Wall, cell);
/// <summary>Shallow water on the cell: walkable, but drop pods refuse water.</summary>
public static void Water(IntVec3 cell) => Map.terrainGrid.SetTerrain(cell, TerrainDefOf.WaterShallow);
/// <summary>
/// An enclosed animal pen around the rect: fences on the edge of rect.ExpandedBy(2) and a pen
/// marker inside the ring at rect.ExpandedBy(1)'s corner, outside the rect itself. Returns the marker.
/// </summary>
public static Thing FenceRing(CellRect rect)
{
ThingDef fence = DefDatabase<ThingDef>.GetNamed("Fence");
ThingDef marker = DefDatabase<ThingDef>.GetNamed("PenMarker");
foreach (IntVec3 c in rect.ExpandedBy(2).EdgeCells)
SpawnBuilding(fence, c);
CellRect inner = rect.ExpandedBy(1);
return SpawnBuilding(marker, new IntVec3(inner.minX, 0, inner.minZ));
}
/// <summary>A player orbital trade beacon on the cell with power on (no power net needed while paused).</summary>
public static Building_OrbitalTradeBeacon PoweredBeacon(IntVec3 cell)
{
var b = (Building_OrbitalTradeBeacon)SpawnBuilding(ThingDefOf.OrbitalTradeBeacon, cell);
CompPowerTrader power = b.GetComp<CompPowerTrader>();
if (power != null)
power.PowerOn = true;
T.Check(Building_OrbitalTradeBeacon.AllPowered(Map).Contains(b), "beacon fixture is not powered");
return b;
}
/// <summary>A default stockpile over the rect.</summary>
public static Zone_Stockpile Stockpile(CellRect rect)
{
var zone = new Zone_Stockpile(StorageSettingsPreset.DefaultStockpile, Map.zoneManager);
Map.zoneManager.RegisterZone(zone);
madeZones.Add(zone);
foreach (IntVec3 c in rect)
zone.AddCell(c);
return zone;
}
/// <summary>
/// A delivery zone over the rect, registered and filled the way the designator does it. A null
/// filter keeps the default (all items).
/// </summary>
public static Zone_Delivery DeliveryZone(CellRect rect, ThingFilter filter = null, StoragePriority priority = StoragePriority.Normal,
bool orbital = true, bool camp = false)
{
var zone = new Zone_Delivery(Map.zoneManager);
Map.zoneManager.RegisterZone(zone);
madeZones.Add(zone);
foreach (IntVec3 c in rect)
zone.AddCell(c);
if (filter != null)
zone.filter.CopyAllowancesFrom(filter);
zone.priority = priority;
zone.acceptOrbital = orbital;
zone.campHere = camp;
return zone;
}
/// <summary>A filter that allows only the given defs.</summary>
public static ThingFilter FilterOf(params ThingDef[] defs)
{
var f = new ThingFilter();
f.SetDisallowAll();
foreach (ThingDef d in defs)
f.SetAllow(d, true);
return f;
}
/// <summary>A stack of the def, not spawned, removed after the test unless kept.</summary>
public static Thing Stack(ThingDef def, int count)
{
Thing t = ThingMaker.MakeThing(def, def.MadeFromStuff ? GenStuff.DefaultStuffFor(def) : null);
t.stackCount = Math.Min(count, def.stackLimit);
return Track(t);
}
public static Zone FindZoneById(int id)
{
foreach (Map m in Find.Maps)
foreach (Zone z in m.zoneManager.AllZones)
if (z.ID == id) return z;
return null;
}
private static Thing SpawnBuilding(ThingDef def, IntVec3 cell)
{
Thing t = ThingMaker.MakeThing(def, def.MadeFromStuff ? GenStuff.DefaultStuffFor(def) : null);
t.SetFactionDirect(Faction.OfPlayer);
GenSpawn.Spawn(t, cell, Map, WipeMode.Vanish);
return Track(t);
}
// ---- tracking --------------------------------------------------------------------
/// <summary>Destroy this thing after the test unless kept.</summary>
public static TT Track<TT>(TT thing) where TT : Thing
{
madeThings.Add(thing);
return thing;
}
/// <summary>Delete this zone after the test unless kept.</summary>
public static TZ TrackZone<TZ>(TZ zone) where TZ : Zone
{
madeZones.Add(zone);
return zone;
}
public static TT Keep<TT>(TT thing) where TT : Thing
{
keptThings.Add(thing);
return thing;
}
public static TZ KeepZone<TZ>(TZ zone) where TZ : Zone
{
keptZones.Add(zone);
return zone;
}
/// <summary>Runs after the test, before things and zones are removed (undo a test-only patch, for example).</summary>
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();
}
public static void QuietStoryteller()
{
Find.Storyteller.incidentQueue.Clear();
Find.Storyteller.storytellerComps.Clear();
}
// ---- 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(BlaxZonesSettings).GetFields(BindingFlags.Public | BindingFlags.Instance))
d[f] = f.GetValue(Settings);
return d;
}
public static void RestoreSettings(Dictionary<FieldInfo, object> snapshot)
{
if (Settings != null)
foreach (var kv in snapshot) kv.Key.SetValue(Settings, kv.Value);
}
public static void Cleanup()
{
List<Action> 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 (Zone z in madeZones)
{
if (z == null || keptZones.Contains(z) || z.zoneManager == null || !z.zoneManager.AllZones.Contains(z)) continue;
z.Delete(playSound: false);
}
madeZones.Clear();
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();
foreach (Pawn p in made)
{
if (p == null || kept.Contains(p)) continue;
DropRitualObligations(p);
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();
}
/// <summary>
/// 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.
/// </summary>
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);
}
}
}
}
}
}

View File

@ -0,0 +1,420 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using BlaxZones;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxZonesTests
{
/// <summary>
/// Marks a public static void method without parameters as a test. Phase 1 runs in a fresh
/// quick-test colony. Phase 2 runs after the runner saved that game and loaded it again. Phase 3
/// runs after the runner saved again, replaced the MapComponent_BlaxZones class in the save with one
/// that doesn't exist and loaded that: the vanilla side of a save whose mod was removed.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class BlaxTestAttribute : Attribute
{
public readonly string Name;
public readonly int Phase;
public BlaxTestAttribute(string name, int phase = 1)
{
Name = name;
Phase = phase;
}
}
public class TestFailure : Exception
{
public TestFailure(string message) : base(message) { }
}
public class TestSkipped : Exception
{
public TestSkipped(string message) : base(message) { }
}
/// <summary>Assertions and notes for test bodies.</summary>
public static class T
{
/// <summary>Values carried from phase 1 into phases 2 and 3. Store ThingIDs, zone IDs or def names, never objects.</summary>
public static readonly Dictionary<string, string> Carry = new Dictionary<string, string>();
/// <summary>Carry values read right before the first save, after every phase-1 test ran.</summary>
internal static readonly Dictionary<string, Func<string>> CarryAtSaveTime = new Dictionary<string, Func<string>>();
/// <summary>
/// Carries a value read right before the save instead of now, for state that later phase-1
/// tests may still change.
/// </summary>
public static void CarryAtSave(string key, Func<string> read) => CarryAtSaveTime[key] = read;
public static void Check(bool condition, string message)
{
if (!condition) throw new TestFailure(message);
}
public static void Equal<TV>(TV expected, TV actual, string what)
{
if (!EqualityComparer<TV>.Default.Equals(expected, actual))
throw new TestFailure($"{what}: expected {Show(expected)}, got {Show(actual)}");
}
public static void NotNull(object value, string what)
{
if (value == null) throw new TestFailure(what + " is null");
}
public static void Fail(string message) => throw new TestFailure(message);
public static void Skip(string reason) => throw new TestSkipped(reason);
/// <summary>Skips the test unless the DLC is active, with "needs &lt;DLC&gt;" as the reason.</summary>
public static void NeedsDlc(string dlc, bool active)
{
if (!active) throw new TestSkipped("needs " + dlc);
}
/// <summary>Adds an INFO line under the current test in the results file.</summary>
public static void Info(string message) => TestRunner.Note(message);
/// <summary>
/// Expects exactly <paramref name="count"/> errors whose text contains <paramref name="fragment"/>,
/// logged during this test or, in phase 3, during the phase-3 load. Checked when the test ends,
/// so call it before or after the action. Matching errors are excused: they never count as
/// Blax Zones errors, here or as stray errors. Several tests may expect the same errors.
/// </summary>
public static void ExpectErrors(string fragment, int count) => TestRunner.Expect(fragment, count);
/// <summary>Error texts (one line each) logged while the phase-3 save loaded. Empty before phase 3.</summary>
public static List<string> Phase3LoadErrors => TestRunner.LoadErrors();
/// <summary>"Could not resolve reference" warnings logged while the phase-3 save loaded.</summary>
public static int Phase3ResolveWarnings => TestRunner.ResolveWarnings;
private static string Show(object o) => o == null ? "null" : o.ToString();
}
/// <summary>
/// Drives the suite when the game runs with -quicktest -blaxzonestests: phase 1, save, load,
/// phase 2, save, strip the component class, load, phase 3, then writes BlaxZonesTestResults.txt
/// into the save data folder and quits.
/// </summary>
public class TestRunner : GameComponent
{
public const string SaveName = "BlaxZonesTest";
public const string Phase3SaveName = "BlaxZonesTest3";
public const string ResultFile = "BlaxZonesTestResults.txt";
/// <summary>The class attribute phase 3 replaces in the save.</summary>
public const string ComponentClassAttr = "Class=\"BlaxZones.MapComponent_BlaxZones\"";
/// <summary>A class that doesn't exist; the phase-3 save names it instead of MapComponent_BlaxZones.</summary>
public const string RemovedComponentClass = "BlaxZonesRemoved.MapComponent_BlaxZones";
/// <summary>Where errors logged during the phase-3 load are filed.</summary>
public const string Phase3LoadTag = "(phase 3 load)";
private class LogEntry
{
public string where;
public string text;
public bool ours;
public bool excused;
}
private static int stage; // 0 waiting, 1 phase 1 done + reload queued, 2 phase 2 done + phase-3 load queued, 3 finished
private static int loadsSeen;
private static int pass, fail, skip;
private static string currentTest;
private static readonly List<LogEntry> errors = new List<LogEntry>();
private static readonly List<(string fragment, int count)> expectations = new List<(string, int)>();
private static int resolveWarnings;
private static bool hooked;
private int settleFrames;
public static bool Enabled => GenCommandLine.CommandLineArgPassed("blaxzonestests");
public static string ResultPath => Path.Combine(GenFilePaths.SaveDataFolderPath, ResultFile);
/// <summary>Maps whose component class phase 3 replaced in the save. Set before the phase-3 load.</summary>
public static int Phase3ReplacedCount { get; private set; }
public static int ResolveWarnings => resolveWarnings;
public TestRunner(Game game) { }
public override void LoadedGame()
{
if (Enabled && (stage == 1 || stage == 2)) loadsSeen++;
}
public override void GameComponentUpdate()
{
if (!Enabled || stage == 3) return;
if (LongEventHandler.AnyEventNowOrWaiting || Find.CurrentMap == null) return;
if (++settleFrames < 30) return;
if (stage == 0)
{
stage = 1;
Begin();
RunPhase(1);
Line("STAGE save+reload");
try
{
foreach (var kv in T.CarryAtSaveTime)
{
try { T.Carry[kv.Key] = kv.Value(); }
catch (Exception e) { Note("carry " + kv.Key + " failed: " + e.Message); }
}
GameDataSaveLoader.SaveGame(SaveName);
GameDataSaveLoader.LoadGame(SaveName);
}
catch (Exception e)
{
Record("FAIL", "save and reload", e.ToString());
Finish();
}
}
else if (stage == 1 && loadsSeen >= 1)
{
stage = 2;
Line("STAGE phase 2 (after reload)");
RunPhase(2);
Line("STAGE phase 3 (component class removed from the save)");
try
{
StartPhase3Load();
}
catch (Exception e)
{
currentTest = null;
Record("FAIL", "phase 3 save and load", e.ToString());
Finish();
}
}
else if (stage == 2 && loadsSeen >= 2)
{
currentTest = null;
Note("phase 3 load: " + Phase3ReplacedCount + " component node(s) replaced, " + LoadErrors().Count + " error(s), " +
resolveWarnings + " 'Could not resolve reference' warning(s)");
RunPhase(3);
Finish();
}
}
/// <summary>
/// Saves as BlaxZonesTest3 (saves are plain XML in 1.7, ScribeSaver.cs:45-49), replaces the
/// component's class with one that doesn't exist and loads it. Zones' assembly stays loaded, so
/// Map.FillComponents adds a fresh, empty component after the load.
/// </summary>
private static void StartPhase3Load()
{
GameDataSaveLoader.SaveGame(Phase3SaveName);
string path = GenFilePaths.FilePathForSavedGame(Phase3SaveName);
string xml = File.ReadAllText(path);
int count = 0;
for (int i = xml.IndexOf(ComponentClassAttr, StringComparison.Ordinal); i >= 0; i = xml.IndexOf(ComponentClassAttr, i + 1, StringComparison.Ordinal))
count++;
if (count == 0)
throw new Exception("the phase-3 save holds no " + ComponentClassAttr);
Phase3ReplacedCount = count;
File.WriteAllText(path, xml.Replace(ComponentClassAttr, "Class=\"" + RemovedComponentClass + "\""));
lock (errors) resolveWarnings = 0;
currentTest = Phase3LoadTag;
GameDataSaveLoader.LoadGame(Phase3SaveName);
}
/// <summary>The game log as it stood when the suite began, before any test ran (the startup test reads it).</summary>
public static List<LogMessage> StartupLog { get; private set; } = new List<LogMessage>();
private static void Begin()
{
try { File.Delete(ResultPath); } catch { }
StartupLog = Log.Messages.ToList();
HookLog();
Line("BEGIN Blax Zones in-game tests, RimWorld " + VersionControl.CurrentVersionStringWithRev);
Line("DLCs: Royalty " + ModsConfig.RoyaltyActive + ", Ideology " + ModsConfig.IdeologyActive + ", Biotech " + ModsConfig.BiotechActive +
", Anomaly " + ModsConfig.AnomalyActive + ", Odyssey " + ModsConfig.OdysseyActive);
Fixtures.QuietStoryteller();
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
}
private static void HookLog()
{
if (hooked) return;
hooked = true;
Application.logMessageReceivedThreaded += (text, stack, type) =>
{
if (type == LogType.Warning)
{
if (currentTest == Phase3LoadTag && text != null && text.Contains("Could not resolve reference"))
lock (errors) resolveWarnings++;
return;
}
if (type != LogType.Error && type != LogType.Exception) return;
bool ours = !IsKnownForeignError(text, stack)
&& ((text != null && (text.Contains("BlaxZones") || text.Contains("Blax Zones"))) || (stack != null && stack.Contains("BlaxZones")));
var entry = new LogEntry { where = currentTest ?? "(between tests)", text = OneLine(text), ours = ours };
lock (errors) errors.Add(entry);
};
}
/// <summary>
/// Errors another mod logs from its own code while a test ticks the game. The test's frames are in the
/// stack, so the check above would blame Blax Zones; these show as LOGERR lines instead. Each entry is a
/// text fragment and the frame that logs it. Add one per mod, with the reason, as Castes does:
/// - Prison Labor (-Compat): its postfix on Pawn_GuestTracker.SetGuestStatus passes its own
/// PrisonLabor_workOption, a non-exclusive mode in 1.7, to SetExclusiveInteraction, so the game logs
/// "Attempted to set guest exclusive interaction to a non-exclusive interaction type" once for the
/// first pawn made a prisoner (the prisoner fixture).
/// </summary>
private static readonly (string text, string frame)[] KnownForeignErrors =
{
("non-exclusive interaction type: PrisonLabor_", "Patch_DefaultInteractionMode"),
};
private static bool IsKnownForeignError(string text, string stack)
{
if (text == null || stack == null)
return false;
foreach (var (fragment, frame) in KnownForeignErrors)
{
if (text.Contains(fragment) && stack.Contains(frame))
return true;
}
return false;
}
internal static void Expect(string fragment, int count)
{
if (fragment.NullOrEmpty()) throw new TestFailure("ExpectErrors needs a text fragment");
expectations.Add((fragment, count));
}
internal static List<string> LoadErrors()
{
lock (errors) return errors.Where(e => e.where == Phase3LoadTag).Select(e => e.text).ToList();
}
private static void RunPhase(int phase)
{
var tests = typeof(TestRunner).Assembly.GetTypes()
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static))
.Select(m => (method: m, attr: m.GetCustomAttribute<BlaxTestAttribute>()))
.Where(x => x.attr != null && x.attr.Phase == phase)
.OrderBy(x => x.method.DeclaringType.FullName)
.ThenBy(x => x.method.MetadataToken)
.ToList();
foreach (var (method, attr) in tests) RunOne(attr.Name, method, phase);
}
private static void RunOne(string name, MethodInfo method, int phase)
{
currentTest = name;
expectations.Clear();
int before;
lock (errors) before = errors.Count;
var settings = Fixtures.SnapshotSettings();
string status = "PASS", detail = "";
try
{
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
method.Invoke(null, null);
}
catch (TargetInvocationException tie) when (tie.InnerException is TestSkipped s)
{
status = "SKIP"; detail = s.Message;
}
catch (TargetInvocationException tie) when (tie.InnerException is TestFailure f)
{
status = "FAIL"; detail = f.Message;
}
catch (TargetInvocationException tie)
{
status = "FAIL"; detail = "exception: " + tie.InnerException;
}
catch (Exception e)
{
status = "FAIL"; detail = "runner exception: " + e;
}
finally
{
Fixtures.RestoreSettings(settings);
try { Fixtures.Cleanup(); } catch (Exception e) { Note("cleanup threw: " + OneLine(e.Message)); }
ZonesTestHooks.Reset();
Compat.SimulatedActive.Clear();
}
List<LogEntry> newErrors;
lock (errors)
{
newErrors = errors.Skip(before).ToList();
var window = phase == 3 ? newErrors.Concat(errors.Take(before).Where(e => e.where == Phase3LoadTag)).ToList() : newErrors;
foreach (var (fragment, count) in expectations)
{
var matches = window.Where(e => e.text.Contains(fragment)).ToList();
foreach (LogEntry m in matches) m.excused = true;
if (matches.Count != count && status == "PASS")
{
status = "FAIL";
detail = $"expected {count} error(s) containing '{fragment}', got {matches.Count}";
}
}
}
expectations.Clear();
var newModErrors = newErrors.Where(e => e.ours && !e.excused).ToList();
var newOtherErrors = newErrors.Where(e => !e.ours && !e.excused).ToList();
if (status == "PASS" && newModErrors.Count > 0)
{
status = "FAIL";
detail = "Blax Zones logged errors: " + string.Join(" | ", newModErrors.Take(3).Select(e => e.text));
}
Record(status, name, detail);
foreach (LogEntry e in newOtherErrors.Take(5)) Line(" LOGERR " + e.where + ": " + e.text);
currentTest = null;
}
private static void Finish()
{
stage = 3;
currentTest = null;
List<LogEntry> stray;
lock (errors) stray = errors.Where(e => e.where.StartsWith("(") && e.ours && !e.excused).ToList();
foreach (LogEntry e in stray.Take(10)) Line(" MODERR " + e.where + ": " + e.text);
Line($"SUMMARY pass={pass} fail={fail} skip={skip} strayModErrors={stray.Count}");
Line("END");
Log.Message($"[BlaxTest] finished: pass={pass} fail={fail} skip={skip}");
Root.Shutdown();
}
internal static void Note(string message) => Line(" INFO " + OneLine(message));
private static void Record(string status, string name, string detail)
{
if (status == "PASS") pass++;
else if (status == "FAIL") fail++;
else skip++;
Line(string.IsNullOrEmpty(detail) ? $"{status} {name}" : $"{status} {name}: {OneLine(detail)}");
}
private static void Line(string text)
{
Log.Message("[BlaxTest] " + text);
try { File.AppendAllText(ResultPath, text + Environment.NewLine); } catch { }
}
private static string OneLine(string s)
{
if (s == null) return "";
s = s.Replace("\r", " ").Replace("\n", " ⏎ ");
return s.Length > 1500 ? s.Substring(0, 1500) + "…" : s;
}
}
}

View File

@ -0,0 +1,477 @@
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");
bool logged = Log.Messages.Any(m => m.text != null && 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++;
}
}
}
}

View File

@ -0,0 +1,505 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BlaxZones;
using RimWorld;
using Verse;
namespace BlaxZonesTests
{
/// <summary>
/// Package Router. Design: "DeliveryRouter, shared by every delivery path"; 1.0 "Delivery zone" > Tests (ZonesApi, overflow radius).
/// Tests: [BlaxTest("router: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped.
///
/// Every test first sets aside the delivery zones earlier tests kept on the map (deregistered, then
/// registered again in cleanup), so only its own zones can be candidates.
/// </summary>
public static class RouterTests
{
// ---- ZonesApi (design 1.0 "Delivery zone" > Tests) --------------------------------
[BlaxTest("router: ZonesApi returns a zone cell for steel, one pod per call, and false for a pawn")]
public static void ApiSteelAndPawn()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3));
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
T.Check(ZonesApi.TryFindDropSpot(map, steel, out IntVec3 first), "ZonesApi refused steel with a fitting zone");
T.Check(zone.cells.Contains(first), "ZonesApi cell " + first + " is not in the zone");
T.Check(DeliveryRules.PodCellOk(map, first), "ZonesApi cell " + first + " fails the pod rule");
T.Equal(Fixtures.Comp.CellsByDistance(zone)[0], first, "first cell (nearest the centroid)");
// The caller spawns the pod at the cell and asks again: the falling pod marks the cell as taken.
DropPodAt(first, steel);
Thing steel2 = Fixtures.Stack(ThingDefOf.Steel, 50);
T.Check(ZonesApi.TryFindDropSpot(map, steel2, out IntVec3 second), "ZonesApi refused the second stack");
T.Check(second != first, "second stack got the cell of the falling pod " + first);
T.Check(zone.cells.Contains(second), "second cell " + second + " is not in the zone");
Pawn colonist = Fixtures.Colonist();
T.Check(!ZonesApi.TryFindDropSpot(map, colonist, out IntVec3 pawnCell), "ZonesApi accepted a pawn");
T.Check(!pawnCell.IsValid, "ZonesApi set a cell for a pawn");
T.Check(!DeliveryRouter.TryFindDropSpot(map, colonist, DeliverySource.Orbital, out _), "router accepted a pawn");
}
[BlaxTest("router: with the zone's orbital checkbox off, ZonesApi returns false")]
public static void ApiOrbitalOff()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2), orbital: false);
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 20);
T.Check(!DeliveryRouter.Refuses(map, steel), "router refused steel on a map with a delivery zone");
T.Equal(0, DeliveryRouter.Candidates(map, steel, DeliverySource.Orbital).Count, "orbital candidates with the checkbox off");
T.Check(!ZonesApi.TryFindDropSpot(map, steel, out IntVec3 cell), "ZonesApi returned " + cell + " with the orbital checkbox off");
T.Check(!cell.IsValid, "ZonesApi set a cell with the orbital checkbox off");
zone.acceptOrbital = true;
T.Check(ZonesApi.TryFindDropSpot(map, steel, out cell) && zone.cells.Contains(cell), "ZonesApi refused steel with the checkbox back on");
}
[BlaxTest("router: ZonesApi ignores Route orbital trade, so Blax Slaves payouts still land in the zone")]
public static void ApiIgnoresRouteOrbital()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
Fixtures.Settings.routeOrbital = false;
T.Check(ZonesApi.TryFindDropSpot(map, Fixtures.Stack(ThingDefOf.Silver, 100), out IntVec3 cell) && zone.cells.Contains(cell),
"ZonesApi returned " + cell + " for silver with Route orbital trade off; the orbital tooltip says Slaves payouts still land");
}
[BlaxTest("router: with overflowRadius 1 the overflow search ends and uses radius 5")]
public static void OverflowRadiusNeverBelow5()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
Fixtures.Settings.overflowRadius = 1;
T.Equal(BlaxZonesSettings.MinOverflowRadius, DeliveryRouter.OverflowRadius, "overflow radius with the setting at 1");
// A 1-cell zone in the middle of an 11x11 area. The area and its margin are roofed, so no cell
// within 8 of the center takes a pod: a search below radius 5 would never end here.
CellRect a = Fixtures.TestArea(11, 11);
IntVec3 center = a.CenterCell;
Zone_Delivery zone = Fixtures.DeliveryZone(CellRect.SingleCell(center));
Fixtures.Roof(a.ExpandedBy(Fixtures.AreaMargin));
T.Check(!DeliveryRouter.TryOverflow(zone, out IntVec3 cell), "overflow found " + cell + " in a fully roofed area");
T.Check(!cell.IsValid, "failed overflow set a cell");
// One free cell 7 away: beyond radius 5, so still nothing.
IntVec3 far = center + new IntVec3(7, 0, 0);
map.roofGrid.SetRoof(far, null);
T.Check(DropCellFinder.IsGoodDropSpot(far, map, allowFogged: false, canRoofPunch: false), "the unroofed cell 7 away is no good drop spot");
T.Check(!DeliveryRouter.TryOverflow(zone, out cell), "overflow with radius 5 found " + cell + ", 7 cells away");
// One free cell exactly 5 away: found, so the search ran out to 5.
IntVec3 edge = center + new IntVec3(0, 0, -5);
map.roofGrid.SetRoof(edge, null);
T.Check(DeliveryRouter.TryOverflow(zone, out cell), "overflow with radius 5 missed the free cell 5 away");
T.Equal(edge, cell, "overflow cell");
Fixtures.Settings.overflowNearZone = false;
T.Check(!DeliveryRouter.TryOverflow(zone, out cell), "overflow ran with 'Overflow lands next to the zone' off");
}
// ---- candidates and refusals --------------------------------------------------------
[BlaxTest("router: candidates order by priority then ID, and a medicine-only filter excludes steel")]
public static void CandidatesOrder()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
CellRect a = Fixtures.TestArea(8, 2);
Zone_Delivery MakeZone(int i, ThingFilter filter, StoragePriority priority) =>
Fixtures.DeliveryZone(new CellRect(a.minX + 2 * i, a.minZ, 2, 2), filter, priority);
Zone_Delivery normalA = MakeZone(0, null, StoragePriority.Normal);
Zone_Delivery important = MakeZone(1, null, StoragePriority.Important);
Zone_Delivery normalB = MakeZone(2, null, StoragePriority.Normal);
Zone_Delivery medicineOnly = MakeZone(3, Fixtures.FilterOf(ThingDefOf.MedicineIndustrial), StoragePriority.Critical);
T.Check(normalA.ID < normalB.ID, "zone IDs are not ascending in creation order");
// Register normalA again so ZoneManager lists it after normalB: the order must come from the ID.
map.zoneManager.DeregisterZone(normalA);
map.zoneManager.RegisterZone(normalA);
T.Check(map.zoneManager.AllZones.IndexOf(normalA) > map.zoneManager.AllZones.IndexOf(normalB), "re-registering did not move the zone");
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 10);
T.Equal(Ids(important, normalA, normalB), Ids(DeliveryRouter.Candidates(map, steel, DeliverySource.Orbital).ToArray()), "steel candidates");
Thing medicine = Fixtures.Stack(ThingDefOf.MedicineIndustrial, 5);
T.Equal(Ids(medicineOnly, important, normalA, normalB), Ids(DeliveryRouter.Candidates(map, medicine, DeliverySource.Orbital).ToArray()), "medicine candidates");
T.Check(DeliveryRouter.TryFindDropSpot(map, medicine, DeliverySource.Orbital, out IntVec3 medCell) && medicineOnly.cells.Contains(medCell),
"medicine did not land in the Critical medicine-only zone (got " + medCell + ")");
T.Check(DeliveryRouter.TryFindDropSpot(map, steel, DeliverySource.Orbital, out IntVec3 steelCell) && important.cells.Contains(steelCell),
"steel did not land in the Important zone (got " + steelCell + ")");
}
[BlaxTest("router: refuses a corpse, a pawn and a map with no delivery zones")]
public static void RefusesCorpseAndEmptyMap()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 10);
CellRect a = Fixtures.TestArea(4, 2);
// A stockpile is no delivery zone.
Fixtures.Stockpile(new CellRect(a.minX + 2, a.minZ, 2, 2));
T.Check(DeliveryRouter.Refuses(map, steel), "router took steel on a map with no delivery zones");
T.Check(!DeliveryRouter.TryFindDropSpot(map, steel, DeliverySource.Orbital, out IntVec3 cell) && !cell.IsValid, "routed with no delivery zones");
Zone_Delivery zone = Fixtures.DeliveryZone(new CellRect(a.minX, a.minZ, 2, 2));
T.Check(!DeliveryRouter.Refuses(map, steel), "router refused steel with a delivery zone");
Pawn chicken = Fixtures.Animal(ThingDefOf.Chicken, tamed: false, at: new IntVec3(a.maxX, 0, a.maxZ + 1));
chicken.Kill(null);
Corpse corpse = chicken.Corpse;
T.NotNull(corpse, "chicken corpse");
T.Check(DeliveryRouter.Refuses(map, corpse), "router took a corpse");
T.Equal(0, DeliveryRouter.Candidates(map, corpse, DeliverySource.Orbital).Count, "candidates for a corpse");
T.Check(!DeliveryRouter.TryFindDropSpot(map, corpse, DeliverySource.Orbital, out cell), "router routed a corpse to " + cell);
T.Check(!ZonesApi.TryFindDropSpot(map, corpse, out cell), "ZonesApi routed a corpse to " + cell);
Pawn colonist = Fixtures.Colonist();
T.Check(DeliveryRouter.Refuses(map, colonist), "router took a pawn");
T.Check(DeliveryRouter.Refuses(map, null), "router took null");
T.Check(DeliveryRouter.Refuses(null, steel), "router took a null map");
T.Check(zone.cells.Count > 0, "zone lost its cells");
}
[BlaxTest("router: refuses Wastepack (Biotech)")]
public static void RefusesWastepack()
{
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
T.NotNull(ThingDefOf.Wastepack, "ThingDefOf.Wastepack with Biotech");
Thing wastepack = Fixtures.Stack(ThingDefOf.Wastepack, 1);
T.Check(DeliveryFilters.NeverRouted(wastepack), "NeverRouted let a wastepack through");
T.Check(DeliveryRouter.Refuses(map, wastepack), "router took a wastepack");
T.Equal(0, DeliveryRouter.Candidates(map, wastepack, DeliverySource.Orbital).Count, "candidates for a wastepack");
T.Check(!ZonesApi.TryFindDropSpot(map, wastepack, out IntVec3 cell), "ZonesApi routed a wastepack to " + cell);
}
[BlaxTest("router: the Wastepack refusal skips a missing def with no error")]
public static void WastepackRefusalWithoutBiotech()
{
Map map = Fixtures.Map;
T.Check(ModsConfig.BiotechActive || ThingDefOf.Wastepack == null, "ThingDefOf.Wastepack is set without Biotech");
SetAsideOtherDeliveryZones();
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 10);
T.Check(!DeliveryFilters.NeverRouted(steel), "NeverRouted refused steel");
T.Check(!DeliveryRouter.Refuses(map, steel), "router refused steel");
T.Check(ZonesApi.TryFindDropSpot(map, steel, out IntVec3 cell) && zone.cells.Contains(cell), "ZonesApi refused steel");
}
[BlaxTest("router: a map whose component was removed refuses everything")]
public static void RefusesWithoutComponent()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 10);
T.Check(!DeliveryRouter.Refuses(map, steel), "router refused steel with the component in place");
MapComponent_BlaxZones comp = Fixtures.Comp;
int index = map.components.IndexOf(comp);
T.Check(index >= 0, "component not in map.components");
Fixtures.OnCleanup(() =>
{
if (!map.components.Contains(comp))
map.components.Insert(Math.Min(index, map.components.Count), comp);
});
map.components.RemoveAt(index);
T.Check(MapComponent_BlaxZones.Of(map) == null, "the component is still found after removal");
T.Check(DeliveryRouter.Refuses(map, steel), "router took steel on a map without the component");
T.Check(!DeliveryRouter.TryFindDropSpot(map, steel, DeliverySource.Orbital, out IntVec3 cell) && !cell.IsValid, "router routed without the component");
T.Check(!ZonesApi.TryFindDropSpot(map, steel, out cell) && !cell.IsValid, "ZonesApi routed without the component");
T.Check(zone.cells.Count > 0, "zone lost its cells");
}
// ---- cells ----------------------------------------------------------------------------
[BlaxTest("router: CellsByDistance puts the centroid-nearest cell first and is rebuilt after AddCell and RemoveCell")]
public static void CellOrder()
{
SetAsideOtherDeliveryZones();
CellRect a = Fixtures.TestArea(5, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(new CellRect(a.minX, a.minZ, 3, 3));
MapComponent_BlaxZones comp = Fixtures.Comp;
List<IntVec3> order = comp.CellsByDistance(zone);
CheckSorted(zone, order, "3x3");
T.Equal(new IntVec3(a.minX + 1, 0, a.minZ + 1), order[0], "3x3 first cell");
T.Check(ReferenceEquals(order, comp.CellsByDistance(zone)), "the cell order is not cached");
T.Equal(order[0], DeliveryRouter.OverflowCenter(zone), "OverflowCenter of the 3x3 zone");
// Two more columns: 5x3, the centroid moves to the middle column.
for (int x = a.minX + 3; x <= a.minX + 4; x++)
for (int z = a.minZ; z < a.minZ + 3; z++)
zone.AddCell(new IntVec3(x, 0, z));
List<IntVec3> grown = comp.CellsByDistance(zone);
T.Check(!ReferenceEquals(order, grown), "the cell order was not rebuilt after AddCell");
CheckSorted(zone, grown, "5x3");
T.Equal(new IntVec3(a.minX + 2, 0, a.minZ + 1), grown[0], "5x3 first cell");
IntVec3 removed = grown[0];
zone.RemoveCell(removed);
List<IntVec3> shrunk = comp.CellsByDistance(zone);
T.Check(!ReferenceEquals(grown, shrunk), "the cell order was not rebuilt after RemoveCell");
T.Check(!shrunk.Contains(removed), "the removed cell is still in the order");
CheckSorted(zone, shrunk, "5x3 minus the center");
// Four cells tie at distance 1 around the removed center; ties go to the lower x.
T.Equal(new IntVec3(a.minX + 1, 0, a.minZ + 1), shrunk[0], "first cell after removing the center");
}
[BlaxTest("router: pass 1 takes an empty cell first, pass 2 a cell with a mergeable stack")]
public static void Pass2Mergeable()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
CellRect a = Fixtures.TestArea(3, 1);
Zone_Delivery zone = Fixtures.DeliveryZone(a);
IntVec3 west = new IntVec3(a.minX, 0, a.minZ);
IntVec3 middle = new IntVec3(a.minX + 1, 0, a.minZ);
IntVec3 east = new IntVec3(a.minX + 2, 0, a.minZ);
T.Equal(middle, Fixtures.Comp.CellsByDistance(zone)[0], "first cell of the 1x3 zone");
Thing lying = SpawnStack(ThingDefOf.Steel, 10, middle);
SpawnStack(ThingDefOf.WoodLog, 10, west);
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 30);
// The middle cell comes first in the order but holds steel: the empty east cell wins.
T.Check(DeliveryRouter.TryPickCellInZone(zone, steel, out IntVec3 cell), "no cell with one empty cell left");
T.Equal(east, cell, "pass 1 cell");
// No empty cell left: pass 2 takes the cell whose steel the stack merges into, never the wood.
SpawnStack(ThingDefOf.WoodLog, 10, east);
T.Check(DeliveryRouter.TryPickCellInZone(zone, steel, out cell), "pass 2 found no cell with a mergeable stack");
T.Equal(middle, cell, "pass 2 cell");
T.Check(DeliveryRouter.TryFindDropSpot(map, steel, DeliverySource.Orbital, out cell), "router found no cell with a mergeable stack");
T.Equal(middle, cell, "router cell in pass 2");
// A full stack has no room left: no cell in the zone.
lying.stackCount = lying.def.stackLimit;
T.Check(!DeliveryRouter.TryPickCellInZone(zone, steel, out cell), "pass 2 took a full stack at " + cell);
T.Check(!cell.IsValid, "failed pick set a cell");
}
[BlaxTest("router: a zone checks at most 400 cells per stack")]
public static void CheckBudget()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
CellRect a = Fixtures.TestArea(21, 20);
Zone_Delivery zone = Fixtures.DeliveryZone(a);
List<IntVec3> order = Fixtures.Comp.CellsByDistance(zone);
T.Equal(420, order.Count, "zone cells");
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 10);
// Roof the 400 cells nearest the centroid: the free 20 lie past the budget.
for (int i = 0; i < DeliveryRouter.MaxChecksPerStack; i++)
map.roofGrid.SetRoof(order[i], RoofDefOf.RoofConstructed);
T.Check(!DeliveryRouter.TryPickCellInZone(zone, steel, out IntVec3 cell), "checked past the budget and found " + cell);
// Free the last cell inside the budget: found.
IntVec3 last = order[DeliveryRouter.MaxChecksPerStack - 1];
map.roofGrid.SetRoof(last, null);
T.Check(DeliveryRouter.TryPickCellInZone(zone, steel, out cell), "missed the free cell at check 400");
T.Equal(last, cell, "cell at check 400");
}
// ---- overflow -------------------------------------------------------------------------
[BlaxTest("router: a 1-cell zone with its cell taken overflows within the radius")]
public static void OneCellOverflow()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
CellRect a = Fixtures.TestArea(1, 1);
IntVec3 only = a.CenterCell;
Zone_Delivery zone = Fixtures.DeliveryZone(a);
T.Check(ZonesApi.TryFindDropSpot(map, Fixtures.Stack(ThingDefOf.Steel, 10), out IntVec3 cell), "ZonesApi refused steel");
T.Equal(only, cell, "cell of the free 1-cell zone");
DropPodAt(only, Fixtures.Stack(ThingDefOf.Silver, 100));
T.Check(!DeliveryRouter.TryPickCellInZone(zone, Fixtures.Stack(ThingDefOf.Steel, 10), out _), "the cell under a falling pod was picked");
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 10);
T.Check(DeliveryRouter.TryFindDropSpot(map, steel, DeliverySource.Orbital, out cell), "no overflow cell next to a taken 1-cell zone");
T.Check(cell != only, "overflow returned the taken cell");
T.Check(WithinRadius(only, cell, DeliveryRouter.OverflowRadius), "overflow cell " + cell + " is farther than " + DeliveryRouter.OverflowRadius + " from " + only);
T.Check(DropCellFinder.IsGoodDropSpot(cell, map, allowFogged: false, canRoofPunch: false), "overflow cell " + cell + " is no good drop spot");
T.Check(ZonesApi.TryFindDropSpot(map, steel, out cell) && WithinRadius(only, cell, DeliveryRouter.OverflowRadius), "ZonesApi did not overflow");
Fixtures.Settings.overflowNearZone = false;
T.Check(!DeliveryRouter.TryFindDropSpot(map, steel, DeliverySource.Orbital, out cell), "overflowed to " + cell + " with the setting off");
T.Check(!ZonesApi.TryFindDropSpot(map, steel, out cell), "ZonesApi overflowed to " + cell + " with the setting off");
}
[BlaxTest("router: an L-shaped zone whose centroid is a wall still overflows")]
public static void LShapedOverflow()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
CellRect a = Fixtures.TestArea(7, 7);
// Bottom row and left column of the 7x7 area.
Zone_Delivery zone = Fixtures.DeliveryZone(new CellRect(a.minX, a.minZ, 7, 1));
for (int z = a.minZ + 1; z <= a.maxZ; z++)
zone.AddCell(new IntVec3(a.minX, 0, z));
T.Equal(13, zone.CellCount, "L-shaped zone cells");
double cx = zone.cells.Average(c => (double)c.x), cz = zone.cells.Average(c => (double)c.z);
IntVec3 centroid = new IntVec3((int)Math.Round(cx), 0, (int)Math.Round(cz));
T.Check(!zone.cells.Contains(centroid), "the centroid cell " + centroid + " is a zone cell");
Fixtures.Wall(centroid);
T.Check(centroid.GetEdifice(map) != null, "no wall on the centroid cell");
IntVec3 center = DeliveryRouter.OverflowCenter(zone);
T.Check(zone.cells.Contains(center), "OverflowCenter " + center + " is not a zone cell");
double best = zone.cells.Min(c => DistSq(c, cx, cz));
T.Check(Math.Abs(DistSq(center, cx, cz) - best) < 1e-9, "OverflowCenter " + center + " is not the zone cell nearest the centroid");
T.Check(DeliveryRouter.TryOverflow(zone, out IntVec3 cell), "no overflow cell next to the L-shaped zone");
T.Check(WithinRadius(center, cell, DeliveryRouter.OverflowRadius), "overflow cell " + cell + " is farther than the radius");
// Every zone cell under a falling pod: the router overflows next to the zone.
foreach (IntVec3 c in zone.cells.ToList())
DropPodAt(c, Fixtures.Stack(ThingDefOf.Silver, 10));
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 10);
T.Check(DeliveryRouter.TryFindDropSpot(map, steel, DeliverySource.Orbital, out cell), "router found no overflow cell for the full L-shaped zone");
T.Check(!zone.cells.Contains(cell), "overflow returned zone cell " + cell + " under a falling pod");
T.Check(WithinRadius(center, cell, DeliveryRouter.OverflowRadius), "overflow cell " + cell + " is farther than the radius");
}
[BlaxTest("router: a walled-off zone never overflows into its own pocket; the pod goes to the vanilla spot")]
public static void WalledOffNoOverflow()
{
Map map = Fixtures.Map;
SetAsideOtherDeliveryZones();
if (map.mapPawns.FreeColonistsSpawned.Count == 0)
Fixtures.Colonist();
Fixtures.Settings.overflowNearZone = true;
Fixtures.Settings.overflowRadius = BlaxZonesSettings.DefaultOverflowRadius;
CellRect a = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(a);
foreach (IntVec3 c in a.ExpandedBy(1).EdgeCells)
Fixtures.Wall(c);
T.Equal(9, zone.CellCount, "zone cells after the walls (none under them)");
IntVec3 center = DeliveryRouter.OverflowCenter(zone);
T.Check(DropCellFinder.IsGoodDropSpot(center, map, allowFogged: false, canRoofPunch: false),
"setup: IsGoodDropSpot refuses the walled-in center, so this would not test the reach rule");
T.Check(!DeliveryRules.ColonyCanReach(map, center), "setup: the reach rule says a colonist reaches a closed wall ring");
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 10);
T.Check(!DeliveryRouter.TryPickCellInZone(zone, steel, out IntVec3 cell), "picked the unreachable zone cell " + cell);
T.Check(!DeliveryRouter.TryOverflow(zone, out cell), "overflow found " + cell + (zone.ContainsCell(cell) ? ", a zone cell" : "")
+ ", reach rule " + DeliveryRules.ColonyCanReach(map, cell));
T.Check(!cell.IsValid, "failed overflow set a cell");
T.Check(!DeliveryRouter.TryFindDropSpot(map, steel, DeliverySource.Orbital, out cell), "the router sent the pod to " + cell + " for a walled-off zone");
T.Check(!ZonesApi.TryFindDropSpot(map, steel, out cell), "ZonesApi returned " + cell + " for a walled-off zone");
}
// ---- failure path ---------------------------------------------------------------------
[BlaxTest("router: RouterThrows makes the router throw and ZonesApi returns false with one logged error")]
public static void RouterThrowsApiFalse()
{
Map map = Fixtures.Map;
ZonesLog.ResetOnce();
Fixtures.OnCleanup(ZonesLog.ResetOnce);
SetAsideOtherDeliveryZones();
Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 10);
T.Check(ZonesApi.TryFindDropSpot(map, steel, out _), "ZonesApi refused steel before the hook");
ZonesTestHooks.RouterThrows = true;
bool threw = false;
try
{
DeliveryRouter.TryFindDropSpot(map, steel, DeliverySource.Orbital, out _);
}
catch (InvalidOperationException)
{
threw = true;
}
T.Check(threw, "DeliveryRouter.TryFindDropSpot did not throw with RouterThrows set");
T.ExpectErrors("ZonesApi.TryFindDropSpot failed", 1);
T.Check(!ZonesApi.TryFindDropSpot(map, steel, out IntVec3 cell), "ZonesApi returned true while the router throws");
T.Check(!cell.IsValid, "ZonesApi set a cell while the router throws");
T.Check(!ZonesApi.TryFindDropSpot(map, steel, out cell), "ZonesApi returned true on the second call");
}
// ---- helpers ----------------------------------------------------------------------------
/// <summary>
/// Deregisters every delivery zone already on the map (zones earlier tests kept for phase 2) and
/// registers them again in cleanup, so only this test's zones are candidates. Their cells stay in
/// the zone grid, so TestArea keeps away from them.
/// </summary>
private static void SetAsideOtherDeliveryZones()
{
Map map = Fixtures.Map;
List<Zone_Delivery> others = map.zoneManager.AllZones.OfType<Zone_Delivery>().ToList();
if (others.Count == 0)
return;
Fixtures.OnCleanup(() =>
{
foreach (Zone_Delivery z in others)
{
if (!map.zoneManager.AllZones.Contains(z))
map.zoneManager.RegisterZone(z);
}
});
foreach (Zone_Delivery z in others)
map.zoneManager.DeregisterZone(z);
T.Info("set aside " + others.Count + " delivery zone(s) of earlier tests");
}
/// <summary>Spawns a drop pod holding the thing at the cell, as ZonesApi callers do, and tracks the falling pod.</summary>
private static Skyfaller DropPodAt(IntVec3 cell, Thing thing)
{
Map map = Fixtures.Map;
var before = new HashSet<Thing>(cell.GetThingList(map));
TradeUtility.SpawnDropPod(cell, map, thing);
Skyfaller pod = cell.GetThingList(map).OfType<Skyfaller>().FirstOrDefault(s => !before.Contains(s));
T.NotNull(pod, "falling drop pod at " + cell);
T.Check(!DropCellFinder.IsGoodDropSpot(cell, map, allowFogged: false, canRoofPunch: false), "a falling pod left " + cell + " a good drop spot");
return Fixtures.Track(pod);
}
private static Thing SpawnStack(ThingDef def, int count, IntVec3 cell)
{
Thing t = Fixtures.Stack(def, count);
GenSpawn.Spawn(t, cell, Fixtures.Map);
T.Check(t.Spawned && t.Position == cell, def.defName + " stack not spawned at " + cell);
return t;
}
/// <summary>TryFindDropSpotNear searches squares (CellFinder.TryFindRandomCellNear), so the radius is per axis.</summary>
private static bool WithinRadius(IntVec3 center, IntVec3 cell, int radius) =>
cell.IsValid && Math.Abs(cell.x - center.x) <= radius && Math.Abs(cell.z - center.z) <= radius;
private static double DistSq(IntVec3 c, double cx, double cz) => (c.x - cx) * (c.x - cx) + (c.z - cz) * (c.z - cz);
/// <summary>The order holds exactly the zone's cells, sorted by distance to their centroid.</summary>
private static void CheckSorted(Zone_Delivery zone, List<IntVec3> order, string what)
{
T.Equal(zone.cells.Count, order.Count, what + ": cells in the order");
T.Check(new HashSet<IntVec3>(order).SetEquals(zone.cells), what + ": the order is not the zone's cells");
double cx = zone.cells.Average(c => (double)c.x), cz = zone.cells.Average(c => (double)c.z);
for (int i = 1; i < order.Count; i++)
T.Check(DistSq(order[i - 1], cx, cz) <= DistSq(order[i], cx, cz) + 1e-9, what + ": " + order[i - 1] + " before " + order[i] + " is out of order");
}
private static string Ids(params Zone_Delivery[] zones) => string.Join(",", zones.Select(z => z.ID));
}
}

View File

@ -0,0 +1,195 @@
using BlaxZones;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxZonesTests
{
/// <summary>
/// Package Rules. Design: 1.0 "Delivery zone" > Tests (unusable cells, pen ring, reach).
/// Tests: [BlaxTest("rules: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped.
/// </summary>
public static class RulesTests
{
private static string UnusableLine(int count) => "BlaxZones_UnusableCells".Translate(count).Resolve();
/// <summary>The reach rule asks free colonists first; make sure there is one before carving an area.</summary>
private static void EnsureFreeColonist()
{
if (Fixtures.Map.mapPawns.FreeColonistsSpawned.Count == 0)
Fixtures.Colonist();
}
[BlaxTest("rules: 3 roofed cells are unusable and the inspect pane says 3; a water cell makes it 4")]
public static void RoofAndWater()
{
MapComponent_BlaxZones comp = Fixtures.Comp;
CellRect a = Fixtures.TestArea(4, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(a);
T.Equal(0, comp.UnusableCellCount(zone), "unusable cells on a fresh zone");
T.Check(comp.InspectLineFor(zone) == null, "inspect line while every cell is usable: " + comp.InspectLineFor(zone));
Fixtures.Roof(new CellRect(a.minX, a.minZ, 3, 1));
T.Equal(3, comp.UnusableCellCount(zone), "unusable cells with 3 roofed");
string inspect = zone.GetInspectString();
T.Check(inspect.Contains(UnusableLine(3)), "inspect string '" + inspect + "' lacks '" + UnusableLine(3) + "'");
IntVec3 water = new IntVec3(a.minX, 0, a.maxZ);
Fixtures.Water(water);
T.Check(zone.ContainsCell(water), "the water cell left the zone");
T.Equal(4, comp.UnusableCellCount(zone), "unusable cells with 3 roofed and 1 water");
inspect = zone.GetInspectString();
T.Check(inspect.Contains(UnusableLine(4)), "inspect string '" + inspect + "' lacks '" + UnusableLine(4) + "'");
T.Check(comp.UnusableCells(zone).Contains(water), "the water cell is not among the unusable cells");
}
[BlaxTest("rules: one unusable cell reads in the singular")]
public static void SingularLine()
{
MapComponent_BlaxZones comp = Fixtures.Comp;
CellRect a = Fixtures.TestArea(3, 1);
Zone_Delivery zone = Fixtures.DeliveryZone(a);
Fixtures.Roof(new CellRect(a.minX, a.minZ, 1, 1));
T.Equal("BlaxZones_UnusableCell".Translate().Resolve(), comp.InspectLineFor(zone), "inspect line for 1 cell");
}
[BlaxTest("rules: a fence ring with a pen marker around the zone makes every cell unusable")]
public static void PenRing()
{
Map map = Fixtures.Map;
MapComponent_BlaxZones comp = Fixtures.Comp;
CellRect a = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(a);
T.Equal(0, comp.UnusableCellCount(zone), "unusable cells before the pen");
Thing marker = Fixtures.FenceRing(a);
T.NotNull(marker, "pen marker");
CompAnimalPenMarker pen = marker.TryGetComp<CompAnimalPenMarker>();
T.NotNull(pen, "CompAnimalPenMarker on the marker");
T.Check(map.animalPenManager.GetPenMarkerState(pen).Enclosed, "the fence ring is not an enclosed pen");
T.Info("reach rule inside the pen: " + DeliveryRules.ColonyCanReach(map, a.CenterCell));
T.Equal(zone.CellCount, comp.UnusableCellCount(zone), "unusable cells inside an enclosed pen");
T.Check(zone.GetInspectString().Contains(UnusableLine(zone.CellCount)), "inspect string lacks the count of " + zone.CellCount);
}
[BlaxTest("rules: player walls closing off a zone make its cells unreachable, though CanReachColony says true")]
public static void WalledOff()
{
Map map = Fixtures.Map;
MapComponent_BlaxZones comp = Fixtures.Comp;
EnsureFreeColonist();
CellRect a = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(a);
// Caches the reach of the open district first, so the walls must not reuse that entry.
T.Equal(0, comp.UnusableCellCount(zone), "unusable cells before the walls");
foreach (IntVec3 c in a.ExpandedBy(1).EdgeCells)
Fixtures.Wall(c);
T.Equal(9, zone.CellCount, "zone cells after the walls (none under them)");
IntVec3 inside = a.CenterCell;
T.Check(DropCellFinder.IsGoodDropSpot(inside, map, allowFogged: false, canRoofPunch: false),
"IsGoodDropSpot refuses the walled-in cell, so this would not test the reach rule");
T.Check(map.reachability.CanReachColony(inside), "CanReachColony is false inside the walls; the test needs it true");
T.Check(!DeliveryRules.ColonyCanReach(map, inside), "the reach rule says a colonist reaches a closed wall ring");
T.Check(!DeliveryRules.PodCellOk(map, inside), "PodCellOk accepts a walled-in cell");
T.Equal(zone.CellCount, comp.UnusableCellCount(zone), "unusable cells inside the walls");
}
[BlaxTest("rules: PodCellOk is true on a plain cell and false on a fogged or roofed cell")]
public static void PodCell()
{
Map map = Fixtures.Map;
EnsureFreeColonist();
CellRect a = Fixtures.TestArea(3, 1);
IntVec3 fogged = new IntVec3(a.minX, 0, a.minZ);
IntVec3 plain = new IntVec3(a.minX + 1, 0, a.minZ);
IntVec3 roofed = new IntVec3(a.maxX, 0, a.minZ);
T.Check(DeliveryRules.PodCellOk(map, plain), "PodCellOk refuses a plain test area cell");
map.fogGrid.Refog(new CellRect(fogged.x, fogged.z, 1, 1));
T.Check(fogged.Fogged(map), "Refog left the cell unfogged");
T.Check(!DeliveryRules.PodCellOk(map, fogged), "PodCellOk accepts a fogged cell");
Fixtures.Roof(new CellRect(roofed.x, roofed.z, 1, 1));
T.Check(!DeliveryRules.PodCellOk(map, roofed), "PodCellOk accepts a roofed cell");
T.Check(DeliveryRules.PodCellOk(map, plain), "PodCellOk refuses the plain cell after its neighbours changed");
T.Check(!DeliveryRules.PodCellOk(null, plain), "PodCellOk accepts a null map");
T.Check(!DeliveryRules.PodCellOk(map, new IntVec3(-1, 0, -1)), "PodCellOk accepts an out-of-bounds cell");
}
[BlaxTest("rules: the reach result is cached per district and recomputed after ReachMaxAgeTicks")]
public static void ReachCacheAge()
{
Map map = Fixtures.Map;
MapComponent_BlaxZones comp = Fixtures.Comp;
EnsureFreeColonist();
CellRect a = Fixtures.TestArea(3, 3);
IntVec3 first = a.CenterCell;
IntVec3 second = new IntVec3(a.minX, 0, a.minZ);
District district = first.GetDistrict(map);
T.NotNull(district, "district of the test area");
T.Check(second.GetDistrict(map) == district, "two cells of one test area lie in different districts");
T.Check(DeliveryRules.ColonyCanReach(map, first), "a free colonist can't reach a plain test area cell");
T.Check(comp.TryGetCachedReach(district, PathEndMode.OnCell, out bool cached) && cached, "no fresh cached OnCell entry after the check");
T.Check(!comp.TryGetCachedReach(district, PathEndMode.Touch, out _), "an OnCell check filled the Touch entry");
// A false entry the live check would never give: only the cache can answer false now.
comp.StoreReach(district, PathEndMode.OnCell, false);
T.Check(!DeliveryRules.ColonyCanReach(map, second), "another cell of the district didn't use the cached entry");
T.Check(!DeliveryRules.PodCellOk(map, second), "PodCellOk ignored the cached reach entry");
Fixtures.Tick(DeliveryRules.ReachMaxAgeTicks);
T.Check(!comp.TryGetCachedReach(district, PathEndMode.OnCell, out _), "an entry ReachMaxAgeTicks old is still trusted");
T.Check(DeliveryRules.ColonyCanReach(map, second), "the reach rule was not recomputed after ReachMaxAgeTicks");
District after = second.GetDistrict(map);
T.Check(comp.TryGetCachedReach(after, PathEndMode.OnCell, out cached) && cached, "the recomputed result was not cached");
}
[BlaxTest("rules: a reach entry is dropped when its district changes")]
public static void ReachCacheDistrictChange()
{
Map map = Fixtures.Map;
MapComponent_BlaxZones comp = Fixtures.Comp;
EnsureFreeColonist();
CellRect a = Fixtures.TestArea(3, 3);
District district = a.CenterCell.GetDistrict(map);
T.NotNull(district, "district of the test area");
comp.StoreReach(district, PathEndMode.OnCell, false);
T.Check(comp.TryGetCachedReach(district, PathEndMode.OnCell, out bool cached) && !cached, "the stored entry is not returned");
// Vanilla stamps a reused district this way when walls go up next to it (RegionAndRoomUpdater.cs:307-314).
Fixtures.Tick(1);
district.Notify_RoomShapeOrContainedBedsChanged();
T.Check(!comp.TryGetCachedReach(district, PathEndMode.OnCell, out _), "an entry of a changed district is still trusted");
T.Check(DeliveryRules.ColonyCanReach(map, a.CenterCell), "the reach rule was not recomputed for the changed district");
}
[BlaxTest("rules: a selected zone's count refreshes within SelectedRecheckTicks after a change")]
public static void SelectedRecheck()
{
MapComponent_BlaxZones comp = Fixtures.Comp;
CellRect a = Fixtures.TestArea(4, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(a);
Find.Selector.ClearSelection();
Find.Selector.Select(zone, playSound: false);
T.Check(Find.Selector.SelectedZone == zone, "the delivery zone is not selected");
T.Equal(0, comp.UnusableCellCount(zone), "unusable cells before the change");
Fixtures.Roof(new CellRect(a.minX, a.minZ, 2, 1));
// Roofing tells the zone nothing; the selected zone's count is a cache, refreshed on a timer.
T.Equal(0, comp.UnusableCellCount(zone), "the selected zone's count before its recheck (expected the cached value)");
Fixtures.Tick(DeliveryRules.SelectedRecheckTicks);
T.Equal(2, comp.UnusableCellCount(zone), "unusable cells " + DeliveryRules.SelectedRecheckTicks + " ticks after roofing 2");
string inspect = zone.GetInspectString();
T.Check(inspect.Contains(UnusableLine(2)), "inspect string '" + inspect + "' lacks '" + UnusableLine(2) + "'");
Find.Selector.ClearSelection();
Fixtures.Roof(new CellRect(a.minX + 2, a.minZ, 1, 1));
T.Equal(3, comp.UnusableCellCount(zone), "an unselected zone counts live");
}
}
}

View File

@ -0,0 +1,137 @@
using System.Linq;
using System.Reflection;
using BlaxZones;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxZonesTests
{
/// <summary>The skeleton and the harness work: patches, settings, the component, the API shape, map fixtures, all three phases.</summary>
public static class SmokeTests
{
private static readonly string[] SharedKeys =
{
"BlaxZones_DeliveryZone", "BlaxZones_NeedsDlc",
"BlaxZones_SettingDeliveryZones", "BlaxZones_SettingRouteOrbital", "BlaxZones_SettingOverflowNearZone",
"BlaxZones_SettingOverflowRadius", "BlaxZones_SettingCampAtZones", "BlaxZones_SettingsReset",
};
[BlaxTest("startup: every patch class applied and logged, no errors mentioning Blax Zones")]
public static void StartupLogged()
{
int ours = Harmony.GetAllPatchedMethods()
.Select(Harmony.GetPatchInfo)
.Where(info => info != null)
.SelectMany(info => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers).Concat(info.Transpilers))
.Count(p => p.owner == BlaxZonesStartup.HarmonyId);
T.Info("Harmony patches owned by " + BlaxZonesStartup.HarmonyId + ": " + ours);
T.Check(BlaxZonesStartup.FailedPatches.Count == 0, "patch classes failed: " + string.Join(", ", BlaxZonesStartup.FailedPatches));
// Only what was logged before the first test: later tests log expected errors on purpose.
var startup = TestRunner.StartupLog;
bool logged = startup.Any(m => m.text != null && m.text.Contains("[Blax Zones]") && m.text.Contains("patches applied"));
T.Check(logged, "startup line '[Blax Zones] N patches applied' not in the log");
var errors = startup.Where(m => m.type == LogMessageType.Error && m.text != null && (m.text.Contains("Blax Zones") || m.text.Contains("BlaxZones"))).ToList();
T.Check(errors.Count == 0, "errors mentioning Blax Zones at startup: " + string.Join(" | ", errors.Take(3).Select(e => e.text)));
}
[BlaxTest("startup: settings, shared strings and one component per map")]
public static void Loaded()
{
T.NotNull(BlaxZonesMod.Settings, "BlaxZonesMod.Settings");
var missing = SharedKeys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
foreach (Map m in Find.Maps)
T.Equal(1, m.components.Count(c => c is MapComponent_BlaxZones), "MapComponent_BlaxZones on map " + m.Index);
T.Check(Fixtures.Comp != null, "MapComponent_BlaxZones.Of(current map) is null");
}
[BlaxTest("settings: the overflow radius clamps to 5..30")]
public static void OverflowRadiusClamp()
{
BlaxZonesSettings s = Fixtures.Settings;
s.overflowRadius = 2;
T.Equal(BlaxZonesSettings.MinOverflowRadius, s.OverflowRadiusClamped, "radius 2 clamped");
s.overflowRadius = 99;
T.Equal(BlaxZonesSettings.MaxOverflowRadius, s.OverflowRadiusClamped, "radius 99 clamped");
T.Equal(BlaxZonesSettings.DefaultOverflowRadius, new BlaxZonesSettings().overflowRadius, "default radius");
}
[BlaxTest("api: ZonesApi version 1 binds the way Blax Slaves binds it and refuses a pawn")]
public static void ApiShape()
{
System.Type api = AccessTools.TypeByName("BlaxZones.ZonesApi");
T.NotNull(api, "BlaxZones.ZonesApi by name");
PropertyInfo version = AccessTools.Property(api, "Version");
T.NotNull(version, "ZonesApi.Version property");
T.Equal(1, (int)version.GetValue(null), "ZonesApi.Version");
MethodInfo m = AccessTools.Method(api, "TryFindDropSpot", new[] { typeof(Map), typeof(Thing), typeof(IntVec3).MakeByRefType() });
T.Check(m != null && m.IsStatic && m.ReturnType == typeof(bool), "ZonesApi.TryFindDropSpot(Map, Thing, out IntVec3) static bool");
Pawn p = Fixtures.Colonist();
T.Check(!ZonesApi.TryFindDropSpot(Fixtures.Map, p, out IntVec3 cell), "TryFindDropSpot accepted a pawn");
T.Check(!cell.IsValid, "TryFindDropSpot set a cell for a pawn");
}
[BlaxTest("harness: TestArea, Roof, Wall, Water and DeliveryZone fixtures")]
public static void MapFixtures()
{
Map map = Fixtures.Map;
CellRect a = Fixtures.TestArea(4, 3);
T.Equal(12, a.Area, "area size");
foreach (IntVec3 c in a.ExpandedBy(Fixtures.AreaMargin))
{
T.Check(c.GetRoof(map) == null, "roof left at " + c);
T.Check(!c.Fogged(map), "fog left at " + c);
T.Check(c.Standable(map), "cell not standable at " + c);
}
CellRect b = Fixtures.TestArea(4, 3);
T.Check(!a.ExpandedBy(Fixtures.AreaMargin).Overlaps(b.ExpandedBy(Fixtures.AreaMargin)), "two test areas overlap");
Zone_Delivery zone = Fixtures.DeliveryZone(a, priority: StoragePriority.Important);
T.Equal(12, zone.CellCount, "zone cells");
T.Check(map.zoneManager.ZoneAt(a.CenterCell) == zone, "ZoneAt(center) is not the delivery zone");
T.Check(map.zoneManager.AllZones.Contains(zone), "zone not registered");
T.Check(zone.Accepts(Fixtures.Stack(ThingDefOf.Steel, 10)), "default filter refuses steel");
Fixtures.Roof(new CellRect(a.minX, a.minZ, 1, 1));
T.Check(new IntVec3(a.minX, 0, a.minZ).Roofed(map), "Roof fixture left the cell unroofed");
IntVec3 wallCell = new IntVec3(a.maxX, 0, a.maxZ);
Fixtures.Wall(wallCell);
T.Equal(11, zone.CellCount, "zone cells after a wall on one");
Fixtures.Water(new IntVec3(a.minX + 1, 0, a.minZ));
T.Check(new IntVec3(a.minX + 1, 0, a.minZ).GetTerrain(map).IsWater, "Water fixture is not water");
}
[BlaxTest("harness: colonist, prisoner and colony slave fixtures")]
public static void PawnFixtures()
{
Pawn c = Fixtures.Colonist();
T.Check(c.Spawned && c.IsFreeColonist, "colonist fixture is not a spawned free colonist");
Pawn pr = Fixtures.Prisoner();
T.Check(pr.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony");
Pawn s = Fixtures.ColonySlave();
T.Check(s.IsSlaveOfColony, "slave fixture is not a slave of the colony");
}
[BlaxTest("harness: the component is on every map after the reload", phase: 2)]
public static void ComponentAfterReload()
{
foreach (Map m in Find.Maps)
T.Equal(1, m.components.Count(c => c is MapComponent_BlaxZones), "MapComponent_BlaxZones on map " + m.Index);
}
[BlaxTest("harness: phase 3 loads with exactly the two removal errors per map and a fresh component", phase: 3)]
public static void Phase3Removal()
{
int maps = TestRunner.Phase3ReplacedCount;
T.Check(maps >= 1, "phase 3 replaced no component node");
T.Equal(Find.Maps.Count, maps, "replaced component nodes vs maps");
T.ExpectErrors("Could not find class " + TestRunner.RemovedComponentClass, maps);
T.ExpectErrors("Can't load abstract class Verse.MapComponent", maps);
T.Info("load errors: " + T.Phase3LoadErrors.Count + ", resolve warnings: " + T.Phase3ResolveWarnings);
T.Equal(2 * maps, T.Phase3LoadErrors.Count, "errors while loading the phase-3 save");
foreach (Map m in Find.Maps)
T.Equal(1, m.components.Count(c => c is MapComponent_BlaxZones), "fresh MapComponent_BlaxZones on map " + m.Index);
}
}
}

View File

@ -0,0 +1,623 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using BlaxZones;
using HarmonyLib;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxZonesTests
{
/// <summary>
/// Package Store. Design: 1.0 "Save-safe zone storage" > Tests.
/// Tests: [BlaxTest("store: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped.
///
/// Phase 1 keeps three delivery zones (A and B with different filters and priorities, E with one
/// saved cell under a wall) and a stockpile S; zone C is deleted and zone D walled over before the
/// save. Every kept delivery zone has its orbital checkbox off, so other packages' routing tests
/// never pick them.
/// </summary>
public static class StoreTests
{
private const string ExtraSaveName = "BlaxZonesStoreExtra";
private const string DeliveryClass = "BlaxZones.Zone_Delivery";
// ---- phase 1 -----------------------------------------------------------------------------
// Runs first in this class (source order): the later phase-1 tests and phases 2 and 3 read what it keeps.
[BlaxTest("store: set up two delivery zones, a deleted zone, a walled-over zone and a stockpile for the reload")]
public static void Setup()
{
Map map = Fixtures.Map;
CellRect area = Fixtures.TestArea(15, 2);
int x0 = area.minX, z0 = area.minZ;
// A: steel and industrial medicine, Important. A kept wall on its corner leaves that cell out.
Zone_Delivery a = Fixtures.KeepZone(Fixtures.DeliveryZone(new CellRect(x0, z0, 3, 2),
Fixtures.FilterOf(ThingDefOf.Steel, ThingDefOf.MedicineIndustrial), StoragePriority.Important, orbital: false));
var aWall = new IntVec3(x0 + 2, 0, z0 + 1);
Fixtures.Keep(Fixtures.Wall(aWall));
T.Equal(5, a.CellCount, "zone A cells after a wall on its corner");
T.Check(map.zoneManager.ZoneAt(aWall) == null, "the walled cell still belongs to a zone");
// B: silver only, Low.
Zone_Delivery b = Fixtures.KeepZone(Fixtures.DeliveryZone(new CellRect(x0 + 4, z0, 2, 2),
Fixtures.FilterOf(ThingDefOf.Silver), StoragePriority.Low, orbital: false));
T.Check(a.filter.Allows(ThingDefOf.Steel) && !a.filter.Allows(ThingDefOf.Silver), "zone A filter setup");
T.Check(b.filter.Allows(ThingDefOf.Silver) && !b.filter.Allows(ThingDefOf.Steel), "zone B filter setup");
// C: deleted before the save.
var cRect = new CellRect(x0 + 7, z0, 1, 2);
Zone_Delivery c = Fixtures.DeliveryZone(cRect, orbital: false);
c.Delete(playSound: false);
T.Check(!map.zoneManager.AllZones.Contains(c), "deleted zone C is still registered");
// D: a wall on its only cell deregisters it (Zone.cs:248-251).
var dCell = new IntVec3(x0 + 9, 0, z0);
Zone_Delivery d = Fixtures.DeliveryZone(new CellRect(dCell.x, dCell.z, 1, 1), orbital: false);
Fixtures.Wall(dCell);
T.Check(!map.zoneManager.AllZones.Contains(d), "walled-over zone D is still registered");
// E: one normal cell plus a saved cell under a wall. Vanilla never makes this state; written
// straight into the cell list it shows that the load prefix registers our zones before
// vanilla's spawn loop, which then trims the walled cell as it trims stockpiles.
var eKeep = new IntVec3(x0 + 11, 0, z0);
var eWalled = new IntVec3(x0 + 11, 0, z0 + 1);
Zone_Delivery e = Fixtures.KeepZone(Fixtures.DeliveryZone(new CellRect(eKeep.x, eKeep.z, 1, 1), orbital: false));
Fixtures.Keep(Fixtures.Wall(eWalled));
e.cells.Add(eWalled);
T.Equal(2, e.CellCount, "zone E cells with the walled cell written in");
// S: a vanilla stockpile for phase 3.
Zone_Stockpile s = Fixtures.KeepZone(Fixtures.Stockpile(new CellRect(x0 + 13, z0, 2, 2)));
T.Carry["store.A.id"] = a.ID.ToString();
T.Carry["store.B.id"] = b.ID.ToString();
T.Carry["store.C.id"] = c.ID.ToString();
T.Carry["store.C.cells"] = Cells(cRect.Cells);
T.Carry["store.D.id"] = d.ID.ToString();
T.Carry["store.D.cells"] = Cells(new[] { dCell });
T.Carry["store.E.id"] = e.ID.ToString();
T.Carry["store.E.keep"] = Cells(new[] { eKeep });
T.Carry["store.E.walled"] = Cells(new[] { eWalled });
T.Carry["store.A.wallCell"] = Cells(new[] { aWall });
T.Carry["store.S.id"] = s.ID.ToString();
// Read at save time: the comparison in phase 2 is against what was saved.
foreach (string key in new[] { "A", "B", "E" })
{
string k = key;
T.CarryAtSave("store." + k + ".label", () => DeliveryByKey(k)?.label ?? "missing");
T.CarryAtSave("store." + k + ".cells", () => DeliveryByKey(k) is Zone_Delivery z ? Cells(z.cells) : "missing");
T.CarryAtSave("store." + k + ".filter", () => DeliveryByKey(k) is Zone_Delivery z ? FilterText(z) : "missing");
T.CarryAtSave("store." + k + ".priority", () => DeliveryByKey(k)?.priority.ToString() ?? "missing");
T.CarryAtSave("store." + k + ".sources", () => DeliveryByKey(k) is Zone_Delivery z ? SourcesText(z) : "missing");
}
T.CarryAtSave("store.S.label", () => Fixtures.FindZoneById(IdOf("S"))?.label ?? "missing");
T.CarryAtSave("store.S.cells", () => Fixtures.FindZoneById(IdOf("S")) is Zone z ? Cells(z.cells) : "missing");
T.Equal(0, Fixtures.Comp.LoadedZones.Count, "loaded zones held by the component while the game runs");
T.Check(!ZoneStore.Loading, "ZoneStore.Loading is set while the game runs");
T.Check(ZoneStore.IsBlaxZone(a), "IsBlaxZone(delivery zone)");
T.Check(!ZoneStore.IsBlaxZone(s), "IsBlaxZone(stockpile)");
T.Check(!ZoneStore.IsBlaxZone(null), "IsBlaxZone(null)");
}
[BlaxTest("store: an extra save without a reload keeps the zones registered, the same list object and the zone grid")]
public static void ExtraSave()
{
Zone_Delivery a = NeedDelivery("A"), b = NeedDelivery("B"), e = NeedDelivery("E");
Map map = a.Map;
List<Zone> before = map.zoneManager.AllZones;
List<Zone> snapshot = before.ToList();
string path = GenFilePaths.FilePathForSavedGame(ExtraSaveName);
Fixtures.OnCleanup(() => DeleteSave(path));
GameDataSaveLoader.SaveGame(ExtraSaveName);
StopScribe();
T.Check(ReferenceEquals(before, map.zoneManager.AllZones), "AllZones is a different list object after the save");
T.Check(before.SequenceEqual(snapshot), "AllZones changed during the save");
foreach (Zone_Delivery z in new[] { a, b })
{
T.Check(map.zoneManager.AllZones.Contains(z), z.label + " left AllZones during the save");
foreach (IntVec3 c in z.cells)
T.Check(map.zoneManager.ZoneAt(c) == z, "ZoneAt(" + c + ") is not " + z.label + " after the save");
}
T.Check(map.zoneManager.ZoneAt(ParseCells(T.Carry["store.E.keep"])[0]) == e, "ZoneAt(E's cell) is not E after the save");
CheckSaveLayout(path, "extra save");
}
[BlaxTest("store: a zone that throws while saving logs one error and the list object is restored")]
public static void ThrowWhileSaving()
{
Map map = Fixtures.Map;
StoreTestZone tz = NewTestZone(map);
List<Zone> before = map.zoneManager.AllZones;
List<Zone> snapshot = before.ToList();
T.Check(snapshot.Any(ZoneStore.IsBlaxZone), "setup: no Blax zone on the map (did the store setup run?)");
T.ExpectErrors(StoreTestZone.SaveMessage, 1);
string xml;
List<Zone> after;
List<Zone> afterContents;
tz.fault = StoreTestZone.Fault.ThrowOnSave;
try
{
xml = Scribe.saver.DebugOutputFor(map.zoneManager);
}
finally
{
tz.fault = StoreTestZone.Fault.None;
after = ZoneStore.AllZonesRef(map.zoneManager);
afterContents = after.ToList();
Repair(map, before, tz);
}
StopScribe();
T.Check(ReferenceEquals(before, after), "AllZones is a different list object after the save threw");
T.Check(afterContents.SequenceEqual(snapshot), "AllZones changed during the save");
T.Check(!xml.NullOrEmpty() && xml.Contains("allZones"), "setup: the debug save wrote no zone list");
T.Check(!xml.Contains("BlaxZones."), "the saved zoneManager holds a Blax zone");
}
[BlaxTest("store: an exception escaping ZoneManager.ExposeData still gets the list object restored by the finalizer")]
public static void EscapingSaveException()
{
Map map = Fixtures.Map;
StoreTestZone tz = NewTestZone(map);
List<Zone> before = map.zoneManager.AllZones;
List<Zone> snapshot = before.ToList();
// The test zone adds itself to the list being written, so the list's enumerator throws in
// Scribe_Collections, outside the per-item catch in Scribe_Deep, and the exception leaves
// ZoneManager.ExposeData. DebugOutputFor's own Scribe_Deep then logs it.
T.ExpectErrors("Exception while saving Verse.ZoneManager", 1);
List<Zone> after;
List<Zone> afterContents;
tz.fault = StoreTestZone.Fault.BreakListOnSave;
try
{
Scribe.saver.DebugOutputFor(map.zoneManager);
}
finally
{
tz.fault = StoreTestZone.Fault.None;
after = ZoneStore.AllZonesRef(map.zoneManager);
afterContents = after.ToList();
Repair(map, before, tz);
}
StopScribe();
T.Check(tz.brokeList, "setup: the test zone never wrote into the list being saved");
T.Check(ReferenceEquals(before, after), "AllZones is a different list object after the exception");
T.Check(afterContents.SequenceEqual(snapshot), "the original list changed: the save wrote the unfiltered list");
}
[BlaxTest("store: ZoneStore has no type initializer, so a failed reflection bind can't make ZoneStore.Loading throw")]
public static void NoTypeInitializer()
{
T.Check(typeof(ZoneStore).TypeInitializer == null,
"ZoneStore has a static initializer: if a bind in it throws, every read of ZoneStore.Loading throws TypeInitializationException in the load hook");
}
[BlaxTest("store: with allZones unbound the save still leaves Blax zones out and restores the list, and the load hooks don't throw")]
public static void UnboundAllZones()
{
Map map = Fixtures.Map;
List<Zone> before = map.zoneManager.AllZones;
List<Zone> snapshot = before.ToList();
T.Check(snapshot.Any(ZoneStore.IsBlaxZone), "setup: no Blax zone on the map (did the store setup run?)");
ZonesTestHooks.AllZonesUnbound = true;
T.Check(ZoneStore.AllZonesRef == null, "setup: the hook left allZones bound");
string xml;
try
{
xml = Scribe.saver.DebugOutputFor(map.zoneManager);
}
finally
{
ZonesTestHooks.AllZonesUnbound = false;
}
StopScribe();
List<Zone> after = map.zoneManager.AllZones;
List<Zone> afterContents = after.ToList();
if (!afterContents.SequenceEqual(snapshot))
{
after.Clear();
after.AddRange(snapshot);
}
T.Check(ReferenceEquals(before, after), "AllZones is a different list object after the unbound save");
T.Check(afterContents.SequenceEqual(snapshot), "AllZones lost or reordered zones in the unbound save");
T.Check(!xml.NullOrEmpty() && xml.Contains("allZones"), "setup: the debug save wrote no zone list");
T.Check(!xml.Contains("BlaxZones."), "the unbound save wrote a Blax zone into the zoneManager");
ZonesTestHooks.AllZonesUnbound = true;
bool wasLoading = ZoneStore.Loading;
Patch_Map_FinalizeLoading.Prefix(map, out bool state);
T.Check(ZoneStore.Loading, "the FinalizeLoading prefix didn't set ZoneStore.Loading");
T.Equal(wasLoading, state, "the prefix's saved load flag");
var vanillaError = new InvalidOperationException("vanilla's own exception");
T.Check(ReferenceEquals(Patch_Map_FinalizeLoading.Finalizer(state, vanillaError), vanillaError), "the finalizer swallowed or replaced vanilla's exception");
T.Equal(wasLoading, ZoneStore.Loading, "ZoneStore.Loading after the finalizer");
}
[BlaxTest("store: RegisterLoadedZones registers loaded zones with their cells, skips nulls and taken cells, and leaves the rest out after an exception")]
public static void RegisterLoadedZones()
{
Map map = Fixtures.Map;
FieldInfo field = AccessTools.Field(typeof(MapComponent_BlaxZones), "loadedZones");
T.NotNull(field, "MapComponent_BlaxZones.loadedZones");
CellRect area = Fixtures.TestArea(5, 1);
IntVec3 Cell(int i) => new IntVec3(area.minX + i, 0, area.minZ);
Zone_Delivery g = LoadedDelivery(map, Cell(0));
Zone_Delivery k = LoadedDelivery(map, Cell(0), Cell(1)); // Cell(0) is g's by then
var tz = new StoreTestZone(map.zoneManager);
tz.cells.Add(Cell(2));
tz.zoneManager = null;
tz.fault = StoreTestZone.Fault.ThrowOnRegister;
Zone_Delivery left = LoadedDelivery(map, Cell(4));
foreach (Zone z in new Zone[] { g, k, tz, left })
Fixtures.TrackZone(z);
var fresh = new MapComponent_BlaxZones(map);
field.SetValue(fresh, new List<Zone> { g, null, k, tz, left });
T.Equal(5, fresh.LoadedZones.Count, "loaded zones before registering");
T.ExpectErrors("Registering loaded zones failed", 1);
try
{
fresh.RegisterLoadedZones();
}
finally
{
tz.fault = StoreTestZone.Fault.None;
}
ZoneManager zm = map.zoneManager;
T.Equal(0, fresh.LoadedZones.Count, "loaded zones after registering");
T.Check(zm.AllZones.Contains(g) && g.zoneManager == zm, "zone g is not registered with its manager");
T.Check(zm.ZoneAt(Cell(0)) == g, "ZoneAt(cell 0) is not zone g");
T.Check(zm.AllZones.Contains(k), "zone k is not registered");
T.Equal(Cells(new[] { Cell(1) }), Cells(k.cells), "zone k cells (cell 0 was taken)");
T.Check(zm.ZoneAt(Cell(1)) == k, "ZoneAt(cell 1) is not zone k");
T.Check(!zm.AllZones.Contains(tz), "the zone that threw while registering stayed registered");
T.Check(zm.ZoneAt(Cell(2)) == null, "the zone that threw left a grid cell");
T.Check(!zm.AllZones.Contains(left) && left.zoneManager == null, "a zone after the exception was registered");
T.Check(zm.ZoneAt(Cell(4)) == null, "a zone after the exception got a grid cell");
T.Check(!ZoneStore.IsBlaxZone(tz), "IsBlaxZone(test zone from another assembly)");
}
[BlaxTest("store: a fresh component (mod added mid-save) starts with no loaded zones and registers nothing")]
public static void FreshComponent()
{
Map map = Fixtures.Map;
var fresh = new MapComponent_BlaxZones(map);
T.Equal(0, fresh.LoadedZones.Count, "loaded zones of a fresh component");
int before = map.zoneManager.AllZones.Count;
fresh.RegisterLoadedZones();
T.Equal(before, map.zoneManager.AllZones.Count, "zones after a fresh component registered its loaded zones");
T.Equal(1, map.components.Count(x => x is MapComponent_BlaxZones), "MapComponent_BlaxZones on the map");
T.Check(MapComponent_BlaxZones.Of(map) != fresh, "the stray component became the map's");
}
// ---- phase 2 -----------------------------------------------------------------------------
[BlaxTest("store: the phase-1 save holds Blax zones only under MapComponent_BlaxZones", phase: 2)]
public static void SaveFileLayout()
{
CheckSaveLayout(GenFilePaths.FilePathForSavedGame(TestRunner.SaveName), TestRunner.SaveName + ".rws");
}
[BlaxTest("store: both delivery zones come back with ID, label, cells, filter, priority and sources", phase: 2)]
public static void ZonesAfterReload()
{
foreach (string key in new[] { "A", "B" })
{
Zone_Delivery z = NeedDelivery(key);
string what = "zone " + key + " (ID " + z.ID + ")";
ZoneManager zm = z.Map.zoneManager;
T.Check(zm.AllZones.Contains(z), what + " is not in AllZones");
T.Check(z.zoneManager == zm, what + " has no zoneManager link");
T.Equal(T.Carry["store." + key + ".label"], z.label, what + " label");
T.Equal(T.Carry["store." + key + ".cells"], Cells(z.cells), what + " cells");
T.Equal(T.Carry["store." + key + ".filter"], FilterText(z), what + " filter");
T.Equal(T.Carry["store." + key + ".priority"], z.priority.ToString(), what + " priority");
T.Equal(T.Carry["store." + key + ".sources"], SourcesText(z), what + " sources");
foreach (IntVec3 c in z.cells)
T.Check(zm.ZoneAt(c) == z, "ZoneAt(" + c + ") is not " + what);
}
Zone_Delivery a = NeedDelivery("A"), b = NeedDelivery("B");
T.Check(FilterText(a) != FilterText(b) && a.priority != b.priority, "setup: zones A and B saved the same filter or priority");
IntVec3 wallCell = ParseCells(T.Carry["store.A.wallCell"])[0];
T.Check(a.Map.zoneManager.ZoneAt(wallCell) == null, "the cell walled before the save is in a zone");
T.Check(wallCell.GetEdifice(a.Map) != null, "the wall on zone A's corner is gone");
foreach (Map m in Find.Maps)
T.Equal(0, MapComponent_BlaxZones.Of(m)?.LoadedZones.Count ?? -1, "loaded zones still held on map " + m.Index);
T.Check(!ZoneStore.Loading, "ZoneStore.Loading is still set after the load");
}
[BlaxTest("store: the deleted and walled-over zones stay gone", phase: 2)]
public static void RemovedZonesStayGone()
{
Map map = Fixtures.Map;
foreach (string key in new[] { "C", "D" })
{
T.Check(Fixtures.FindZoneById(IdOf(key)) == null, "zone " + key + " (ID " + IdOf(key) + ") came back");
foreach (IntVec3 c in ParseCells(T.Carry["store." + key + ".cells"]))
T.Check(map.zoneManager.ZoneAt(c) == null, "ZoneAt(" + c + ") of removed zone " + key + " is " + map.zoneManager.ZoneAt(c));
}
int max = new[] { "A", "B", "C", "D", "E", "S" }.Select(IdOf).Max();
int next = Find.UniqueIDsManager.GetNextZoneID();
T.Check(next > max, "next zone ID " + next + " reuses a saved or removed zone ID (max " + max + ")");
}
[BlaxTest("store: a saved zone cell under a wall is trimmed by vanilla's spawn loop on load", phase: 2)]
public static void WalledCellTrimmedOnLoad()
{
IntVec3 keep = ParseCells(T.Carry["store.E.keep"])[0];
IntVec3 walled = ParseCells(T.Carry["store.E.walled"])[0];
T.Equal(Cells(new[] { keep, walled }), T.Carry["store.E.cells"], "setup: zone E's cells at save time");
Zone_Delivery e = NeedDelivery("E");
ZoneManager zm = e.Map.zoneManager;
T.Equal(Cells(new[] { keep }), Cells(e.cells), "zone E cells after the load");
T.Check(zm.ZoneAt(keep) == e, "ZoneAt(E's open cell) is not E");
T.Check(zm.ZoneAt(walled) == null, "the walled cell is still in a zone");
T.Check(walled.GetEdifice(e.Map) != null, "the wall on zone E's saved cell did not spawn");
}
// ---- phase 3 -----------------------------------------------------------------------------
[BlaxTest("store: after removal the save loads, the stockpile is intact and no Blax zones exist", phase: 3)]
public static void RemovedModLoad()
{
int maps = TestRunner.Phase3ReplacedCount;
T.Check(maps >= 1, "phase 3 replaced no component node");
T.ExpectErrors("Could not find class " + TestRunner.RemovedComponentClass, maps);
T.ExpectErrors("Can't load abstract class Verse.MapComponent", maps);
List<string> loadErrors = T.Phase3LoadErrors;
List<string> nre = loadErrors.Where(x => x.Contains("NullReferenceException")).ToList();
T.Check(nre.Count == 0, "NullReferenceException while loading: " + string.Join(" | ", nre.Take(2)));
List<string> mapLoad = loadErrors.Where(x => x.Contains("Error in Map.FinalizeLoading")).ToList();
T.Check(mapLoad.Count == 0, "Map.FinalizeLoading failed: " + string.Join(" | ", mapLoad.Take(2)));
T.Check(Current.ProgramState == ProgramState.Playing && Find.CurrentMap != null, "the game is not running a map after the load");
foreach (Map m in Find.Maps)
{
T.NotNull(m.zoneManager, "zoneManager of map " + m.Index);
List<Zone> blax = m.zoneManager.AllZones.Where(ZoneStore.IsBlaxZone).ToList();
T.Check(blax.Count == 0, "Blax zones on map " + m.Index + ": " + string.Join(", ", blax.Select(z => z.label)));
MapComponent_BlaxZones comp = MapComponent_BlaxZones.Of(m);
T.NotNull(comp, "fresh MapComponent_BlaxZones on map " + m.Index);
T.Equal(0, comp.LoadedZones.Count, "loaded zones of the fresh component on map " + m.Index);
}
Map map = Fixtures.Map;
foreach (string key in new[] { "A", "B", "E" })
{
T.Check(Fixtures.FindZoneById(IdOf(key)) == null, "zone " + key + " exists after removal");
}
foreach (string key in new[] { "A", "B" })
{
foreach (IntVec3 c in ParseCells(T.Carry["store." + key + ".cells"]))
T.Check(map.zoneManager.ZoneAt(c) == null, "ZoneAt(" + c + ") of removed zone " + key + " is " + map.zoneManager.ZoneAt(c));
}
Zone s = Fixtures.FindZoneById(IdOf("S"));
T.Check(s is Zone_Stockpile, "the kept stockpile (ID " + IdOf("S") + ") is gone or not a stockpile: " + s);
T.Equal(T.Carry["store.S.label"], s.label, "stockpile label");
T.Equal(T.Carry["store.S.cells"], Cells(s.cells), "stockpile cells");
foreach (IntVec3 c in s.cells)
T.Check(s.Map.zoneManager.ZoneAt(c) == s, "ZoneAt(" + c + ") is not the kept stockpile");
}
// ---- helpers -----------------------------------------------------------------------------
private static int IdOf(string key)
{
T.Check(T.Carry.TryGetValue("store." + key + ".id", out string id), "phase 1 value store." + key + ".id missing (did the store setup run?)");
return int.Parse(id);
}
private static Zone_Delivery DeliveryByKey(string key) =>
T.Carry.TryGetValue("store." + key + ".id", out string id) ? Fixtures.FindZoneById(int.Parse(id)) as Zone_Delivery : null;
private static Zone_Delivery NeedDelivery(string key)
{
int id = IdOf(key);
Zone_Delivery z = Fixtures.FindZoneById(id) as Zone_Delivery;
T.NotNull(z, "delivery zone " + key + " (ID " + id + ")");
return z;
}
/// <summary>A delivery zone in the state the loader leaves it: cells set, no manager, not registered.</summary>
private static Zone_Delivery LoadedDelivery(Map map, params IntVec3[] cells)
{
var z = new Zone_Delivery(map.zoneManager);
z.cells.AddRange(cells);
z.zoneManager = null;
return z;
}
/// <summary>A registered test zone with no cells, deleted after the test.</summary>
private static StoreTestZone NewTestZone(Map map)
{
var tz = new StoreTestZone(map.zoneManager);
map.zoneManager.RegisterZone(tz);
return Fixtures.TrackZone(tz);
}
/// <summary>
/// Keeps the rest of the run sane if the finalizer failed: puts the original list back and drops
/// extra copies of the test zone. Callers read the list state before calling this.
/// </summary>
private static void Repair(Map map, List<Zone> original, StoreTestZone tz)
{
if (!ReferenceEquals(ZoneStore.AllZonesRef(map.zoneManager), original))
{
T.Info("AllZones was not restored; put the original list back so later tests run");
ZoneStore.AllZonesRef(map.zoneManager) = original;
}
while (original.Count(z => z == tz) > 1)
original.Remove(tz);
}
/// <summary>A Scribe left mid-save would break the runner's save and reload after phase 1.</summary>
private static void StopScribe()
{
if (Scribe.mode == LoadSaveMode.Inactive)
return;
T.Info("Scribe was left in mode " + Scribe.mode + "; forced stop");
Scribe.ForceStop();
T.Fail("Scribe was left active after saving");
}
private static void DeleteSave(string path)
{
foreach (string p in new[] { path, path + ".old", path + ".new" })
{
try
{
if (File.Exists(p))
File.Delete(p);
}
catch (Exception e)
{
TestRunner.Note("could not delete " + p + ": " + e.Message);
}
}
}
/// <summary>
/// Parses a save: no "BlaxZones." inside any map's zoneManager or things, zones A, B and E sit under
/// the MapComponent_BlaxZones node (E with its walled cell), and neither zone C nor D is anywhere.
/// </summary>
private static void CheckSaveLayout(string path, string what)
{
T.Check(File.Exists(path), what + ": no file at " + path);
var doc = new XmlDocument();
doc.Load(path);
XmlNodeList maps = doc.SelectNodes("/savegame/game/maps/li");
T.Check(maps != null && maps.Count > 0, what + ": no map nodes under savegame/game/maps");
var inComponent = new Dictionary<int, (string cls, int cells)>();
var inManager = new HashSet<int>();
foreach (XmlNode m in maps)
{
XmlNode zm = m["zoneManager"];
T.NotNull(zm, what + ": <zoneManager> of a map");
T.Check(!zm.OuterXml.Contains("BlaxZones."), what + ": \"BlaxZones.\" inside <zoneManager>");
XmlNode things = m["things"];
T.Check(things == null || !things.OuterXml.Contains("BlaxZones."), what + ": \"BlaxZones.\" inside <things>");
foreach (XmlNode id in zm.SelectNodes("allZones/li/ID"))
{
if (int.TryParse(id.InnerText, out int n))
inManager.Add(n);
}
XmlNode comp = m.SelectSingleNode("components/li[@Class='BlaxZones.MapComponent_BlaxZones']");
T.NotNull(comp, what + ": MapComponent_BlaxZones node of a map");
foreach (XmlNode z in comp.SelectNodes("zones/li"))
{
XmlNode id = z["ID"];
if (id != null && int.TryParse(id.InnerText, out int n))
inComponent[n] = (z.Attributes?["Class"]?.Value, z.SelectNodes("cells/li").Count);
}
}
foreach (string key in new[] { "A", "B", "E" })
{
int id = IdOf(key);
T.Check(inComponent.TryGetValue(id, out var saved), what + ": zone " + key + " (ID " + id + ") is not under MapComponent_BlaxZones");
T.Equal(DeliveryClass, saved.cls, what + ": class of zone " + key);
T.Check(!inManager.Contains(id), what + ": zone " + key + " is under <zoneManager>");
}
T.Equal(2, inComponent[IdOf("E")].cells, what + ": saved cells of zone E (one under a wall)");
foreach (string key in new[] { "C", "D" })
{
int id = IdOf(key);
T.Check(!inComponent.ContainsKey(id) && !inManager.Contains(id), what + ": removed zone " + key + " (ID " + id + ") was saved");
}
T.Check(inManager.Contains(IdOf("S")), what + ": the kept stockpile is not under <zoneManager>");
}
private static string Cells(IEnumerable<IntVec3> cells) =>
string.Join(";", cells.OrderBy(c => c.x).ThenBy(c => c.z).Select(c => c.x + "," + c.z));
private static List<IntVec3> ParseCells(string text)
{
var list = new List<IntVec3>();
if (text.NullOrEmpty())
return list;
foreach (string part in text.Split(';'))
{
string[] xz = part.Split(',');
list.Add(new IntVec3(int.Parse(xz[0]), 0, int.Parse(xz[1])));
}
return list;
}
private static string FilterText(Zone_Delivery z) =>
z.filter == null ? "null" : string.Join(",", z.filter.AllowedThingDefs.Select(d => d.defName).OrderBy(n => n, StringComparer.Ordinal));
private static string SourcesText(Zone_Delivery z) => "orbital=" + z.acceptOrbital + ",camp=" + z.campHere;
}
/// <summary>
/// A test-only zone from this assembly, so ZoneStore treats it as vanilla and it stays in the list
/// ZoneManager writes. Each instance can fail on purpose in one place.
/// </summary>
public class StoreTestZone : Zone
{
public enum Fault
{
None,
/// <summary>ExposeData throws while saving; Scribe_Deep catches it per zone.</summary>
ThrowOnSave,
/// <summary>ExposeData adds this zone to the list being saved once, so the save's enumerator throws.</summary>
BreakListOnSave,
/// <summary>PostRegister throws, as a zone whose registration fails halfway.</summary>
ThrowOnRegister,
}
public const string SaveMessage = "store test zone threw while saving on purpose";
public const string RegisterMessage = "store test zone threw while registering on purpose";
public Fault fault;
public bool brokeList;
public StoreTestZone()
{
}
public StoreTestZone(ZoneManager zoneManager) : base("Store test zone", zoneManager)
{
}
protected override Color NextZoneColor => new Color(0.5f, 0.5f, 0.5f, 0.09f);
public override void ExposeData()
{
if (Scribe.mode == LoadSaveMode.Saving)
{
if (fault == Fault.ThrowOnSave)
throw new InvalidOperationException(SaveMessage);
if (fault == Fault.BreakListOnSave && zoneManager != null)
{
fault = Fault.None;
brokeList = true;
ZoneStore.AllZonesRef(zoneManager).Add(this);
}
}
base.ExposeData();
}
public override void PostRegister()
{
if (fault == Fault.ThrowOnRegister)
throw new InvalidOperationException(RegisterMessage);
base.PostRegister();
}
}
}

View File

@ -0,0 +1,364 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxZones;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxZonesTests
{
/// <summary>
/// Package Tab. Design: 1.0 "Delivery zone" > Tests (default filter, filter/priority/orbital/camp persist in phase 2, copy/paste).
/// Tests: [BlaxTest("tab: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped.
/// FillTab needs the GUI, so these test what it draws from: the dropdown entries, the tooltips, the hidden defs.
/// </summary>
public static class TabTests
{
private const string PersistKey = "tab.persistZone";
private static readonly string[] TabKeys =
{
"BlaxZones_TabDelivery", "BlaxZones_PriorityTip",
"BlaxZones_AcceptOrbital", "BlaxZones_AcceptOrbitalTip", "BlaxZones_AcceptOrbitalSlavesTip", "BlaxZones_AcceptOrbitalOffTip",
"BlaxZones_AcceptOrbitalOffSlavesTip", "BlaxZones_CampHere", "BlaxZones_CampHereTip", "BlaxZones_CampHereOffTip", "BlaxZones_CampHereStandDownTip",
"BlaxZones_CopySettings", "BlaxZones_CopySettingsDesc", "BlaxZones_PasteSettings", "BlaxZones_PasteSettingsDesc",
"BlaxZones_SettingsCopied", "BlaxZones_SettingsPasted", "BlaxZones_NothingCopied",
};
// ---- default filter ----------------------------------------------------------------
[BlaxTest("tab: the default filter allows silver, medicine and steel and hides every corpse")]
public static void DefaultFilterAllowsGoods()
{
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
foreach (ThingDef def in new[] { ThingDefOf.Silver, ThingDefOf.MedicineHerbal, ThingDefOf.MedicineIndustrial, ThingDefOf.Steel })
{
T.Check(zone.filter.Allows(def), "default filter refuses " + def.defName);
T.Check(zone.Accepts(Fixtures.Stack(def, 10)), "zone refuses a stack of " + def.defName);
}
List<ThingDef> hidden = ITab_Delivery.HiddenDefs();
int corpses = 0;
foreach (ThingDef corpse in ThingCategoryDefOf.Corpses.DescendantThingDefs)
{
corpses++;
T.Check(!zone.filter.Allows(corpse), "default filter allows " + corpse.defName);
T.Check(!DeliveryFilters.Parent.Allows(corpse), "parent filter allows " + corpse.defName);
T.Check(hidden.Contains(corpse), "tab doesn't hide " + corpse.defName);
}
T.Check(corpses > 0, "no corpse defs found under ThingCategoryDefOf.Corpses");
}
[BlaxTest("tab: the default filter refuses Wastepack, also after Allow all and a category checkbox")]
public static void DefaultFilterRefusesWastepack()
{
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
ThingDef wastepack = ThingDefOf.Wastepack;
T.NotNull(wastepack, "ThingDefOf.Wastepack with Biotech");
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
T.Check(!zone.filter.Allows(wastepack), "default filter allows Wastepack");
T.Check(!DeliveryFilters.Parent.Allows(wastepack), "parent filter allows Wastepack");
T.Check(!zone.Accepts(Fixtures.Stack(wastepack, 1)), "zone accepts a Wastepack");
T.Check(ITab_Delivery.HiddenDefs().Contains(wastepack), "tab doesn't hide Wastepack");
// What the tab's buttons do: "Allow all" (SetAllowAll(parent)) and a category checkbox
// (SetAllow(category, true, forceHiddenDefs)), ThingFilterUI.cs and Listing_TreeThingFilter.cs:177.
zone.filter.SetDisallowAll(ITab_Delivery.HiddenDefs());
zone.filter.SetAllowAll(DeliveryFilters.Parent);
T.Check(!zone.filter.Allows(wastepack), "Allow all let Wastepack in");
foreach (ThingCategoryDef cat in wastepack.thingCategories ?? new List<ThingCategoryDef>())
{
zone.filter.SetAllow(cat, true, ITab_Delivery.HiddenDefs());
T.Check(!zone.filter.Allows(wastepack), "ticking category " + cat.defName + " let Wastepack in");
}
T.Check(!zone.Accepts(Fixtures.Stack(wastepack, 1)), "zone accepts a Wastepack after the filter buttons");
}
[BlaxTest("tab: without Biotech a delivery zone, its filter, tab and gizmos build with no error")]
public static void BuildsWithoutBiotech()
{
if (ModsConfig.BiotechActive)
T.Skip("runs without Biotech only");
T.Check(ThingDefOf.Wastepack == null, "ThingDefOf.Wastepack is set without Biotech");
var errors = new List<string>();
Application.LogCallback hook = (text, stack, type) =>
{
if (type == LogType.Error || type == LogType.Exception)
lock (errors) errors.Add(text);
};
Application.logMessageReceivedThreaded += hook;
try
{
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
T.Check(zone.filter.Allows(ThingDefOf.Steel), "default filter refuses steel");
T.Check(zone.Accepts(Fixtures.Stack(ThingDefOf.Steel, 10)), "zone refuses steel");
T.Check(ITab_Delivery.HiddenDefs().All(d => d != null), "hidden defs hold a null");
T.Check(zone.GetInspectTabs().Single() is ITab_Delivery, "tab is not ITab_Delivery");
T.Check(zone.GetGizmos().Count() >= 2, "gizmos missing");
T.Check(!ITab_Delivery.OrbitalTip().NullOrEmpty(), "orbital tooltip empty");
T.Check(!ITab_Delivery.CampTip().NullOrEmpty(), "camp tooltip empty");
DeliveryClipboard.Copy(zone);
DeliveryClipboard.PasteInto(zone);
}
finally
{
Application.logMessageReceivedThreaded -= hook;
}
T.Check(errors.Count == 0, "errors while building: " + string.Join(" | ", errors.Take(3)));
}
// ---- persistence (needs package Store; green at integration) -------------------------
[BlaxTest("tab: filter, priority, orbital and camp flags set up for the reload")]
public static void PersistSetup()
{
Zone_Delivery zone = Fixtures.KeepZone(Fixtures.DeliveryZone(Fixtures.TestArea(3, 2),
Fixtures.FilterOf(ThingDefOf.MedicineIndustrial, ThingDefOf.Silver), StoragePriority.Critical, orbital: false, camp: false));
T.Carry[PersistKey + ".defs"] = zone.filter.AllowedDefCount.ToString();
// "Caravans camp here" goes on only right before the save, so no later phase-1 camp test meets
// a stray camp zone. Orbital is off, so the router never picks this zone either.
T.CarryAtSave(PersistKey, () =>
{
zone.campHere = true;
return zone.ID.ToString();
});
}
[BlaxTest("tab: filter, priority, orbital and camp flags persist", phase: 2)]
public static void PersistCheck()
{
int zoneId = -1;
if (!T.Carry.TryGetValue(PersistKey, out string id) || !int.TryParse(id, out zoneId))
T.Fail("phase 1 carried no zone ID");
var zone = Fixtures.FindZoneById(zoneId) as Zone_Delivery;
T.NotNull(zone, "delivery zone " + zoneId + " after the reload");
Fixtures.OnCleanup(() => zone.campHere = false); // no stray camp zone for later phase-2 tests
T.Equal(6, zone.CellCount, "cells");
T.Equal(StoragePriority.Critical, zone.priority, "priority");
T.Equal(false, zone.acceptOrbital, "orbital checkbox");
T.Equal(true, zone.campHere, "camp checkbox");
T.NotNull(zone.filter, "filter");
if (T.Carry.TryGetValue(PersistKey + ".defs", out string defs))
T.Equal(defs, zone.filter.AllowedDefCount.ToString(), "allowed defs");
T.Check(zone.filter.Allows(ThingDefOf.MedicineIndustrial), "filter lost industrial medicine");
T.Check(zone.filter.Allows(ThingDefOf.Silver), "filter lost silver");
T.Check(!zone.filter.Allows(ThingDefOf.Steel), "filter allows steel");
}
// ---- copy and paste --------------------------------------------------------------------
[BlaxTest("tab: copy then paste moves filter, priority, orbital and camp to another zone, never its cells")]
public static void CopyPaste()
{
Map map = Fixtures.Map;
CellRect ra = Fixtures.TestArea(3, 2);
CellRect rb = Fixtures.TestArea(2, 2);
Zone_Delivery a = Fixtures.DeliveryZone(ra, Fixtures.FilterOf(ThingDefOf.MedicineIndustrial), StoragePriority.Important, orbital: false, camp: true);
Zone_Delivery b = Fixtures.DeliveryZone(rb);
List<IntVec3> bCells = b.Cells.ToList();
string bLabel = b.label;
int bId = b.ID;
int copiedDefs = a.filter.AllowedDefCount;
DeliveryClipboard.Copy(a);
T.Check(DeliveryClipboard.HasCopy, "HasCopy after Copy");
// Change the source after copying: the clipboard must hold a detached copy.
a.filter.SetAllow(ThingDefOf.Steel, true);
a.priority = StoragePriority.Low;
a.acceptOrbital = true;
a.campHere = false;
DeliveryClipboard.PasteInto(b);
T.Equal(StoragePriority.Important, b.priority, "pasted priority");
T.Equal(false, b.acceptOrbital, "pasted orbital checkbox");
T.Equal(true, b.campHere, "pasted camp checkbox");
T.Check(b.filter.Allows(ThingDefOf.MedicineIndustrial), "pasted filter refuses industrial medicine");
T.Check(!b.filter.Allows(ThingDefOf.Steel), "pasted filter allows steel, changed on the source after the copy");
T.Equal(copiedDefs, b.filter.AllowedDefCount, "pasted filter's allowed defs");
T.Check(!ReferenceEquals(a.filter, b.filter), "paste shared the source's filter object");
T.Equal(bCells.Count, b.CellCount, "target cells after paste");
T.Check(bCells.All(b.ContainsCell), "target lost a cell");
T.Check(bCells.All(c => map.zoneManager.ZoneAt(c) == b), "a target cell left the target zone");
T.Check(ra.Cells.All(c => map.zoneManager.ZoneAt(c) == a), "a source cell left the source zone");
T.Equal(6, a.CellCount, "source cells after paste");
T.Equal(bLabel, b.label, "target label");
T.Equal(bId, b.ID, "target ID");
T.Check(!b.Cells.Any(ra.Contains), "paste moved source cells");
foreach (FieldInfo f in typeof(DeliveryClipboard).GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
T.Check(!typeof(Zone).IsAssignableFrom(f.FieldType), "DeliveryClipboard." + f.Name + " is typed " + f.FieldType.Name);
AssertNoZone(f.GetValue(null), "DeliveryClipboard." + f.Name, depth: 2);
}
}
/// <summary>Fails if the value is a Zone, holds one in a collection or a delegate target, or in its own fields, down to <paramref name="depth"/> levels.</summary>
private static void AssertNoZone(object value, string where, int depth)
{
if (value == null)
return;
T.Check(!(value is Zone), where + " holds a Zone");
if (value is Delegate d)
{
foreach (Delegate inv in d.GetInvocationList())
T.Check(!(inv.Target is Zone), where + " is a delegate bound to a Zone");
if (depth > 0)
foreach (Delegate inv in d.GetInvocationList())
AssertNoZone(inv.Target, where + ".Target", depth - 1);
return;
}
Type type = value.GetType();
if (type.IsPrimitive || type.IsEnum || value is string || value is Def || value is UnityEngine.Object)
return;
if (value is IEnumerable list)
{
foreach (object item in list)
{
T.Check(!(item is Zone), where + " lists a Zone");
if (depth > 0)
AssertNoZone(item, where + "[]", depth - 1);
}
return;
}
if (depth <= 0)
return;
for (Type t = type; t != null && t != typeof(object); t = t.BaseType)
{
foreach (FieldInfo f in t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly))
AssertNoZone(f.GetValue(value), where + "." + f.Name, depth - 1);
}
}
// ---- tab and gizmos --------------------------------------------------------------------
[BlaxTest("tab: GetInspectTabs returns the shared ITab_Delivery, which shows the selected zone")]
public static void InspectTab()
{
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
List<InspectTabBase> tabs = zone.GetInspectTabs()?.ToList();
T.NotNull(tabs, "GetInspectTabs()");
T.Equal(1, tabs.Count, "tab count");
var tab = tabs[0] as ITab_Delivery;
T.NotNull(tab, "the tab as ITab_Delivery (got " + tabs[0]?.GetType().Name + ")");
T.Check(ReferenceEquals(tab, InspectTabManager.GetSharedInstance(typeof(ITab_Delivery))), "tab is not the shared instance");
T.Equal("BlaxZones_TabDelivery", tab.labelKey, "labelKey");
Find.Selector.ClearSelection();
Find.Selector.Select(zone, playSound: false, forceDesignatorDeselect: false);
T.Check(tab.SelZone == zone, "SelZone is not the selected zone");
T.Check(tab.IsVisible, "tab hidden while a delivery zone is selected");
Find.Selector.ClearSelection();
T.Check(tab.SelZone == null, "SelZone set with nothing selected");
}
[BlaxTest("tab: GetGizmos holds the base zone gizmos plus copy and paste")]
public static void Gizmos()
{
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
List<Gizmo> gizmos = zone.GetGizmos().ToList();
string deleteLabel = "CommandDeleteZoneLabel".Translate();
T.Check(gizmos.OfType<Command_Action>().Any(c => c.defaultLabel == deleteLabel), "base delete command missing");
Command_Action copy = FindCommand(gizmos, "BlaxZones_CopySettings");
Command_Action paste = FindCommand(gizmos, "BlaxZones_PasteSettings");
T.NotNull(copy, "copy command");
T.NotNull(paste, "paste command");
T.NotNull(copy.action, "copy action");
T.NotNull(paste.action, "paste action");
T.Check(gizmos.IndexOf(copy) < gizmos.IndexOf(paste), "paste comes before copy");
T.Equal(!DeliveryClipboard.HasCopy, paste.Disabled, "paste disabled exactly while nothing is copied");
DeliveryClipboard.Copy(zone);
Command_Action pasteAfter = FindCommand(zone.GetGizmos().ToList(), "BlaxZones_PasteSettings");
T.NotNull(pasteAfter, "paste command after a copy");
T.Check(!pasteAfter.Disabled, "paste disabled after a copy");
}
private static Command_Action FindCommand(List<Gizmo> gizmos, string labelKey)
{
string label = labelKey.Translate();
return gizmos.OfType<Command_Action>().FirstOrDefault(c => c.defaultLabel == label);
}
[BlaxTest("tab: the priority dropdown lists Low to Critical and sets the zone's priority")]
public static void PriorityDropdown()
{
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2));
StoragePriority[] expected =
{
StoragePriority.Low, StoragePriority.Normal, StoragePriority.Preferred, StoragePriority.Important, StoragePriority.Critical,
};
T.Check(ITab_Delivery.Priorities().SequenceEqual(expected), "priorities: " + string.Join(", ", ITab_Delivery.Priorities()));
List<FloatMenuOption> options = ITab_Delivery.PriorityMenuOptions(zone);
T.Equal(expected.Length, options.Count, "dropdown entries");
for (int i = 0; i < expected.Length; i++)
{
T.Equal(expected[i].Label().CapitalizeFirst(), options[i].Label, "entry " + i);
options[i].action();
T.Equal(expected[i], zone.priority, "priority after picking entry " + i);
}
T.Check(ITab_Delivery.PriorityButtonLabel(StoragePriority.Important).Contains(StoragePriority.Important.Label().CapitalizeFirst()),
"button label doesn't name the priority");
}
// ---- strings and tooltips --------------------------------------------------------------
[BlaxTest("tab: the tab label, tooltip and gizmo keys translate")]
public static void KeysTranslate()
{
var missing = TabKeys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
T.Check("Priority".CanTranslate(), "vanilla key Priority missing");
T.Equal("BlaxZones_TabDelivery", new ITab_Delivery().labelKey, "labelKey of a new tab");
}
[BlaxTest("tab: the orbital tooltip adds the Blax Slaves line only while Slaves is active")]
public static void SlavesTooltip()
{
string slavesLine = "BlaxZones_AcceptOrbitalSlavesTip".Translate();
Fixtures.OnCleanup(() => Compat.SimulatedActive.Remove(Compat.BlaxSlaves));
bool slavesReallyActive = ModLister.GetActiveModWithIdentifier(Compat.BlaxSlaves, ignorePostfix: true) != null;
if (slavesReallyActive)
T.Info("Blax Slaves is loaded in this run; the tooltip-without-Slaves check is skipped");
else
T.Check(!ITab_Delivery.OrbitalTip().Contains(slavesLine), "Slaves line shown without Blax Slaves");
Compat.SimulatedActive.Add(Compat.BlaxSlaves);
T.Check(ITab_Delivery.OrbitalTip().Contains(slavesLine), "Slaves line missing while Blax Slaves is active");
}
[BlaxTest("tab: the orbital and camp tooltips say when the mod settings turn them off")]
public static void SettingsOffTooltips()
{
BlaxZonesSettings s = Fixtures.Settings;
// With Blax Slaves loaded in this run the off note names its payouts (tested below).
string orbitalOff = (Compat.SlavesActive ? "BlaxZones_AcceptOrbitalOffSlavesTip" : "BlaxZones_AcceptOrbitalOffTip").Translate();
string campOff = "BlaxZones_CampHereOffTip".Translate();
s.routeOrbital = true;
s.campAtZones = true;
T.Check(!ITab_Delivery.OrbitalTip().Contains(orbitalOff), "orbital off note while routing is on");
T.Check(!ITab_Delivery.CampTip().Contains(campOff), "camp off note while camping is on");
s.routeOrbital = false;
s.campAtZones = false;
T.Check(ITab_Delivery.OrbitalTip().Contains(orbitalOff), "orbital off note missing while routing is off");
T.Check(ITab_Delivery.CampTip().Contains(campOff), "camp off note missing while camping is off");
}
[BlaxTest("tab: with Blax Slaves active and orbital routing off, the tooltip says Slaves payouts still land")]
public static void SlavesOffTooltip()
{
string plainOff = "BlaxZones_AcceptOrbitalOffTip".Translate();
string slavesOff = "BlaxZones_AcceptOrbitalOffSlavesTip".Translate();
Fixtures.OnCleanup(() => Compat.SimulatedActive.Remove(Compat.BlaxSlaves));
Compat.SimulatedActive.Add(Compat.BlaxSlaves);
Fixtures.Settings.routeOrbital = false;
string tip = ITab_Delivery.OrbitalTip();
T.Check(tip.Contains(slavesOff), "the off note doesn't say Blax Slaves payouts still land");
T.Check(!tip.Contains(plainOff), "the tooltip says nothing lands here, though Blax Slaves payouts still do");
Fixtures.Settings.routeOrbital = true;
T.Check(!ITab_Delivery.OrbitalTip().Contains(slavesOff), "orbital off note while routing is on");
}
}
}

228
Tests/run-tests.ps1 Normal file
View File

@ -0,0 +1,228 @@
<#
Runs the in-game test suite. RimWorld 1.7 starts headless (no window, no focus change) with its
own save data folder, so your mod list, saves and settings stay untouched. Needs Steam running and
the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures, 2 the run didn't finish.
.\Tests\run-tests.ps1 Harmony, the installed DLCs, Blax Zones
.\Tests\run-tests.ps1 -Compat also Blax Castes, Blax Slaves and the installed mods Zones is tested next to:
Hospitality, Pick Up And Haul, Haul to Stack, RimFridge, Weapon Racks, Prison Labor,
Prisoner Realism, Replace Stuff, VEF with VFE Core and VFE Medical, Dubs Skylights,
Vanilla Events Expanded, and Blax Defaults once it is installed
.\Tests\run-tests.ps1 -NoDlc core only, no DLC (tests that need a DLC skip with "needs <DLC>")
.\Tests\run-tests.ps1 -Dlc Royalty,Biotech only these installed DLCs
.\Tests\run-tests.ps1 -NoBuild skip dotnet build
.\Tests\run-tests.ps1 -AllowWhileRunning run next to an open RimWorld (the test game runs at below-normal priority)
.\Tests\run-tests.ps1 -Worktree run from a copy of the repo (a work package built in parallel): Mods\BlaxZones
points at this copy for the run and back at its old target afterwards
.\Tests\run-tests.ps1 -WaitSeconds 1800 wait up to this long for another run's lock instead of failing at once
Mods that change TradeDropSpot or AllLaunchableThingsForTrade stay out of -Compat, so they can't hide Zones' own path.
Mods\BlaxZones must be a directory junction to this repo; it is created if missing and left in place. With -Worktree
it may point at another copy: it is retargeted for the run and restored afterwards, under the lock.
While the suite runs, the test mod is linked into the game's Mods folder; that link is removed afterwards.
Only one run at a time: a lock file in the data folder holds the running script's process id. Copies that test in
parallel keep the default -DataDir, so they share that lock.
Every run starts from default mod settings: the Blax Zones, Blax Castes and Blax Slaves settings files in the data folder are deleted.
#>
param(
[string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld',
[string]$DataDir = (Join-Path $env:TEMP 'BlaxZonesTest'),
[switch]$Compat,
[switch]$NoDlc,
[string[]]$Dlc,
[switch]$NoBuild,
[switch]$AllowWhileRunning,
[switch]$Worktree,
[int]$WaitSeconds = 0,
[int]$TimeoutSeconds = 900
)
$ErrorActionPreference = 'Stop'
# A wrong path (for example a switch passed as a positional value) would put the Mods junction somewhere odd.
if (-not (Test-Path -LiteralPath (Join-Path $RimWorldDir 'Assembly-CSharp.dll'))) { throw "No RimWorld 1.7 install at '$RimWorldDir'." }
$repo = Split-Path -Parent $PSScriptRoot
$testMod = Join-Path $PSScriptRoot 'BlaxZonesTests'
$modLink = Join-Path $RimWorldDir 'Mods\BlaxZones'
$link = Join-Path $RimWorldDir 'Mods\BlaxZonesTests'
$workshop = Join-Path $RimWorldDir '..\..\workshop\content\294100'
$lockFile = Join-Path $DataDir 'run.lock'
if ((Get-Process -Name RimWorld -ErrorAction SilentlyContinue) -and -not $AllowWhileRunning) {
throw 'RimWorld is running. Close it first, or pass -AllowWhileRunning.'
}
function Get-FullPath([string]$path) { [IO.Path]::GetFullPath($path).TrimEnd('\') }
# One run at a time. A lock whose process is gone is stale and taken over; a live one is waited for up to -WaitSeconds.
New-Item -ItemType Directory -Force $DataDir | Out-Null
function Enter-Lock {
$deadline = [DateTime]::UtcNow.AddSeconds([Math]::Max(0, $WaitSeconds))
$stale = 0
$waiting = $false
while ($true) {
try {
$stream = [IO.File]::Open($lockFile, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::Read)
$bytes = [Text.Encoding]::ASCII.GetBytes([string]$PID)
$stream.Write($bytes, 0, $bytes.Length)
$stream.Close()
return
}
catch [IO.IOException] {
$owner = (Get-Content -LiteralPath $lockFile -Raw -ErrorAction SilentlyContinue)
$ownerPid = 0
if ($owner -and [int]::TryParse($owner.Trim(), [ref]$ownerPid) -and $ownerPid -ne $PID -and (Get-Process -Id $ownerPid -ErrorAction SilentlyContinue)) {
if ([DateTime]::UtcNow -ge $deadline) { throw "Another test run (process $ownerPid) is in progress. Lock: $lockFile" }
if (-not $waiting) { Write-Host "Waiting for test run $ownerPid to finish..."; $waiting = $true }
Start-Sleep -Seconds 5
continue
}
if (++$stale -gt 3) { throw "Could not take the lock $lockFile" }
Write-Warning "removing stale lock from process $owner"
Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue
}
}
}
Enter-Lock
$restoreTarget = $null
try {
# Mods\BlaxZones: a junction to this repo. Created if missing; replaced only with -Worktree, and put back afterwards.
if (Test-Path -LiteralPath $modLink) {
$item = Get-Item -LiteralPath $modLink -Force
if (-not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw "$modLink is a real folder, not a junction to $repo. Move it away and run again."
}
$target = @($item.Target)[0]
if (-not $target -or (Get-FullPath $target) -ne (Get-FullPath $repo)) {
if (-not $Worktree) { throw "$modLink points to '$target', not to $repo. Pass -Worktree to run from this copy." }
cmd /c rmdir "$modLink" | Out-Null
New-Item -ItemType Junction -Path $modLink -Target $repo | Out-Null
$restoreTarget = $target
Write-Host "Mods\BlaxZones points at $repo for this run (was $target)"
}
}
else {
New-Item -ItemType Junction -Path $modLink -Target $repo | Out-Null
Write-Host "Created junction $modLink -> $repo"
}
if (-not $NoBuild) {
foreach ($proj in (Join-Path $repo 'Source\BlaxZones\BlaxZones.csproj'), (Join-Path $testMod 'Source\BlaxZonesTests.csproj')) {
& dotnet build $proj -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir"
if ($LASTEXITCODE -ne 0) { throw "build failed: $proj" }
}
}
# packageId (lower case) -> About.xml, for every installed local and Workshop mod
$installed = @{}
foreach ($about in @(Get-ChildItem (Join-Path $RimWorldDir 'Mods\*\About\About.xml') -ErrorAction SilentlyContinue) +
@(Get-ChildItem (Join-Path $workshop '*\About\About.xml') -ErrorAction SilentlyContinue)) {
$x = [xml](Get-Content -LiteralPath $about.FullName -Raw -Encoding UTF8)
if ($x.ModMetaData.packageId) { $installed[$x.ModMetaData.packageId.Trim().ToLower()] = $x }
}
function Add-WithDependencies([string]$id, [System.Collections.ArrayList]$list) {
$id = $id.ToLower()
if ($list -contains $id -or $id -like 'ludeon.*') { return }
$x = $installed[$id]
if (-not $x) { Write-Warning "not installed, skipped: $id"; return }
foreach ($dep in @($x.ModMetaData.modDependencies.li)) { if ($dep.packageId) { Add-WithDependencies $dep.packageId $list } }
[void]$list.Add($id)
}
# Load order: Harmony, core, DLCs, the mods Zones is tested next to, Blax Castes, Blax Zones, Blax Slaves, the tests.
# Castes loads before Zones (Zones' loadAfter), Zones before Slaves (Slaves lists blax.zones).
# Every installed DLC is listed as known, so the game does not switch on a left-out DLC as "new".
$installedDlcs = @(@('Royalty', 'Ideology', 'Biotech', 'Anomaly', 'Odyssey') | Where-Object { Test-Path (Join-Path $RimWorldDir "Data\$_") })
if ($NoDlc) { $loadDlcs = @() }
elseif ($Dlc) {
$wanted = @($Dlc | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
foreach ($w in $wanted) { if ($installedDlcs -notcontains $w) { Write-Warning "DLC not installed or unknown, skipped: $w" } }
$loadDlcs = @($installedDlcs | Where-Object { $wanted -contains $_ })
}
else { $loadDlcs = @($installedDlcs) }
$mods = New-Object System.Collections.ArrayList
$expansions = @($installedDlcs | ForEach-Object { 'ludeon.rimworld.' + $_.ToLower() })
[void]$mods.Add('brrainz.harmony')
[void]$mods.Add('ludeon.rimworld')
foreach ($d in $loadDlcs) { [void]$mods.Add('ludeon.rimworld.' + $d.ToLower()) }
Write-Host ("DLCs: " + $(if ($loadDlcs.Count) { $loadDlcs -join ', ' } else { 'none' }))
if ($Compat) {
# Package ids read from the installed copies' About/About.xml (2026-11-29). Mods that change TradeDropSpot or
# AllLaunchableThingsForTrade (Trade Ships Drop Spot, Trading Control, Trade as Slave or Colonist) stay out.
foreach ($id in 'orion.hospitality', 'mehni.pickupandhaul', 'jkluch.haultostack', 'rimfridge.kv.rw', 'aelanna.weaponracks',
'avius.prisonlabor', 'legator.prisonerrealism', 'memegoddess.replacestuff',
'oskarpotocki.vanillafactionsexpanded.core', 'vanillaexpanded.vfecore', 'vanillaexpanded.vfemedical',
'dubwise.dubsskylights', 'vanillaexpanded.vee') {
Add-WithDependencies $id $mods
}
Add-WithDependencies 'blax.castes' $mods
# Blax Defaults joins once it has code; skipped with a warning while it is not installed.
Add-WithDependencies 'blax.defaults' $mods
}
[void]$mods.Add('blax.zones')
if ($Compat) { Add-WithDependencies 'blax.slaves' $mods }
[void]$mods.Add('blax.zones.tests')
# fresh test data folder: mod list only, no old saves, results or mod settings (files are named Mod_<folder>_<class>.xml)
New-Item -ItemType Directory -Force (Join-Path $DataDir 'Config') | Out-Null
Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxZonesTest.rws'), (Join-Path $DataDir 'Saves\BlaxZonesTest3.rws'),
(Join-Path $DataDir 'BlaxZonesTestResults.txt')
Get-ChildItem -LiteralPath (Join-Path $DataDir 'Config') -Filter 'Mod_*.xml' -ErrorAction SilentlyContinue |
Where-Object { $_.Name -like 'Mod_BlaxZones_*' -or $_.Name -like 'Mod_blax.zones_*' -or $_.Name -like 'Mod_BlaxCastes_*' -or
$_.Name -like 'Mod_blax.castes_*' -or $_.Name -like 'Mod_BlaxSlaves_*' -or $_.Name -like 'Mod_blax.slaves_*' } |
Remove-Item -Force -ErrorAction SilentlyContinue
$li = { param($ids) ($ids | ForEach-Object { " <li>$_</li>" }) -join "`n" }
$modsConfig = "<?xml version=`"1.0`" encoding=`"utf-8`"?>`n<ModsConfigData>`n <version>1.7</version>`n <activeMods>`n" +
(& $li $mods) + "`n </activeMods>`n <knownExpansions>`n" + (& $li $expansions) + "`n </knownExpansions>`n</ModsConfigData>`n"
[IO.File]::WriteAllText((Join-Path $DataDir 'Config\ModsConfig.xml'), $modsConfig)
Write-Host ("Mods: " + ($mods -join ', '))
$createdLink = $false
try {
# A test-mod link left by a run from another copy that died is replaced, never reused.
if (Test-Path -LiteralPath $link) {
$item = Get-Item -LiteralPath $link -Force
if (-not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw "$link is a real folder, not a junction. Move it away and run again." }
$target = @($item.Target)[0]
if (-not $target -or (Get-FullPath $target) -ne (Get-FullPath $testMod)) {
Write-Warning "replacing stale test-mod link $link -> $target"
cmd /c rmdir "$link" | Out-Null
}
}
if (-not (Test-Path -LiteralPath $link)) {
New-Item -ItemType Junction -Path $link -Target $testMod | Out-Null
$createdLink = $true
}
$gameArgs = "-headless -quicktest -blaxzonestests -NoFileLog -NoCrashDialog `"-savedatafolder=$DataDir`""
$sw = [Diagnostics.Stopwatch]::StartNew()
$p = Start-Process -FilePath (Join-Path $RimWorldDir 'RimWorld.exe') -WorkingDirectory $RimWorldDir -ArgumentList $gameArgs `
-RedirectStandardOutput (Join-Path $DataDir 'game.log') -RedirectStandardError (Join-Path $DataDir 'game.err.log') `
-WindowStyle Hidden -PassThru
if ($AllowWhileRunning) {
try { $p.PriorityClass = [Diagnostics.ProcessPriorityClass]::BelowNormal } catch { Write-Warning "could not lower the test game's priority: $_" }
}
if (-not $p.WaitForExit($TimeoutSeconds * 1000)) {
$p.Kill()
Write-Warning "timed out after $TimeoutSeconds s, test game (process $($p.Id)) killed"
}
Write-Host ("Game ran {0:N0} s. Log: {1}" -f $sw.Elapsed.TotalSeconds, (Join-Path $DataDir 'game.log'))
}
finally {
if ($createdLink -and (Test-Path $link)) { cmd /c rmdir "$link" | Out-Null }
}
}
finally {
if ($restoreTarget) {
cmd /c rmdir "$modLink" | Out-Null
New-Item -ItemType Junction -Path $modLink -Target $restoreTarget | Out-Null
Write-Host "Mods\BlaxZones points at $restoreTarget again"
}
Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue
}
$results = Join-Path $DataDir 'BlaxZonesTestResults.txt'
if (-not (Test-Path $results)) { Write-Host 'No results file: the suite never started. See game.log.'; exit 2 }
$lines = Get-Content -LiteralPath $results -Encoding UTF8
$lines | ForEach-Object { Write-Host $_ }
if (-not ($lines -match '^END$')) { Write-Host 'The run did not finish.'; exit 2 }
if ($lines -match '^FAIL ') { exit 1 }
exit 0

46
docs/ingame-check.md Normal file
View File

@ -0,0 +1,46 @@
# In-game check for 1.0
The headless suite covers the logic but draws nothing. These are the checks only a real game can do. Activate Blax Zones yourself (Mods > Blax Zones, below Harmony, after Blax Castes if you use it; `Mods\BlaxZones` is a junction to this repo) and use a throwaway save. Tick each box, and note what looked wrong next to it.
## Zone menu and designators
- [ ] Zone menu: "Delivery zone" sits right after "Growing zone" (with Odyssey, Fishing follows it). Its stockpile icon is tinted amber.
- [ ] Its tooltip has two paragraphs; the second says the zone extends the home area 4 cells while auto home area is on.
- [ ] The delivery button shows no hotkey label, because Dumping already shows that key, as with vanilla Fishing.
- [ ] Dragging plays the stockpile sounds. The cursor reads "Create new Delivery zone" or "Expand ... or create new Delivery zone" with the stockpile icon, untinted, as vanilla draws it.
- [ ] A new zone draws amber at the vanilla zone opacity and is labelled "Delivery zone 1".
- [ ] A selected delivery zone shows the amber Expand gizmo first, then Shrink and Delete. Expanding only adds cells, and dragging across a stockpile leaves the stockpile cells alone.
- [ ] Mod settings: unticking "Delivery zones" hides the menu button and the Expand gizmo at once, without reopening the menu; existing zones stay. Ticking it shows both again.
## Delivery tab
- [ ] Select a delivery zone. A "Delivery" tab opens with, top to bottom: "Priority: Normal", "Orbital trade lands here" ticked, "Caravans camp here" unticked, then the item filter (Clear all and Allow all, a search box, the hit points and quality sliders, the category tree).
- [ ] The priority button lists Low, Normal, Preferred, Important and Critical in that order. Picking one updates the button.
- [ ] The tree shows no Corpses category and, with Biotech, no Wastepack. With Biotech, Clear all, then Allow all, then ticking Items > Misc never shows Wastepack allowed.
- [ ] With Ideology, the vegetarian, carnivore, cannibal and insect meat filters are hidden, as in the stockpile tab.
- [ ] Hover the orbital row: with Blax Slaves active the tooltip ends with "Also Blax Slaves payouts (ransom, buy-back, wages)."; without Slaves that line is absent. With "Route orbital trade" off in the mod settings, the off note shows; with Blax Slaves active it says Slaves payouts still land here.
- [ ] Hover the camp row: with "Caravans may camp at zones" off, the off note shows.
- [ ] Gizmo bar: Copy settings and Paste settings with the vanilla icons, after Expand, Shrink and Delete. Paste is greyed out with its reason until a copy exists.
- [ ] Copy zone A, select zone B, paste: B takes A's filter, priority and both checkboxes, keeps its cells and name, and the copied and pasted messages appear. The copy and paste hotkeys work.
## Cells drop pods can't use
- [ ] Select a delivery zone that has roofed cells, a shallow water cell, a cell inside an enclosed animal pen and a part walled off from the colonists: red outlines sit exactly on those cells.
- [ ] No outlines while the zone is not selected, in world view, or for a zone on another map.
- [ ] The inspect pane reads "N cells drop pods can't use", or "1 cell drop pods can't use".
- [ ] After a roof finishes or a wall goes up at 1x speed, the outlines and the count update within about 4 seconds.
- [ ] Selecting the zone while paused shows current outlines at once.
- [ ] No frame-rate drop with a large zone selected.
## Orbital trade
- [ ] Call an orbital trader with a powered comms console and buy steel and medicine. The drop pods fall on the delivery zone, not next to the trade beacon, and spread over the zone's cells.
- [ ] Sell something: the silver lands in the zone too. A bought animal or person lands next to the beacon, as in vanilla.
## Caravan camps
- [ ] Tick "Caravans camp here" on a delivery zone and force a trader caravan (dev mode). The trader and pack animals gather beside the zone, and goods bought from them drop next to it.
## Existing save
- [ ] Save with a few delivery zones, load the save: the zones come back with their names, cells, filters and priorities, and the log shows nothing from Blax Zones.