Compare commits

..

No commits in common. "5bf6c73e903e5226dacc3955e7f7fb5f6bfa3d84" and "09ecc5a50665487d34856e21d873c742e7aa052e" have entirely different histories.

44 changed files with 313 additions and 3039 deletions

Binary file not shown.

Binary file not shown.

View File

@ -3,7 +3,7 @@
<name>Blax Zones</name>
<author>Blax Gaming</author>
<packageId>blax.zones</packageId>
<modVersion>1.1.0</modVersion>
<modVersion>1.0.0</modVersion>
<supportedVersions>
<li>1.7</li>
</supportedVersions>
@ -19,17 +19,15 @@
<li>brrainz.harmony</li>
<li>blax.castes</li>
</loadAfter>
<description>Choose where deliveries land. Drag a delivery zone and what you buy from orbital traders and trader caravans, plus quest rewards, lands in it. Trader caravans camp next to a zone you pick. Works with any DLC combination, core only included.
<description>Choose where deliveries land. Drag a delivery zone and what you buy from orbital traders drops into it. Trader caravans camp next to a zone you pick. Works with any DLC combination, core only included.
&lt;color=#19C63C&gt;Delivery zones&lt;/color&gt;
- "Delivery zone" sits in the Zone menu after "Growing zone". Drag it like a stockpile.
- What you buy from orbital traders, plus the silver from selling, lands in the best matching zone instead of next to the trade beacon.
- Goods bought from trader caravans and Hospitality guests, and the silver from selling to them, appear in the zone instead of at the pack animals' feet, even in a roofed zone. One message per trade names the zone.
- Item rewards from quests drop into the zone, and the quest letter points there.
- Each zone's Delivery tab has an item filter and a priority from Low to Critical: medicine by the hospital, steel by the workshop.
- When every fitting zone is full, pods and caravan purchases land next to the top one, on a cell your colonists can reach. With no fitting zone they land where they always did.
- When every fitting zone is full, pods land next to the top one, on a cell your colonists can reach. With no fitting zone they land where they always did.
- While a zone is selected, red outlines mark the cells drop pods can't use: roofed, water, inside an enclosed pen, blocked, fogged or out of reach.
- Bought people and animals, refugees, prisoners, raids and colonists you ransom back land as before.
- Bought people and animals, raids and colonists you ransom back land as before.
&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. Visitor groups and Hospitality guests pick their own spot.

View File

@ -1,17 +1,5 @@
# Changelog
## 1.1.0
- Caravan purchases land in the zone: goods you buy from a visiting trader caravan, or from a Hospitality guest, and the silver from selling to them appear in the best matching delivery zone instead of at the pack animals' feet. Nothing falls from the sky, so a roofed zone works too, for example a medicine zone inside the hospital. The filter decides what fits, then the highest priority wins, then the oldest zone. When every fitting zone is full, the goods appear next to the top one while "Overflow lands next to the zone" is on and your colonists can reach it; otherwise they stay at the pack animals' feet.
- One message per trade names the delivery zone the goods went to, or says they lie next to it when it was full; click it to jump to them.
- Quest rewards land in the zone: item rewards that quests drop at the trade beacon (with Royalty, Empire quests too) fall into the best matching delivery zone, and the quest letter points there. Each stack gets its own pod. Full zones overflow next to the top zone, as orbital purchases do.
- Refugees, prisoners, mechanoids, Wastepack, colonists you ransom back and raids never come to the zone. Bought people and animals stay with the caravan.
- Delivery tab: two new checkboxes, "Quest rewards land here" and "Caravan purchases land here", both on for new zones and for zones from 1.0 saves. Copy settings and Paste settings move them too.
- Settings: "Route quest rewards", "Route caravan purchases" and "Message when goods arrive", all on.
- With Trade Ships Drop Spot active, a one-time message says you can unsubscribe from it, since Blax Zones now places both orbital purchases and quest rewards. It shows once you have a delivery zone, and never again after that, in any save.
- The Zone menu's description of the delivery zone now names caravan purchases and quest rewards, and the "Overflow lands next to the zone" tooltip says it also covers caravan purchases.
- Nothing is ever lost: if no zone fits, or anything in Blax Zones goes wrong, goods land where vanilla puts them.
## 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.

View File

@ -12,16 +12,10 @@
<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_SettingRouteRewards>Route quest rewards</BlaxZones_SettingRouteRewards>
<BlaxZones_SettingRouteRewardsTip>Item rewards from quests drop into the best matching delivery zone instead of next to a trade beacon. People, animals and Wastepack never do. Off: rewards land where they always did.</BlaxZones_SettingRouteRewardsTip>
<BlaxZones_SettingOverflowNearZone>Overflow lands next to the zone</BlaxZones_SettingOverflowNearZone>
<BlaxZones_SettingOverflowNearZoneTip>When every cell of the fitting zones is taken, pods and caravan purchases land near the top zone, on a spot your colonists can reach. Off: they land where they always did.</BlaxZones_SettingOverflowNearZoneTip>
<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_SettingRouteCaravan>Route caravan purchases</BlaxZones_SettingRouteCaravan>
<BlaxZones_SettingRouteCaravanTip>What you buy from trader caravans and Hospitality guests, and the silver from selling to them, appears in the best matching delivery zone instead of at the pack animals' feet, also under a roof. Bought people and animals stay with the caravan. Off: goods land where they always did.</BlaxZones_SettingRouteCaravanTip>
<BlaxZones_SettingCaravanMessage>Message when goods arrive</BlaxZones_SettingCaravanMessage>
<BlaxZones_SettingCaravanMessageTip>After a trade with a caravan or a guest, one message names the delivery zone the goods went to, or says they lie next to it when it was full.</BlaxZones_SettingCaravanMessageTip>
<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>

View File

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Package Caravan: its own keys only, prefixed BlaxZones_. -->
<BlaxZones_CaravanGoodsInZone>Goods from the trade were delivered to {ZONE}.</BlaxZones_CaravanGoodsInZone>
<BlaxZones_CaravanGoodsNextToZone>Goods from the trade were delivered next to {ZONE}, which is full.</BlaxZones_CaravanGoodsNextToZone>
<BlaxZones_CaravanGoodsInZones>Goods from the trade were delivered to {COUNT} delivery zones.</BlaxZones_CaravanGoodsInZones>
</LanguageData>

View File

@ -3,6 +3,6 @@
<!-- Package Designators: its own keys only, prefixed BlaxZones_. -->
<BlaxZones_DesignatorDeliveryZoneDesc>Mark where deliveries land. What you buy from orbital traders and trader caravans, the silver from selling, and item rewards from quests land here. Each zone's tab sets what may land there, from where, and its priority.\n\nLike every zone, it extends the home area 4 cells around itself while auto home area is on.</BlaxZones_DesignatorDeliveryZoneDesc>
<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

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Package Rewards: its own keys only, prefixed BlaxZones_. -->
<BlaxZones_TradeShipsDropSpotHint>Blax Zones now lands orbital purchases and quest rewards in delivery zones, so you can unsubscribe from Trade Ships Drop Spot.</BlaxZones_TradeShipsDropSpotHint>
</LanguageData>

View File

@ -9,12 +9,6 @@
<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_AcceptOrbitalOffTip>"Route orbital trade" is off in the mod settings, so orbital trade doesn't land here now.</BlaxZones_AcceptOrbitalOffTip>
<BlaxZones_AcceptRewards>Quest rewards land here</BlaxZones_AcceptRewards>
<BlaxZones_AcceptRewardsTip>Item rewards from quests drop here when the item filter allows it, and the quest letter points here. People, animals and Wastepack never do.</BlaxZones_AcceptRewardsTip>
<BlaxZones_AcceptRewardsOffTip>"Route quest rewards" is off in the mod settings, so quest rewards don't land here now.</BlaxZones_AcceptRewardsOffTip>
<BlaxZones_AcceptCaravan>Caravan purchases land here</BlaxZones_AcceptCaravan>
<BlaxZones_AcceptCaravanTip>What you buy from trader caravans and guests (Hospitality), and the silver from selling to them, appears here when the item filter allows it, also under a roof. Bought people and animals stay with the caravan.</BlaxZones_AcceptCaravanTip>
<BlaxZones_AcceptCaravanOffTip>"Route caravan purchases" is off in the mod settings, so caravan purchases don't land here now.</BlaxZones_AcceptCaravanOffTip>
<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>

View File

@ -6,34 +6,30 @@
[![Steam Workshop](https://img.shields.io/badge/Steam_Workshop-subscribe-1b2838?logo=steam)](https://steamcommunity.com/sharedfiles/filedetails/?id=3848261160)
[![Needs Harmony](https://img.shields.io/badge/needs-Harmony-050805)](https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077)
[![Any DLC combination](https://img.shields.io/badge/DLCs-any_combination-5a6b5d)](#dlc-support)
[![Status: 1.1](https://img.shields.io/badge/status-1.1-CDCDCD)](CHANGELOG.md)
[![Status: 1.0](https://img.shields.io/badge/status-1.0-CDCDCD)](CHANGELOG.md)
RimWorld mod (1.7) by Blax Gaming. Drag a delivery zone and what you buy from orbital traders and trader caravans, plus quest rewards, lands in it, sorted by item filter and priority: medicine by the hospital, steel by the workshop. Trader caravans camp next to a zone you pick. Needs Harmony. Works with any DLC combination, core only included.
RimWorld mod (1.7) by Blax Gaming. Drag a delivery zone and what you buy from orbital traders lands in it, sorted by item filter and priority: medicine by the hospital, steel by the workshop. Trader caravans camp next to a zone you pick. Needs Harmony. Works with any DLC combination, core only included.
## Features
### Delivery zones
![Orbital purchases in a delivery zone](docs/media/delivery-zone.jpg)
- 📦 **Delivery zone.** "Delivery zone" sits in the Zone menu right after "Growing zone" and is dragged like a stockpile. It draws amber and grows with "Expand zone". Like every zone, it extends the home area 4 cells around itself while auto home area is on. `Source/BlaxZones/Designator_ZoneAdd_Delivery.cs`
- 🔽 **Delivery tab.** A priority from Low to Critical, "Orbital trade lands here", "Quest rewards land here" and "Caravan purchases land here" (all 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 every checkbox to another delivery zone. `Source/BlaxZones/ITab_Delivery.cs`
- 🔽 **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 to another delivery zone. `Source/BlaxZones/ITab_Delivery.cs`
- 🛰️ **Orbital purchases land in the zone.** Every item 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 filter decides what fits, then the highest priority wins, then the oldest zone. Pods use the 400 cells nearest the middle of a zone: the free ones first, from the middle out, then a matching stack. `Source/BlaxZones/DeliveryRouter.cs`
- 👣 **Overflow you can reach.** When every fitting zone is full, pods land next to the top one, on a cell your colonists can reach, within 16 cells (5 to 30). Overflow from a zone your colonists can't reach lands at the vanilla spot, and so does all overflow with "Overflow lands next to the zone" off.
- 🎁 **Quest rewards land in the zone.** Item rewards that quests drop at the trade beacon, with Royalty Empire quests too, fall into the best matching delivery zone with "Quest rewards land here" ticked, one pod per stack, and the quest letter points there. Full zones overflow as orbital purchases do. `Source/BlaxZones/DeliveryRouter.Rewards.cs`
- 🐪 **Caravan purchases appear in the zone.** Goods bought from a visiting trader caravan or a Hospitality guest, and the silver from selling to them, appear in the best matching delivery zone with "Caravan purchases land here" ticked, instead of at the pack animals' feet. Nothing falls, so a roofed zone works: a medicine zone inside the hospital takes caravan medicine. When every fitting zone is full, the goods appear next to the top one while "Overflow lands next to the zone" is on and your colonists can reach it; otherwise they stay at the pack animals' feet. One message per trade names the zone, or says the goods lie next to it when it was full. `Source/BlaxZones/DeliveryRouter.Caravan.cs`
- 🟥 **Unusable cells marked.** 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. `Source/BlaxZones/DeliveryRules.cs`
- 🛡️ **Nothing is lost.** Bought people and animals, refugees, prisoners, mechanoids and Wastepack from quests, raids, colonists you ransom back and lent colonists coming home land as before. With no fitting zone goods land at the vanilla spot, and so do they if anything in Blax Zones goes wrong. A mod that moves the vanilla drop spot keeps working as the fallback.
- 🛡️ **Nothing is lost.** Bought people and animals, raids, colonists you ransom back and lent colonists coming home 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. A mod that moves the vanilla drop spot keeps working as the fallback.
### Caravan camps
- ⛺ **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 appear in a delivery zone, or with "Route caravan purchases" off drop at their pack animals' feet, next to the zone. Visitor groups and Hospitality guests pick their own spot. `Source/BlaxZones/CampScope.cs`
- ⛺ **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, next to the zone. Visitor groups and Hospitality guests pick their own spot. `Source/BlaxZones/CampScope.cs`
- 🤝 **Trading-spot mods win.** Camping stands down, with one log line, while Trading Spot Rewritten, [KV] Trading Spot, [GMT] Trading Spot or Trading Control is active. `Source/BlaxZones/Compat.TradingSpots.cs`
### Save and settings
- 💾 **Save-safe.** Delivery zones are saved with Blax Zones' own map data, never in the game's zone list. Blax Zones can be added to a running save. Unsubscribing leaves a save that loads: the delivery zones are gone, vanilla zones stay, and the log shows two errors per map. `Source/BlaxZones/ZoneStore.cs`
- ⚙️ **Mod settings.** "Delivery zones" (hides the designator; existing zones stay and still receive deliveries), "Route orbital trade", "Route quest rewards", "Overflow lands next to the zone" with its overflow radius, "Route caravan purchases", "Message when goods arrive", "Caravans may camp at zones", "Reset to defaults".
- ⚙️ **Mod settings.** "Delivery zones" (hides the designator; existing zones stay and still receive deliveries), "Route orbital trade", "Overflow lands next to the zone" with its overflow radius, "Caravans may camp at zones", "Reset to defaults".
### For other mods
@ -43,28 +39,29 @@ RimWorld mod (1.7) by Blax Gaming. Drag a delivery zone and what you buy from or
Later releases, in order (details in `docs/design.md`):
- 🎁 **1.1 Quest rewards and caravan purchases.** Item rewards from quests drop into the zone. Goods bought from trader caravans and Hospitality guests appear in the zone, even a roofed one.
- 🐔 **1.2 Animal sleeping zones.** Every cell is a sleeping spot, with species and body-size filters, so big stalls stay free of chickens. A button in the mod settings strips Blax Zones from a save first, for a removal with no errors.
- 🧹 **1.3 Work rule areas.** Paint named areas over anything, stockpiles and fields included, and tick rules per area: No cleaning, No firefighting, No repairs, Don't haul from here, Clean first, Haul first. A barn nobody cleans still gets its fires fought, and a hospital is cleaned first. Work rules never change work priorities or allowed areas, and right-click orders work in every area.
- 🗄️ **1.4 Storage, roofs and selling.** Stockpiles, shelves, racks and fridges receive deliveries directly, also under a roof. Orbital traders buy from flagged storage (needs a powered trade beacon). Random cargo pod events land in a zone you pick. All optional, off by default.
- 🛏️ **1.5 People sleeping zones.** Dorms and prisons for colonists, slaves (needs Ideology) and prisoners, one cell per sleeper. Medical and shared zones.
- 🏷️ **1.6 Castes.** With Blax Castes, people sleeping zones can be limited by caste.
- 🗄️ **1.3 Storage, roofs and selling.** Stockpiles, shelves, racks and fridges receive deliveries directly, also under a roof. Orbital traders buy from flagged storage (needs a powered trade beacon). Random cargo pod events land in a zone you pick. All optional, off by default.
- 🛏️ **1.4 People sleeping zones.** Dorms and prisons for colonists, slaves (needs Ideology) and prisoners, one cell per sleeper. Medical and shared zones.
- 🏷️ **1.5 Castes.** With Blax Castes, people sleeping zones can be limited by caste.
- 🧹 **1.6 Work rule areas.** Paint named areas over anything, stockpiles and fields included, and tick rules per area: No cleaning, No firefighting, No repairs, Don't haul from here, Clean first, Haul first. A barn nobody cleans still gets its fires fought, and a hospital is cleaned first. Work rules never change work priorities or allowed areas, and right-click orders work in every area.
## DLC support
Blax Zones works with any combination of DLCs, core only included, and lists none as a dependency. Nothing in it needs a DLC.
Blax Zones works with any combination of DLCs, core only included, and lists none as a dependency. Nothing in 1.0 needs a DLC.
- **Royalty** adds tribute collectors, who camp at the zone like trader caravans, and Empire quests, whose item rewards land in the zone like any other.
- **Royalty** adds tribute collectors, who camp at the zone like trader caravans.
- **Biotech** adds Wastepack, which never lands in a zone and is hidden from the filter.
- **Ideology**, **Anomaly** and **Odyssey**: Blax Zones uses none of their content. Slave sleeping zones (planned for 1.5) will need Ideology.
- **Ideology**, **Anomaly** and **Odyssey**: 1.0 uses none of their content. Slave sleeping zones (planned for 1.4) will need Ideology.
- **A save made with a DLC** loads without it. Delivery zone filters drop the missing items, with the same "Could not load reference" error per missing def that vanilla stockpile filters log, and the zone keeps working.
## Compatibility
- ✔️ Hospitality guests pick their own spot and never camp at the zone. Goods bought from them land in the zone like caravan goods.
- ✔️ Hospitality guests pick their own spot and never camp at the zone.
- ✔️ Trading Spot Rewritten, [KV] Trading Spot, [GMT] Trading Spot and Trading Control: while one is active, caravan camps stand down and leave caravans to it.
- ✔️ A mod that moves vanilla's trade drop spot stays the fallback: a fitting zone wins, everything else lands at that mod's spot.
- ✔️ The `-Compat` test run loads Hospitality, Pick Up And Haul, Haul to Stack, RimFridge, Weapon Racks, Prison Labor, Prisoner Realism, Replace Stuff, Vanilla Expanded Framework, Vanilla Furniture Expanded with its Medical Module, Dubs Skylights, Vanilla Events Expanded, Blax Castes, Blax Defaults and Blax Slaves, and every test passes. Prison Labor logs one error of its own when a test makes a prisoner.
- ♻️ Replaces the orbital trade part of Trade Ships Drop Spot, the orbital trade and caravan spot parts of Trading Control, and [KV] Trading Spot and [GMT] Trading Spot. Since 1.1 also their quest reward part; while Trade Ships Drop Spot is active, a one-time message says you can unsubscribe from it, once you have a delivery zone.
- ♻️ Replaces the orbital trade part of Trade Ships Drop Spot, the orbital trade and caravan spot parts of Trading Control, and [KV] Trading Spot and [GMT] Trading Spot. The quest reward part of Trade Ships Drop Spot and Trading Control follows in 1.1.
- ❌ Multiplayer: not supported.
Load order: Harmony, Blax Castes, Blax Zones, Blax Slaves. No Blax mod needs another.

View File

@ -15,23 +15,12 @@ namespace BlaxZones
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>Item rewards quests drop at the trade spot land in delivery zones (1.1).</summary>
public bool routeRewards = 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;
/// <summary>Goods bought from trader caravans and Hospitality guests appear in delivery zones (1.1).</summary>
public bool routeCaravan = true;
/// <summary>One message per trade names the delivery zone the caravan goods went to (1.1).</summary>
public bool caravanMessage = true;
/// <summary>
/// The Trade Ships Drop Spot hint was shown (1.1). Not a setting the player sees: it makes the hint
/// one-time across saves and games without putting anything in a save. Reset to defaults keeps it.
/// </summary>
public bool tradeShipsHintShown;
public const int DefaultOverflowRadius = 16;
public const int MinOverflowRadius = 5;
@ -45,13 +34,9 @@ namespace BlaxZones
base.ExposeData();
Scribe_Values.Look(ref deliveryZones, "deliveryZones", true);
Scribe_Values.Look(ref routeOrbital, "routeOrbital", true);
Scribe_Values.Look(ref routeRewards, "routeRewards", true);
Scribe_Values.Look(ref overflowNearZone, "overflowNearZone", true);
Scribe_Values.Look(ref overflowRadius, "overflowRadius", DefaultOverflowRadius);
Scribe_Values.Look(ref campAtZones, "campAtZones", true);
Scribe_Values.Look(ref routeCaravan, "routeCaravan", true);
Scribe_Values.Look(ref caravanMessage, "caravanMessage", true);
Scribe_Values.Look(ref tradeShipsHintShown, "tradeShipsHintShown", false);
if (Scribe.mode == LoadSaveMode.PostLoadInit || Scribe.mode == LoadSaveMode.LoadingVars)
overflowRadius = Mathf.Clamp(overflowRadius, MinOverflowRadius, MaxOverflowRadius);
}
@ -61,12 +46,9 @@ namespace BlaxZones
var d = new BlaxZonesSettings();
deliveryZones = d.deliveryZones;
routeOrbital = d.routeOrbital;
routeRewards = d.routeRewards;
overflowNearZone = d.overflowNearZone;
overflowRadius = d.overflowRadius;
campAtZones = d.campAtZones;
routeCaravan = d.routeCaravan;
caravanMessage = d.caravanMessage;
}
}
@ -78,31 +60,11 @@ namespace BlaxZones
public static BlaxZonesSettings S => Settings ?? (fallback ??= new BlaxZonesSettings());
private static BlaxZonesSettings fallback;
private static BlaxZonesMod instance;
public BlaxZonesMod(ModContentPack content) : base(content)
{
instance = this;
Settings = GetSettings<BlaxZonesSettings>();
}
/// <summary>
/// Writes the settings file now (the hint flag), as closing the settings window does. Skipped while
/// another Scribe session runs (the flag then waits in memory for the next write). Never throws.
/// </summary>
public static void SaveSettings()
{
try
{
if (Scribe.mode == LoadSaveMode.Inactive)
instance?.WriteSettings();
}
catch (Exception e)
{
ZonesLog.Once("Writing the mod settings", e);
}
}
public override string SettingsCategory() => "Blax Zones";
public override void DoSettingsWindowContents(Rect inRect)
@ -114,7 +76,6 @@ namespace BlaxZones
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_SettingRouteRewards".Translate(), ref s.routeRewards, "BlaxZones_SettingRouteRewardsTip".Translate());
l.CheckboxLabeled("BlaxZones_SettingOverflowNearZone".Translate(), ref s.overflowNearZone, "BlaxZones_SettingOverflowNearZoneTip".Translate());
if (s.overflowNearZone)
{
@ -125,8 +86,6 @@ namespace BlaxZones
}
l.GapLine();
l.CheckboxLabeled("BlaxZones_SettingRouteCaravan".Translate(), ref s.routeCaravan, "BlaxZones_SettingRouteCaravanTip".Translate());
l.CheckboxLabeled("BlaxZones_SettingCaravanMessage".Translate(), ref s.caravanMessage, "BlaxZones_SettingCaravanMessageTip".Translate());
l.CheckboxLabeled("BlaxZones_SettingCampAtZones".Translate(), ref s.campAtZones, "BlaxZones_SettingCampAtZonesTip".Translate());
l.Gap();

View File

@ -21,13 +21,10 @@ namespace BlaxZones
CampScope.Active = true;
}
/// <summary>
/// Returns void on purpose: Harmony then rethrows an exception with its stack trace intact. One
/// finalizer that returns Exception makes it throw the exception anew, and the trace starts here.
/// </summary>
public static void Finalizer(bool __state)
public static Exception Finalizer(bool __state, Exception __exception)
{
CampScope.Active = __state;
return __exception;
}
}

View File

@ -1,130 +0,0 @@
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Caravan. One message per trade naming the delivery zone the caravan goods went to (design:
/// 1.1 "Caravan purchases appear in the zone" > Message). The TradeDeal.TryExecute prefix opens a batch,
/// DeliveryRouter.PlaceFromCaravan records each placed stack with its own zone, and the postfix (or, if
/// the trade threw, the finalizer) sends one message for the batch. Outside a trade, a mod calling
/// GiveSoldThingToPlayer directly, each call sends its own message. The text says "goods from the
/// trade", since sale silver comes through the same call as purchases.
///
/// A batch lives for one TryExecute call on this thread and is never saved.
/// </summary>
public static class CaravanDeliveries
{
public sealed class Batch
{
internal readonly Batch previous;
internal readonly List<Zone_Delivery> zones = new List<Zone_Delivery>();
/// <summary>Zones that got at least one stack inside them; the others only got overflow next to them.</summary>
internal readonly HashSet<Zone_Delivery> inside = new HashSet<Zone_Delivery>();
internal readonly List<Thing> things = new List<Thing>();
internal bool ended;
internal Batch(Batch previous)
{
this.previous = previous;
}
/// <summary>Distinct zones goods went to (in or next to) in this batch, in the order they first got some. Read by tests.</summary>
public IReadOnlyList<Zone_Delivery> Zones => zones;
/// <summary>True when the batch went to one zone and every stack of it lies next to that zone (overflow).</summary>
public bool OnlyNextToZone => zones.Count == 1 && !inside.Contains(zones[0]);
internal void Add(DeliveryRouter.PlacedPiece piece)
{
if (piece.Zone == null)
return;
if (!zones.Contains(piece.Zone))
zones.Add(piece.Zone);
if (!piece.NextToZone)
inside.Add(piece.Zone);
if (piece.Thing != null && !things.Contains(piece.Thing))
things.Add(piece.Thing);
}
}
[ThreadStatic] private static Batch current;
/// <summary>The open batch of the trade running on this thread, or null.</summary>
public static Batch Current => current;
/// <summary>Opens a batch for one trade; the previous one (none outside a nested call) comes back at End.</summary>
public static Batch Begin()
{
var batch = new Batch(current);
current = batch;
return batch;
}
/// <summary>Closes the batch and sends its message. A second call for the same batch does nothing.</summary>
public static void End(Batch batch)
{
if (batch == null || batch.ended)
return;
batch.ended = true;
if (current == batch)
current = batch.previous;
Send(batch);
}
/// <summary>Adds placed stacks, each under its own zone, to the open batch, or sends a message at once when no trade is open.</summary>
public static void Record(List<DeliveryRouter.PlacedPiece> pieces)
{
if (pieces == null || pieces.Count == 0)
return;
Batch batch = current;
bool alone = batch == null || batch.ended;
if (alone)
batch = new Batch(null);
for (int i = 0; i < pieces.Count; i++)
batch.Add(pieces[i]);
if (alone)
Send(batch);
}
/// <summary>
/// "Goods from the trade were delivered to Delivery zone 1.", "... delivered next to Delivery zone 1,
/// which is full." when nextToZone (one zone, every stack overflowed), or "... delivered to 2 delivery
/// zones." Null for no zone.
/// </summary>
public static string MessageText(IReadOnlyList<Zone_Delivery> zones, bool nextToZone = false)
{
if (zones == null || zones.Count == 0)
return null;
if (zones.Count == 1)
return (nextToZone ? "BlaxZones_CaravanGoodsNextToZone" : "BlaxZones_CaravanGoodsInZone").Translate(zones[0].label.Named("ZONE"));
return "BlaxZones_CaravanGoodsInZones".Translate(zones.Count.Named("COUNT"));
}
private static void Send(Batch batch)
{
try
{
if (batch.zones.Count == 0 || !BlaxZonesMod.S.caravanMessage)
return;
var targets = new List<Thing>();
for (int i = 0; i < batch.things.Count; i++)
{
Thing t = batch.things[i];
if (t != null && t.Spawned && !targets.Contains(t))
targets.Add(t);
}
string text = MessageText(batch.zones, batch.OnlyNextToZone);
if (text.NullOrEmpty())
return;
Messages.Message(text, targets.Count > 0 ? new LookTargets(targets) : LookTargets.Invalid, MessageTypeDefOf.NeutralEvent, historical: true);
}
catch (Exception e)
{
ZonesLog.Once("Caravan delivery message", e);
}
}
}
}

View File

@ -1,127 +0,0 @@
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 Caravan. A caller-scoped transpiler on Pawn_TraderTracker.GiveSoldThingToPlayer replaces its
/// one GenPlace.TryPlaceThing call (Pawn_TraderTracker.cs:194) with DeliveryRouter.PlaceFromCaravan, which
/// has the same signature. Hospitality guests sell through Pawn.GiveSoldThingToPlayer, which calls this
/// method (Verse/Pawn.cs:4711-4714), so their goods route too. GenPlace itself is never patched.
/// </summary>
[HarmonyPatch(typeof(Pawn_TraderTracker), nameof(Pawn_TraderTracker.GiveSoldThingToPlayer))]
public static class Patch_Pawn_TraderTracker_GiveSoldThingToPlayer
{
private static readonly Type[] PlaceArgs =
{
typeof(Thing), typeof(IntVec3), typeof(Map), typeof(ThingPlaceMode), typeof(Action<Thing, int>), typeof(Predicate<IntVec3>),
typeof(Rot4?), typeof(int),
};
public static readonly MethodInfo TryPlaceThing = AccessTools.Method(typeof(GenPlace), nameof(GenPlace.TryPlaceThing), PlaceArgs);
public static readonly MethodInfo PlaceFromCaravan = AccessTools.Method(typeof(DeliveryRouter), nameof(DeliveryRouter.PlaceFromCaravan), PlaceArgs);
/// <summary>Calls of TryPlaceThing the last transpiler run found. The test checks it is exactly 1.</summary>
public static int LastCallCount = -1;
/// <summary>
/// Exactly one TryPlaceThing call: replace it. Any other count: log an error ("unexpected call
/// count") and return the instructions unchanged, so caravan goods land as in vanilla.
/// </summary>
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
List<CodeInstruction> list = instructions.ToList();
try
{
if (TryPlaceThing == null || PlaceFromCaravan == null)
{
LastCallCount = -1;
Log.Error("[Blax Zones] Caravan purchase routing is off: GenPlace.TryPlaceThing or DeliveryRouter.PlaceFromCaravan not found. Caravan goods land next to the pack animals.");
return list;
}
int count = 0;
int at = -1;
for (int i = 0; i < list.Count; i++)
{
if (list[i].Calls(TryPlaceThing))
{
count++;
at = i;
}
}
LastCallCount = count;
if (count != 1)
{
Log.Error("[Blax Zones] Caravan purchase routing is off: unexpected call count " + count + " of GenPlace.TryPlaceThing in Pawn_TraderTracker.GiveSoldThingToPlayer, expected 1. Caravan goods land next to the pack animals.");
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 = PlaceFromCaravan;
return list;
}
catch (Exception e)
{
Log.Error("[Blax Zones] Caravan purchase routing is off: the Pawn_TraderTracker.GiveSoldThingToPlayer transpiler failed: " + e);
return instructions;
}
}
}
/// <summary>
/// Package Caravan. Opens a CaravanDeliveries batch for one trade (TradeDeal.TryExecute, TradeDeal.cs:150),
/// so every stack bought in it makes one message. Prefix, postfix and finalizer only, so the trade mods
/// that also touch TryExecute compose. The finalizer sends what was collected if the trade threw and
/// restores the previous batch.
/// </summary>
[HarmonyPatch(typeof(TradeDeal), nameof(TradeDeal.TryExecute))]
public static class Patch_TradeDeal_TryExecute
{
public static void Prefix(out CaravanDeliveries.Batch __state)
{
__state = null;
try
{
__state = CaravanDeliveries.Begin();
}
catch (Exception e)
{
ZonesLog.Once("Caravan trade message", e);
}
}
public static void Postfix(CaravanDeliveries.Batch __state)
{
try
{
CaravanDeliveries.End(__state);
}
catch (Exception e)
{
ZonesLog.Once("Caravan trade message", e);
}
}
/// <summary>Returns void, so Harmony rethrows a trade exception with its stack trace intact.</summary>
public static void Finalizer(CaravanDeliveries.Batch __state)
{
try
{
CaravanDeliveries.End(__state);
}
catch (Exception e)
{
ZonesLog.Once("Caravan trade message", e);
}
}
}
}

View File

@ -1,75 +0,0 @@
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Rewards. Trade Ships Drop Spot (Workshop 1969732297, package id smashphil.dropspot) moves
/// both orbital drops and quest rewards to its marker. With 1.1 Zones covers both, so a one-time
/// message says the player can unsubscribe (design: 1.1 "Quest rewards land in the zone", Unsubscribe
/// hint). Detected by its marker def, read from github.com/SmashPhil/TradeShips-Drop-Spot,
/// Defs/DropSpotIndicator.xml (checked 2026-11-30): ThingDef "DropSpotTradeShip". The mod isn't installed
/// on the test machine; tests simulate the def through Compat.SimulatedActive.
/// </summary>
public static partial class Compat
{
/// <summary>Trade Ships Drop Spot's marker ThingDef.</summary>
public const string TradeShipsDropSpotDef = "DropSpotTradeShip";
/// <summary>Defs never change after startup, so the lookup runs once.</summary>
private static bool? tradeShipsDropSpotDefLoaded;
/// <summary>The marker def exists (the mod is active), or a test simulates it.</summary>
public static bool TradeShipsDropSpotActive
{
get
{
if (SimulatedActive.Count > 0 && SimulatedActive.Contains(TradeShipsDropSpotDef))
return true;
tradeShipsDropSpotDefLoaded ??= DefDatabase<ThingDef>.GetNamedSilentFail(TradeShipsDropSpotDef) != null;
return tradeShipsDropSpotDefLoaded.Value;
}
}
}
/// <summary>
/// The unsubscribe hint for Trade Ships Drop Spot: shown once, ever, on a map tick once the map has a
/// delivery zone, while "Route orbital trade" and "Route quest rewards" are both on. Before the
/// player makes a delivery zone Zones routes nothing, so the advice would be wrong. "Shown" is kept
/// in the mod settings file (BlaxZonesSettings.tradeShipsHintShown), so nothing enters a save and the
/// hint doesn't come back on the next load or game.
/// </summary>
public static class TradeShipsDropSpotHint
{
/// <summary>The mod is active and Zones routes everything it would place.</summary>
public static bool Applies =>
BlaxZonesMod.S.routeOrbital && BlaxZonesMod.S.routeRewards && Compat.TradeShipsDropSpotActive;
/// <summary>The hint text, also logged.</summary>
public static string Text => "BlaxZones_TradeShipsDropSpotHint".Translate();
/// <summary>Called on every map tick. After the hint was shown it costs one bool read.</summary>
public static void Check(Map map)
{
if (BlaxZonesMod.S.tradeShipsHintShown || !Applies || !DeliveryRouter.HasDeliveryZone(map))
return;
Show();
}
/// <summary>Shows the message, logs it and remembers it in the mod settings.</summary>
private static void Show()
{
BlaxZonesMod.S.tradeShipsHintShown = true;
BlaxZonesMod.SaveSettings();
string text = Text;
Messages.Message(text, MessageTypeDefOf.NeutralEvent, historical: true);
Log.Message("[Blax Zones] " + text);
}
/// <summary>Forgets that the hint was shown, so the next check may show it again. Tests only.</summary>
public static void Reset()
{
BlaxZonesMod.S.tradeShipsHintShown = false;
}
}
}

View File

@ -16,8 +16,6 @@ namespace BlaxZones
private static ThingFilter filter;
private static StoragePriority priority = StoragePriority.Normal;
private static bool acceptOrbital = true;
private static bool acceptRewards = true;
private static bool acceptCaravan = true;
private static bool campHere;
private static bool copied;
@ -35,8 +33,6 @@ namespace BlaxZones
filter.CopyAllowancesFrom(DeliveryFilters.NewDefaultFilter());
priority = zone.priority;
acceptOrbital = zone.acceptOrbital;
acceptRewards = zone.acceptRewards;
acceptCaravan = zone.acceptCaravan;
campHere = zone.campHere;
copied = true;
}
@ -54,8 +50,6 @@ namespace BlaxZones
zone.filter.CopyAllowancesFrom(filter);
zone.priority = priority;
zone.acceptOrbital = acceptOrbital;
zone.acceptRewards = acceptRewards;
zone.acceptCaravan = acceptCaravan;
zone.campHere = campHere;
}
}

View File

@ -1,49 +0,0 @@
using System;
namespace BlaxZones
{
/// <summary>
/// Package Rewards. Design: "DeliveryRouter, shared by every delivery path" > Context. Callers that can't
/// pass a source down to DropPodUtility.DropThingGroupsNear set Current in a prefix, keep the previous
/// value in __state and restore it in a finalizer (RewardPatches.cs). The DropThingGroupsNear prefix
/// reads it. SignalManager.SendSignal saves and clears it around every signal, so a quest part chained
/// through outSignalResult never sees a context that wasn't set for it. Cargo pods (1.4) reuse it.
///
/// The instances are fixed and hold no game state; only Current changes, for the length of one call.
/// </summary>
public sealed class DeliveryContext
{
/// <summary>Item rewards quests drop at the trade spot.</summary>
public static readonly DeliveryContext QuestRewards = new DeliveryContext(DeliverySource.Rewards, "Quest reward delivery");
/// <summary>The context of the call running on this thread, or null. Set and restored only by the patches.</summary>
[ThreadStatic] public static DeliveryContext Current;
/// <summary>Which zone checkbox decides.</summary>
public readonly DeliverySource Source;
/// <summary>The ZonesLog key for failures on this path.</summary>
public readonly string LogKey;
private DeliveryContext(DeliverySource source, string logKey)
{
Source = source;
LogKey = logKey;
}
/// <summary>The global setting for this path ("Route quest rewards"), read live.</summary>
public bool Enabled
{
get
{
switch (Source)
{
case DeliverySource.Rewards:
return BlaxZonesMod.S.routeRewards;
default:
return false;
}
}
}
}
}

View File

@ -8,10 +8,6 @@ namespace BlaxZones
{
/// <summary>Orbital trade purchases and sale silver, and ZonesApi callers (Blax Slaves payouts).</summary>
Orbital,
/// <summary>Item rewards quests drop at the trade spot (QuestPart_DropPods, QuestPart_GiveNearPawn), from 1.1.</summary>
Rewards,
/// <summary>Goods bought from trader caravans and Hospitality guests (Pawn_TraderTracker), from 1.1.</summary>
Caravan,
}
/// <summary>
@ -65,23 +61,5 @@ namespace BlaxZones
ThingDef wastepack = ThingDefOf.Wastepack;
return wastepack != null && inner.def == wastepack;
}
/// <summary>
/// A thing that carries a pawn inside it (a casket or pod holding a refugee or prisoner, as
/// QuestPart_DropPods tracks in pawnsInContainers, QuestPart_DropPods.cs:79-89). Never routed:
/// people arrive as in vanilla.
/// </summary>
public static bool HoldsPawn(Thing thing)
{
ThingOwner owner = thing?.TryGetInnerInteractableThingOwner();
if (owner == null)
return false;
for (int i = 0; i < owner.Count; i++)
{
if (owner[i] is Pawn || owner[i] is Corpse)
return true;
}
return false;
}
}
}

View File

@ -1,123 +0,0 @@
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Caravan. Design: 1.1 "Caravan purchases appear in the zone". Goods bought from a trader
/// caravan or a Hospitality guest, and the silver from selling to them, appear in the best matching
/// delivery zone instead of at the pack animal's feet. Roofs don't matter: nothing falls.
/// </summary>
public static partial class DeliveryRouter
{
/// <summary>One stack a caravan placement put on the map or merged into, and the zone it went to.</summary>
public struct PlacedPiece
{
public Thing Thing;
public Zone_Delivery Zone;
/// <summary>Every fitting zone was full: the stack lies next to Zone (overflow), not in it.</summary>
public bool NextToZone;
}
/// <summary>
/// Replaces the one GenPlace.TryPlaceThing call in Pawn_TraderTracker.GiveSoldThingToPlayer
/// (Pawn_TraderTracker.cs:194, GenPlace.cs:27), same signature. Bought pawns never get here: vanilla
/// returns early for them (:180-188). Sale silver does: when the player sells more than they buy, the
/// trader hands over silver through the same call (TradeDeal.cs:147, Tradeable.cs:472-478). With
/// "Route caravan purchases" on, tries the delivery zones (TryPlaceInZones) and records what it placed
/// for the trade's message (CaravanDeliveries). Whatever is left, and everything on an exception
/// (logged once), goes to the original call with the original arguments, so vanilla's destroy path
/// is reached only where vanilla would reach it. On a true result vanilla adds the thing to the lord's
/// extraForbiddenThings (:196), as before.
/// </summary>
public static bool PlaceFromCaravan(Thing thing, IntVec3 center, Map map, ThingPlaceMode mode, Action<Thing, int> placedAction,
Predicate<IntVec3> extraValidator, Rot4? rot, int squareRadius)
{
try
{
if (BlaxZonesMod.S.routeCaravan && mode == ThingPlaceMode.Near)
{
bool done = TryPlaceInZones(thing, map, placedAction, extraValidator, rot, out List<PlacedPiece> pieces);
if (pieces.Count > 0)
CaravanDeliveries.Record(pieces);
if (done)
return true;
}
}
catch (Exception e)
{
ZonesLog.Once("Caravan delivery", e);
// Already on the map (placed, or merged into a stack, before the failure): placing it again would fail.
if (thing != null && (thing.Spawned || thing.Destroyed))
return true;
}
return GenPlace.TryPlaceThing(thing, center, map, mode, placedAction, extraValidator, rot, squareRadius);
}
/// <summary>
/// Places the thing in a delivery zone with "Caravan purchases land here" ticked and a filter that
/// allows it, by priority, then zone ID. In each zone it picks a cell by the placement rule
/// (TryPickCellInZone with DeliveryRules.PlacementCellOk: free cells nearest the middle first, then a
/// matching stack) and places there with GenPlace in Near mode, limited to that zone's cells that
/// pass the placement rule. When every fitting zone is full, it places next to the top zone with
/// GenPlace in Near mode from the top zone's overflow center, with "Overflow lands next to the zone"
/// on and that cell reachable by the colony, as orbital overflow does.
///
/// True when the whole thing was placed. pieces holds every stack placed or merged into, each with
/// the zone it went to and whether it lies next to that zone (overflow), also when only part of a
/// large stack found room (the rest is still in thing for the caller). Throws only when
/// ZonesTestHooks.RouterThrows is set.
/// </summary>
public static bool TryPlaceInZones(Thing thing, Map map, Action<Thing, int> placedAction, Predicate<IntVec3> extraValidator,
Rot4? rot, out List<PlacedPiece> pieces)
{
if (ZonesTestHooks.RouterThrows)
throw new InvalidOperationException("ZonesTestHooks.RouterThrows");
pieces = new List<PlacedPiece>();
if (thing == null || thing.Spawned || thing.Destroyed || Refuses(map, thing) || DeliveryFilters.HoldsPawn(thing))
return false;
List<Zone_Delivery> candidates = Candidates(map, thing, DeliverySource.Caravan);
if (candidates.Count == 0)
return false;
// GenPlace reports each stack it placed or merged into; the zone and overflow flag of the current try go with it.
List<PlacedPiece> placed = pieces;
Zone_Delivery target = null;
bool nextTo = false;
void Record(Thing t, int count)
{
if (t != null && !placed.Exists(p => p.Thing == t))
placed.Add(new PlacedPiece { Thing = t, Zone = target, NextToZone = nextTo });
placedAction?.Invoke(t, count);
}
for (int i = 0; i < candidates.Count; i++)
{
Zone_Delivery candidate = candidates[i];
if (!TryPickCellInZone(candidate, thing, DeliveryRules.PlacementCellOk, null, out IntVec3 cell))
continue;
bool InZone(IntVec3 c) =>
map.zoneManager.ZoneAt(c) == candidate
&& DeliveryRules.PlacementCellOk(map, c)
&& (extraValidator == null || extraValidator(c));
target = candidate;
nextTo = false;
if (GenPlace.TryPlaceThing(thing, cell, map, ThingPlaceMode.Near, Record, InZone, rot) || thing.Destroyed)
return true;
}
// Every fitting zone is full: next to the top one, if the colony can reach it.
Zone_Delivery top = candidates[0];
if (!BlaxZonesMod.S.overflowNearZone)
return false;
IntVec3 center = OverflowCenter(top);
if (!center.IsValid || !center.InBounds(map) || !DeliveryRules.ColonyCanReach(map, center))
return false;
target = top;
nextTo = true;
return GenPlace.TryPlaceThing(thing, center, map, ThingPlaceMode.Near, Record, extraValidator, rot) || thing.Destroyed;
}
}
}

View File

@ -1,217 +0,0 @@
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Rewards. Design: 1.1 "Quest rewards land in the zone". The groups of one
/// DropPodUtility.DropThingGroupsNear call made inside a DeliveryContext: plan every group's cell
/// first, then drop the qualifying groups as their own pods, and hand vanilla the rest.
/// </summary>
public static partial class DeliveryRouter
{
/// <summary>Where one group of a drop goes: the group's index in the caller's list, its cell and zone.</summary>
public struct GroupPlan
{
public int Index;
public IntVec3 Cell;
public Zone_Delivery Zone;
/// <summary>Every fitting zone was full: the cell lies next to Zone, the top candidate.</summary>
public bool Overflow;
}
/// <summary>
/// A group that may be routed: not empty, and every thing in it is free (not spawned, in no
/// container, not destroyed), never routed (no pawn, corpse or Wastepack, DeliveryFilters.NeverRouted)
/// and carries no pawn inside it. A refugee or prisoner in the group keeps the whole group, items
/// included, with vanilla (dropAllInSamePod puts them in one group, QuestPart_DropPods.cs:209-212).
/// </summary>
public static bool GroupQualifies(List<Thing> group)
{
if (group == null || group.Count == 0)
return false;
for (int i = 0; i < group.Count; i++)
{
Thing t = group[i];
if (t == null || t.Destroyed || t.Spawned || t.holdingOwner != null)
return false;
if (DeliveryFilters.NeverRouted(t) || DeliveryFilters.HoldsPawn(t))
return false;
}
return true;
}
/// <summary>Candidates (source checkbox, filter, priority, ID) whose filter accepts every thing of the group.</summary>
public static List<Zone_Delivery> CandidatesForGroup(Map map, List<Thing> group, DeliverySource source)
{
List<Zone_Delivery> result = Candidates(map, group[0], source);
for (int i = 1; i < group.Count && result.Count > 0; i++)
{
Thing t = group[i];
result.RemoveAll(z => !z.Accepts(t));
}
return result;
}
/// <summary>
/// Plans a cell for every qualifying group, nothing dropped yet: the candidates in order, each
/// zone's cells by the pod rule (TryPickCellInZone), then overflow next to the top candidate. A cell
/// planned for one group is never planned again, since no pod marks it before the drop. Groups with
/// no plan stay with vanilla. Throws only when ZonesTestHooks.RouterThrows is set; the caller falls
/// back to vanilla with the original list.
/// </summary>
public static List<GroupPlan> PlanGroups(Map map, List<List<Thing>> groups, DeliverySource source)
{
if (ZonesTestHooks.RouterThrows)
throw new InvalidOperationException("ZonesTestHooks.RouterThrows");
var plans = new List<GroupPlan>();
if (map == null || groups == null || groups.Count == 0)
return plans;
if (MapComponent_BlaxZones.Of(map) == null || !HasDeliveryZone(map))
return plans;
var taken = new HashSet<IntVec3>();
for (int i = 0; i < groups.Count; i++)
{
List<Thing> group = groups[i];
if (!GroupQualifies(group))
continue;
List<Zone_Delivery> candidates = CandidatesForGroup(map, group, source);
if (candidates.Count == 0)
continue;
var plan = new GroupPlan { Index = i, Cell = IntVec3.Invalid };
for (int z = 0; z < candidates.Count; z++)
{
if (TryPickCellInZone(candidates[z], group[0], DeliveryRules.PodCellOk, taken, out IntVec3 cell))
{
plan.Cell = cell;
plan.Zone = candidates[z];
break;
}
}
if (plan.Zone == null)
{
if (!TryOverflow(candidates[0], taken, out IntVec3 cell))
continue;
plan.Cell = cell;
plan.Zone = candidates[0];
plan.Overflow = true;
}
if (!plan.Cell.IsValid || !plan.Cell.InBounds(map))
continue;
taken.Add(plan.Cell);
plans.Add(plan);
}
return plans;
}
/// <summary>
/// Drops each planned group as its own pod, as vanilla drops a group (DropPodUtility.cs:64-86): the
/// forbid flag per thing, an ActiveTransporterInfo with the call's openDelay and leaveSlag, then
/// DropPodUtility.MakeDropPodAt(cell, map, info, faction), so faction pod skins survive. With
/// instaDrop the things are placed directly, as vanilla does.
///
/// Returns the groups vanilla still has to drop, in their original order, as a new list; null when
/// nothing was planned. When a group fails (logged once under logKey), its things that are not on
/// the map yet are taken back out of the pod that never fell and go to vanilla, with every later
/// group. Groups already dropped are left out, so nothing drops twice and nothing is lost.
/// </summary>
public static List<List<Thing>> DropPlannedGroups(Map map, List<List<Thing>> groups, List<GroupPlan> plans,
int openDelay, bool instaDrop, bool leaveSlag, bool forbid, Faction faction, string logKey)
{
if (plans == null || plans.Count == 0)
return null;
var dropped = new HashSet<int>();
int failedIndex = -1;
List<Thing> failedLeft = null;
for (int p = 0; p < plans.Count; p++)
{
GroupPlan plan = plans[p];
List<Thing> group = groups[plan.Index];
try
{
DropGroup(map, group, plan.Cell, openDelay, instaDrop, leaveSlag, forbid, faction, p);
dropped.Add(plan.Index);
}
catch (Exception e)
{
ZonesLog.Once(logKey, e);
failedIndex = plan.Index;
failedLeft = NotYetDropped(group, logKey);
break;
}
}
var remaining = new List<List<Thing>>(groups.Count);
for (int i = 0; i < groups.Count; i++)
{
if (dropped.Contains(i))
continue;
if (i == failedIndex)
{
if (failedLeft != null && failedLeft.Count > 0)
remaining.Add(failedLeft);
continue;
}
remaining.Add(groups[i]);
}
return remaining;
}
private static void DropGroup(Map map, List<Thing> group, IntVec3 cell, int openDelay, bool instaDrop, bool leaveSlag,
bool forbid, Faction faction, int routedIndex)
{
if (forbid)
{
for (int i = 0; i < group.Count; i++)
group[i].SetForbidden(value: true, warnOnFail: false);
}
if (instaDrop)
{
if (ZonesTestHooks.RoutedGroupThrowsAt == routedIndex)
throw new InvalidOperationException("ZonesTestHooks.RoutedGroupThrowsAt");
for (int i = 0; i < group.Count; i++)
GenPlace.TryPlaceThing(group[i], cell, map, ThingPlaceMode.Near);
return;
}
var info = new ActiveTransporterInfo();
for (int i = 0; i < group.Count; i++)
{
// Vanilla ignores a failed TryAdd and loses the thing; here the group goes back to vanilla instead.
if (!info.innerContainer.TryAdd(group[i]))
throw new InvalidOperationException("could not put " + group[i].ToStringSafe() + " into a drop pod");
}
info.openDelay = openDelay;
info.leaveSlag = leaveSlag;
if (ZonesTestHooks.RoutedGroupThrowsAt == routedIndex)
throw new InvalidOperationException("ZonesTestHooks.RoutedGroupThrowsAt");
DropPodUtility.MakeDropPodAt(cell, map, info, faction);
}
/// <summary>
/// The group's things vanilla may still drop: not destroyed and not on the map in any form. A thing
/// still held by a pod that never fell is taken out first, because a thing in a container can't be
/// added to vanilla's pod.
/// </summary>
private static List<Thing> NotYetDropped(List<Thing> group, string logKey)
{
var left = new List<Thing>();
for (int i = 0; i < group.Count; i++)
{
Thing t = group[i];
try
{
if (t == null || t.Destroyed || t.SpawnedOrAnyParentSpawned)
continue;
t.holdingOwner?.Remove(t);
left.Add(t);
}
catch (Exception e)
{
ZonesLog.Once(logKey + " fallback", e);
}
}
return left;
}
}
}

View File

@ -96,20 +96,9 @@ namespace BlaxZones
/// 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) =>
TryPickCellInZone(zone, thing, DeliveryRules.PodCellOk, null, out cell);
/// <summary>
/// TryPickCellInZone with another cell rule (DeliveryRules.PodCellOk for pods, PlacementCellOk for
/// goods that appear) and cells to skip: ones already planned for an earlier group of the same
/// drop, which no falling pod marks yet. A null set skips nothing.
/// </summary>
public static bool TryPickCellInZone(Zone_Delivery zone, Thing thing, Func<Map, IntVec3, bool> cellOk,
ICollection<IntVec3> taken, out IntVec3 cell)
public static bool TryPickCellInZone(Zone_Delivery zone, Thing thing, out IntVec3 cell)
{
cell = IntVec3.Invalid;
if (cellOk == null)
return false;
Map map = zone?.MapOrNull;
if (map == null || thing == null || zone.cells.Count == 0)
return false;
@ -120,12 +109,12 @@ namespace BlaxZones
for (int i = 0; i < checks; i++)
{
IntVec3 c = cells[i];
if (!c.InBounds(map) || (taken != null && taken.Contains(c)))
if (!c.InBounds(map))
continue;
switch (Occupancy(map, c, thing))
{
case CellOccupancy.Empty:
if (cellOk(map, c))
if (DeliveryRules.PodCellOk(map, c))
{
cell = c;
return true;
@ -140,7 +129,7 @@ namespace BlaxZones
{
for (int i = 0; i < mergeable.Count; i++)
{
if (cellOk(map, mergeable[i]))
if (DeliveryRules.PodCellOk(map, mergeable[i]))
{
cell = mergeable[i];
return true;
@ -171,10 +160,7 @@ namespace BlaxZones
/// 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) => TryOverflow(top, null, out cell);
/// <summary>TryOverflow that skips cells already planned for an earlier group of the same drop (null skips nothing).</summary>
public static bool TryOverflow(Zone_Delivery top, ICollection<IntVec3> taken, out IntVec3 cell)
public static bool TryOverflow(Zone_Delivery top, out IntVec3 cell)
{
cell = IntVec3.Invalid;
if (top == null || !BlaxZonesMod.S.overflowNearZone)
@ -190,8 +176,7 @@ namespace BlaxZones
if (step <= 0)
return false;
bool Fits(IntVec3 c) =>
(taken == null || !taken.Contains(c))
&& DeliveryRules.PodCellOk(map, 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)
{
@ -237,7 +222,7 @@ namespace BlaxZones
}
/// <summary>Any delivery zone registered on the map. Cheap: one pass over ZoneManager's list.</summary>
internal static bool HasDeliveryZone(Map map)
private static bool HasDeliveryZone(Map map)
{
List<Zone> zones = map.zoneManager?.AllZones;
if (zones == null)

View File

@ -65,18 +65,5 @@ namespace BlaxZones
&& DropCellFinder.IsGoodDropSpot(cell, map, allowFogged: false, canRoofPunch: false)
&& ColonyCanReach(map, cell, PathEndMode.OnCell);
}
/// <summary>
/// Placement rule, for goods that appear instead of falling in a pod (caravan purchases from 1.1,
/// direct delivery from 1.4): standable, unfogged, the reach rule with OnCell. Roofs don't matter.
/// GenPlace still applies its own checks (items per cell, storage that refuses the thing).
/// </summary>
public static bool PlacementCellOk(Map map, IntVec3 cell)
{
return map != null && cell.InBounds(map)
&& cell.Standable(map)
&& !cell.Fogged(map)
&& ColonyCanReach(map, cell, PathEndMode.OnCell);
}
}
}

View File

@ -8,16 +8,16 @@ namespace BlaxZones
{
/// <summary>
/// Package Tab. The delivery zone tab: priority dropdown (Low to Critical), source checkboxes
/// (orbital trade, quest rewards and caravan purchases), the "Caravans camp here" checkbox and
/// ThingFilterUI.DoThingFilterConfigWindow under DeliveryFilters.Parent.
/// (orbital in 1.0), the
/// "Caravans camp here" checkbox and ThingFilterUI.DoThingFilterConfigWindow under
/// DeliveryFilters.Parent.
///
/// Layout follows ITab_Storage (ITab_Storage.cs:104-151): the same window width contracted by 10, the
/// priority button top left, the filter below. Four checkbox rows sit between them, so the window is
/// two rows taller than the stockpile tab's 480.
/// 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, 528f);
private static readonly Vector2 WinSize = new Vector2(300f, 480f);
private const float PriorityButtonWidth = 160f;
private const float PriorityButtonHeight = 29f;
@ -70,22 +70,12 @@ namespace BlaxZones
TooltipHandler.TipRegion(priorityRect, "BlaxZones_PriorityTip".Translate());
y += PriorityButtonHeight + Gap;
// Sources: orbital trade, quest rewards, caravan purchases.
// 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 rewardsRect = new Rect(0f, y, rect.width, RowHeight);
Widgets.CheckboxLabeled(rewardsRect, "BlaxZones_AcceptRewards".Translate(), ref zone.acceptRewards);
TooltipHandler.TipRegion(rewardsRect, RewardsTip());
y += RowHeight;
Rect caravanRect = new Rect(0f, y, rect.width, RowHeight);
Widgets.CheckboxLabeled(caravanRect, "BlaxZones_AcceptCaravan".Translate(), ref zone.acceptCaravan);
TooltipHandler.TipRegion(caravanRect, CaravanTip());
y += RowHeight;
Rect campRect = new Rect(0f, y, rect.width, RowHeight);
Widgets.CheckboxLabeled(campRect, "BlaxZones_CampHere".Translate(), ref zone.campHere);
TooltipHandler.TipRegion(campRect, CampTip());
@ -144,24 +134,6 @@ namespace BlaxZones
return tip;
}
/// <summary>The quest rewards checkbox's tooltip. Adds a note while "Route quest rewards" is off.</summary>
public static string RewardsTip()
{
string tip = "BlaxZones_AcceptRewardsTip".Translate();
if (!BlaxZonesMod.S.routeRewards)
tip += "\n\n" + "BlaxZones_AcceptRewardsOffTip".Translate();
return tip;
}
/// <summary>The caravan checkbox's tooltip ("Trader caravans and guests"). Adds a note while "Route caravan purchases" is off.</summary>
public static string CaravanTip()
{
string tip = "BlaxZones_AcceptCaravanTip".Translate();
if (!BlaxZonesMod.S.routeCaravan)
tip += "\n\n" + "BlaxZones_AcceptCaravanOffTip".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()
{

View File

@ -53,7 +53,6 @@ namespace BlaxZones
try
{
TickRules();
TradeShipsDropSpotHint.Check(map);
}
catch (Exception e)
{

View File

@ -1,130 +0,0 @@
using System;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxZones
{
/// <summary>
/// Package Rewards. Sets the quest reward context for QuestPart_DropPods.Notify_QuestSignalReceived
/// (QuestPart_DropPods.cs:124), only when useTradeDropSpot is true and dropSpot is invalid (:165,
/// 298-303): exactly the drops vanilla sends to the trade spot, the ones Reward_Items creates
/// (Reward_Items.cs:180). Any other part runs with no context, also when an outer one is set. The
/// finalizer restores the previous value, even on an exception.
///
/// Every finalizer here returns void: Harmony then rethrows an exception from the quest part with its
/// stack trace intact. A finalizer that returns Exception makes Harmony throw it anew, the trace then
/// starts at the patched method, and the log would blame Blax Zones for another mod's bug.
/// </summary>
[HarmonyPatch(typeof(QuestPart_DropPods), nameof(QuestPart_DropPods.Notify_QuestSignalReceived))]
public static class Patch_QuestPart_DropPods_Notify_QuestSignalReceived
{
public static void Prefix(QuestPart_DropPods __instance, out DeliveryContext __state)
{
__state = DeliveryContext.Current;
DeliveryContext next = null;
try
{
if (__instance != null && __instance.useTradeDropSpot && !__instance.dropSpot.IsValid)
next = DeliveryContext.QuestRewards;
}
catch (Exception e)
{
ZonesLog.Once("Quest reward context", e);
}
DeliveryContext.Current = next;
}
public static void Finalizer(DeliveryContext __state)
{
DeliveryContext.Current = __state;
}
}
/// <summary>
/// Package Rewards. QuestPart_GiveNearPawn.Notify_QuestSignalReceived (QuestPart_GiveNearPawn.cs:107)
/// always drops at the trade spot (:187-188), so it always runs in the quest reward context. Gifts to
/// a pawn in a world caravan go into the caravan's inventory and never reach a drop.
/// </summary>
[HarmonyPatch(typeof(QuestPart_GiveNearPawn), nameof(QuestPart_GiveNearPawn.Notify_QuestSignalReceived))]
public static class Patch_QuestPart_GiveNearPawn_Notify_QuestSignalReceived
{
public static void Prefix(out DeliveryContext __state)
{
__state = DeliveryContext.Current;
DeliveryContext.Current = DeliveryContext.QuestRewards;
}
public static void Finalizer(DeliveryContext __state)
{
DeliveryContext.Current = __state;
}
}
/// <summary>
/// Package Rewards. Signals are delivered inside SendSignal (SignalManager.cs:38-60), so a quest part
/// chained through outSignalResult (QuestPart_DropPods.cs:239-251, QuestPart_GiveNearPawn.cs:224-238)
/// would run inside the sender's context. The prefix saves and clears it; the finalizer restores it.
/// </summary>
[HarmonyPatch(typeof(SignalManager), nameof(SignalManager.SendSignal))]
public static class Patch_SignalManager_SendSignal
{
public static void Prefix(out DeliveryContext __state)
{
__state = DeliveryContext.Current;
DeliveryContext.Current = null;
}
public static void Finalizer(DeliveryContext __state)
{
DeliveryContext.Current = __state;
}
}
/// <summary>
/// Package Rewards. DropPodUtility.DropThingGroupsNear (DropPodUtility.cs:40) inside a DeliveryContext:
/// plans every group first (DeliveryRouter.PlanGroups), drops the qualifying ones as their own pods in
/// delivery zones (DeliveryRouter.DropPlannedGroups), then assigns a new list holding the rest, so
/// vanilla drops only those and the caller's list is never changed. DropThingsNear passes its shared
/// static list here and clears it afterwards (DropPodUtility.cs:10, 27-38); Zones never calls
/// DropThingsNear. Without a context (raids, ransom, lent colonists, edge and center drops) nothing
/// changes. A failed plan leaves the caller's list to vanilla.
/// </summary>
[HarmonyPatch(typeof(DropPodUtility), nameof(DropPodUtility.DropThingGroupsNear))]
public static class Patch_DropPodUtility_DropThingGroupsNear
{
public static void Prefix(Map map, ref List<List<Thing>> thingsGroups, int openDelay, bool instaDrop, bool leaveSlag, bool forbid, Faction faction)
{
DeliveryContext context = DeliveryContext.Current;
if (context == null)
return;
List<DeliveryRouter.GroupPlan> plans;
try
{
if (!context.Enabled)
return;
plans = DeliveryRouter.PlanGroups(map, thingsGroups, context.Source);
if (plans.Count == 0)
return;
}
catch (Exception e)
{
ZonesLog.Once(context.LogKey, e);
return;
}
try
{
List<List<Thing>> remaining = DeliveryRouter.DropPlannedGroups(map, thingsGroups, plans, openDelay, instaDrop, leaveSlag,
forbid, faction, context.LogKey);
if (remaining != null)
thingsGroups = remaining;
}
catch (Exception e)
{
// DropPlannedGroups catches per group; this only guards its list handling.
ZonesLog.Once(context.LogKey, e);
}
}
}
}

View File

@ -219,11 +219,8 @@ namespace BlaxZones
}
}
/// <summary>
/// Puts the original list object, or its contents, back, even when saving threw. Returns void, so
/// Harmony rethrows a saving exception with its stack trace intact.
/// </summary>
public static void Finalizer(ZoneManager __instance, ZoneSaveState __state)
/// <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)
{
@ -236,6 +233,7 @@ namespace BlaxZones
ZonesLog.Once("Zone save restore", e);
}
}
return __exception;
}
}
@ -263,8 +261,7 @@ namespace BlaxZones
}
}
/// <summary>Restores the load flag. Returns void, so Harmony rethrows vanilla's exception with its stack trace intact.</summary>
public static void Finalizer(bool __state)
public static Exception Finalizer(bool __state, Exception __exception)
{
try
{
@ -274,6 +271,7 @@ namespace BlaxZones
{
ZonesLog.Once("Clearing the zone load flag", e);
}
return __exception;
}
}
}

View File

@ -30,12 +30,6 @@ namespace BlaxZones
/// <summary>Orbital trade purchases, sale silver and ZonesApi callers (Blax Slaves payouts) may land here.</summary>
public bool acceptOrbital = true;
/// <summary>Item rewards from quests may land here (1.1).</summary>
public bool acceptRewards = true;
/// <summary>Goods bought from trader caravans and Hospitality guests may appear here (1.1).</summary>
public bool acceptCaravan = true;
/// <summary>Trader caravans and tribute collectors camp next to this zone.</summary>
public bool campHere;
@ -59,8 +53,6 @@ namespace BlaxZones
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 acceptRewards, "acceptRewards", true);
Scribe_Values.Look(ref acceptCaravan, "acceptCaravan", true);
Scribe_Values.Look(ref campHere, "campHere", false);
if (Scribe.mode == LoadSaveMode.PostLoadInit)
{
@ -77,10 +69,6 @@ namespace BlaxZones
{
case DeliverySource.Orbital:
return acceptOrbital;
case DeliverySource.Rewards:
return acceptRewards;
case DeliverySource.Caravan:
return acceptCaravan;
default:
return false;
}
@ -104,8 +92,6 @@ namespace BlaxZones
filter.CopyAllowancesFrom(other.filter);
priority = other.priority;
acceptOrbital = other.acceptOrbital;
acceptRewards = other.acceptRewards;
acceptCaravan = other.acceptCaravan;
campHere = other.campHere;
}

View File

@ -49,17 +49,10 @@ namespace BlaxZones
/// <summary>ZoneStore.AllZonesRef returns null, as when a game update renames ZoneManager.allZones.</summary>
public static bool AllZonesUnbound;
/// <summary>
/// Routing a quest reward group throws at this routed group of one drop (0 the first, -1 never), after
/// its things went into the pod's container and before the pod falls, to test the fallback.
/// </summary>
public static int RoutedGroupThrowsAt = -1;
public static void Reset()
{
RouterThrows = false;
AllZonesUnbound = false;
RoutedGroupThrowsAt = -1;
}
}
}

View File

@ -1,464 +0,0 @@
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 Caravan. Design: 1.1 "Caravan purchases appear in the zone" > Tests.
/// Tests: [BlaxTest("caravan: 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 (the caravan checkbox persists in TabTests and StoreTests).
///
/// Each test forces a trader caravan, puts a known stack on one of its pack animals and buys it through the
/// trader's Pawn_TraderTracker, as Tradeable.ResolveTrade does (Tradeable.cs:472-478). The caravan leaves
/// after the test. Each test turns the caravan checkbox off on delivery zones other tests left on the map.
/// </summary>
public static class CaravanTests
{
private const string HarmonyId = "blax.zones.tests.caravan";
private const string HospitalityId = "Orion.Hospitality";
/// <summary>How far from the carrier vanilla's Near placement puts a stack on open ground, with some slack.</summary>
private const int NextToCarrier = 3;
private static Harmony harmony;
private static Harmony H => harmony ??= new Harmony(HarmonyId);
/// <summary>Texts of messages sent since ObserveMessages().</summary>
private static readonly List<string> messages = new List<string>();
// ---- into the zone --------------------------------------------------------------------
[BlaxTest("caravan: an item bought from a trader caravan appears in the zone and is in the lord's extraForbiddenThings")]
public static void ItemAppearsInZone()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Caravan);
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3));
Lord lord = Fixtures.TraderCaravan();
Pawn trader = Fixtures.TraderOf(lord);
Pawn carrier = Fixtures.CarrierOf(lord);
Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30);
T.Check(trader.trader.Goods.Contains(steel), "the steel on the carrier is not one of the trader's goods");
trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, Fixtures.Negotiator());
T.Check(steel.Spawned, "the steel is not on the map; it is in " + steel.ParentHolder);
T.Check(zone.ContainsCell(steel.Position), "the steel lies at " + steel.Position + ", not in the zone");
T.Equal(30, steel.stackCount, "steel count");
T.Check(lord.extraForbiddenThings.Contains(steel), "the steel is not in the lord's extraForbiddenThings");
T.Check(steel.Faction == null || steel.Faction == Faction.OfPlayer, "the steel belongs to " + steel.Faction);
}
[BlaxTest("caravan: a fully roofed zone still receives caravan goods")]
public static void RoofedZoneReceives()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Caravan);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
Fixtures.Roof(area);
T.Check(area.Cells.All(c => c.Roofed(Fixtures.Map)), "the zone is not fully roofed");
Lord lord = Fixtures.TraderCaravan();
Pawn trader = Fixtures.TraderOf(lord);
Thing medicine = Fixtures.GoodsOnCarrier(Fixtures.CarrierOf(lord), ThingDefOf.MedicineIndustrial, 5);
trader.trader.GiveSoldThingToPlayer(medicine, medicine.stackCount, Fixtures.Negotiator());
T.Check(medicine.Spawned && zone.ContainsCell(medicine.Position), "the medicine lies at " + medicine.PositionHeld + ", not in the roofed zone");
}
[BlaxTest("caravan: medicine goes to a medicine-only zone at Important, steel to the general zone")]
public static void FilterAndPriority()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Caravan);
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);
Lord lord = Fixtures.TraderCaravan();
Pawn trader = Fixtures.TraderOf(lord);
Pawn carrier = Fixtures.CarrierOf(lord);
Thing medicine = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.MedicineIndustrial, 5);
Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30);
Pawn negotiator = Fixtures.Negotiator();
trader.trader.GiveSoldThingToPlayer(medicine, medicine.stackCount, negotiator);
trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, negotiator);
T.Check(medicine.Spawned && medical.ContainsCell(medicine.Position), "medicine lies at " + medicine.PositionHeld + ", not in the medicine zone");
T.Check(steel.Spawned && general.ContainsCell(steel.Position), "steel lies at " + steel.PositionHeld + ", not in the general zone");
}
[BlaxTest("caravan: with every zone cell holding another item the goods land next to the zone and the message says so; with overflow off they land next to the carrier")]
public static void FullZoneLandsNextToIt()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Caravan);
Fixtures.Settings.overflowNearZone = true;
CellRect area = Fixtures.TestArea(2, 2);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
foreach (IntVec3 c in area)
GenSpawn.Spawn(Fixtures.Stack(ThingDefOf.WoodLog, 10), c, Fixtures.Map);
Lord lord = Fixtures.TraderCaravan();
Pawn trader = Fixtures.TraderOf(lord);
Pawn carrier = Fixtures.CarrierOf(lord);
Pawn negotiator = Fixtures.Negotiator();
Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30);
string nextTo = CaravanDeliveries.MessageText(new[] { zone }, nextToZone: true);
T.Check(nextTo.Contains(zone.label) && nextTo != CaravanDeliveries.MessageText(new[] { zone }),
"the next-to message '" + nextTo + "' doesn't name " + zone.label + " or reads like the in-zone one");
ObserveMessages();
trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, negotiator);
T.Check(steel.Spawned, "the steel is not on the map");
T.Check(!zone.ContainsCell(steel.Position), "the steel lies on a full zone cell " + steel.Position);
int d = Fixtures.DistanceToZone(zone, steel.Position);
T.Check(d <= 2, "the steel lies " + d + " cells from the zone, at " + steel.Position);
T.Check(Fixtures.Chebyshev(steel.Position, carrier.Position) > NextToCarrier, "the steel lies next to the carrier, not next to the zone");
T.Equal(1, messages.Count(m => m == nextTo), "messages saying the goods lie next to the zone (all: " + string.Join(" | ", messages) + ")");
T.Equal(1, messages.Count, "messages after one purchase");
// Overflow off: the full zone sends the next purchase to vanilla's spot, with no message.
Fixtures.Settings.overflowNearZone = false;
Thing cloth = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Cloth, 20);
trader.trader.GiveSoldThingToPlayer(cloth, cloth.stackCount, negotiator);
NextToCarrierCheck(cloth, carrier, lord);
T.Equal(1, messages.Count, "messages after a purchase that went to the carrier");
}
[BlaxTest("caravan: silver from a sale too big for the first zone splits over two zones, and the message counts both")]
public static void SplitPayoutNamesBothZones()
{
Map map = Fixtures.Map;
Fixtures.OnlyThisTestsZones(DeliverySource.Caravan);
CellRect area = Fixtures.TestArea(5, 1);
// A: one cell at Important takes one full stack of silver; B gets the rest.
Zone_Delivery a = Fixtures.DeliveryZone(new CellRect(area.minX, area.minZ, 1, 1), priority: StoragePriority.Important);
Zone_Delivery b = Fixtures.DeliveryZone(new CellRect(area.minX + 2, area.minZ, 3, 1));
Lord lord = Fixtures.TraderCaravan();
Pawn trader = Fixtures.TraderOf(lord);
Pawn carrier = Fixtures.CarrierOf(lord);
int total = ThingDefOf.Silver.stackLimit * 2 + 200;
// Sale silver comes through the same call as a purchase (Tradeable.cs:472-478); one stack over the limit, as a big sale pays.
Thing silver = ThingMaker.MakeThing(ThingDefOf.Silver);
silver.stackCount = total;
Fixtures.Track(silver);
T.Check(carrier.inventory.innerContainer.TryAdd(silver, canMergeWithExistingStacks: false), "could not put the silver on " + carrier.LabelShort);
ObserveMessages();
trader.trader.GiveSoldThingToPlayer(silver, silver.stackCount, Fixtures.Negotiator());
List<Thing> inA = map.listerThings.ThingsOfDef(ThingDefOf.Silver).Where(t => t.Spawned && a.ContainsCell(t.Position)).ToList();
List<Thing> inB = map.listerThings.ThingsOfDef(ThingDefOf.Silver).Where(t => t.Spawned && b.ContainsCell(t.Position)).ToList();
foreach (Thing t in inA.Concat(inB))
Fixtures.Track(t);
T.Equal(ThingDefOf.Silver.stackLimit, inA.Sum(t => t.stackCount), "silver in zone A");
T.Equal(total - ThingDefOf.Silver.stackLimit, inB.Sum(t => t.stackCount), "silver in zone B");
string expected = CaravanDeliveries.MessageText(new[] { a, b });
T.Equal(1, messages.Count(m => m == expected), "messages naming 2 delivery zones (all: " + string.Join(" | ", messages) + ")");
T.Equal(1, messages.Count, "messages after one payout");
}
// ---- vanilla paths ---------------------------------------------------------------------
[BlaxTest("caravan: with no zones the goods land next to the carrier")]
public static void NoZonesNextToCarrier()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Caravan);
Lord lord = Fixtures.TraderCaravan();
Pawn trader = Fixtures.TraderOf(lord);
Pawn carrier = Fixtures.CarrierOf(lord);
Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30);
trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, Fixtures.Negotiator());
NextToCarrierCheck(steel, carrier, lord);
}
[BlaxTest("caravan: with Route caravan purchases off or the zone's checkbox off the goods land next to the carrier")]
public static void SwitchesOffNextToCarrier()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Caravan);
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3));
Lord lord = Fixtures.TraderCaravan();
Pawn trader = Fixtures.TraderOf(lord);
Pawn carrier = Fixtures.CarrierOf(lord);
Pawn negotiator = Fixtures.Negotiator();
Fixtures.Settings.routeCaravan = false;
Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30);
trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, negotiator);
NextToCarrierCheck(steel, carrier, lord);
Fixtures.Settings.routeCaravan = true;
zone.acceptCaravan = false;
Thing wood = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.WoodLog, 30);
trader.trader.GiveSoldThingToPlayer(wood, wood.stackCount, negotiator);
NextToCarrierCheck(wood, carrier, lord);
}
[BlaxTest("caravan: a bought animal doesn't move")]
public static void AnimalDoesNotMove()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Caravan);
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3));
Lord lord = Fixtures.TraderCaravan();
Pawn trader = Fixtures.TraderOf(lord);
Pawn animal = lord.ownedPawns.Where(p => p.GetTraderCaravanRole() == TraderCaravanRole.Chattel && p.RaceProps.Animal)
.OrderBy(p => p.thingIDNumber).FirstOrDefault();
if (animal == null)
{
// No animal for sale in this caravan: a chicken of the caravan's faction joins it as chattel.
IntVec3 near = CellFinder.RandomClosewalkCellNear(trader.Position, Fixtures.Map, 3);
animal = Fixtures.Spawn(Fixtures.Generate(DefDatabase<PawnKindDef>.AllDefsListForReading.First(k => k.race == ThingDefOf.Chicken), trader.Faction), near);
lord.AddPawn(animal);
T.Equal(TraderCaravanRole.Chattel, animal.GetTraderCaravanRole(), "the chicken's caravan role");
}
T.Check(trader.trader.Goods.Contains(animal), "the animal is not one of the trader's goods");
IntVec3 before = animal.Position;
trader.trader.GiveSoldThingToPlayer(animal, 1, Fixtures.Negotiator());
T.Check(animal.Spawned, "the bought animal left the map");
T.Equal(before, animal.Position, "the bought animal's cell");
T.Check(!zone.ContainsCell(animal.Position), "the bought animal stands in the zone");
}
[BlaxTest("caravan: when the router throws the item lands next to the carrier, nothing is destroyed, and Zones logs one error")]
public static void RouterThrowsFallsBack()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Caravan);
Fixtures.DeliveryZone(Fixtures.TestArea(3, 3));
Lord lord = Fixtures.TraderCaravan();
Pawn trader = Fixtures.TraderOf(lord);
Pawn carrier = Fixtures.CarrierOf(lord);
Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30);
ZonesLog.ResetOnce();
Fixtures.OnCleanup(ZonesLog.ResetOnce);
ZonesTestHooks.RouterThrows = true;
T.ExpectErrors("[Blax Zones] Caravan delivery failed", 1);
trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, Fixtures.Negotiator());
T.Check(!steel.Destroyed, "the steel was destroyed");
T.Equal(30, steel.stackCount, "steel count");
NextToCarrierCheck(steel, carrier, lord);
}
// ---- one message per trade -----------------------------------------------------------
[BlaxTest("caravan: buying 3 stacks in one TradeDeal.TryExecute posts exactly 1 message that names the zone")]
public static void OneMessagePerTrade()
{
Map map = Fixtures.Map;
Fixtures.OnlyThisTestsZones(DeliverySource.Caravan);
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3));
Lord lord = Fixtures.TraderCaravan();
Pawn trader = Fixtures.TraderOf(lord);
Pawn carrier = Fixtures.CarrierOf(lord);
var bought = new List<Thing>
{
Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 20),
Fixtures.GoodsOnCarrier(carrier, ThingDefOf.MedicineHerbal, 3),
Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Cloth, 20),
};
ColonySilverNear(trader, 1500);
Pawn negotiator = Fixtures.Negotiator();
TradeSession.SetupWith(trader, negotiator, giftMode: false);
Fixtures.OnCleanup(() =>
{
TradeSession.Close();
TradeSession.deal = null;
});
foreach (Thing t in bought)
{
Tradeable tradeable = TradeSession.deal.AllTradeables.FirstOrDefault(x => x.thingsTrader.Contains(t));
T.NotNull(tradeable, "a tradeable for " + t.def.defName);
tradeable.ForceToSource(t.stackCount);
T.Equal(TradeAction.PlayerBuys, tradeable.ActionToDo, t.def.defName + " trade action");
}
ObserveMessages();
T.Check(TradeSession.deal.TryExecute(out bool traded), "TradeDeal.TryExecute refused the trade (the colony's silver: " +
TradeSession.deal.CurrencyTradeable?.CountHeldBy(Transactor.Colony) + ")");
T.Check(traded, "TryExecute traded nothing");
int inZone = map.listerThings.AllThings.Count(t => t.Spawned && zone.ContainsCell(t.Position)
&& bought.Any(b => b.def == t.def));
T.Check(inZone >= 3, "stacks of the bought defs in the zone: " + inZone + ", expected at least 3");
string expected = CaravanDeliveries.MessageText(new[] { zone });
T.Check(expected.Contains(zone.label), "the message text '" + expected + "' doesn't name " + zone.label);
T.Equal(1, messages.Count(m => m == expected), "messages naming the zone (all: " + string.Join(" | ", messages) + ")");
T.Equal(1, messages.Count(m => m.Contains(zone.label)), "messages mentioning " + zone.label);
T.Check(CaravanDeliveries.Current == null, "a caravan message batch is still open after the trade");
}
[BlaxTest("caravan: a purchase outside a trade sends its own message, and none with Message when goods arrive off")]
public static void MessageOutsideTrade()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Caravan);
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3));
Lord lord = Fixtures.TraderCaravan();
Pawn trader = Fixtures.TraderOf(lord);
Pawn carrier = Fixtures.CarrierOf(lord);
Pawn negotiator = Fixtures.Negotiator();
string expected = CaravanDeliveries.MessageText(new[] { zone });
ObserveMessages();
Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30);
trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, negotiator);
T.Equal(1, messages.Count(m => m == expected), "messages after one purchase outside a trade");
Fixtures.Settings.caravanMessage = false;
Thing wood = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.WoodLog, 30);
trader.trader.GiveSoldThingToPlayer(wood, wood.stackCount, negotiator);
T.Check(wood.Spawned && zone.ContainsCell(wood.Position), "with the message off the wood lies at " + wood.PositionHeld + ", not in the zone");
T.Equal(1, messages.Count(m => m == expected), "messages after a purchase with the message setting off");
}
// ---- Hospitality ---------------------------------------------------------------------------
[BlaxTest("caravan: with Hospitality a purchase from a guest lands in the zone")]
public static void HospitalityGuestPurchase()
{
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.OnlyThisTestsZones(DeliverySource.Caravan);
Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3));
var parms = new IncidentParms { target = map, forced = true, points = 100f };
var arrive = (IncidentWorker_PawnsArrive)worker;
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 guests");
Lord lord = Fixtures.Arrive(worker, parms, "Hospitality guest group");
T.Check(lord.LordJob.GetType().Namespace == "Hospitality", "guest lord job is " + lord.LordJob.GetType().FullName);
Pawn guest = lord.ownedPawns.Where(p => p.RaceProps.Humanlike).OrderBy(p => p.thingIDNumber).FirstOrDefault();
T.NotNull(guest, "a humanlike guest");
if (guest.trader == null)
{
MethodInfo convert = AccessTools.Method(AccessTools.TypeByName("Hospitality.Utilities.GuestUtility") ?? AccessTools.TypeByName("Hospitality.GuestUtility"),
"ConvertToTrader");
T.NotNull(convert, "Hospitality's GuestUtility.ConvertToTrader");
convert.Invoke(null, new object[] { guest, true });
}
T.NotNull(guest.trader, "the guest's trader tracker");
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 30);
T.Check(guest.inventory.innerContainer.TryAdd(steel, canMergeWithExistingStacks: false), "could not put steel into the guest's inventory");
guest.GiveSoldThingToPlayer(steel, steel.stackCount, Fixtures.Negotiator());
T.Check(steel.Spawned && zone.ContainsCell(steel.Position), "the steel bought from the guest lies at " + steel.PositionHeld + ", not in the zone");
}
// ---- patch ---------------------------------------------------------------------------------
[BlaxTest("caravan: the transpiler replaced exactly one TryPlaceThing call and logged no call-count error")]
public static void TranspilerCount()
{
T.Equal(1, Patch_Pawn_TraderTracker_GiveSoldThingToPlayer.LastCallCount, "Patch_Pawn_TraderTracker_GiveSoldThingToPlayer.LastCallCount");
// Errors only: the runner logs test names as messages, and a name may contain the phrase.
bool logged = Log.Messages.Any(m => m.type == LogMessageType.Error && m.text != null && m.text.Contains("[Blax Zones]") && m.text.Contains("unexpected call count"));
T.Check(!logged, "the log has an 'unexpected call count' error");
MethodInfo give = AccessTools.Method(typeof(Pawn_TraderTracker), nameof(Pawn_TraderTracker.GiveSoldThingToPlayer));
Patches info = Harmony.GetPatchInfo(give);
T.Check(info != null && info.Transpilers.Any(p => p.owner == BlaxZonesStartup.HarmonyId), "no Blax Zones transpiler on Pawn_TraderTracker.GiveSoldThingToPlayer");
T.Check(Patch_Pawn_TraderTracker_GiveSoldThingToPlayer.TryPlaceThing != null, "the 8-argument GenPlace.TryPlaceThing overload is gone");
Patches place = Harmony.GetPatchInfo(Patch_Pawn_TraderTracker_GiveSoldThingToPlayer.TryPlaceThing);
bool ours = place != null && place.Prefixes.Concat(place.Postfixes).Concat(place.Transpilers).Concat(place.Finalizers)
.Any(p => p.owner == BlaxZonesStartup.HarmonyId);
T.Check(!ours, "Blax Zones patches GenPlace.TryPlaceThing");
}
// ---- helpers -------------------------------------------------------------------------------
/// <summary>Vanilla's spot: on the map, next to the carrier, in no delivery zone, in the lord's extraForbiddenThings.</summary>
private static void NextToCarrierCheck(Thing thing, Pawn carrier, Lord lord)
{
T.Check(thing.Spawned, thing.def.defName + " is not on the map; it is in " + thing.ParentHolder);
int d = Fixtures.Chebyshev(thing.Position, carrier.Position);
T.Check(d <= NextToCarrier, thing.def.defName + " lies " + d + " cells from the carrier, at " + thing.Position);
T.Check(!Fixtures.InDeliveryZone(thing.Position), thing.def.defName + " lies in a delivery zone at " + thing.Position);
T.Check(lord.extraForbiddenThings.Contains(thing), thing.def.defName + " is not in the lord's extraForbiddenThings");
}
/// <summary>Silver stacks the colony can pay with: spawned next to the trader on home-area cells (restored after the test).</summary>
private static void ColonySilverNear(Pawn trader, int total)
{
Map map = Fixtures.Map;
Area home = map.areaManager.Home;
int left = total;
int tries = 0;
while (left > 0 && tries++ < 50)
{
IntVec3 c = CellFinder.RandomClosewalkCellNear(trader.Position, map, 4, x => x.GetFirstItem(map) == null && !x.Fogged(map));
if (!c.IsValid || c.GetFirstItem(map) != null)
continue;
int n = Math.Min(left, ThingDefOf.Silver.stackLimit);
Thing silver = Fixtures.Stack(ThingDefOf.Silver, n);
GenSpawn.Spawn(silver, c, map);
if (!home[c])
{
home[c] = true;
IntVec3 cell = c;
Fixtures.OnCleanup(() => home[cell] = false);
}
left -= n;
}
T.Check(left <= 0, "could not lay out " + total + " silver next to the trader");
}
/// <summary>Records the text of every Messages.Message(string, LookTargets, MessageTypeDef, bool) call until the test ends.</summary>
private static void ObserveMessages()
{
messages.Clear();
MethodInfo target = AccessTools.Method(typeof(Messages), nameof(Messages.Message),
new[] { typeof(string), typeof(LookTargets), typeof(MessageTypeDef), typeof(bool) });
T.NotNull(target, "Messages.Message(string, LookTargets, MessageTypeDef, bool)");
MethodInfo prefix = AccessTools.Method(typeof(CaravanTests), nameof(OnMessage));
H.Patch(target, prefix: new HarmonyMethod(prefix));
Fixtures.OnCleanup(() => H.Unpatch(target, prefix));
}
private static void OnMessage(string text)
{
if (text != null)
messages.Add(text);
}
/// <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

@ -138,8 +138,6 @@ namespace BlaxZonesTests
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.acceptRewards, "rewards checkbox off on a new zone");
T.Check(zone.acceptCaravan, "caravan checkbox off on a new zone");
T.Check(!zone.campHere, "camp checkbox on on a new zone");
}

View File

@ -16,7 +16,7 @@ namespace BlaxZonesTests
/// 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 partial class Fixtures
public static class Fixtures
{
private static readonly List<Pawn> made = new List<Pawn>();
private static readonly HashSet<Pawn> kept = new HashSet<Pawn>();
@ -317,7 +317,7 @@ namespace BlaxZonesTests
/// 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, bool rewards = true, bool caravan = true)
bool orbital = true, bool camp = false)
{
var zone = new Zone_Delivery(Map.zoneManager);
Map.zoneManager.RegisterZone(zone);
@ -328,8 +328,6 @@ namespace BlaxZonesTests
zone.filter.CopyAllowancesFrom(filter);
zone.priority = priority;
zone.acceptOrbital = orbital;
zone.acceptRewards = rewards;
zone.acceptCaravan = caravan;
zone.campHere = camp;
return zone;
}

View File

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

View File

@ -3,10 +3,8 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using BlaxZones;
using RimWorld;
using RimWorld.Planet;
using UnityEngine;
using Verse;
@ -99,15 +97,6 @@ namespace BlaxZonesTests
/// <summary>"Could not resolve reference" warnings logged while the phase-3 save loaded.</summary>
public static int Phase3ResolveWarnings => TestRunner.ResolveWarnings;
/// <summary>"Could not resolve reference" warnings (one line each) logged while the phase-1 save loaded for phase 2.</summary>
public static List<string> Phase2ResolveWarnings => TestRunner.Phase2Warnings();
/// <summary>
/// The warning names a pawn vanilla's TaleData_Pawn.GenerateRandom made for a book or tale and never
/// saved (a vanilla leak, see TestRunner.vanillaTalePawns), not anything Blax Zones saved.
/// </summary>
public static bool NamesVanillaTalePawn(string warning) => TestRunner.NamesVanillaTalePawn(warning);
private static string Show(object o) => o == null ? "null" : o.ToString();
}
@ -131,9 +120,6 @@ namespace BlaxZonesTests
/// <summary>Where errors logged during the phase-3 load are filed.</summary>
public const string Phase3LoadTag = "(phase 3 load)";
/// <summary>Where errors logged while the phase-1 save loads for phase 2 are filed.</summary>
public const string Phase2LoadTag = "(phase 2 load)";
private class LogEntry
{
public string where;
@ -149,8 +135,6 @@ namespace BlaxZonesTests
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 readonly List<string> phase2Warnings = new List<string>();
private static readonly HashSet<string> danglingSeen = new HashSet<string>();
private static bool hooked;
private int settleFrames;
@ -189,15 +173,11 @@ namespace BlaxZonesTests
try { T.Carry[kv.Key] = kv.Value(); }
catch (Exception e) { Note("carry " + kv.Key + " failed: " + e.Message); }
}
NoteDanglingRelations();
GameDataSaveLoader.SaveGame(SaveName);
lock (errors) phase2Warnings.Clear();
currentTest = Phase2LoadTag;
GameDataSaveLoader.LoadGame(SaveName);
}
catch (Exception e)
{
currentTest = null;
Record("FAIL", "save and reload", e.ToString());
Finish();
}
@ -205,9 +185,7 @@ namespace BlaxZonesTests
else if (stage == 1 && loadsSeen >= 1)
{
stage = 2;
currentTest = null;
Line("STAGE phase 2 (after reload)");
Note("phase 2 load: " + Phase2Warnings().Count + " 'Could not resolve reference' warning(s)");
RunPhase(2);
Line("STAGE phase 3 (component class removed from the save)");
try
@ -261,7 +239,6 @@ namespace BlaxZonesTests
try { File.Delete(ResultPath); } catch { }
StartupLog = Log.Messages.ToList();
HookLog();
HookPawnWatchers();
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);
@ -277,13 +254,8 @@ namespace BlaxZonesTests
{
if (type == LogType.Warning)
{
if (text != null && text.Contains("Could not resolve reference"))
{
if (currentTest == Phase3LoadTag)
lock (errors) resolveWarnings++;
else if (currentTest == Phase2LoadTag)
lock (errors) phase2Warnings.Add(OneLine(text));
}
if (currentTest == Phase3LoadTag && text != null && text.Contains("Could not resolve reference"))
lock (errors) resolveWarnings++;
return;
}
if (type != LogType.Error && type != LogType.Exception) return;
@ -331,127 +303,6 @@ namespace BlaxZonesTests
lock (errors) return errors.Where(e => e.where == Phase3LoadTag).Select(e => e.text).ToList();
}
internal static List<string> Phase2Warnings()
{
lock (errors) return phase2Warnings.ToList();
}
/// <summary>
/// Notes every pawn relation, new since the last check, whose other pawn no save holds (discarded,
/// or on no map, in no container and not a world pawn). Each one becomes a "Could not resolve
/// reference" warning when the save loads. Runs after every test, so the note sits right above the
/// result line of the test that left it, and once more right before the phase-1 save. Pawns vanilla
/// made for books and tales are left out here (see vanillaTalePawns); the reload test counts them.
/// </summary>
private static void NoteDanglingRelations()
{
try
{
var all = new HashSet<Pawn>(PawnsFinder.All_AliveOrDead);
foreach (Pawn p in all.ToList())
{
if (p?.relations == null)
continue;
foreach (DirectPawnRelation r in p.relations.DirectRelations)
{
Pawn o = r.otherPawn;
if (o != null && !o.Discarded && all.Contains(o))
continue;
if (!danglingSeen.Add(p.ThingID + ">" + (o?.ThingID ?? "null")))
continue;
// Vanilla's own leak; the phase-2 reload test counts these.
if (o != null && IsVanillaTalePawn(o.ThingID))
continue;
Note("dangling relation: " + p.ThingID + " (" + p.LabelShort + ", " + (p.Faction?.GetUniqueLoadID() ?? "no faction") + ") " +
r.def.defName + " -> " + Describe(o));
}
}
}
catch (Exception e)
{
Note("relation check threw: " + OneLine(e.Message));
}
}
private static string Describe(Pawn o)
{
if (o == null)
return "null";
string removed;
lock (worldRemovals) worldRemovals.TryGetValue(o.ThingID, out removed);
return o.ThingID + " (" + o.LabelShort + ", kind " + o.kindDef?.defName + ", " + (o.Faction?.GetUniqueLoadID() ?? "no faction") +
", destroyed " + o.Destroyed + ", discarded " + o.Discarded + ", dead " + o.Dead + ", spawned " + o.Spawned +
", world pawn " + o.IsWorldPawn() + ", held by " + (o.ParentHolder?.ToString() ?? "nothing") + ")" +
(IsVanillaTalePawn(o.ThingID) ? "; vanilla: made by TaleData_Pawn.GenerateRandom and never saved" : "") +
(removed != null ? "; left the world pawns from: " + removed : "");
}
/// <summary>Who took each pawn out of WorldPawns this run (ThingID to the calling frames), for the dangling-relation notes.</summary>
private static readonly Dictionary<string, string> worldRemovals = new Dictionary<string, string>();
private static bool pawnWatchersHooked;
/// <summary>
/// Pawns vanilla's TaleData_Pawn.GenerateRandom made this run (ThingIDs). It generates a pawn for a
/// book's text (Book.GenerateBook, Book.cs:235, also for every book in a trader's stock), a unique
/// weapon's name or a tale, keeps only its TaleData and never saves or discards the pawn
/// (TaleData_Pawn.cs:110-115). PawnGenerator may hand it a world pawn (it leaves WorldPawns) or a new
/// one with relations to existing pawns, colonists included. Either way those relations point at a
/// pawn no save holds, and every trader caravan in the suite can make some.
/// </summary>
private static readonly HashSet<string> vanillaTalePawns = new HashSet<string>();
private static readonly Regex ResolveWarningId = new Regex(@"loadID Thing_(\S+) of type Verse\.Pawn");
private static bool IsVanillaTalePawn(string thingId)
{
lock (vanillaTalePawns) return thingId != null && vanillaTalePawns.Contains(thingId);
}
/// <summary>The "Could not resolve reference" warning names a pawn vanilla's TaleData_Pawn.GenerateRandom made and never saved.</summary>
internal static bool NamesVanillaTalePawn(string warning)
{
Match m = warning == null ? null : ResolveWarningId.Match(warning);
return m != null && m.Success && IsVanillaTalePawn(m.Groups[1].Value);
}
/// <summary>Installs the WorldPawns.RemovePawn and TaleData_Pawn.GenerateRandom watchers once, at startup (QuickTestMap), before the world exists.</summary>
internal static void HookPawnWatchers()
{
if (pawnWatchersHooked)
return;
pawnWatchersHooked = true;
try
{
var harmony = new HarmonyLib.Harmony("blax.zones.tests.harness");
harmony.Patch(HarmonyLib.AccessTools.Method(typeof(WorldPawns), nameof(WorldPawns.RemovePawn)),
postfix: new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(TestRunner), nameof(OnWorldPawnRemoved))));
harmony.Patch(HarmonyLib.AccessTools.Method(typeof(TaleData_Pawn), nameof(TaleData_Pawn.GenerateRandom)),
postfix: new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(TestRunner), nameof(OnTalePawnGenerated))));
}
catch (Exception e)
{
Note("could not watch WorldPawns.RemovePawn or TaleData_Pawn.GenerateRandom: " + OneLine(e.Message));
}
}
private static void OnTalePawnGenerated(TaleData_Pawn __result)
{
string id = __result?.pawn?.ThingID;
if (id != null)
lock (vanillaTalePawns) vanillaTalePawns.Add(id);
}
private static void OnWorldPawnRemoved(Pawn p)
{
if (p == null)
return;
var frames = new System.Diagnostics.StackTrace(2, false).GetFrames() ?? new System.Diagnostics.StackFrame[0];
string where = string.Join(" < ", frames.Take(8).Select(f => f.GetMethod()).Where(m => m != null)
.Select(m => m.DeclaringType?.Name + "." + m.Name));
lock (worldRemovals) worldRemovals[p.ThingID] = where;
}
private static void RunPhase(int phase)
{
var tests = typeof(TestRunner).Assembly.GetTypes()
@ -499,7 +350,6 @@ namespace BlaxZonesTests
try { Fixtures.Cleanup(); } catch (Exception e) { Note("cleanup threw: " + OneLine(e.Message)); }
ZonesTestHooks.Reset();
Compat.SimulatedActive.Clear();
NoteDanglingRelations();
}
List<LogEntry> newErrors;

View File

@ -269,8 +269,7 @@ namespace BlaxZonesTests
public static void TranspilerCount()
{
T.Equal(1, Patch_TradeShip_GiveSoldThingToPlayer.LastCallCount, "Patch_TradeShip_GiveSoldThingToPlayer.LastCallCount");
// Errors only: the runner logs test names as messages, and a name may contain the phrase.
bool logged = Log.Messages.Any(m => m.type == LogMessageType.Error && m.text != null && m.text.Contains("[Blax Zones]") && m.text.Contains("unexpected call count"));
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));

View File

@ -24,8 +24,6 @@ namespace BlaxZonesTests
new Harmony("blax.zones.tests.quicktestmap").Patch(
AccessTools.Method(typeof(Root_Play), nameof(Root_Play.SetupForQuickTestPlay)),
postfix: new HarmonyMethod(typeof(QuickTestMap), nameof(Postfix)));
// Before the world and map are made, so every pawn vanilla makes for a book or tale is known.
TestRunner.HookPawnWatchers();
}
public static void Postfix()

View File

@ -1,676 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxZones;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxZonesTests
{
/// <summary>
/// Package Rewards. Design: 1.1 "Quest rewards land in the zone" > Tests.
/// Tests: [BlaxTest("rewards: 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 (the rewards checkbox persists in TabTests and StoreTests).
///
/// Parts are fired directly with Notify_QuestSignalReceived on a raw quest that is never in the quest
/// manager. TradeDropSpot is fixed far from the test's zones by a test-only prefix, so a pod at the
/// vanilla spot can't be mistaken for a routed one. Each test turns the rewards checkbox off on delivery
/// zones other tests left on the map. Pods and letters are removed after the test; nothing ticks.
/// </summary>
public static class RewardTests
{
private const string HarmonyId = "blax.zones.tests.rewards";
private const string ForcedFailure = "BlaxZonesTests: forced failure inside the quest reward context";
private static Harmony harmony;
private static Harmony H => harmony ??= new Harmony(HarmonyId);
private static DeliveryContext contextAtFailure;
/// <summary>DeliveryContext.Current at each DropThingGroupsNear call while RecordContext is patched in.</summary>
private static readonly List<DeliveryContext> contextsSeen = new List<DeliveryContext>();
// ---- into the zone ---------------------------------------------------------------------
[BlaxTest("rewards: gold and medicine from a trade-spot QuestPart_DropPods land in their zones, and the letter points into the zone")]
public static void ItemsLandInZones()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(7, 2);
Zone_Delivery goldZone = Fixtures.DeliveryZone(new CellRect(area.minX, area.minZ, 2, 2), Fixtures.FilterOf(ThingDefOf.Gold));
Zone_Delivery medZone = Fixtures.DeliveryZone(new CellRect(area.maxX - 1, area.minZ, 2, 2), Fixtures.FilterOf(ThingDefOf.MedicineIndustrial));
IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area);
HashSet<Letter> letters = Fixtures.DropLettersAfterTest();
Thing gold = Fixtures.Stack(ThingDefOf.Gold, 50);
Thing medicine = Fixtures.Stack(ThingDefOf.MedicineIndustrial, 5);
QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { gold, medicine }, useTradeDropSpot: true);
part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
Skyfaller goldPod = Fixtures.PodOf(gold);
Skyfaller medPod = Fixtures.PodOf(medicine);
T.Check(goldPod != medPod, "gold and medicine share one pod");
T.Check(goldZone.ContainsCell(goldPod.Position), "the gold pod falls on " + goldPod.Position + ", not in the gold zone (vanilla spot " + vanilla + ")");
T.Check(medZone.ContainsCell(medPod.Position), "the medicine pod falls on " + medPod.Position + ", not in the medicine zone");
T.Check(!gold.IsForbidden(Faction.OfPlayer) && !medicine.IsForbidden(Faction.OfPlayer), "the quest dropped with forbid off, but a routed reward is forbidden");
Letter letter = Find.LetterStack.LettersListForReading.LastOrDefault(l => !letters.Contains(l));
T.NotNull(letter, "the quest letter");
IntVec3 target = letter.lookTargets?.PrimaryTarget.Cell ?? IntVec3.Invalid;
T.Check(Fixtures.InDeliveryZone(target), "the letter points at " + target + ", not into a delivery zone");
}
[BlaxTest("rewards: QuestPart_GiveNearPawn drops its items into the zone and the letter points there")]
public static void GiveNearPawnLandsInZone()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
Fixtures.FixTradeDropSpotAwayFrom(area);
HashSet<Letter> letters = Fixtures.DropLettersAfterTest();
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
Quest quest = Fixtures.TestQuest();
var part = new QuestPart_GiveNearPawn { inSignal = Fixtures.QuestSignal, nearPawn = Fixtures.Negotiator() };
part.Things = new[] { steel };
quest.AddPart(part);
part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
Skyfaller pod = Fixtures.PodOf(steel);
T.Check(zone.ContainsCell(pod.Position), "the steel pod falls on " + pod.Position + ", not in the zone");
Letter letter = Find.LetterStack.LettersListForReading.LastOrDefault(l => !letters.Contains(l));
T.NotNull(letter, "the quest letter");
IntVec3 target = letter.lookTargets?.PrimaryTarget.Cell ?? IntVec3.Invalid;
T.Check(zone.ContainsCell(target), "the letter points at " + target + ", not into the zone");
}
[BlaxTest("rewards: a 1-cell zone with 3 reward stacks gets 1 pod, the other 2 land within 16 cells on separate cells; with overflow off more stacks go to the vanilla spot")]
public static void OneCellZoneOverflows()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
Fixtures.Settings.overflowNearZone = true;
Fixtures.Settings.overflowRadius = BlaxZonesSettings.DefaultOverflowRadius;
CellRect area = Fixtures.TestArea(1, 1);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
var things = new[] { Fixtures.Stack(ThingDefOf.Steel, 50), Fixtures.Stack(ThingDefOf.WoodLog, 50), Fixtures.Stack(ThingDefOf.ComponentIndustrial, 5) };
QuestPart_DropPods part = Fixtures.QuestDropPods(things, useTradeDropSpot: true);
part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
List<Skyfaller> pods = things.Select(Fixtures.PodOf).ToList();
T.Equal(3, pods.Distinct().Count(), "pods for 3 stacks");
T.Equal(3, pods.Select(p => p.Position).Distinct().Count(), "distinct pod cells");
T.Equal(1, pods.Count(p => zone.ContainsCell(p.Position)), "pods on the zone cell");
foreach (Skyfaller p in pods.Where(p => !zone.ContainsCell(p.Position)))
{
T.Check(Fixtures.Chebyshev(p.Position, vanilla) > BlaxZonesSettings.DefaultOverflowRadius, "an overflow pod went to the vanilla spot " + vanilla);
int d = Fixtures.DistanceToZone(zone, p.Position);
T.Check(d <= BlaxZonesSettings.DefaultOverflowRadius, "an overflow pod falls " + d + " cells from the zone, at " + p.Position);
}
// Overflow off: the zone's one cell holds a falling pod, so every further stack goes to the vanilla spot.
Fixtures.Settings.overflowNearZone = false;
var more = new[] { Fixtures.Stack(ThingDefOf.Cloth, 20), Fixtures.Stack(ThingDefOf.Plasteel, 20) };
Fixtures.QuestDropPods(more, useTradeDropSpot: true).Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
foreach (Thing t in more)
{
IntVec3 c = Fixtures.PodOf(t).Position;
T.Check(!Fixtures.InDeliveryZone(c) && Fixtures.Chebyshev(c, vanilla) < Fixtures.FarSpotDistance / 2,
"with overflow off the " + t.def.defName + " pod falls at " + c + ", not near the vanilla spot " + vanilla);
}
}
// ---- never routed ------------------------------------------------------------------------
[BlaxTest("rewards: a refugee's pod stays out of the zone while the items' pods land in it")]
public static void RefugeeNotRouted()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
Pawn refugee = Refugee();
QuestPart_DropPods part = Fixtures.QuestDropPods(new Thing[] { steel, refugee }, useTradeDropSpot: true);
part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
Skyfaller steelPod = Fixtures.PodOf(steel);
Skyfaller refugeePod = Fixtures.PodOf(refugee);
T.Check(zone.ContainsCell(steelPod.Position), "the steel pod falls on " + steelPod.Position + ", not in the zone");
T.Check(!Fixtures.InDeliveryZone(refugeePod.Position), "the refugee's pod falls into a delivery zone at " + refugeePod.Position);
T.Check(Fixtures.Chebyshev(refugeePod.Position, vanilla) < Fixtures.FarSpotDistance / 2, "the refugee's pod falls at " + refugeePod.Position + ", far from the vanilla spot " + vanilla);
}
[BlaxTest("rewards: a mechanoid's pod stays out of the zone while the items' pods land in it")]
public static void MechNotRouted()
{
PawnKindDef kind = DefDatabase<PawnKindDef>.GetNamedSilentFail("Mech_Scyther");
T.NotNull(kind, "PawnKindDef Mech_Scyther (Core)");
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
Pawn mech = Fixtures.Generate(kind, Faction.OfPlayer);
QuestPart_DropPods part = Fixtures.QuestDropPods(new Thing[] { mech, steel }, useTradeDropSpot: true);
part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
T.Check(zone.ContainsCell(Fixtures.PodOf(steel).Position), "the steel pod is not in the zone");
T.Check(!Fixtures.InDeliveryZone(Fixtures.PodOf(mech).Position), "the mechanoid's pod falls into a delivery zone");
}
[BlaxTest("rewards: a Wastepack is never routed")]
public static void WastepackNotRouted()
{
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
ThingDef wastepack = ThingDefOf.Wastepack;
T.NotNull(wastepack, "ThingDefOf.Wastepack with Biotech");
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
zone.filter.SetAllow(wastepack, true); // even a filter that allows it can't pull it in
Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
Thing waste = Fixtures.Stack(wastepack, 5);
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { waste, steel }, useTradeDropSpot: true);
part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
T.Check(!Fixtures.InDeliveryZone(Fixtures.PodOf(waste).Position), "the Wastepack pod falls into a delivery zone");
T.Check(zone.ContainsCell(Fixtures.PodOf(steel).Position), "the steel pod is not in the zone");
}
[BlaxTest("rewards: dropAllInSamePod with a refugee and items routes nothing")]
public static void SamePodRoutesNothing()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Fixtures.DeliveryZone(area);
Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
Thing medicine = Fixtures.Stack(ThingDefOf.MedicineIndustrial, 5);
Pawn refugee = Refugee();
QuestPart_DropPods part = Fixtures.QuestDropPods(new Thing[] { steel, medicine, refugee }, useTradeDropSpot: true);
part.dropAllInSamePod = true;
part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
Skyfaller pod = Fixtures.PodOf(refugee);
T.Check(Fixtures.PodOf(steel) == pod && Fixtures.PodOf(medicine) == pod, "the things are not in one pod");
T.Check(!Fixtures.InDeliveryZone(pod.Position), "the shared pod falls into a delivery zone at " + pod.Position);
}
[BlaxTest("rewards: DropThingsNear without the context, as a raid calls it, is untouched")]
public static void NoContextUntouched()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Fixtures.DeliveryZone(area);
IntVec3 far = Fixtures.FarCell(area);
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current before the call");
DropPodUtility.DropThingsNear(far, Fixtures.Map, new[] { steel }, canRoofPunch: false, forbid: false);
Skyfaller pod = Fixtures.PodOf(steel);
T.Check(!Fixtures.InDeliveryZone(pod.Position), "the pod falls into a delivery zone at " + pod.Position);
T.Check(Fixtures.Chebyshev(pod.Position, far) < Fixtures.FarSpotDistance / 2, "the pod falls at " + pod.Position + ", not near " + far);
}
[BlaxTest("rewards: with Route quest rewards off or the zone's checkbox off, rewards land at the vanilla spot")]
public static void SwitchesOffVanilla()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
Fixtures.Settings.routeRewards = false;
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
Fixtures.QuestDropPods(new[] { steel }, useTradeDropSpot: true).Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
IntVec3 a = Fixtures.PodOf(steel).Position;
T.Check(!zone.ContainsCell(a) && Fixtures.Chebyshev(a, vanilla) < Fixtures.FarSpotDistance / 2, "with Route quest rewards off the pod falls at " + a);
Fixtures.Settings.routeRewards = true;
zone.acceptRewards = false;
Thing wood = Fixtures.Stack(ThingDefOf.WoodLog, 50);
Fixtures.QuestDropPods(new[] { wood }, useTradeDropSpot: true).Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
IntVec3 b = Fixtures.PodOf(wood).Position;
T.Check(!zone.ContainsCell(b) && Fixtures.Chebyshev(b, vanilla) < Fixtures.FarSpotDistance / 2, "with the zone's checkbox off the pod falls at " + b);
}
// ---- the caller's list, instaDrop, pod skins ----------------------------------------------
[BlaxTest("rewards: the list passed to DropThingGroupsNear still holds every group afterwards")]
public static void CallerListUnchanged()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area, Fixtures.FilterOf(ThingDefOf.Steel));
IntVec3 far = Fixtures.FarCell(area);
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
Thing wood = Fixtures.Stack(ThingDefOf.WoodLog, 50);
var steelGroup = new List<Thing> { steel };
var woodGroup = new List<Thing> { wood };
var groups = new List<List<Thing>> { steelGroup, woodGroup };
InRewardContext(() => DropPodUtility.DropThingGroupsNear(far, Fixtures.Map, groups, canRoofPunch: false, forbid: false));
T.Equal(2, groups.Count, "groups in the caller's list");
T.Check(groups[0] == steelGroup && groups[1] == woodGroup, "the caller's list holds other group lists");
T.Check(steelGroup.Count == 1 && steelGroup[0] == steel && woodGroup.Count == 1 && woodGroup[0] == wood, "a group list changed");
T.Check(zone.ContainsCell(Fixtures.PodOf(steel).Position), "the steel pod is not in the steel zone");
T.Check(!Fixtures.InDeliveryZone(Fixtures.PodOf(wood).Position), "the wood pod falls into a delivery zone");
T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current after the call");
}
[BlaxTest("rewards: with instaDrop the items appear in the zone with no pod")]
public static void InstaDropPlaces()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
IntVec3 far = Fixtures.FarCell(area);
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
var groups = new List<List<Thing>> { new List<Thing> { steel } };
InRewardContext(() => DropPodUtility.DropThingGroupsNear(far, Fixtures.Map, groups, instaDrop: true, canRoofPunch: false, forbid: true));
T.Check(steel.Spawned, "the steel is not on the map; it is in " + steel.ParentHolder);
T.Check(zone.ContainsCell(steel.Position), "the steel lies at " + steel.Position + ", not in the zone");
T.Check(steel.IsForbidden(Faction.OfPlayer), "forbid: true left the steel allowed");
}
[BlaxTest("rewards: a mechanoid-faction drop keeps the mechanoid pod skin in the zone")]
public static void FactionPodSkinKept()
{
Faction mechs = Faction.OfMechanoids;
if (mechs == null)
T.Skip("no mechanoid faction in this world");
ThingDef skin = mechs.def.dropPodIncoming;
T.NotNull(skin, "the mechanoid faction's dropPodIncoming (Core Factions_Hidden.xml)");
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { steel }, useTradeDropSpot: true);
part.faction = mechs;
part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
Skyfaller pod = Fixtures.PodOf(steel);
T.Equal(skin, pod.def, "pod def");
T.Check(zone.ContainsCell(pod.Position), "the pod falls on " + pod.Position + ", not in the zone");
}
// ---- context scope -----------------------------------------------------------------------
[BlaxTest("rewards: a chained part with useTradeDropSpot off, fired through outSignalResult, is not routed")]
public static void ChainedPartNotRouted()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
// The second part's own drop spot: far from the zone, so only a leaked context could pull it in.
IntVec3 secondSpot = Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
Thing wood = Fixtures.Stack(ThingDefOf.WoodLog, 50);
QuestPart_DropPods first = Fixtures.QuestDropPods(new[] { steel }, true, new[] { wood }, secondSpot, out QuestPart_DropPods second);
first.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
T.Check(zone.ContainsCell(Fixtures.PodOf(steel).Position), "the first part's steel is not in the zone");
Skyfaller woodPod = Fixtures.PodOf(wood); // fails when the chained part never fired
T.Check(!Fixtures.InDeliveryZone(woodPod.Position), "the chained part's wood falls into a delivery zone at " + woodPod.Position);
T.Check(Fixtures.Chebyshev(woodPod.Position, secondSpot) < Fixtures.FarSpotDistance / 2, "the chained part's pod falls at " + woodPod.Position + ", not near its drop spot " + secondSpot);
T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current after the chain");
}
[BlaxTest("rewards: a chained quest part with no Zones prefix of its own sees no context, and its DropThingsNear is not routed")]
public static void ChainedReceiverWithoutPrefixNotRouted()
{
// Only the SendSignal patch clears the context here: the probe part has no Zones prefix that
// could do it, unlike a chained QuestPart_DropPods.
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
IntVec3 far = Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
Thing wood = Fixtures.Stack(ThingDefOf.WoodLog, 50);
Quest quest = Fixtures.TestQuest();
QuestPart_DropPods first = Fixtures.QuestDropPods(new[] { steel }, useTradeDropSpot: true, quest);
first.outSignalResult = "Quest" + quest.id + ".blax.probe";
var probe = new ContextProbePart(first.outSignalResult, far, wood);
quest.AddPart(probe);
first.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
T.Check(probe.Fired, "the chained probe part never got its signal");
T.Equal(null, probe.ContextSeen, "DeliveryContext.Current inside the chained part");
T.Check(zone.ContainsCell(Fixtures.PodOf(steel).Position), "the first part's steel is not in the zone");
Skyfaller woodPod = Fixtures.PodOf(wood);
T.Check(!Fixtures.InDeliveryZone(woodPod.Position), "the probe's wood falls into a delivery zone at " + woodPod.Position);
T.Check(Fixtures.Chebyshev(woodPod.Position, far) < Fixtures.FarSpotDistance / 2, "the probe's pod falls at " + woodPod.Position + ", not near " + far);
T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current after the chain");
}
[BlaxTest("rewards: a trade-spot part with its own dropSpot, and a part with a random spot, run with no context")]
public static void ContextOnlyForTradeSpotWithoutDropSpot()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Fixtures.DeliveryZone(area);
IntVec3 far = Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
MethodInfo target = AccessTools.Method(typeof(DropPodUtility), nameof(DropPodUtility.DropThingGroupsNear));
MethodInfo recorder = AccessTools.Method(typeof(RewardTests), nameof(RecordContext));
H.Patch(target, prefix: new HarmonyMethod(recorder) { priority = Priority.First });
Fixtures.OnCleanup(() => H.Unpatch(target, recorder));
contextsSeen.Clear();
// useTradeDropSpot with a fixed dropSpot: vanilla drops at that spot (QuestPart_DropPods.cs:165).
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
QuestPart_DropPods fixedSpot = Fixtures.QuestDropPods(new[] { steel }, useTradeDropSpot: true);
fixedSpot.dropSpot = far;
fixedSpot.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
T.Equal(1, contextsSeen.Count, "DropThingGroupsNear calls for the part with its own dropSpot");
T.Equal(null, contextsSeen[0], "DeliveryContext.Current inside a trade-spot part with its own dropSpot");
IntVec3 a = Fixtures.PodOf(steel).Position;
T.Check(!Fixtures.InDeliveryZone(a) && Fixtures.Chebyshev(a, far) < Fixtures.FarSpotDistance / 2,
"the pod of the part with its own dropSpot falls at " + a + ", not near " + far);
// No trade spot and no dropSpot: a random spot (QuestPart_DropPods.cs:298-303), which may lie in a zone, so only the context counts.
Thing wood = Fixtures.Stack(ThingDefOf.WoodLog, 50);
Fixtures.QuestDropPods(new[] { wood }, useTradeDropSpot: false).Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
T.Equal(2, contextsSeen.Count, "DropThingGroupsNear calls after the part with a random spot");
T.Equal(null, contextsSeen[1], "DeliveryContext.Current inside a part with a random drop spot");
Fixtures.PodOf(wood);
}
[BlaxTest("rewards: an exception inside the context leaves DeliveryContext.Current null")]
public static void ExceptionLeavesContextNull()
{
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Fixtures.DeliveryZone(area);
Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
MethodInfo target = AccessTools.Method(typeof(DropPodUtility), nameof(DropPodUtility.DropThingGroupsNear));
MethodInfo thrower = AccessTools.Method(typeof(RewardTests), nameof(ThrowInsideContext));
H.Patch(target, prefix: new HarmonyMethod(thrower) { priority = Priority.First });
Fixtures.OnCleanup(() => H.Unpatch(target, thrower));
Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50);
QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { steel }, useTradeDropSpot: true);
contextAtFailure = null;
DeliveryContext.Current = null;
bool threw = false;
string failureTrace = null;
try
{
part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
}
catch (Exception e) when (Mentions(e, ForcedFailure))
{
threw = true;
for (Exception x = e; x != null; x = x.InnerException)
{
if (x.Message != null && x.Message.Contains(ForcedFailure))
failureTrace = x.StackTrace;
}
}
T.Check(threw, "the forced failure never reached the caller");
T.Check(contextAtFailure == DeliveryContext.QuestRewards, "the quest reward context was not set inside the part");
T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current after the exception");
// The finalizers return void, so Harmony rethrows: the trace still starts where the exception was thrown.
T.Check(failureTrace != null && failureTrace.Contains(nameof(ThrowInsideContext)),
"the exception's stack trace lost the frame that threw: " + failureTrace);
}
[BlaxTest("rewards: when planning throws, vanilla drops every group at its spot and Zones logs one error")]
public static void PlanningFailureFallsBack()
{
Map map = Fixtures.Map;
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
Thing gold = Fixtures.Stack(ThingDefOf.Gold, 50);
Thing medicine = Fixtures.Stack(ThingDefOf.MedicineIndustrial, 5);
QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { gold, medicine }, useTradeDropSpot: true);
int podsBefore = map.listerThings.ThingsOfDef(ThingDefOf.DropPodIncoming).Count;
ZonesLog.ResetOnce();
Fixtures.OnCleanup(ZonesLog.ResetOnce);
ZonesTestHooks.RouterThrows = true;
T.ExpectErrors("[Blax Zones] Quest reward delivery failed", 1);
part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
Skyfaller goldPod = Fixtures.PodOf(gold);
Skyfaller medPod = Fixtures.PodOf(medicine);
T.Equal(2, map.listerThings.ThingsOfDef(ThingDefOf.DropPodIncoming).Count - podsBefore, "new drop pods");
foreach (Skyfaller pod in new[] { goldPod, medPod })
{
T.Check(!zone.ContainsCell(pod.Position) && Fixtures.Chebyshev(pod.Position, vanilla) < Fixtures.FarSpotDistance / 2,
"a pod falls at " + pod.Position + ", not near the vanilla spot " + vanilla);
}
T.Equal(50, gold.stackCount, "gold count");
T.Equal(5, medicine.stackCount, "medicine count");
T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current after the failed plan");
}
[BlaxTest("rewards: a failure on the second group drops nothing twice and Zones logs one error")]
public static void FailureOnSecondGroup()
{
Map map = Fixtures.Map;
Fixtures.OnlyThisTestsZones(DeliverySource.Rewards);
CellRect area = Fixtures.TestArea(3, 3);
Zone_Delivery zone = Fixtures.DeliveryZone(area);
IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area);
Fixtures.DropLettersAfterTest();
Thing gold = Fixtures.Stack(ThingDefOf.Gold, 50);
Thing medicine = Fixtures.Stack(ThingDefOf.MedicineIndustrial, 5);
QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { gold, medicine }, useTradeDropSpot: true);
int podsBefore = map.listerThings.ThingsOfDef(ThingDefOf.DropPodIncoming).Count;
ZonesLog.ResetOnce();
Fixtures.OnCleanup(ZonesLog.ResetOnce);
ZonesTestHooks.RoutedGroupThrowsAt = 1;
T.ExpectErrors("[Blax Zones] Quest reward delivery failed", 1);
part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal));
Skyfaller goldPod = Fixtures.PodOf(gold);
Skyfaller medPod = Fixtures.PodOf(medicine);
T.Check(goldPod != medPod, "gold and medicine share one pod");
T.Equal(2, map.listerThings.ThingsOfDef(ThingDefOf.DropPodIncoming).Count - podsBefore, "new drop pods");
T.Check(zone.ContainsCell(goldPod.Position), "the first group's pod is not in the zone");
T.Check(!zone.ContainsCell(medPod.Position) && Fixtures.Chebyshev(medPod.Position, vanilla) < Fixtures.FarSpotDistance / 2,
"the failed group's pod falls at " + medPod.Position + ", not near the vanilla spot " + vanilla);
T.Equal(50, gold.stackCount, "gold count");
T.Equal(5, medicine.stackCount, "medicine count");
}
// ---- Trade Ships Drop Spot ---------------------------------------------------------------
[BlaxTest("rewards: with Trade Ships Drop Spot simulated the unsubscribe hint shows once on a map tick, only with a delivery zone and both routing toggles on")]
public static void TradeShipsDropSpotHintOnce()
{
Map map = Fixtures.Map;
MapComponent_BlaxZones comp = Fixtures.Comp;
T.NotNull(comp, "MapComponent_BlaxZones of the current map");
string text = TradeShipsDropSpotHint.Text;
T.Check(text.Contains("Trade Ships Drop Spot"), "the hint '" + text + "' doesn't name Trade Ships Drop Spot");
DropHintsAfterTest(text);
// Messages drops a repeat of a live message, so each tick starts with none live and every call counts.
void Tick()
{
Messages.Clear();
comp.MapComponentTick();
}
TradeShipsDropSpotHint.Reset();
Fixtures.Settings.routeOrbital = true;
Fixtures.Settings.routeRewards = true;
Fixtures.DeliveryZone(Fixtures.TestArea(1, 1));
T.Check(!Compat.TradeShipsDropSpotActive, "Trade Ships Drop Spot counts as active with nothing simulated");
Tick();
T.Equal(0, Hints(text), "hints without Trade Ships Drop Spot");
Compat.SimulatedActive.Add(Compat.TradeShipsDropSpotDef);
WithoutDeliveryZones(map, Tick);
T.Equal(0, Hints(text), "hints on a map with no delivery zone");
T.Check(!Fixtures.Settings.tradeShipsHintShown, "the hint counts as shown on a map with no delivery zone");
Tick();
Tick();
Tick();
T.Equal(1, Hints(text), "hints after three map ticks with a delivery zone and both routing toggles on");
T.Check(Fixtures.Settings.tradeShipsHintShown, "the shown hint is not remembered in the mod settings");
TradeShipsDropSpotHint.Reset();
Fixtures.Settings.routeRewards = false;
Tick();
T.Equal(1, Hints(text), "hints after a map tick with Route quest rewards off");
Fixtures.Settings.routeRewards = true;
Fixtures.Settings.routeOrbital = false;
Tick();
T.Equal(1, Hints(text), "hints after a map tick with Route orbital trade off");
}
// ---- helpers ---------------------------------------------------------------------------------
/// <summary>A friendly pawn for a quest drop, as a refugee quest hands it over (removed after the test).</summary>
private static Pawn Refugee()
{
Faction friendly = Fixtures.FriendlyFaction();
if (friendly == null)
T.Skip("no friendly faction in this world");
return Fixtures.Generate(PawnKindDefOf.Colonist, friendly);
}
/// <summary>Runs the action with the quest reward context set, as the patched callers do, and restores it.</summary>
private static void InRewardContext(Action action)
{
DeliveryContext previous = DeliveryContext.Current;
DeliveryContext.Current = DeliveryContext.QuestRewards;
try
{
action();
}
finally
{
DeliveryContext.Current = previous;
}
}
private static void ThrowInsideContext()
{
contextAtFailure = DeliveryContext.Current;
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 void RecordContext() => contextsSeen.Add(DeliveryContext.Current);
/// <summary>Messages with the text the player got (the message history; Messages.Message archives them).</summary>
private static int Hints(string text) =>
Find.Archive.ArchivablesListForReading.Count(a => a is Message m && m.text == text.CapitalizeFirst());
/// <summary>Removes the hint messages from the message history after the test.</summary>
private static void DropHintsAfterTest(string text)
{
Fixtures.OnCleanup(() =>
{
foreach (IArchivable a in Find.Archive.ArchivablesListForReading.Where(a => a is Message m && m.text == text.CapitalizeFirst()).ToList())
Find.Archive.Remove(a);
});
}
/// <summary>
/// Runs the action while ZoneManager's list holds no delivery zone, then puts the list back exactly as
/// it was. Nothing deregisters: zone grid, caches and the zones themselves stay untouched.
/// </summary>
private static void WithoutDeliveryZones(Map map, Action action)
{
List<Zone> all = map.zoneManager.AllZones;
List<Zone> before = all.ToList();
Fixtures.OnCleanup(() =>
{
if (!all.SequenceEqual(before))
{
all.Clear();
all.AddRange(before);
}
});
all.RemoveAll(z => z is Zone_Delivery);
try
{
action();
}
finally
{
all.Clear();
all.AddRange(before);
}
}
}
/// <summary>
/// A test-only quest part with no Zones patch of its own: on its signal it records DeliveryContext.Current
/// and drops its things near a fixed cell with DropPodUtility.DropThingsNear, as a mod's quest part might.
/// Lives on a raw test quest that is never in the quest manager, so it is never saved.
/// </summary>
public class ContextProbePart : QuestPart
{
private readonly string inSignal;
private readonly IntVec3 spot;
private readonly List<Thing> things;
public bool Fired;
public DeliveryContext ContextSeen;
public ContextProbePart(string inSignal, IntVec3 spot, params Thing[] things)
{
this.inSignal = inSignal;
this.spot = spot;
this.things = things.ToList();
signalListenMode = SignalListenMode.Always;
}
public override void Notify_QuestSignalReceived(Signal signal)
{
base.Notify_QuestSignalReceived(signal);
if (signal.tag != inSignal)
return;
Fired = true;
ContextSeen = DeliveryContext.Current;
DropPodUtility.DropThingsNear(spot, Fixtures.Map, things, canRoofPunch: false, forbid: false);
}
}
}

View File

@ -1,4 +1,3 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxZones;
@ -14,9 +13,8 @@ namespace BlaxZonesTests
private static readonly string[] SharedKeys =
{
"BlaxZones_DeliveryZone", "BlaxZones_NeedsDlc",
"BlaxZones_SettingDeliveryZones", "BlaxZones_SettingRouteOrbital", "BlaxZones_SettingRouteRewards", "BlaxZones_SettingOverflowNearZone",
"BlaxZones_SettingOverflowRadius", "BlaxZones_SettingRouteCaravan", "BlaxZones_SettingCaravanMessage",
"BlaxZones_SettingCampAtZones", "BlaxZones_SettingsReset",
"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")]
@ -37,22 +35,6 @@ namespace BlaxZonesTests
T.Check(errors.Count == 0, "errors mentioning Blax Zones at startup: " + string.Join(" | ", errors.Take(3).Select(e => e.text)));
}
[BlaxTest("startup: every Blax Zones finalizer returns void, so Harmony rethrows exceptions with their stack trace")]
public static void FinalizersReturnVoid()
{
// One finalizer returning Exception on a method makes Harmony "throw ex" instead of "rethrow"
// (0Harmony EmitFinalizers), which cuts the inner frames off every exception passing through it.
var finalizers = Harmony.GetAllPatchedMethods()
.Select(Harmony.GetPatchInfo)
.Where(info => info != null)
.SelectMany(info => info.Finalizers)
.Where(p => p.owner == BlaxZonesStartup.HarmonyId)
.ToList();
T.Check(finalizers.Count >= 6, "Blax Zones finalizers found: " + finalizers.Count + ", expected at least 6");
var bad = finalizers.Where(p => p.PatchMethod.ReturnType != typeof(void)).Select(p => p.PatchMethod.DeclaringType?.Name).ToList();
T.Check(bad.Count == 0, "finalizers that return a value: " + string.Join(", ", bad));
}
[BlaxTest("startup: settings, shared strings and one component per map")]
public static void Loaded()
{
@ -138,29 +120,6 @@ namespace BlaxZonesTests
T.Equal(1, m.components.Count(c => c is MapComponent_BlaxZones), "MapComponent_BlaxZones on map " + m.Index);
}
[BlaxTest("harness: the reload logs no 'Could not resolve reference' warning except for vanilla's unsaved tale pawns and Hospitality's stale lords", phase: 2)]
public static void ReloadResolvesEveryReference()
{
// A reference Blax Zones saves but can't load would show here. Phase-1 tests that leave a pawn
// with a relation to a pawn nobody saves show as "dangling relation" INFO lines under that test.
// Two leaks of other code are excused by name:
// - vanilla: a pawn TaleData_Pawn.GenerateRandom made for a book in a trader caravan's stock,
// which every forced caravan can bring;
// - Hospitality (-Compat): CompGuest.PostSpawnSetup stores Pawn.GetLord() on every humanlike pawn
// and saves it with Scribe_References, and nothing clears it when the pawn leaves the map
// (Hospitality Source/CompGuest.cs, lord; PostDeSpawn only drops PresentGuests). Every forced
// caravan's pawns keep their ended lord. Blax Zones saves no Lord reference.
List<string> all = T.Phase2ResolveWarnings;
List<string> vanilla = all.Where(T.NamesVanillaTalePawn).ToList();
bool hospitality = Compat.IsActive("Orion.Hospitality");
List<string> staleLords = hospitality ? all.Where(w => w.Contains("of type Verse.AI.Group.Lord.")).ToList() : new List<string>();
List<string> rest = all.Where(w => !vanilla.Contains(w) && !staleLords.Contains(w)).ToList();
T.Info(all.Count + " warning(s) on the reload: " + vanilla.Count + " for pawns vanilla made for books or tales and never saved, " +
staleLords.Count + " for lords Hospitality's CompGuest still names");
T.Equal(0, rest.Count, "other 'Could not resolve reference' warnings while the phase-1 save loaded (first: " +
string.Join(" | ", rest.Take(3)) + ")");
}
[BlaxTest("harness: phase 3 loads with exactly the two removal errors per map and a fresh component", phase: 3)]
public static void Phase3Removal()
{

View File

@ -36,17 +36,17 @@ namespace BlaxZonesTests
CellRect area = Fixtures.TestArea(15, 2);
int x0 = area.minX, z0 = area.minZ;
// A: steel and industrial medicine, Important, quest rewards off. A kept wall on its corner leaves that cell out.
// 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, rewards: false));
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, caravan purchases off.
// 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, caravan: false));
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");
@ -237,10 +237,8 @@ namespace BlaxZonesTests
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");
// A void finalizer can't swallow or replace vanilla's exception: Harmony rethrows it unchanged.
T.Equal(typeof(void), AccessTools.Method(typeof(Patch_Map_FinalizeLoading), nameof(Patch_Map_FinalizeLoading.Finalizer)).ReturnType,
"the FinalizeLoading finalizer's return type");
Patch_Map_FinalizeLoading.Finalizer(state);
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");
}
@ -563,8 +561,7 @@ namespace BlaxZonesTests
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 + ",rewards=" + z.acceptRewards + ",caravan=" + z.acceptCaravan + ",camp=" + z.campHere;
private static string SourcesText(Zone_Delivery z) => "orbital=" + z.acceptOrbital + ",camp=" + z.campHere;
}
/// <summary>

View File

@ -23,9 +23,6 @@ namespace BlaxZonesTests
{
"BlaxZones_TabDelivery", "BlaxZones_PriorityTip",
"BlaxZones_AcceptOrbital", "BlaxZones_AcceptOrbitalTip", "BlaxZones_AcceptOrbitalOffTip",
"BlaxZones_AcceptRewards", "BlaxZones_AcceptRewardsTip", "BlaxZones_AcceptRewardsOffTip",
"BlaxZones_AcceptCaravan", "BlaxZones_AcceptCaravanTip", "BlaxZones_AcceptCaravanOffTip",
"BlaxZones_CaravanGoodsInZone", "BlaxZones_CaravanGoodsNextToZone", "BlaxZones_CaravanGoodsInZones", "BlaxZones_TradeShipsDropSpotHint",
"BlaxZones_CampHere", "BlaxZones_CampHereTip", "BlaxZones_CampHereOffTip", "BlaxZones_CampHereStandDownTip",
"BlaxZones_CopySettings", "BlaxZones_CopySettingsDesc", "BlaxZones_PasteSettings", "BlaxZones_PasteSettingsDesc",
"BlaxZones_SettingsCopied", "BlaxZones_SettingsPasted", "BlaxZones_NothingCopied",
@ -101,8 +98,6 @@ namespace BlaxZonesTests
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.RewardsTip().NullOrEmpty(), "rewards tooltip empty");
T.Check(!ITab_Delivery.CaravanTip().NullOrEmpty(), "caravan tooltip empty");
T.Check(!ITab_Delivery.CampTip().NullOrEmpty(), "camp tooltip empty");
DeliveryClipboard.Copy(zone);
DeliveryClipboard.PasteInto(zone);
@ -116,14 +111,14 @@ namespace BlaxZonesTests
// ---- persistence (needs package Store; green at integration) -------------------------
[BlaxTest("tab: filter, priority, orbital, rewards, caravan and camp flags set up for the reload")]
[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, rewards: false, caravan: false));
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, rewards and caravan are off, so the router never picks this zone either.
// a stray camp zone. Orbital is off, so the router never picks this zone either.
T.CarryAtSave(PersistKey, () =>
{
zone.campHere = true;
@ -131,7 +126,7 @@ namespace BlaxZonesTests
});
}
[BlaxTest("tab: filter, priority, orbital, rewards, caravan and camp flags persist", phase: 2)]
[BlaxTest("tab: filter, priority, orbital and camp flags persist", phase: 2)]
public static void PersistCheck()
{
int zoneId = -1;
@ -143,8 +138,6 @@ namespace BlaxZonesTests
T.Equal(6, zone.CellCount, "cells");
T.Equal(StoragePriority.Critical, zone.priority, "priority");
T.Equal(false, zone.acceptOrbital, "orbital checkbox");
T.Equal(false, zone.acceptRewards, "rewards checkbox");
T.Equal(false, zone.acceptCaravan, "caravan checkbox");
T.Equal(true, zone.campHere, "camp checkbox");
T.NotNull(zone.filter, "filter");
if (T.Carry.TryGetValue(PersistKey + ".defs", out string defs))
@ -156,13 +149,13 @@ namespace BlaxZonesTests
// ---- copy and paste --------------------------------------------------------------------
[BlaxTest("tab: copy then paste moves filter, priority, the three source checkboxes and camp to another zone, never its cells")]
[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, rewards: false, caravan: false);
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;
@ -176,15 +169,11 @@ namespace BlaxZonesTests
a.filter.SetAllow(ThingDefOf.Steel, true);
a.priority = StoragePriority.Low;
a.acceptOrbital = true;
a.acceptRewards = true;
a.acceptCaravan = 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(false, b.acceptRewards, "pasted rewards checkbox");
T.Equal(false, b.acceptCaravan, "pasted caravan 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");
@ -357,22 +346,5 @@ namespace BlaxZonesTests
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: the rewards and caravan tooltips say when the mod settings turn them off, and the caravan one names guests")]
public static void SourceTooltips()
{
BlaxZonesSettings s = Fixtures.Settings;
string rewardsOff = "BlaxZones_AcceptRewardsOffTip".Translate();
string caravanOff = "BlaxZones_AcceptCaravanOffTip".Translate();
s.routeRewards = true;
s.routeCaravan = true;
T.Check(!ITab_Delivery.RewardsTip().Contains(rewardsOff), "rewards off note while routing is on");
T.Check(!ITab_Delivery.CaravanTip().Contains(caravanOff), "caravan off note while routing is on");
T.Check(ITab_Delivery.CaravanTip().Contains("guests"), "the caravan tooltip doesn't name guests");
s.routeRewards = false;
s.routeCaravan = false;
T.Check(ITab_Delivery.RewardsTip().Contains(rewardsOff), "rewards off note missing while routing is off");
T.Check(ITab_Delivery.CaravanTip().Contains(caravanOff), "caravan off note missing while routing is off");
}
}
}

View File

@ -2,7 +2,7 @@
Drag a delivery zone and everything you buy from orbital or caravan traders, plus quest rewards, lands in it, sorted by item filter: medicine by the hospital, steel by the workshop. Drag a sleeping zone over the barn and every chicken and duck has a bed, so you stop placing sleeping spots one at a time. Paint a work rule area and colonists stop cleaning the barn without giving up its fire watch, leave the killbox's loot alone until you untick the rule, and clean the hospital first.
Status: 1.0 and 1.1 are built; 1.2 to 1.6 are designed, no code yet. Checked against the RimWorld 1.7.5021 game code on 2026-11-29. RimWorld 1.7, package id `blax.zones`. From the first release a plain unsubscribe leaves a loadable save with vanilla zones intact; from 1.2 a button removes it with no errors.
Status: 1.0 is built; 1.1 to 1.6 are designed, no code yet. Checked against the RimWorld 1.7.5021 game code on 2026-11-29. RimWorld 1.7, package id `blax.zones`. From the first release a plain unsubscribe leaves a loadable save with vanilla zones intact; from 1.2 a button removes it with no errors.
Changes on 2026-11-29, after two review rounds:
@ -20,8 +20,6 @@ Changes on 2026-11-29, after two review rounds:
- Matched with the Castes and Defaults docs: At a glance gains a Needs column in the shared format. The ownership line lists every Castes slot, work priorities and weapon loadout included, and Defaults' sentence now says its forbid rules write outside creation.
- New release 1.6, work rule areas, from Fabian's request for "No cleaning" and "Priority zones" (2026-11-29): one painted layer of named areas, each with rule checkboxes (no cleaning, no firefighting, no repairs, don't haul from here, clean first, haul first). Kept in the component, not as vanilla Areas or Zones; seven postfixes and two work givers that need no patch. Construction and plant work first went to the Backlog.
- 1.6 after review: CleaningArea, Cleaning Area Relaunched and Cleaning Priority (Continued) don't reorder vanilla cleaning, they replace CleanFilth's work giver class. The "No cleaning" postfixes now also go on the class the CleanFilth def names, and "Clean first" stands down for Cleaning Priority (Continued). "Haul first" hands a pawn to Pick Up And Haul only when Pick Up And Haul's own `ShouldSkip` lets it through, so guests, working prisoners and quest lodgers never get inventory hauls. Hospitality guests do help with colony work and follow all six rules. The Defaults notes follow its forbid rework. The ownership line gains per-cell work rules, and Castes, Slaves and Defaults now carry the same Zones sentence; all four docs say "allowed area" for Castes' area slot, so it isn't read as a work rule area. The performance test runs 60 colonists. 1.6 takes 8 days, so the plan takes 37.
- 2026-11-30: Work rule areas moved up to 1.3, the later releases shift by one; name confirmed.
- 2026-11-30: 1.1 built as specified, with these differences. Caravan overflow follows "Overflow lands next to the zone" and needs a colony-reachable overflow center, as orbital overflow does. A reward group also stays with vanilla when a thing in it is already spawned, sits in a container or carries a pawn inside (a casket). A group that fails while dropping goes back to vanilla with every later group, its things taken out of the pod that never fell; only a failed plan hands vanilla the original list. The delivery tab is 528 high, two rows taller than the stockpile tab, for the two new checkboxes. The Trade Ships Drop Spot hint shows on the first map tick of a game, as a message and a log line; its marker def `DropSpotTradeShip` was read from SmashPhil/TradeShips-Drop-Spot, Defs/DropSpotIndicator.xml. Tests put a known stack on a pack animal instead of picking from the caravan's random stock, and the `dropAllInSamePod` test has a refugee in the shared group (a shared group of items only routes as one pod).
## At a glance
@ -30,26 +28,26 @@ Changes on 2026-11-29, after two review rounds:
| 1.0 | Delivery zones: orbital buys land in them, by item filter and priority. Trader caravans camp next to a zone you pick | The orbital half of Trade Ships Drop Spot (206k, no official 1.7) and of Trading Control (111k, no 1.7); [KV] Trading Spot (126k) and [GMT] Trading Spot (118k), both dead; Trading Spot (44k), 1.6 only. Stands down for Trading Spot Rewritten (2.2k), which has a 1.7 build | None | 6 |
| 1.1 | Quest rewards land in delivery zones. Goods bought from trader caravans and Hospitality guests appear in them | The quest-reward half of Trade Ships Drop Spot and Trading Control | None | 3 |
| 1.2 | Animal sleeping zones: every cell is a sleeping spot, with species and body-size filters. A button removes Zones from a save with no errors | Covers the spot-grid use of Designator Shapes (332k, a general shape tool, so not a demand count), Barn Stall's size filter (29k) and Hidden Spots (13k), all alive on 1.7 | None | 6 |
| 1.3 | Work rule areas, painted over anything: a barn nobody cleans that still gets its fires fought, a killbox where nobody fights fires, repairs or hauls until you untick it, a hospital cleaned first, a landing pad hauled first | Covers the use of CleaningArea (114k, last 1.4), Cleaning Area Relaunched (23k, 1.6 only) and Cleaning Priority - 1.0 (1.8k, dead). Overlaps Cleaning Priority (Continued) (23k, 1.7), for which "Clean first" stands down, and the per-item "haul urgently" of Allow Tool (1.4M, last 1.6) and Keyz' Allow Utilities (91k, 1.7) | None | 8 |
| 1.4 | Goods go straight into stockpiles, shelves, racks and fridges, and under roofs; orbital traders buy from flagged storage; cargo pods land in a zone | Covers the use of Map Wide Orbital Trade Beacon (51k) and Wall-Mounted Orbital Trade Beacon (16k), both alive on 1.7. Replaces 3 small pod mods with no 1.7 build (6.5k combined) | None | 6 |
| 1.5 | People sleeping zones for colonists, slaves (Ideology) and prisoners; medical and shared zones | None directly; extends 1.2 to people | None (slaves: Ideology) | 6 |
| 1.6 | With Blax Castes, sleeping zones limited by caste | None | None | 2 |
| 1.3 | Goods go straight into stockpiles, shelves, racks and fridges, and under roofs; orbital traders buy from flagged storage; cargo pods land in a zone | Covers the use of Map Wide Orbital Trade Beacon (51k) and Wall-Mounted Orbital Trade Beacon (16k), both alive on 1.7. Replaces 3 small pod mods with no 1.7 build (6.5k combined) | None | 6 |
| 1.4 | People sleeping zones for colonists, slaves (Ideology) and prisoners; medical and shared zones | None directly; extends 1.2 to people | None (slaves: Ideology) | 6 |
| 1.5 | With Blax Castes, sleeping zones limited by caste | None | None | 2 |
| 1.6 | Work rule areas, painted over anything: a barn nobody cleans that still gets its fires fought, a killbox where nobody fights fires, repairs or hauls until you untick it, a hospital cleaned first, a landing pad hauled first | Covers the use of CleaningArea (114k, last 1.4), Cleaning Area Relaunched (23k, 1.6 only) and Cleaning Priority - 1.0 (1.8k, dead). Overlaps Cleaning Priority (Continued) (23k, 1.7), for which "Clean first" stands down, and the per-item "haul urgently" of Allow Tool (1.4M, last 1.6) and Keyz' Allow Utilities (91k, 1.7) | None | 8 |
| Total | | | | 37 |
Effort: S = 0.5 days, M = 2, L = 5, summed per release and rounded up. Subscriber counts were read from the Workshop on 2026-11-29. Needs: "None" means the release runs on the core game, and a DLC in brackets marks the parts that switch off without it (see "DLC support").
Total: 37 working days: 29 for the other six releases (up from 28: the removal button, plus the test work of shipping sleeping zones in two releases), 6 of them for 1.0, which is built, and 8 for work rule areas (1.3). 1.3 needs only the 1.0 component and the 1.2 removal button, so it ships right after 1.2 without changes; if it slips, Clean first and Haul first move to 1.3.1 and the four "No" rules ship first.
Total: 37 working days: 29 for 1.0 to 1.5 (up from 28: the removal button, plus the test work of shipping sleeping zones in two releases), 6 of them for 1.0, which is built, and 8 for work rule areas (1.6). 1.6 needs only the 1.0 component and the 1.2 removal button, so it can move ahead of 1.3 to 1.5 without changes; if it slips, Clean first and Haul first move to 1.6.1 and the four "No" rules ship first.
## Defaults I picked
Change if you disagree.
- Caravan camps ship in 1.0 and caravan purchase routing in 1.1. Camping fills a 1.7 gap (the trading-spot mods are dead or 1.6 only), and with the caravan camped by the zone, vanilla's drops at the pack animal's feet already land near it.
- Deliveries get their own zone type in 1.0, not a flag on stockpiles. Most stockpiles are roofed, where pods can't land, and a landing pad keeps pods out of the warehouse. Flagged stockpiles and shelves come in 1.4 together with roofed delivery.
- Deliveries get their own zone type in 1.0, not a flag on stockpiles. Most stockpiles are roofed, where pods can't land, and a landing pad keeps pods out of the warehouse. Flagged stockpiles and shelves come in 1.3 together with roofed delivery.
- Goods bought from Hospitality guests land in delivery zones too (1.1), because guests sell through the same caravan code. The caravan checkbox's tooltip says so.
- When every zone cell is taken, pods land within 16 cells of the top zone. The radius goes from 5 to 30, because the game's search can hang below 5. A setting sends overflow to the vanilla spot instead.
- Blax Slaves payouts (ransom, buy-back, wages) follow a zone's orbital checkbox. Its tooltip says so while Slaves is active.
- Roofed delivery (goods appear, no drop pod) exists, per zone, off by default, from 1.4.
- Roofed delivery (goods appear, no drop pod) exists, per zone, off by default, from 1.3.
- Sleeping-zone cells match vanilla sleeping spots: 80% rest, "slept on ground" -4 mood, comfort 0.4, count for barracks, sleeper drawn lying on the ground.
- Sleeping zones don't extend the home area. Delivery zones do, like every vanilla zone.
- A zone's owner type wins. Vanilla turns every bed in a prison cell into a prisoner bed; a colonist or slave zone in such a room stays as it is, and the inspect pane warns.
@ -62,9 +60,9 @@ Change if you disagree.
- Caravan goods appear in the zone. Pack animals don't walk them over; I cut that.
- Trader caravans and tribute collectors camp at a "Caravans camp here" zone. Visitor groups don't.
- Odyssey gravships leave Blax zones and their beds behind. Zone beds never fly.
- Caste limits (1.6) apply to medical zones too, so a medical zone can be kept for the Miner caste.
- Caste limits (1.5) apply to medical zones too, so a medical zone can be kept for the Miner caste.
- A Zones error never costs an item: every routed path falls back to vanilla.
- Work rules (1.3) are named areas with checkboxes, not one layer per rule: a killbox gets "No firefighting", "No repairs" and "Don't haul from here" in one drag, and unticking "Don't haul from here" after the raid lets haulers empty it without repainting. Up to 10 per map, like allowed areas.
- Work rules (1.6) are named areas with checkboxes, not one layer per rule: a killbox gets "No firefighting", "No repairs" and "Don't haul from here" in one drag, and unticking "Don't haul from here" after the raid lets haulers empty it without repainting. Up to 10 per map, like allowed areas.
- A new work rule area has no rule ticked, so painting alone changes nothing.
- "No" beats "first": a cell in a "No cleaning" area and a "Clean first" area isn't cleaned automatically.
- Player orders win over every "No" rule: right-click cleaning and repairing, the right-click extinguish order and the vanilla Haul designation work in every area. Like a forbidden item, an item in a "Don't haul from here" cell has no right-click "Prioritize hauling"; the Haul designation or unticking the rule brings it in.
@ -85,7 +83,7 @@ Three parts carry everything. Build them first, in 1.0 and 1.2. The rules and th
### Zone store, safe to remove from a save
All Blax state lives in one `MapComponent_BlaxZones` per map: our zones while saving and loading (1.0), the zone beds (1.2), the work rule areas (1.3), the stockpile and shelf flags (1.4), and every cache (cell lists, reachability, pending respawns, the work-rule mask and filth lists). No Blax zone, area or field ever enters a vanilla save list.
All Blax state lives in one `MapComponent_BlaxZones` per map: our zones while saving and loading (1.0), the zone beds (1.2), the stockpile and shelf flags (1.3), the work rule areas (1.6), and every cache (cell lists, reachability, pending respawns, the work-rule mask and filth lists). No Blax zone, area or field ever enters a vanilla save list.
- Why: `ZoneManager.ExposeData` (ZoneManager.cs:21) deep-saves the private `allZones` (ZoneManager.cs:9). An unknown zone class falls back to the abstract `Zone`, throws and loads as null (ScribeExtractor.cs:105-118, 146-150). `UpdateZoneManagerLinks` (ZoneManager.cs:31) then throws an NRE in the same load. `Scribe_Deep` catches it in `SaveableFromNode` and leaves `map.zoneManager` null (Scribe_Deep.cs:84; Map.cs:873), so the map loses every zone and every later zone access throws. A MapComponent with a missing class also loads as null, but `Map.FillComponents` removes nulls (Map.cs:712, called again after loading at Map.cs:929), so nothing breaks.
- Save: a prefix on `ZoneManager.ExposeData`, only when `Scribe.mode == Saving`, swaps `allZones` for a filtered copy without our zones. A finalizer puts the original list object back, even if saving throws.
@ -94,7 +92,7 @@ All Blax state lives in one `MapComponent_BlaxZones` per map: our zones while sa
- Plain unsubscribe: the save loads. In 1.0 and 1.1 the log shows exactly 2 errors per map: "Could not find class BlaxZones.MapComponent_BlaxZones" and "SaveableFromNode exception: ... Can't load abstract class Verse.MapComponent" (ScribeExtractor.cs:111, 116; MapComponent.cs:3). From 1.2 the zone beds go with the component node, which adds:
- one "Could not resolve reference" warning per bed owner, job target and reservation that pointed at a zone bed;
- about two "tried to get CurToil with curToilIndex=2" errors (JobDriver.cs:52-66) per pawn that lay in a zone bed when the game was saved. Its `JobDriver_LayDown` had 3 toils with the bed (JobDriver_LayDown.cs:55-60). With the target unresolved, `SetupToils` on PostLoadInit (JobDriver.cs:268-271) builds 2 toils, or 1 for a pawn that can't move (JobDriver_LayDown.cs:61-69). The error comes at spawn, when `Pawn_RotationTracker.Notify_Spawned` reads `HandlingFacing` (Pawn_RotationTracker.cs:14-31; JobDriver.cs:122-131), and on the first tick in `DriverTick` (JobDriver.cs:350); the job then runs out of toils and ends. Saves made at night have many sleepers.
- From 1.3, one "Could not load reference to RimWorld.WorkGiverDef named BlaxZones_CleanFirst" (or `BlaxZones_HaulFirst`) error per current or queued job that one of Zones' two work givers handed out. `Job.ExposeData` saves the giver as a def reference (Job.cs:553), a missing def logs that error and loads as null (ScribeExtractor.cs:44-63, error at :56), and every vanilla reader of `job.workGiverDef` checks for null (Pawn_JobTracker.cs:116, JobQueue.cs:152, LearningGiver_Workwatching.cs:43, JobDriver_Workwatching.cs:65), so the job runs on. The work rule areas go with the component node and add no error.
- From 1.6, one "Could not load reference to RimWorld.WorkGiverDef named BlaxZones_CleanFirst" (or `BlaxZones_HaulFirst`) error per current or queued job that one of Zones' two work givers handed out. `Job.ExposeData` saves the giver as a def reference (Job.cs:553), a missing def logs that error and loads as null (ScribeExtractor.cs:44-63, error at :56), and every vanilla reader of `job.workGiverDef` checks for null (Pawn_JobTracker.cs:116, JobQueue.cs:152, LearningGiver_Workwatching.cs:43, JobDriver_Workwatching.cs:65), so the job runs on. The work rule areas go with the component node and add no error.
- The removal button (1.2) avoids all of these.
- Removal flag (1.2): vanilla re-creates a missing MapComponent. `Map.FillComponents` (Map.cs:710-726) adds every missing MapComponent subclass on new maps (Map.cs:617) and at the end of every `ExposeComponents`, saving included (Map.cs:929, after the components list is written at :898). So after the button, a postfix on the private `Map.FillComponents` removes `MapComponent_BlaxZones` again while the removal flag, a weak reference to the current `Game`, names the current game. That covers every later save, autosave and new map in that game. The component is never removed inside a `FinalizeInit`: `MapComponentUtility.FinalizeInit` loops by index (MapComponentUtility.cs:72-84), so removing an entry would skip the next component's `FinalizeInit`. Zones' own code never creates the component, and every patch reads `map.GetComponent<MapComponent_BlaxZones>()` and routes to vanilla on null.
- Map removal: a `MapRemoved` override (MapComponent.cs:40, called from Game.cs:766) only drops caches. It never calls `Zone.Delete` or `Deregister` on a removed map. Vanilla doesn't either: it unclaims the map's pawns and only notifies things (MapDeiniter.cs:218-254).
@ -104,12 +102,12 @@ All Blax state lives in one `MapComponent_BlaxZones` per map: our zones while sa
One static class that orbital trade, rewards, caravans, cargo pods, direct delivery and `ZonesApi.TryFindDropSpot` all call. Its build counts in the delivery zone's effort, so each routing feature stays small.
- Refuses: `Pawn`, `Corpse`, Wastepack (Biotech; the check skips a null `ThingDefOf.Wastepack`), maps with no zones, and maps without the component (after the removal button).
- Candidates: delivery zones (from 1.4 also flagged stockpiles and shelves) that accept the source and pass the filter, ordered by priority, then zone ID (shelves: ThingID).
- Cells: sorted by distance to the zone centroid, cached in the component and rebuilt in `AddCell`/`RemoveCell`. Delivery zones: pass 1 takes empty valid cells, pass 2 cells with a mergeable stack, because pods spread out. Storage targets (1.4): mergeable stacks first, then empty cells, the order Haul to Stack uses. At most 400 checks per stack.
- Candidates: delivery zones (from 1.3 also flagged stockpiles and shelves) that accept the source and pass the filter, ordered by priority, then zone ID (shelves: ThingID).
- Cells: sorted by distance to the zone centroid, cached in the component and rebuilt in `AddCell`/`RemoveCell`. Delivery zones: pass 1 takes empty valid cells, pass 2 cells with a mergeable stack, because pods spread out. Storage targets (1.3): mergeable stacks first, then empty cells, the order Haul to Stack uses. At most 400 checks per stack.
- Reach rule: a spawned free colonist (`map.mapPawns.FreeColonistsSpawned`) can reach the cell, with `PathEndMode.OnCell` for pods and placement and `Touch` for storage. Checked once per district and cached in the component; with no free colonist on the map, `Reachability.CanReachColony` decides. Not `CanReachColony` first: it returns true for any cell that reaches any colony building (Reachability.cs:387-435), so a walled-off area holding a sleeping zone (1.2), or player walls, would count as colony.
- Pod rule: `DropCellFinder.IsGoodDropSpot(c, map, allowFogged: false, canRoofPunch: false)` (DropCellFinder.cs:319-362) plus the reach rule. It refuses unwalkable cells, water and vacuum terrain (DropCellFinder.cs:509-516), any roof (:518-527), districts with an enclosed animal pen marker (:537-549), skyfallers and active transporters, and edifices that aren't clearable free buildings (:338-358). Shelves are edifices, so they fail it roofed or not.
- Placement rule (caravan goods, direct delivery into delivery zones): standable, unfogged, the reach rule, roof ignored.
- Storage rule (1.4 storage targets): `StoreUtility.IsValidStorageFor(c, map, thing)` (StoreUtility.cs:103-115: the slot group accepts the thing, no storage blockers, items per cell respected) and `StoreUtility.IsGoodStoreCell(c, map, thing, null, Faction.OfPlayer)` (StoreUtility.cs:327: no player reservation, no fire, no blocking frame), unfogged, and the reach rule with `Touch`. Not standable: vanilla shelves and RimFridge fridges are PassThroughOnly, RimFridge wall fridges Impassable, and `Standable` (GenGrid.cs:144-159) refuses both.
- Storage rule (1.3 storage targets): `StoreUtility.IsValidStorageFor(c, map, thing)` (StoreUtility.cs:103-115: the slot group accepts the thing, no storage blockers, items per cell respected) and `StoreUtility.IsGoodStoreCell(c, map, thing, null, Faction.OfPlayer)` (StoreUtility.cs:327: no player reservation, no fire, no blocking frame), unfogged, and the reach rule with `Touch`. Not standable: vanilla shelves and RimFridge fridges are PassThroughOnly, RimFridge wall fridges Impassable, and `Standable` (GenGrid.cs:144-159) refuses both.
- Overflow center: the top zone's cell nearest its centroid, not the raw centroid. `TryFindDropSpotNear` needs reachability from its center (DropCellFinder.cs:309-312), and the centroid of an L-shaped zone can be a wall.
- Overflow: `DropCellFinder.TryFindDropSpotNear(center, map, out cell, allowFogged: false, canRoofPunch: false, maxRadius)` (DropCellFinder.cs:229) with the radius setting, never below 5. The search grows by `Mathf.Min(maxRadius / 5, 1)` (DropCellFinder.cs:272), which is 0 below 5, so a failed search never ends. Then the vanilla spot.
- Context (from 1.1): callers that can't pass a source set a `[ThreadStatic] DeliveryContext` in a prefix, keep the previous value in `__state` and restore it in a finalizer. The `DropPodUtility.DropThingGroupsNear` prefix reads it. A prefix on `SignalManager.SendSignal` (SignalManager.cs:38) saves and clears the context and its finalizer restores it: signals are delivered inside the same call (SignalManager.cs:38-60), so quest parts chained through `outSignalResult` (QuestPart_DropPods.cs:239-251, QuestPart_GiveNearPawn.cs:224-238) never see a context that wasn't set for them.
@ -117,19 +115,19 @@ One static class that orbital trade, rewards, caravans, cargo pods, direct deliv
### Zone beds
One invisible bed per sleeping-zone cell: `Building_ZoneBed : Building_Bed`, player faction, not an edifice, def `isSaveable` false. Animal zones use them from 1.2, people zones from 1.5.
One invisible bed per sleeping-zone cell: `Building_ZoneBed : Building_Bed`, player faction, not an edifice, def `isSaveable` false. Animal zones use them from 1.2, people zones from 1.4.
- Why real beds: ownership, prisoner capture, slave beds, patients, rescue, babies and `Alert_NeedColonistBeds` keep working with no extra patches. Ground sleep without beds covers voluntary sleep only (see Cut).
- Not an edifice: an edifice without a `sowTag` blocks planting and wipes the pasture grass under it (ThingDef.cs:625-655, 1360-1387; GenSpawn.cs:445-447).
- Saving: `Map.ExposeData` skips things whose def has `isSaveable` false (Map.cs:652, the only check in the code), so the component deep-saves the beds instead and the load prefix hands them to vanilla. Without the mod they vanish with the component node, and the vanilla things list never holds a missing def. Before saving, the component drops destroyed and despawned beds from its list; a destroyed bed left there would come back next to its replacement.
- Spawning: make the bed, `SetFaction(Faction.OfPlayer)` (`IsValidBedFor` needs it, RestUtility.cs:185), set `ForOwnerType` and `Medical` while it is unspawned and the bypass flag below is set, then `GenSpawn.Spawn`. On an unspawned bed the setters find no owners and no room (Building_Bed.cs:92-131, 753-756). `Building_Bed.SpawnSetup` then recomputes the district and room with the bed already the right type (Building_Bed.cs:274-282), so a prisoner zone in a closed room becomes a prison cell. The bed never wipes anything: a cell holding a skyfaller, an active transporter or another bed waits for the next sweep.
- Owner type comes from the zone (people zones, 1.5): prefixes on the `ForPrisoners` setter (Building_Bed.cs:44-73) and the `ForOwnerType` setter (Building_Bed.cs:92-108) refuse any change to a zone bed unless Zones' own `[ThreadStatic]` bypass flag is set. Vanilla changes owner types behind the zone's back in three places, and each flip posts one message per owner (`RemoveAllOwners`, Building_Bed.cs:738-751):
- Owner type comes from the zone (people zones, 1.4): prefixes on the `ForPrisoners` setter (Building_Bed.cs:44-73) and the `ForOwnerType` setter (Building_Bed.cs:92-108) refuse any change to a zone bed unless Zones' own `[ThreadStatic]` bypass flag is set. Vanilla changes owner types behind the zone's back in three places, and each flip posts one message per owner (`RemoveAllOwners`, Building_Bed.cs:738-751):
- at spawn in a prison cell (Building_Bed.cs:272-276);
- on every room recalculation of a prison cell, through `ForPrisoners` (Room.cs:721-727);
- through the bed gizmo: `SetBedOwnerTypeByInterface` collects every bed in the room, all of them when switching to Prisoner in a room that can be a prison cell and every prisoner bed when switching away, and sets them through `ForOwnerType` (Building_Bed.cs:395-473, collected at :419-436, set at :448, :452).
- Zones sets the flag around its own owner-type changes and around `base.DeSpawn` in `Building_ZoneBed`, where vanilla resets the type to Colonist (Building_Bed.cs:301). Vanilla's confirm for the gizmo (:475-480) may still count zone-bed owners who keep their cells; accepted.
- Choke point: `Building_ZoneBed.DeSpawn` is our own override, no Harmony. If Zones didn't start the removal, the mode isn't `WillReplace` and the cell is still a sleeping-zone cell, it unclaims the owners silently and queues a respawn for the next tick with the zone's flags.
- Sweep: every 250 ticks the component trims sleeping-zone cells that hold an edifice (backstop for the 1.2 edifice postfix), and from 1.5 it also runs the shared-zone and caste checks.
- Sweep: every 250 ticks the component trims sleeping-zone cells that hold an edifice (backstop for the 1.2 edifice postfix), and from 1.4 it also runs the shared-zone and caste checks.
- Reconcile: `MapComponent.FinalizeInit` (MapComponent.cs:32, called from Map.cs:851) drops sleeping-zone cells that hold an edifice, destroys beds whose cell is no longer in a sleeping zone and spawns missing beds. It never resets the owners, medical flag or owner type of a bed that still exists.
### Rules every feature follows
@ -143,7 +141,6 @@ From the three Castes review rounds.
- Judge removals at the choke point, never in a passing state: `Building_ZoneBed.DeSpawn` for beds, reconcile after loading.
- Optional-mod state can be missing at load. Map `FinalizeInit` runs inside `Map.FinalizeLoading`, before the game components' `FinalizeInit` and `LoadedGame` (Game.cs:611-647), so nothing drops stored data because a sibling looks empty there.
- Every hook body sits in try/catch with a one-time log. On routing paths the catch calls the original vanilla method.
- Finalizers return void. If any finalizer on a method returns `Exception`, Harmony throws the exception anew instead of rethrowing it (0Harmony EmitFinalizers, rethrowPossible), so its stack trace starts at the patched method: an exception from vanilla or another mod would be logged without its inner frames and blamed on Zones. A smoke test checks every Zones finalizer.
- Prefer a route without a patch where one exists, and never prefix a method of a few lines that the JIT may inline into its callers.
- Designators read their master toggle live through `Gizmo.Visible` (Gizmo.cs:31). A setting written into defs at startup says "restart required" in its tooltip, and code reads the def, not the setting.
@ -152,9 +149,9 @@ From the three Castes review rounds.
Every Blax mod works with any DLC combination, core only included (rule of 2026-11-29). For Zones:
- About.xml names no DLC, neither as a dependency nor in loadAfter.
- Every feature runs on the core game. The one part that needs a DLC is slave sleeping zones (Ideology, 1.5). Work rule areas (1.3) name no DLC def; with Biotech, cleansweepers and lifters follow the rules through the same work givers (`canBeDoneByMechs` defaults to true, WorkGiverDef.cs:50; `IsColonyMech` passes `PawnCanUseWorkGiver`, JobGiver_Work.cs:270). Biotech's pollution clearing (`CleanClearPollution`, Biotech WorkGiverDefs/WorkGivers.xml:347) and Odyssey's sand clearing (the snow clear area and `WorkGiver_ClearSnowOrSand`) have their own areas and aren't touched. Tribute collectors and Empire quests exist only with Royalty, but they reach Zones through core code (the caravan incident's base class, `QuestPart_DropPods`), so camping and reward routing have no Royalty code.
- Every feature runs on the core game. The one part that needs a DLC is slave sleeping zones (Ideology, 1.4). Work rule areas (1.6) name no DLC def; with Biotech, cleansweepers and lifters follow the rules through the same work givers (`canBeDoneByMechs` defaults to true, WorkGiverDef.cs:50; `IsColonyMech` passes `PawnCanUseWorkGiver`, JobGiver_Work.cs:270). Biotech's pollution clearing (`CleanClearPollution`, Biotech WorkGiverDefs/WorkGivers.xml:347) and Odyssey's sand clearing (the snow clear area and `WorkGiver_ClearSnowOrSand`) have their own areas and aren't touched. Tribute collectors and Empire quests exist only with Royalty, but they reach Zones through core code (the caravan incident's base class, `QuestPart_DropPods`), so camping and reward routing have no Royalty code.
- DLC defs only through `MayRequire` in XML and null-checked DefOf members in code. Zones' defs and patches name no DLC def: the designator patch anchors on Growing because the Fishing entry carries `MayRequire` Odyssey (Core Misc/Designations/DesignationCategories.xml:40-41), and the bed defs' `artificialForMeditationPurposes` and `bringAlongOnGravship` are core fields (BuildingProperties.cs:334, set by Core's own sleeping spots at Buildings_Furniture.xml:71 and :490; ThingDef.cs:167). The only DLC def the code reads is Biotech's Wastepack (Biotech ThingDefs_Items/Items_Resource_Manufactured.xml:280) through `ThingDefOf.Wastepack`, which is `[MayRequireBiotech]` (ThingDefOf.cs:235-236) and null without Biotech; every use checks for null.
- DLC code only behind `ModsConfig.<DLC>Active`. `ModLister.Check<DLC>` is no guard: it checks that the DLC is installed, not active (ModLister.cs:283-287, 347-364), so it passes in a run that leaves an installed DLC out and logs an error for a player who doesn't own it. Vanilla's `ForOwnerType` setter relies on it for slave beds (Building_Bed.cs:100), hence the 1.5 guard.
- DLC code only behind `ModsConfig.<DLC>Active`. `ModLister.Check<DLC>` is no guard: it checks that the DLC is installed, not active (ModLister.cs:283-287, 347-364), so it passes in a run that leaves an installed DLC out and logs an error for a player who doesn't own it. Vanilla's `ForOwnerType` setter relies on it for slave beds (Building_Bed.cs:100), hence the 1.4 guard.
- Settings and gizmos: no global setting needs a DLC. A per-zone choice that does shows disabled with a "Needs <DLC>" note instead of hiding: the owner-type gizmo's "Slaves" shows "Needs Ideology".
- A save made with a DLC loads without it:
- A slave zone keeps its owner type, as vanilla keeps a slave bed's (`forOwnerType` loads with no DLC check, Building_Bed.cs:319), and can still be switched to colonists or prisoners. With Ideology back it works as a slave zone again.
@ -174,11 +171,11 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
| Quest rewards land in the zone | 1.1 | None | Every item reward routes; Empire quests exist only with Royalty |
| Caravan purchases | 1.1 | None | Unchanged |
| Animal sleeping zones, animal filters, removal button | 1.2 | None | Unchanged |
| Work rule areas: no cleaning, firefighting, repairs or hauling; clean first, haul first | 1.3 | None | Unchanged; without Biotech there are no mechs to follow the rules |
| Stockpile and shelf deliveries, delivery under a roof, sell zones, cargo pods | 1.4 | None | Unchanged |
| People sleeping zones for colonists and prisoners; medical, shared and comfort; zone tints | 1.5 | None | Unchanged |
| Slave sleeping zones | 1.5 | Ideology | "Slaves" shows disabled with "Needs Ideology"; a slave zone from a save made with Ideology stays one and can be switched to colonists or prisoners |
| Caste filter | 1.6 | None (Blax Castes is a mod) | Unchanged |
| Stockpile and shelf deliveries, delivery under a roof, sell zones, cargo pods | 1.3 | None | Unchanged |
| People sleeping zones for colonists and prisoners; medical, shared and comfort; zone tints | 1.4 | None | Unchanged |
| Slave sleeping zones | 1.4 | Ideology | "Slaves" shows disabled with "Needs Ideology"; a slave zone from a save made with Ideology stays one and can be switched to colonists or prisoners |
| Caste filter | 1.5 | None (Blax Castes is a mod) | Unchanged |
| Work rule areas: no cleaning, firefighting, repairs or hauling; clean first, haul first | 1.6 | None | Unchanged; without Biotech there are no mechs to follow the rules |
| Royal title rewards | Backlog | Royalty | Not offered |
| Age limits on people zones | Backlog | Biotech | Shown disabled with "Needs Biotech" |
| Blax zones fly with gravships | Backlog | Odyssey | Zones stay behind, as today |
@ -210,7 +207,7 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
- **Players get:** A new "Delivery zone" in the Zone menu, dragged like a stockpile. Its tab has an item filter (what may land here), a priority from Low to Critical, and source checkboxes (orbital traders now, quest rewards and caravan traders in 1.1). While the zone is selected, red outlines mark cells drop pods can't use (roofed, inside an enclosed pen, water or vacuum, a building in the way, blocked, fogged, unreachable), and the inspect pane gives their total. Like every vanilla zone, it extends the home area 4 cells around itself; the tooltip says so.
- **How:**
- `Zone_Delivery : Verse.Zone` with `ThingFilter filter` (all items allowed; corpses and, with Biotech, Wastepack hidden and always refused; a null `ThingDefOf.Wastepack` is skipped), `StoragePriority priority = Normal`, `acceptOrbital` (true) and `campHere` (false), each scribed with its default. 1.1 adds `acceptRewards` and `acceptCaravan`, 1.4 `acceptCargoPods` and `directDelivery`, the same way.
- `Zone_Delivery : Verse.Zone` with `ThingFilter filter` (all items allowed; corpses and, with Biotech, Wastepack hidden and always refused; a null `ThingDefOf.Wastepack` is skipped), `StoragePriority priority = Normal`, `acceptOrbital` (true) and `campHere` (false), each scribed with its default. 1.1 adds `acceptRewards` and `acceptCaravan`, 1.3 `acceptCargoPods` and `directDelivery`, the same way.
- Designators: `Designator_ZoneAdd_Delivery` plus an `_Expand` subclass reached through `DesignatorUtility.FindAllowedDesignator` (DesignatorUtility.cs:25-46), as `Zone_Fishing` does (Zone_Fishing.cs:196-199). `Designator_ZoneAdd` compares the exact zone type and refuses cells in other zones (Designator_ZoneAdd.cs:46, 73, 114, 127). Expanding over the zone only adds new cells. A namespace-qualified `PatchOperationInsert` adds the designator after the `Designator_ZoneAdd_Growing` entry in DesignationCategoryDef Zone `specialDesignatorClasses` (Core Misc/Designations/DesignationCategories.xml:40); anchor on Growing, because the Fishing entry (:41) carries `MayRequire`. `Visible` reads the master toggle live.
- Tab: `ITab_Delivery` holds the priority dropdown, the source checkboxes, the camp checkbox, `ThingFilterUI.DoThingFilterConfigWindow` and copy/paste gizmos with our own clipboard.
- Cell validity uses the router's pod rule. `MapComponentUpdate` draws `GenDraw.DrawFieldEdges` over invalid cells while the zone is selected. `GetInspectString` adds "N cells drop pods can't use"; the breakdown by reason is in the Backlog.
@ -223,7 +220,7 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
- **Replaces:** Together with the routing below: Trade Ships Drop Spot (1969732297, 206,371 subs, official versions up to 1.6) and its unofficial 1.7 ports (3828260574, 127; 3837213962, 70), the orbital drop spot of Trading Control (2007107588, 111,091, up to 1.6), Orbital Trade Goods Landing Zone (3015945224, 161, 1.5). Quest rewards, the other half of what Trade Ships Drop Spot does, follow in 1.1.
- **Effort:** M, 2 days, router included.
- **Tests:** Designating unroofed cells creates a `Zone_Delivery`; the expand gizmo grows it and only adds cells. The designator refuses cells in an existing stockpile. Roof 3 cells and `GetInspectString` reports 3 unusable cells; a water cell makes it 4. A fence ring with an animal pen marker around the zone makes every cell unusable. The default filter allows silver, medicine and steel and refuses Wastepack (Biotech); without Biotech it builds with no error. Filter, priority, orbital and camp flags persist in phase 2. `ZonesApi.TryFindDropSpot` returns a zone cell for steel and false for a pawn; with the zone's orbital checkbox off it returns false. The overflow radius setting can't go below 5.
- **Risks:** One zone per cell, so a delivery zone can't overlap a stockpile. Goods land and haulers store them; 1.4 lets stockpiles receive deliveries directly. Pods never land in an enclosed pen (vanilla rule). The red overlay shows this instead of failing silently like Trading Control's spot. Pick Up And Haul (1279012058, 1,784,752 subs) patches hauling only; it collects goods from the zone several stacks per trip, and nothing changes for us.
- **Risks:** One zone per cell, so a delivery zone can't overlap a stockpile. Goods land and haulers store them; 1.3 lets stockpiles receive deliveries directly. Pods never land in an enclosed pen (vanilla rule). The red overlay shows this instead of failing silently like Trading Control's spot. Pick Up And Haul (1279012058, 1,784,752 subs) patches hauling only; it collects goods from the zone several stacks per trip, and nothing changes for us.
#### Orbital purchases land in the zone
@ -260,8 +257,8 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
- **Harness:** copy Castes' Tests/BlaxCastesTests to Tests/BlaxZonesTests. Command-line switch `-blaxzonestests`, data folder `%TEMP%\BlaxZonesTest`, results file `BlaxZonesTestResults.txt`. Keep from Castes' run-tests.ps1: the RimWorld path guard, the lock file and the junction check, `-AllowWhileRunning`, `-NoBuild`, `-NoDlc` and `-Dlc`, and deleting the settings files every run (renamed to `Mod_BlaxZones_*`). The game runs headless (run-tests.ps1:157), so no test asserts on a screenshot; what needs eyes goes into `docs/ingame-check.md`, as in Castes. A release runs all 8 DLC combinations (see "DLC support").
- **Phase 3:** after phase 2 the runner saves as `BlaxZonesTest3` (saves are plain XML in 1.7, ScribeSaver.cs:45-49), replaces `Class="BlaxZones.MapComponent_BlaxZones"` with a type that doesn't exist, loads, and runs the `phase: 3` tests. Zones' assembly stays loaded, so `Map.FillComponents` adds a fresh, empty component: phase 3 proves the vanilla side of a removed-mod save loads cleanly, not that the game runs without the code (a full removal run is in the Backlog).
- **Expected errors:** add `T.ExpectErrors(fragment, count)`. Both removal errors include the node's OuterXml, so the harness's "ours" check would count them as Zones errors. Phase 3 allows exactly two per map. "Could not resolve reference" warnings are counted and reported as INFO (from 1.1 the phase-2 reload fails on them, see "Headless tests in 1.1"). From 1.2, `T.ExpectCurToilErrorsFor(pawns)` accepts "tried to get CurToil" errors only when they name a pawn the phase-2 run recorded as lying in a zone bed, and requires at least one per such pawn.
- **KnownForeignErrors:** the `CanUseBedNow` postfix (1.2) and the `Toils_LayDown.ApplyBedRelatedEffects` postfix (1.5) sit in many stacks. Errors that Hospitality, Prison Labor or VEF log from their own code while a test ticks would name BlaxZones frames. Add each one with its text and frame, as Castes did for Weapons Tab Reborn.
- **Expected errors:** add `T.ExpectErrors(fragment, count)`. Both removal errors include the node's OuterXml, so the harness's "ours" check would count them as Zones errors. Phase 3 allows exactly two per map. "Could not resolve reference" warnings are counted and reported as INFO. From 1.2, `T.ExpectCurToilErrorsFor(pawns)` accepts "tried to get CurToil" errors only when they name a pawn the phase-2 run recorded as lying in a zone bed, and requires at least one per such pawn.
- **KnownForeignErrors:** the `CanUseBedNow` postfix (1.2) and the `Toils_LayDown.ApplyBedRelatedEffects` postfix (1.4) sit in many stacks. Errors that Hospitality, Prison Labor or VEF log from their own code while a test ticks would name BlaxZones frames. Add each one with its text and frame, as Castes did for Weapons Tab Reborn.
- **Compat runs:** `-Compat` adds 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, Blax Castes, Blax Slaves, and Blax Defaults once it has code. Mods that change `TradeDropSpot` or `AllLaunchableThingsForTrade` stay out of `-Compat`, so they can't hide Zones' own path (the Castes spec review found Trade as Slave or Colonist hiding Blax Slaves' buy mode). None of the replaced mods is installed; compose with them through test-only prefixes.
- **Stand-down tests:** inject package ids into a `SimulatedActive` set, the Castes overlap-warning pattern. One per trading-spot id in Compat.cs.
- **Fixtures to add**, only those 1.0 uses; later releases list their own:
@ -280,7 +277,7 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
- **Players get:** Item rewards from quests (Empire quests included, with Royalty) drop into a delivery zone that has rewards ticked, and the quest letter points there. Refugees, prisoners, mechs, wastepacks, ransom returns and raids never come to the zone.
- **How:**
- This feature builds the DeliveryContext from the data model, which cargo pods (1.4) reuse. A context prefix and finalizer sit on two callers:
- This feature builds the DeliveryContext from the data model, which cargo pods (1.3) reuse. A context prefix and finalizer sit on two callers:
- `QuestPart_DropPods.Notify_QuestSignalReceived` (QuestPart_DropPods.cs:124), only when `useTradeDropSpot` is true and `dropSpot` is invalid (:165, 298-303): exactly the drops vanilla sends to the trade spot. `Reward_Items` creates these (Reward_Items.cs:180).
- `QuestPart_GiveNearPawn.Notify_QuestSignalReceived` (QuestPart_GiveNearPawn.cs:107), which always uses the trade spot (:187-188).
- While the context is set, a prefix on `DropPodUtility.DropThingGroupsNear` (DropPodUtility.cs:40) takes `thingsGroups` as a ref parameter. A group qualifies when it holds no Pawn and no Wastepack and all its things pass one zone (rewards ticked, filter). The prefix plans every group's target before it drops anything, so a failure halfway can't drop a group twice; on an exception vanilla gets the original list.
@ -289,7 +286,7 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
- With `dropAllInSamePod`, a pawn and the items share one group (QuestPart_DropPods.cs:209-212), so nothing routes.
- The letter needs no patch: `QuestPart_DropPods` builds its look target after dropping, from the first dropped thing that is spawned (:219-233), and `QuestPart_GiveNearPawn` does the same (:190-197). If a refugee comes first in the list, the letter points at the refugee's pod, as in vanilla.
- Ransom (`ChoiceLetter_RansomDemand` calls `SpawnDropPod`), lent-colonist returns, edge drops and center drops never set the context.
- Unsubscribe hint: if def `DropSpotTradeShip` exists (Trade Ships Drop Spot's marker; check the def name in its files before shipping) while "Route orbital trade" and "Route quest rewards" are both on, a one-time message says the player can unsubscribe from it. The map tick shows it once the map has a delivery zone: before that Zones routes nothing, and unsubscribing would send rewards back to the beacon. "Shown" is a hidden bool in the mod settings file, never in the save, so the hint doesn't come back on the next load or game; after that the tick check is one bool read.
- Unsubscribe hint: if def `DropSpotTradeShip` exists (Trade Ships Drop Spot's marker; check the def name in its files before shipping) while "Route orbital trade" and "Route quest rewards" are both on, a one-time message says the player can unsubscribe from it.
- **Settings:** Global "Route quest rewards" (on). Per zone: rewards checkbox (on).
- **Save and removal:** Nothing saved. The context lives for one call.
- **Replaces:** The quest-reward half of Trade Ships Drop Spot (206k) and Trading Control (111k).
@ -299,11 +296,9 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
- Add a refugee pawn: its pod is not in a zone, the items' pods are. A Wastepack is never routed (Biotech; skipped without). `dropAllInSamePod` routes nothing.
- The list passed in still holds every group afterwards. With `instaDrop`, items appear with no pod. A faction-skinned call keeps its faction on the pod.
- `DropThingsNear` without the context, as a raid would call it, is untouched.
- A chained part: the first part's `outSignalResult` triggers a second `QuestPart_DropPods` with `useTradeDropSpot` false; the second part's drop is not routed. A chained test-only part with no Zones prefix of its own sees no context, so only the `SendSignal` patch can keep its `DropThingsNear` unrouted.
- Each half of the context condition alone: a trade-spot part with its own `dropSpot`, and a part with a random spot, run with no context.
- An exception inside the context leaves `DeliveryContext.Current` null, and its stack trace still names the frame that threw. A failure on the second group drops nothing twice. Planning throws: vanilla drops every group at its spot.
- With overflow off, stacks that don't fit the zone go to the vanilla spot.
- With `DropSpotTradeShip` simulated, map ticks show the unsubscribe message once with a delivery zone and both routing toggles on, never without a delivery zone or with either toggle off.
- A chained part: the first part's `outSignalResult` triggers a second `QuestPart_DropPods` with `useTradeDropSpot` false; the second part's drop is not routed.
- An exception inside the context leaves `DeliveryContext.Current` null. A failure on the second group drops nothing twice.
- With `DropSpotTradeShip` simulated, the unsubscribe message appears once with both routing toggles on and never with rewards off.
- **Risks:** Mod quests that drop rewards through their own code aren't covered unless they use `QuestPart_DropPods` with `useTradeDropSpot` or `DropThingsNear` inside one of the two callers. Finalizers keep the context from leaking.
#### Caravan purchases appear in the zone
@ -313,21 +308,18 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
- `Pawn_TraderTracker.GiveSoldThingToPlayer` (Pawn_TraderTracker.cs:178-203): pawns return early (:180-188) and are never touched. Items go through exactly one `GenPlace.TryPlaceThing(Thing, IntVec3, Map, ThingPlaceMode, Action<Thing,int>, Predicate<IntVec3>, Rot4?, int)` call (GenPlace.cs:27) at :194, in Near mode at the carrier's `PositionHeld`. On success vanilla adds the item to `lord.extraForbiddenThings` (:196); on failure it logs an error and destroys the item (:199-202).
- A transpiler replaces that call with `DeliveryRouter.PlaceFromCaravan`, same signature. For each candidate zone (caravan ticked, filter, priority) it tries `GenPlace.TryPlaceThing` at the best cell in Near mode with the placement rule plus "cell is in this zone" as validator. Next it tries Near at the top zone's overflow center with no validator. Last it calls the original with the original arguments, also on any exception, so the vanilla destroy path is reached only where vanilla would reach it. Vanilla then adds the item to `extraForbiddenThings` as before.
- Hospitality guests sell through `Pawn.GiveSoldThingToPlayer`, which calls this method (Verse/Pawn.cs:4711-4714), so their goods route too. Hospitality's own prefix there only records item IDs. Routing everything that comes through this method is the simple rule; checking for a `LordJob_TradeWithColony` lord would exclude guests (cut).
- Sale silver comes through the same call: when the player sells more than they buy, `CurrencyTradeable` is forced to source (TradeDeal.cs:147) and `ResolveTrade` hands the trader's silver over with `GiveSoldThingToPlayer` (Tradeable.cs:472-478). It lands in the zone like a purchase, as sale silver from orbital traders does, and the texts say so.
- Overflow follows "Overflow lands next to the zone" and the reach rule, as for pods; otherwise the goods stay at the carrier's feet.
- Message: a prefix on `TradeDeal.TryExecute(out bool)` (TradeDeal.cs:150) opens a `[ThreadStatic]` list, and `PlaceFromCaravan` adds each placed stack with its own zone, and whether it lies next to that zone (overflow), to it. A stack split over two zones counts both. A postfix sends one message naming the zone, "next to" the zone when every stack overflowed, or "N delivery zones", with look targets on the placed things. The text says "goods from the trade", since sale silver comes the same way; a finalizer clears the list and sends what it collected if the trade threw. Outside a trade (a mod calling `GiveSoldThingToPlayer` directly), `PlaceFromCaravan` sends one message per call. Prefix and postfix only, so the trade mods that also touch `TryExecute` compose. Vanilla selling also moves colony goods out of stockpiles instantly (Pawn_TraderTracker.cs:149-176), so goods appearing matches it. Own patch class and toggle.
- Message: a prefix on `TradeDeal.TryExecute(out bool)` (TradeDeal.cs:150) opens a `[ThreadStatic]` list, and `PlaceFromCaravan` adds each placed thing and its zone to it. A postfix sends one message naming the zone (or "N delivery zones") with look targets on the placed things; a finalizer clears the list and sends what it collected if the trade threw. Outside a trade (a mod calling `GiveSoldThingToPlayer` directly), `PlaceFromCaravan` sends one message per call. Prefix and postfix only, so the trade mods that also touch `TryExecute` compose. Vanilla selling also moves colony goods out of stockpiles instantly (Pawn_TraderTracker.cs:149-176), so goods appearing matches it. Own patch class and toggle.
- **Settings:** Global "Route caravan purchases" (on), "Message when goods arrive" (on). Per zone: caravan checkbox (on), tooltip "Trader caravans and guests".
- **Save and removal:** Nothing saved. Goods already placed stay where they are.
- **Replaces:** Nothing directly. The trading-spot mods only move the caravan; 1.0 covers them.
- **Effort:** S, half a day.
- **Tests:** Force `IncidentWorker_TraderCaravanArrival`, take the trader pawn and a non-pawn Thing from `trader.Goods`, call `GiveSoldThingToPlayer(thing, 1, negotiator)`. The item is spawned in the zone and listed in the lord's `extraForbiddenThings`. A fully roofed zone still receives it. With every zone cell holding a different item, it lands near the zone and the message says "next to"; with overflow off, next to the carrier. Silver over the first zone's room splits over two zones, and the message counts both. With no zones, next to the carrier. A bought animal doesn't move. The router throws: the item lands next to the carrier, nothing is destroyed. Buying 3 stacks in one `TradeDeal.TryExecute` posts exactly 1 message that names the zone. With Hospitality (`-Compat`), a purchase from a guest lands in the zone. The transpiler logged no "unexpected call count" error.
- **Tests:** Force `IncidentWorker_TraderCaravanArrival`, take the trader pawn and a non-pawn Thing from `trader.Goods`, call `GiveSoldThingToPlayer(thing, 1, negotiator)`. The item is spawned in the zone and listed in the lord's `extraForbiddenThings`. A fully roofed zone still receives it. With every zone cell holding a different item, it lands near the zone. With no zones, next to the carrier. A bought animal doesn't move. The router throws: the item lands next to the carrier, nothing is destroyed. Buying 3 stacks in one `TradeDeal.TryExecute` posts exactly 1 message that names the zone. With Hospitality (`-Compat`), a purchase from a guest lands in the zone. The transpiler logged no "unexpected call count" error.
- **Risks:** Goods appear instead of being carried; carried delivery is cut. A mod that rewrites `Pawn_TraderTracker.GiveSoldThingToPlayer` would conflict; none in the active set. Hospitality (753498552, 768,480 subs, 1.6 build) only adds a pass-through prefix on `Pawn.GiveSoldThingToPlayer` (its Source/Patches/Pawn_Patch.cs), and its records don't depend on where the item lies.
#### Headless tests in 1.1
- Fixture `QuestDropPods(things, useTradeDropSpot)` with an optional chained second part.
- `-NoDlc` and `-Dlc` runs: everything runs on the core game; only the Wastepack test needs Biotech.
- Reload check: the harness files the phase-2 load under its own tag and a phase-2 test fails on any "Could not resolve reference" warning, so a reference Zones saves but can't load turns the run red. After every test it notes each pawn relation whose other pawn no save holds, with who took that pawn out of the world pawns. One vanilla leak is excused by name: `TaleData_Pawn.GenerateRandom` (TaleData_Pawn.cs:110-115) makes a pawn for a book's text (Book.cs:235), also for every book in a trader caravan's stock, keeps only its tale data and never saves the pawn. PawnGenerator may hand it a world pawn or a new one with relations to existing pawns, so the forced caravans leave up to about 20 such warnings per run (none to 19 seen). With Hospitality (`-Compat`) also Lord warnings: its `CompGuest.PostSpawnSetup` stores `Pawn.GetLord()` on every humanlike pawn, saves it as a reference and never clears it when the pawn leaves the map, so the forced caravans' pawns keep their ended lord. Zones saves no Lord reference.
### 1.2 Animal sleeping zones (6 days)
@ -335,19 +327,19 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
- **Players get:** A new "Animal sleeping zone" in the Zone menu. Every cell works like an animal sleeping spot, so one drag over the barn beds every chicken and duck. Shrinking or deleting the zone removes its cells. Sleeping zones don't extend the home area.
- **How:**
- Zone beds as in the data model. `Zone_SleepingBase : Zone` holds what both kinds share; `Zone_SleepingAnimals` ships now and `Zone_SleepingPeople` in 1.5. Separate types keep the designators from expanding each other's zones, since `Designator_ZoneAdd` compares the exact type. Animal zones get one fixed tint, brown at alpha 0.09.
- Zone beds as in the data model. `Zone_SleepingBase : Zone` holds what both kinds share; `Zone_SleepingAnimals` ships now and `Zone_SleepingPeople` in 1.4. Separate types keep the designators from expanding each other's zones, since `Designator_ZoneAdd` compares the exact type. Animal zones get one fixed tint, brown at alpha 0.09.
- `AddCell` calls the base, then spawns a `Building_ZoneBed` as the data model describes. The designator refuses cells with an edifice or bed.
- Cap: `Designator_ZoneAdd_SleepingBase` overrides `DesignateMultiCell` (Designator_ZoneAdd.cs:104). When the map's sleeping-zone cells plus the dragged cells exceed the cap, it passes only the first cells of the drag up to the cap to the base and posts one message naming the cap; at the cap it adds nothing and posts the same message.
- Home area: `Zone_SleepingBase.AddCell` sets `Find.PlaySettings.autoHomeArea` to false around `base.AddCell` and restores it in a `finally`. `AutoHomeAreaMaker.Notify_ZoneCellAdded` reads that setting first (AutoHomeAreaMaker.cs:9-16, 48-58), and the base `Zone.AddCell` always calls it (Zone.cs:232). No patch: a prefix on that 10-line static method could be inlined. `expandHomeArea` false on the bed def covers the bed's own spawn (AutoHomeAreaMaker.cs:18-24).
- Spawn cost: each bed spawn runs `District.Notify_RoomShapeOrContainedBedsChanged`, which walks regions only when the map has facilities (District.cs:235-247, FacilitiesUtility.cs:19-60), and `Room.Notify_RoomShapeChanged` with its temperature, auto roof area and prison-cell work (Room.cs:686-729). If a 500-cell drag takes more than 100 ms in the harness, spawn a drag's beds 50 per tick.
- `RemoveCell` and deregistration unclaim owners first with `pawn.ownership.UnclaimBed()`, then destroy, so there is no "lost assignment" spam; the loading flag skips this during load.
- Def `BlaxZones_ZoneAnimalBed` (`bed_humanlike` false): 1x1, Standable, FloorEmplacement, no `sowTag` (so `CanOverlapZones` stays true), `building.isEdifice` false, `building.deconstructible` false, `building.bed_showSleeperBody` true, `building.expandHomeArea` false, `bringAlongOnGravship` false, `selectable` false, `drawGUIOverlay` false, `drawerType` None, `useHitPoints` false, WorkToBuild 0, Flammability 0, no cost list (no wealth), no designationCategory, `tickerType` Never, `isSaveable` false, `CompAssignableToPawn_Bed`. The uiIcon uses the vanilla AnimalSleepSpot texture. 1.5 adds the humanlike defs with the same flags.
- Def `BlaxZones_ZoneAnimalBed` (`bed_humanlike` false): 1x1, Standable, FloorEmplacement, no `sowTag` (so `CanOverlapZones` stays true), `building.isEdifice` false, `building.deconstructible` false, `building.bed_showSleeperBody` true, `building.expandHomeArea` false, `bringAlongOnGravship` false, `selectable` false, `drawGUIOverlay` false, `drawerType` None, `useHitPoints` false, WorkToBuild 0, Flammability 0, no cost list (no wealth), no designationCategory, `tickerType` Never, `isSaveable` false, `CompAssignableToPawn_Bed`. The uiIcon uses the vanilla AnimalSleepSpot texture. 1.4 adds the humanlike defs with the same flags.
- Why those flags:
- `deconstructible` false: they are player buildings and `deconstructible` defaults to true (BuildingProperties.cs:21, 436-449). A deconstruct drag over a barn would destroy every bed at once, since work 0 destroys immediately (Designator_Deconstruct.cs:69-76).
- `bed_showSleeperBody` true: the default false hides a humanlike sleeper's body (BuildingProperties.cs:174; PawnRenderNodeWorker_Body.cs:29-31, PawnRenderer.cs:448), and with `drawerType` None there is no blanket either, so an adult would show as a floating head. Both vanilla spots set it (Core ThingDefs_Buildings/Buildings_Furniture.xml:64, :479). It matters for the 1.5 people defs; the animal def sets it to match.
- `bed_showSleeperBody` true: the default false hides a humanlike sleeper's body (BuildingProperties.cs:174; PawnRenderNodeWorker_Body.cs:29-31, PawnRenderer.cs:448), and with `drawerType` None there is no blanket either, so an adult would show as a floating head. Both vanilla spots set it (Core ThingDefs_Buildings/Buildings_Furniture.xml:64, :479). It matters for the 1.4 people defs; the animal def sets it to match.
- `bringAlongOnGravship` false (ThingDef.cs:167, checked in Gravship.cs:607-634): takeoff would otherwise despawn the beds with `WillReplace` (GravshipUtility.cs:389), keep their owners and, in a save made during flight, deep-save them inside `Gravship.things` (Gravship.cs:335). That bypasses `isSaveable`, which only `Map.ExposeData` checks, and would break the save after mod removal. Landing runs on a map that already exists (WorldComponent_GravshipController.cs:529-538), so reconcile never sees carried beds. It is a core `ThingDef` field (ThingDef.cs:167), so the def loads without Odyssey.
- Copied from the vanilla spots: SurgerySuccessChanceFactor 0.7, `scatterableOnMapGen` false (needed for `IsClearableFreeBuilding`, Building.cs:64-74), `ai_chillDestination` false, `artificialForMeditationPurposes` false, `wakeDormantPawnsOnConstruction` false (Core Buildings_Furniture.xml:49-79, 459-491). Like the vanilla spots they leave `socialPropernessMatters` off. The vanilla spots carry `sowTag` SupportPlantsOnly, which is why ours can't copy it.
- Bed search order: `RestUtility.Reset` (RestUtility.cs:25-44) builds the best-to-worst bed lists, sorted by `bed_maxBodySize`, then rest effectiveness, keeping definition order on ties. It runs before `[StaticConstructorOnStartup]` (PlayDataLoader.cs:207 vs 360). A postfix moves our animal def directly before AnimalSleepingSpot (1.5 adds the people defs before SleepingSpot), and the patch class calls `RestUtility.Reset()` once after patching. Otherwise unowned animals walk to any free vanilla spot first.
- Bed search order: `RestUtility.Reset` (RestUtility.cs:25-44) builds the best-to-worst bed lists, sorted by `bed_maxBodySize`, then rest effectiveness, keeping definition order on ties. It runs before `[StaticConstructorOnStartup]` (PlayDataLoader.cs:207 vs 360). A postfix moves our animal def directly before AnimalSleepingSpot (1.4 adds the people defs before SleepingSpot), and the patch class calls `RestUtility.Reset()` once after patching. Otherwise unowned animals walk to any free vanilla spot first.
- Edifices: a postfix on `EdificeGrid.Register` (EdificeGrid.cs:21-33) queues the cell when any edifice spawns on a sleeping-zone cell, so no cell holds two beds. `Building.SpawnSetup` registers the edifice before the rest of its spawn (Building.cs:113-127), so destroying our bed inside the postfix would run mid-spawn. The component handles the queue on its next tick and before saving: `RemoveCell`, then `CheckContiguous`, as vanilla does for overlap (ZoneManager.cs:97-112). This replaces a hook on the hot virtual `Building.SpawnSetup`. If the JIT inlines `Register` into a caller and the postfix stops firing there, the 250-tick sweep from the data model trims the cell instead. Vanilla already trims zone cells for walls, storage and tables, which can't overlap zones (ThingDef.cs:625-655); beds and doors can, hence the postfix.
- Building over a zone bed needs no patch: `GenConstruct.CanPlaceBlueprintOver` already allows it over non-edifices (GenConstruct.cs:676-703), and `SpawnBuildingAsPossible` won't wipe a non-edifice zone bed on load (GenSpawn.cs:196-235).
- Cutting the zone: a wall line across it removes the wall cells, and `Zone.CheckContiguous` keeps the part holding the zone's first cell and removes the rest (Zone.cs:345-397). The zone does not split in two. Removed cells lose their beds and owners silently.
@ -380,7 +372,7 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
- **Players get:** The animal zone tab lists species with checkboxes and a body-size range, so big stalls stay free of chickens. The inspect pane warns when the filter leaves out every tamed animal on the map.
- **How:**
- `Zone_SleepingAnimals` gets `HashSet<string> disallowedRaces`, a deny-list of race defNames resolved with `GetNamedSilentFail`, so new species are allowed by default and a removed animal mod leaves nothing unresolved. Plus `FloatRange bodySize` (0 to unlimited).
- A postfix on `RestUtility.CanUseBedNow(Thing bedThing, Pawn sleeper, bool checkSocialProperness, bool allowMedBedEvenIfSetToNoCare, GuestStatus? guestStatusOverride)` (RestUtility.cs:72) at `Priority.Low` checks the bed type first. For a `Building_ZoneBed` whose zone rejects the sleeper it sets false. The zone comes from `zoneGrid` in O(1). This one patch covers `FindBedFor` (RestUtility.cs:235), `FindPatientBedFor` (:328), rescue, capture, `Toils_Bed.BedNoLongerUsable` and `FailOnBedNoLongerUsable` (Toils_Bed.cs:58-96), childcare and rituals. 1.6 adds the caste check to the same postfix.
- A postfix on `RestUtility.CanUseBedNow(Thing bedThing, Pawn sleeper, bool checkSocialProperness, bool allowMedBedEvenIfSetToNoCare, GuestStatus? guestStatusOverride)` (RestUtility.cs:72) at `Priority.Low` checks the bed type first. For a `Building_ZoneBed` whose zone rejects the sleeper it sets false. The zone comes from `zoneGrid` in O(1). This one patch covers `FindBedFor` (RestUtility.cs:235), `FindPatientBedFor` (:328), rescue, capture, `Toils_Bed.BedNoLongerUsable` and `FailOnBedNoLongerUsable` (Toils_Bed.cs:58-96), childcare and rituals. 1.5 adds the caste check to the same postfix.
- Changing a filter, or pasting settings onto a zone, unclaims the owners that no longer pass, with one message naming the count. Vanilla's `FailOnBedNoLongerUsable` gets an animal already lying there out of bed.
- The tab has a search field, the species list (species tamed on this map first, then all animal races) and `Widgets.FloatRange` for size.
- **Settings:** Per animal zone: species deny-list (empty), body size (any). No global setting.
@ -394,8 +386,8 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
- **Players get:** Click "Remove Blax Zones from this game" in the mod settings, save, then disable the mod, and the save loads with no errors and no warnings from Zones. Without the button the save still loads, with the warnings and errors listed in the data model.
- **How:**
- Needs a loaded game and a confirmation dialog that names the counts (zones, zone beds; from 1.3 work rule areas; from 1.4 flagged storage).
- From 1.3 it also ends every current job and drops every queued job whose `workGiverDef` is `BlaxZones_CleanFirst` or `BlaxZones_HaulFirst`, then deletes the work rule areas through the component's own delete, which calls `ListerHaulables.RecalcAllInCell` (ListerHaulables.cs:146-153) on every cell that had "Don't haul from here" once the rule is gone, so those items are hauled again in the same game.
- Needs a loaded game and a confirmation dialog that names the counts (zones, zone beds; from 1.3 flagged storage; from 1.6 work rule areas).
- From 1.6 it also ends every current job and drops every queued job whose `workGiverDef` is `BlaxZones_CleanFirst` or `BlaxZones_HaulFirst`, then deletes the work rule areas through the component's own delete, which calls `ListerHaulables.RecalcAllInCell` (ListerHaulables.cs:146-153) on every cell that had "Don't haul from here" once the rule is gone, so those items are hauled again in the same game.
- On every map: unclaim owners of zone beds silently, end every job whose target is a zone bed (`jobs.EndCurrentJob(JobCondition.InterruptForced)`), destroy the beds with the choke point told that Zones started it, deregister our zones, then remove the component from `map.components`.
- Set the removal flag from the data model; the `Map.FillComponents` postfix keeps the component off every map of this game from then on.
- It ends with the message "Save now, then disable the mod". A dev debug action does the same.
@ -413,12 +405,191 @@ Every Blax mod works with any DLC combination, core only included (rule of 2026-
#### Headless tests in 1.2
- Fixture `SleepingZone(rect, kind)`; 1.5 adds the owner type.
- Fixture `SleepingZone(rect, kind)`; 1.4 adds the owner type.
- Performance in `-Compat`: time 2500 ticks with and without 500 animal zone beds, median of three runs each, written to the results file. The test fails when the zone beds add more than 10%.
- KnownForeignErrors: add any foreign error found in these runs.
- Effort: S, half a day for the performance and compat runs.
### 1.3 Work rule areas (8 days)
### 1.3 Stockpiles, shelves, roofs and selling (6 days)
Stockpile deliveries and direct delivery ship together: most freezers and hospital shelves are roofed, so the flag alone does little for orbital goods.
#### Stockpiles and shelves receive deliveries
- **Players get:** A "Receive deliveries" gizmo on any stockpile, shelf, rack or fridge lets bought goods and rewards go straight into it, by its own filter and priority: medicine onto the hospital shelves, food into the freezer, no hauling. Delivery zones and flagged storage compete by priority.
- **How:**
- Flags live in `MapComponent_BlaxZones` as a `HashSet<int>` of stockpile zone IDs and a `HashSet<int>` of storage building ThingIDs, never as fields on `Zone_Stockpile` or `Building_Storage`. Zone IDs and ThingIDs are never reused, so a stale flag can't land on a new storage.
- Gizmos come from postfixes on `Zone_Stockpile.GetGizmos` (Zone_Stockpile.cs:75) and `Building_Storage.GetGizmos` (Building_Storage.cs:227). RimFridge's and Weapon Racks' storage buildings call the base, so they get the gizmo.
- Storage groups: shelves can be linked into a group (Building_Storage.cs:13), whose settings every member reads through `GetStoreSettings()` (Building_Storage.cs:100-107). Group membership changes through vanilla's link gizmos (Building_Storage.cs:241-244) without calling Zones. So a storage building counts as flagged when it or any member of its `StorageGroup` is flagged, and the gizmo on a grouped building sets or clears the flag on every member. A shelf linked into a flagged group later is flagged through the group. A shelf leaving a group keeps its own flag, as vanilla copies the group's settings onto it (StorageGroupUtility.cs:163-184); one that joined after the flag was set has none of its own and leaves unflagged.
- The router adds flagged storage as candidates, with accept from `StorageSettings.AllowedToAccept(thing)` and priority from `StorageSettings.Priority`, both through `GetStoreSettings()`; building cells come from `AllSlotCells()`. Storage targets use the storage rule from the data model and fill mergeable stacks first.
- Pods use only stockpile cells that pass the pod rule. Shelves are edifices, so they get orbital goods only with direct delivery. Caravan placement and direct delivery put the thing on a storage cell with `GenPlace.TryPlaceThing(thing, cell, map, ThingPlaceMode.Direct)` and try the next cell on failure.
- A deleted stockpile or storage building drops its ID on the next lookup. The gizmo tooltip says roofed targets need direct delivery for orbital goods and rewards.
- **Settings:** Global "Stockpiles and shelves may receive deliveries" (on). Per stockpile and storage building: gizmo (off).
- **Save and removal:** The flag sets save in the component. Without the mod they vanish with the component node; the stockpiles and shelves keep their own settings.
- **Replaces:** [DHM]Organized Trade Pod System (3490887589, 1,816 subs, no 1.7), Skipdoor Delivery (3233578663, 2,749, no 1.7) for trade goods.
- **Effort:** M plus S, 2.5 days. The S is the storage rule and storage groups.
- **Tests:** An unroofed flagged food stockpile at Important plus a general delivery zone at Normal: bought rice lands in the stockpile, steel in the zone. A flagged medicine shelf in a roofed hospital with direct delivery on: orbital medicine appears on the shelf. A vanilla shelf cell (PassThroughOnly) receives a direct delivery. Caravan rice goes into a roofed flagged freezer. A linked shelf group: flagging one shelf flags every member, and priority and filter come from the group. A new shelf linked into the flagged group receives a delivery; unlinked again, it doesn't. A shelf that was in the group when it was flagged keeps receiving after it is unlinked. Storage targets fill mergeable stacks before empty cells. Flags survive reload. A deleted stockpile is no longer a target. Phase 3 loads with no errors from the flag sets. `-Compat`: a RimFridge fridge (PassThroughOnly) and a RimFridge wall fridge (Impassable) each receive a delivery; a Weapon Racks rack holds no more than its items per cell.
- **Risks:** Without direct delivery, roofed freezers and shelves get only caravan goods; the tooltip says so. Overlapping mods:
- RimFridge: Now with Shelves! (2898411376, 282,094 subs, 1.6 build): `RimFridge_Building` is a `Building_Storage` (its Source/RimFridge_Building.cs:11) with its own items-per-cell setting, which the storage rule reads through `GetMaxItemsAllowedInCell`. Its fridges are PassThroughOnly and its wall fridge Impassable (its 1.6 Defs/ThingDefs_Buildings/Fridge_Base.xml:25, WallFridge_Building.xml:6), so neither is standable and both need the storage rule.
- Weapon Racks (2788630748, 57,447 subs, 1.7): `Building_WeaponStorage` holds 1 to 4 items per cell (its 1.7/Defs/ThingDefs/ThingDefs_Buildings.xml); the storage rule respects that. Bought weapons can land on a flagged rack.
- Haul to Stack (949498803, 77,412 subs, 1.6 build) makes haulers fill stacks first; storage targets use the same order.
- Vanilla Furniture Expanded's storage furniture is `Building_Storage`, so it is covered.
#### Delivery under a roof
- **Players get:** An option "No drop pods, goods appear here" on delivery zones, flagged stockpiles and flagged storage buildings. Roofed warehouses and rooms then receive orbital goods and rewards. Off by default.
- **How:** For targets with direct delivery, orbital and reward routing skip the pod. Delivery zones use `GenPlace.TryPlaceThing(thing, cell, map, Near, null, validator)` with the placement rule, roof ignored; storage targets use Direct mode with the storage rule. For rewards, the `DropThingGroupsNear` prefix takes the group out of the list and places it, applying the call's forbid flag. A dust fleck marks the arrival. The stockpile and storage flags sit in the MapComponent next to the receive flags, and follow storage groups the same way. No roof punching: `Skyfaller.HitRoof` collapses a 3x3 roof (Skyfaller.cs:399-435).
- **Settings:** Global "Allow direct delivery" (on, makes the per-target option available). Per zone, stockpile and storage building: off.
- **Save and removal:** The flags save in the component and vanish with it.
- **Replaces:** Nothing.
- **Effort:** S, half a day.
- **Tests:** In a fully roofed zone with the option on, orbital steel spawns on a zone cell the same tick with no pod. Without the option, it falls back. A quest reward goes to a roofed direct zone, forbid flag kept.
- **Risks:** Immersion only. Goods arrive either way, so balance is neutral. Dubs Skylights (833899765, 272,595 subs, 1.7): skylights sit in roofed cells, so pods can't land under them; the red overlay shows those cells and direct delivery covers them.
#### Sell zone
- **Players get:** A gizmo "Orbital traders can buy from here" on stockpiles and storage buildings. While at least one powered trade beacon stands on the map, orbital traders see every item in flagged storage and can take payment silver from it, so goods don't have to be hauled to the beacon. The shelves themselves are never for sale. Off by default for balance.
- **How:**
- Flags (zone IDs and storage ThingIDs) in the MapComponent, with the storage-group rule from "Stockpiles and shelves receive deliveries".
- A postfix on `TradeUtility.AllLaunchableThingsForTrade(Map, ITrader)` (TradeUtility.cs:84, an iterator) at `Priority.Last` wraps the result. It yields everything, keeping a HashSet, then appends things on flagged cells whose `def.category` is `Item` and that pass `TradeUtility.PlayerSellableNow` (TradeUtility.cs:43) and aren't in the set. Only when `Building_OrbitalTradeBeacon.AllPowered(map)` is not empty. RimFridge's "fridges act as beacons" postfix appends without deduping (its 1.6 Source/HarmonyPatches.cs, `LaunchItemsFromFridges`), hence the late priority and the full set.
- Items only, as vanilla takes only `ThingCategory.Item` from beacon cells (TradeUtility.cs:134). `EverPlayerSellable` accepts minifiable buildings (TradeUtility.cs:32-39), vanilla shelves are minifiable and tradeable, so without the category check a flagged shelf or fridge, or a lamp standing on a flagged stockpile, would be offered, and selling it removes it from the map (TradeShip.cs:179-197). Pawns fail the check too, so prisoner and slave sales stay with vanilla and Blax Slaves. Bookcases and outfit stands aren't `Building_Storage` and get no gizmo.
- The trade dialog lists and pays from what `TradeShip.ColonyThingsWillingToBuy` collects through that method (TradeShip.cs:89-100; Tradeable.cs:463-471), so the postfix alone lets trades sell from and pay with flagged storage.
- `TradeUtility.LaunchThingsOfType(ThingDef resDef, int debt, Map map, TradeShip trader)` (TradeUtility.cs:185-222) searches beacon cells only. Its only vanilla callers are the ransom fee through `LaunchSilver` (:225) and the AI core information request (FactionDialogMaker.cs:196), and both check affordability through `AllLaunchableThingsForTrade`. A prefix with `ref int debt` (Harmony lets a prefix change a plain argument) pays from flagged cells first, the way vanilla pays from beacon cells, lowers `debt`, and lets vanilla pay the rest. Without it vanilla logs "Could not find any Silver" and underpays (:207-211).
- **Settings:** Global "Sell zones" (off). Per stockpile and storage building: off.
- **Save and removal:** The flags save in the component and vanish with it; trade goes back to beacon range.
- **Replaces:** Covers the use of Map Wide Orbital Trade Beacon (1839069104, 50,625 subs, alive on 1.7), Wall-Mounted Orbital Trade Beacon (3553078564, 15,875, alive on 1.7), Trade Beacon Shapes (3533891331, 610, a drawing shape for placing beacons; a weak overlap) and [DHM]Adjustable Trade Beacon Range (3823054506, 27).
- **Effort:** M, 2 days. Two trade methods change.
- **Tests:** A flagged stockpile far from the beacon holds 100 steel. With a powered beacon the trade dialog lists the steel; with the beacon off it doesn't. Selling it removes it from the stockpile. Buying with silver that sits only in a flagged stockpile pays from it. A ransom fee paid from flagged silver logs no error and takes the full amount. A flagged shelf and a standing lamp on a flagged stockpile never show up in `ColonyThingsWillingToBuy`. A prisoner standing in a flagged stockpile isn't offered. `-Compat`: with RimFridge's beacon setting on and a fridge also flagged as a sell zone, the dialog lists each item once.
- **Risks:** Beacon mods also patch `AllLaunchableThingsForTrade`; our wrapper skips things already in the list, so running Map Wide Orbital Trade Beacon alongside doesn't list items twice. It removes hauling to the beacon, hence off by default. [RH2] Rimdeed (2411722784, 83,107 subs, 1.6 build) reads `AllLaunchableThingsForTrade`, so sell-zone silver may pay its fees, which is harmless.
#### Cargo pod events land in the zone
- **Players get:** Optional: random cargo pod events drop their goods into a delivery zone that has "Cargo pods" ticked, and the letter points there.
- **How:** A DeliveryContext prefix and finalizer on `IncidentWorker_ResourcePodCrash.TryExecuteWorker` (IncidentWorker_ResourcePodCrash.cs:8-16) with source CargoPod. While it is set, a prefix on `DropCellFinder.RandomDropSpot(Map, bool)` (DropCellFinder.cs:16) returns the top cargo-pod zone's overflow center, so the drop center and the letter target (IncidentWorker_ResourcePodCrash.cs:12-14) both point at the zone; with no such zone vanilla runs. The `DropThingGroupsNear` prefix from rewards routes the groups and keeps the call's forbid (default true) and `leaveSlag` (true, :13).
- **Settings:** Global "Route cargo pod events" (off). Per zone: "Cargo pods" (off).
- **Save and removal:** The per-zone flag saves with the zone.
- **Replaces:** Resource Drop Pod Redirection (2944180046, 1,984 subs, no 1.7).
- **Effort:** S, half a day.
- **Tests:** The incident with the toggle on puts forbidden pods in the zone, and the letter's target is a zone cell. With the toggle off, vanilla. Vanilla Events Expanded's ApparelPod and WeaponPod events (`-Compat`) stay vanilla.
- **Risks:** It takes the surprise out of cargo pods, hence off by default. Vanilla Events Expanded (1938420742, 836,672 subs, 1.7) drops apparel and weapon pods through `DropThingsNear` without our context; adding them is in the Backlog.
#### Headless tests in 1.3
- Fixtures: `Shelf(cell)`, `LinkShelves(a, b)`, `UnlinkShelf(a)`, a roofed `Stockpile(rect)`.
- Phase 2: every flag set survives. Phase 3: the flags vanish with no errors.
- `-Compat` adds the RimFridge, Weapon Racks and Vanilla Events Expanded tests above; RimFridge's beacon setting is switched on through its settings for the dedupe test.
### 1.4 People sleeping zones (6 days)
#### Sleeping zones for colonists, slaves and prisoners
- **Players get:** A new "Sleeping zone" for people. Colonists claim cells in a dorm zone. A gizmo switches the zone between colonists, slaves and prisoners, as on a bed; without Ideology "Slaves" shows disabled with "Needs Ideology". A prisoner zone can't be dragged into a closed room that holds colonist or slave beds, and switching a zone to prisoners asks first and names the vanilla beds in its rooms that become prisoner beds.
- **How:**
- `Zone_SleepingPeople : Zone_SleepingBase` with an owner type (Colonist by default), the same `AddCell`, cap and home-area handling as animal zones.
- Defs `BlaxZones_ZoneBed` (`bed_humanlike` true, Comfort 0.4) with the animal def's flags, uiIcon from the vanilla SleepSpot texture. `bed_showSleeperBody` true keeps an adult's body drawn on the 1x1 bed (vanilla has 1x1 beds only for babies, Biotech Buildings_Furniture.xml:165-177). `bed_maxBodySize` stays 9999, so `ForHumanBabies` is false and the owner-type setters work (Building_Bed.cs:52, 80-90, 100).
- The bed search order postfix also moves `BlaxZones_ZoneBed` directly before SleepingSpot.
- Owner-type change: unclaim owners silently, set `ForOwnerType` on every bed with the bypass flag set, then call `District.Notify_RoomShapeOrContainedBedsChanged` and `Room.Notify_RoomShapeChanged` once for each distinct district and room of the zone's beds, as vanilla's `SetBedOwnerTypeByInterface` does (Building_Bed.cs:395-473). The setter only marks the room's stats dirty (Building_Bed.cs:92-108, Room.cs:673-676), so without that call a prisoner zone never becomes a prison cell and `CanUseBedNow` fails on `ForPrisoners && !IsInPrisonCell` (RestUtility.cs:121-124). The slave option is enabled only while `ModsConfig.IdeologyActive`, otherwise it shows disabled with "Needs Ideology". The setter's own `ModLister.CheckIdeology("Slavery")` (Building_Bed.cs:100) checks that Ideology is installed, not active (ModLister.cs:283-287, 361-364), so it isn't the guard.
- Slave zones without Ideology, from a save made with it: the zone keeps Slave, as vanilla slave beds do (Building_Bed.cs:319). Beds spawned for it by reconcile or a drag get the type through `AccessTools.FieldRefAccess<Building_Bed, BedOwnerType>("forOwnerType")` while Ideology is inactive, because the setter refuses Slave and logs an error where Ideology isn't installed (ModLister.cs:347-353). On an unspawned bed that field is all the setter would write. The gizmo still switches the zone to colonists or prisoners.
- Vanilla beds in a prisoner zone's rooms: when a room that can be a prison cell (`Building_Bed.RoomCanBePrisonCell`, Building_Bed.cs:333-340) gets a prisoner bed, `Room.Notify_RoomShapeChanged` marks it a prison cell (Room.cs:704-715) and sets `ForPrisoners` on every bed in it (Room.cs:721-727). Each zone bed spawn triggers that (Building_Bed.cs:277-282), and so does the owner-type change. The vanilla beds' setter unclaims their owners with one message each (Building_Bed.cs:61, 738-751). So:
- Switching a zone to prisoners first collects, in the zone's rooms that can be prison cells, the vanilla beds that aren't for prisoners and their humanlike owners. The confirm names the zone's own owners and those beds and owners, as vanilla's own gizmo asks before such a change (Building_Bed.cs:475-480). On confirm, Zones unclaims all of those owners silently and posts one message naming the count, then switches the zone; the room recalculation makes the vanilla beds prisoner beds, as vanilla's gizmo would.
- Expanding a prisoner zone refuses cells whose room can be a prison cell and holds a vanilla bed that isn't for prisoners, with the reason "This room has colonist or slave beds". A drag can't stop to ask.
- A wall that later closes a room around a prisoner zone and vanilla colonist beds flips them, as it would for a vanilla prisoner bed; accepted.
- A closed room that holds a prisoner zone stays a prison cell, so vanilla beds there stay prisoner beds, as in any vanilla prison cell. The zone's owner type wins until the player switches the zone.
- New zones start as colonist zones. A new colonist zone in an existing prison cell keeps Colonist through the setter prefixes, and the inspect pane warns.
- **Settings:** Per people zone: owner-type gizmo (colonists, slaves with Ideology, prisoners). Global: "Zone cells count for bedroom or barracks" (on, as vanilla spots; written to the people defs' `bed_countsForBedroomOrBarracks` at startup, tooltip "restart required").
- **Save and removal:** The owner type saves with the zone and on each bed. Removal as in 1.2.
- **Replaces:** None directly. It extends 1.2's coverage of Designator Shapes and BuilderTweaksReplica spot grids to dorms and prisons.
- **Effort:** M plus S, 2.5 days. The S is the owner-type protection and the prison-room rules.
- **Tests:**
- A colonist gets a bed in a people zone. Render inputs for the drawn body: once it lies down, `CurrentBed()` is the zone bed, its posture is `LayingInBed` and the bed's def has `bed_showSleeperBody` true. Seeing the body is a step in `docs/ingame-check.md`.
- Switched to slaves (Ideology, skipped without): the colonist is refused, a slave accepted, and zero `MessageBedLostAssignment` appear.
- Without Ideology: the gizmo's "Slaves" entry is disabled with "Needs Ideology". A zone set to Slave through the field, as a save made with Ideology holds it, keeps Slave through phase 2. A drag adds Slave beds to it while a test-only counter on `ModLister.CheckIdeology` stays at 0, and switching it to colonists gives Colonist beds.
- A prisoner zone in a walled room: the room `IsPrisonCell`, and `FindBedFor(prisoner, warden, checkSocialProperness: false)` (RestUtility.cs:235) finds a zone bed.
- A colonist zone in a room that also holds a vanilla prisoner bed keeps its owner type and posts no messages.
- The bed gizmo: a closed room with a colonist zone (one cell owned) and a vanilla colonist bed. Select the vanilla bed (the method reads `Find.Selector`) and call `SetBedOwnerTypeByInterface(Prisoner)`; if vanilla opens its confirm, accept it through the dialog's first button. The zone beds stay Colonist, the owner keeps its cell and no `MessageBedLostAssignment` appears. The reverse, on a later frame (a second call in the same frame returns early, Building_Bed.cs:397-401): a prisoner zone and a vanilla prisoner bed, `SetBedOwnerTypeByInterface(Colonist)` on the vanilla bed; the zone beds stay Prisoner.
- Expanding a prisoner zone into a closed room with an owned vanilla colonist bed refuses those cells, and the bed keeps its owner and type.
- Switching a colonist zone in that room to prisoners: the confirm names 1 vanilla bed and 1 owner; after confirming, the vanilla bed is a prisoner bed and exactly one message appears.
- `Alert_NeedColonistBeds` clears with a large enough people zone; the alert only runs in the first 30 days (Alert_NeedColonistBeds.cs:20), which a quick-test game is.
- Phase 2: owner types and owners survive.
- Phase 3, with occupied beds at save time (a colonist asleep in a zone bed, a prisoner in a prison zone bed, a doctor's tend job on a patient in a medical zone bed): no beds, no zones, every former owner's owned bed is null, warnings only, and beyond the two expected errors per map only CurToil errors that name the colonist, the prisoner or the patient, no NRE.
- **Risks:** Overlapping mods:
- Hospitality (753498552): its `IsValidBedFor` postfix lets a guest use a plain `Building_Bed` when it needs medical rest, has any naturally healing injury, or is a prisoner or slave (its Source/Patches/RestUtility_Patch.cs). So an injured guest who doesn't need medical rest may take, and through `ClaimBedIfNonMedical` (JobDriver_LayDown.cs:58) claim, a free cell in a colonist zone, as with a vanilla colonist bed. Zones doesn't refuse guests; zone beds behave like vanilla beds.
- Prisoner Realism (3760196312, 23,829 subs, 1.6 and 1.7): it adds two zones, `Zone_PrisonCommons` and `Zone_PrisonWork` (its Source/Features/Commons/Zone_PrisonCommons.cs:12, Work/Zone_PrisonWork.cs:13), and `Designator_ZoneAdd` refuses cells of another zone type (Designator_ZoneAdd.cs:72-76), so a sleeping zone can't share cells with them. Its postfix on the `Room.IsPrisonCell` getter makes commons rooms count as prison cells (its Patch_CommonsIntegration.cs:22-40). Bed spawn reads that getter (Building_Bed.cs:272-276), so a colonist zone in a commons room would turn prisoner without the setter prefixes; with them it keeps Colonist. The "colonist zone in a prison cell" warning uses Zones' own test (a room that can be a prison cell and holds a prisoner bed) instead of the getter, so commons rooms don't trigger it. Its gratitude silver drops (its Features/Recidivism/RecidivismUtility.cs:127-138) use `TradeDropSpot` with `DropThingsNear` outside any Zones context, so they land at the vanilla spot.
- Replace Stuff - Continued (3526354009, 539,387 subs, 1.7): it replaces only beds whose def is deconstructible (its NewThingFrame.cs), so it leaves zone beds alone; a real bed built on a zone cell takes the cell through the edifice postfix.
- Prison Labor (1899474310, 174,952 subs, 1.7): its `FindBedFor` postfix nulls a bed a prisoner traveler can't reach, which composes. Its candidate prefix only affects the assign dialog, which zone beds never open.
- Vanilla Furniture Expanded (1718190143, 1,119,241 subs) and its Medical module (1718191613, 933,630): their beds sort before ours in the bed search order. No conflict.
#### Medical, shared and comfort
- **Players get:** A gizmo makes a whole zone medical, so patients and injured animals are brought there; it works on people and animal zones. On people zones another gizmo makes the zone shared: nobody keeps a cell, pawns take the nearest free one each night, and the shared cells don't make the room a barracks. A zone is medical or shared, not both: while one is on, the other gizmo is greyed out with the reason. Cells in people zones give the same comfort as a vanilla sleeping spot.
- **How:**
- Medical: unclaim owners silently, then set `Building_Bed.Medical` on every bed through the vanilla setter (Building_Bed.cs:110-131).
- Shared: vanilla claiming stays. Blocking `ClaimBedIfNonMedical` breaks sleep (see Cut). The component's 250-tick sweep unclaims shared-zone beds whose owner isn't lying in them. It skips owners whose `CurJob` targets the bed: `JobDriver_LayDown` claims the bed first and walks there afterwards (JobDriver_LayDown.cs:58-59), and a pawn that arrives as a non-owner fails `CanUseBedNow` on its sleeping slot (RestUtility.cs:142-146) and gets kicked out. Shared zones use a third def, `BlaxZones_ZoneBedShared`, with `bed_countsForBedroomOrBarracks` false; flipping the toggle unclaims silently and respawns the zone's beds with the other def. I picked the sweep over a `CanUseBedNow` postfix that returns true for an unowned sleeper, because the sweep never overrides a false from vanilla or another mod.
- Comfort: `PawnUtility.GainComfortFromCellIfPossible` (PawnUtility.cs:317-327) reads only the edifice, so a non-edifice bed gives none. A postfix on the private `Toils_LayDown.ApplyBedRelatedEffects(Pawn p, Building_Bed bed, bool asleep, bool gainRest, int delta)` (Toils_LayDown.cs:91), which the LayDown toil calls every tick with the bed (:73), calls `PawnUtility.GainComfortFromThingIfPossible(p, bed, delta)` (PawnUtility.cs:329) when `bed` is a `Building_ZoneBed` with a humanlike def; that uses the def's Comfort 0.4 and checks its own 15-tick interval. The method is larger and runs only while lying down, so it is a safer target than the small, widely called `GainComfortFromCellIfPossible`.
- Everything else already matches vanilla spots: rest effectiveness 0.8 (`BedRestEffectiveness` valueIfMissing, Toils_LayDown.cs:95-96; Stats_Building_Special.xml:36), SleptOnGround -4 when the cost list is empty, SleptOutside outdoors (Toils_LayDown.cs:208-215; Thoughts_Memory_Misc.xml:84-97). `Toils_LayDown.ApplyBedThoughts` (Toils_LayDown.cs:172) is private and not patched. Animals have no mood need, so for them only location, ownership and medical matter.
- Switching medical or shared on a zone that has owners asks first and names the count.
- **Settings:** Per zone: Medical (off); per people zone: Shared (off). Global: "Zone cells give sleeping-spot comfort" (on).
- **Save and removal:** Both flags save with the zone; the medical flag also saves on each bed. Removal leaves owners without a bed, as in 1.2.
- **Replaces:** Nothing.
- **Effort:** M, 2 days.
- **Tests:** Medical zone: `RestUtility.FindPatientBedFor` returns a zone bed for an injured colonist, an injured tamed animal goes to a medical animal zone, and no lost-assignment messages appear. With Medical on, the Shared gizmo is disabled, and the reverse; animal zones show no Shared gizmo. Shared zone: a colonist sleeps a full night without `FailOnBedNoLongerUsable` ending the job; 250 ticks after waking, `ownership.OwnedBed` is null; a pawn whose LayDown job targets a shared bed it doesn't lie in yet keeps its claim through a sweep; no SleptInBarracks thought in a room with only shared cells. Comfort rises over 2500 ticks in a zone bed and stays flat on bare ground. SleptOnGround is present after waking. Toggles persist in phase 2.
- **Risks:** A signature change of `ApplyBedRelatedEffects` breaks only this patch class. A medical prisoner zone still needs a prison cell, as in vanilla. A shared pawn owns its cell while asleep, so bed lists show it as claimed overnight. If the room also holds beds that count, it is still a barracks, and a shared sleeper gets SleptInBarracks, as on a vanilla spot (Toils_LayDown.cs:217-239; RoomRoleWorker_Barracks.cs:17). Priority Treatment Ressurected (3009738919, 135,928 subs, 1.7) carries downed colonists to bed first through the vanilla bed search, so medical zones help it.
#### Visible zone state
- **Players get:** The zone tint shows its type: colonist, slave, prisoner and medical zones each get their own color, and animal zones keep theirs. The inspect pane shows the owner type, claimed and free cells, and a warning when a prisoner zone isn't in a prison cell or a colonist or slave zone sits in one.
- **How:**
- Vanilla shows owner type and medical by sheet color, which `drawerType` None hides. The owner-type and medical gizmos set `Zone.color` from a fixed palette. `Zone.Material` builds its material once and caches it in the private `materialInt` (Zone.cs:26, 86-95), so after setting the color Zones nulls `materialInt` through `AccessTools.FieldRefAccess<Zone, Material>` and marks the zone mesh dirty on every cell (`MapMeshDirty(cell, MapMeshFlagDefOf.Zone)`, as `Zone.Hidden` does, Zone.cs:70-84). Without that the tint changes only after a reload.
- `GetInspectString` counts owners over the zone's beds. The prisoner-zone warning reads `IsPrisonCell` on the zone's rooms (GridsUtility.cs:475-485), the same check `CanUseBedNow` makes. The colonist or slave warning uses Zones' own test, `Building_Bed.RoomCanBePrisonCell(room)` plus a prisoner bed in `room.ContainedBeds`, so a room another mod counts as a prison cell, such as a Prisoner Realism commons, doesn't trigger it. It also shows the filter warning from "Which animals may sleep here" and, from 1.5, the caste warnings.
- **Settings:** None.
- **Save and removal:** The color saves with the zone, like any zone color.
- **Replaces:** Nothing.
- **Effort:** S, half a day.
- **Tests:** Switching a zone to prisoners changes `zone.Material.color`, not only `zone.color`. After 3 chickens sleep in a 16-cell zone, the inspect string says 3 claimed, 13 free. An outdoor prisoner zone shows the warning. A colonist zone in a room with a vanilla prisoner bed shows the prison-cell warning.
- **Risks:** Two colonist zones share a color; the zone label tells them apart.
#### Headless tests in 1.4
- Fixture `SleepingZone(rect, kind, ownerType)`.
- Performance: the 1.2 timing again with 500 people zone beds, same 10% limit.
- Compat (`-Compat`): Replace Stuff builds a real bed blueprint on a zone cell, the cell leaves the zone and no error is logged. Prison Labor: `FindBedFor(prisoner, warden, false)` finds a prison zone bed. Hospitality: a healthy guest is refused a zone cell, a guest with a naturally healing injury who doesn't need medical rest may use a free non-medical colonist zone cell, and one that needs medical rest may use a medical zone cell. Prisoner Realism: a colonist zone spawned in a commons room keeps Colonist and shows no prison-cell warning.
- KnownForeignErrors: add any foreign error found in these runs.
- Effort: S, half a day.
### 1.5 Caste filter (2 days)
Ships once Blax Castes publishes `CastesApi` version 1, planned for Castes 1.1 in both design docs.
#### Sleeping zones by caste
- **Players get:** With Blax Castes active, a people sleeping zone can be limited to castes, for example the field hands' barn dorm or a medical zone for the Miner caste. Without Castes the option doesn't show, and limits you set stay stored for when Castes comes back.
- **How:**
- Binding: in the `[StaticConstructorOnStartup]` patcher, only when `Compat.IsActive("blax.castes")` (`ignorePostfix: true`). `AccessTools.TypeByName("BlaxCastes.CastesApi")`, with `Bind<T>`, `ReadVersion` and `WarnOnce` copied from Blax Slaves' Siblings.cs (Siblings.cs:27, 61, 153-157). It needs Version 1 or higher and `Active`, `CasteIdOf` and `CasteLabels`, bound by exact delegate and return types; otherwise it stays unbound with one log line. A call that throws turns the link off until the next game, with one warning, the rule Castes uses for Weapons Tab Reborn. Calls run on the main thread only.
- Ids: `CasteLabels()` and `CasteIdOf(Pawn)` both return the token-prefixed id `"<token>:<id>"`, so ids picked from the list compare directly with a pawn's id.
- Data on `Zone_SleepingPeople`: `HashSet<string> allowedCasteIds` (empty means any), `bool allowNoCaste` (only used while the set isn't empty) and `Dictionary<string, string> lastLabels`, so the UI can name a caste that has gone. All three are always scribed with `LookMode.Value`, kept while unbound, and never pruned in ExposeData, PostLoadInit or FinalizeInit: `CasteLabels()` can still be empty during map `FinalizeInit` (Game.cs:611-647), because Castes seeds its starter castes in `LoadedGame`.
- The check: in the 1.2 `CanUseBedNow` postfix, after the type and zone checks. It returns early when `__result` is already false, the zone has no caste limit, or the link isn't usable (bound and `Active`, read once per tick). Otherwise it gets the sleeper's id from a one-entry cache keyed by `(thingIDNumber, TicksGame)`. `FindBedFor` asks about one sleeper for hundreds of beds in a row through its `GenClosest` validators (RestUtility.cs:235 onwards), so the cache nearly always hits. It refuses when the id is null and `allowNoCaste` is off, or when the id isn't in the set.
- Caste changes: Castes moves pawns one tick after a join and calls no other mod, so Zones polls. The 250-tick sweep also silently unclaims owners of caste-limited beds who no longer pass, while the link is usable. A pawn asleep at that moment is woken by `Toils_Bed.BedNoLongerUsable` through the same postfix (Toils_Bed.cs:58-69). A pawn with another valid bed re-claims it on its own through `FindBedFor`.
- Filter edits unclaim owners that no longer pass, with one message naming the count.
- UI: a "Castes" section in the people-zone tab, shown only while bound. One checkbox per caste from `CasteLabels()`, sorted by label to match Castes' pickers, plus "Pawns without a caste". Stored ids whose caste is gone show greyed as "Deleted caste (last label)" with a remove button. While unbound with ids stored, the inspect pane says the caste limit is inactive because Blax Castes isn't loaded. The inspect pane also warns when no current pawn of the zone's owner type fits.
- Medical zones: the limit applies to them too. It still composes with Blax Slaves' shared infirmary, because Zones runs at `Priority.Low`.
- Load order: About.xml keeps loadAfter `blax.castes` only.
- **Settings:** Per people zone: caste list (empty, any caste) and "Pawns without a caste" (off), hidden without Castes. No global setting.
- **Save and removal:** Caste ids are strings in the zone, saved in the component. Removing Castes keeps them, unused. Removing Castes and adding it back creates a new caste token, so old ids match no new caste and show as deleted castes instead of silently matching a new caste with the same number. Removing Zones drops them with the component; Castes keeps nothing for Zones.
- **Replaces:** Nothing.
- **Effort:** M, 2 days: the token, the cache, the sweep and the deleted-caste UI.
- **Tests:** Run with Castes in `-Compat`; create castes through reflection on `BlaxCastes.CasteManager`, so the test mod gets no assembly reference to Castes. Skip without Castes.
- Phase 1, with Castes: a zone limited to caste A refuses a caste B pawn and accepts an A pawn. Every id from `CasteLabels()` has the same token prefix as `CasteIdOf` returns. A casteless pawn is refused until "Pawns without a caste" is ticked. A bought slave queued by Castes is refused before `Tick(1)` and accepted after it. Assigning the owner to caste B unclaims its zone bed within 250 ticks, and a sleeping owner is woken. A deleted caste's id stays stored and matches nobody. With Castes' API switched off, the limits are ignored and nobody is evicted. Ids from an older token (simulate a new component) match no new caste. `GC.GetAllocatedBytesForCurrentThread` across 1,000 `CanUseBedNow` calls on a caste-limited bed stays below 1 KB. `FindBedFor` across 500 caste-limited cells fails above 10 ms.
- Phase 1, without Castes: the section is hidden, stored ids are ignored but kept.
- Phase 2: ids and `allowNoCaste` survive the reload, and the binding still works.
- Load hook: a save loaded with Castes just added keeps every stored id, although `CasteLabels()` is empty during map `FinalizeInit`.
- **Risks:** It depends on Castes shipping API version 1 with `Active`, the token and `List<KeyValuePair<string, string>>`. An older or different API means unbound, with one log line.
#### Headless tests in 1.5
- Castes joins the default `-Compat` set; the caste tests skip in plain runs.
- A test helper builds castes through reflection only, so the test mod compiles without Castes.
### 1.6 Work rule areas (8 days)
From Fabian's request of 2026-11-29: a "No cleaning zone", "Priority zones (colonists should prefer work in that zone)", or one "Restrict" zone for firefighting, hauling and cleaning. What vanilla gives today:
@ -457,7 +628,7 @@ Why this shape:
- 50 steel in a "Don't haul from here" area: unticking the rule puts it in `ThingsPotentiallyNeedingHauling()` within the same call; deleting the area does too.
- A stored rule name that doesn't resolve stays stored and changes nothing.
- Removal button: with a pawn on a "Clean first" job, afterwards no current or queued job names either giver, the steel on a former "Don't haul" cell is in the haulables set, and two saves contain no "BlaxZones".
- Phase 3: see "Headless tests in 1.3".
- Phase 3: see "Headless tests in 1.6".
- **Risks:** Gravships leave work rule areas behind, as they leave Blax zones (Backlog). Seeing the areas needs a designator selected, as with vanilla allowed areas.
#### No cleaning, firefighting, repairs or hauling
@ -539,194 +710,15 @@ Why this shape:
- With "Apply work rules" off, both givers give nothing and log nothing.
- **Risks:** A pawn may walk across the map for one old filth in a "Clean first" area; that is what the rule asks. `JobGiver_Work` stamps our def on the job Pick Up And Haul builds (JobGiver_Work.cs:240); if its driver reads `workGiverDef`, the `-Compat` test shows it, and the fallback is vanilla jobs only when it is active. Mods that show work givers one by one list ours as their own rows, so a player can set them apart.
#### Headless tests in 1.3
#### Headless tests in 1.6
- Fixtures: `WorkRuleArea(rect, rules)`, `Filth(cell)` thickened past 600 ticks, `Fire(cell)`, `DamagedWall(cell)`, `BrokenDown(building)`, `OnlyWorkType(pawn, workType)`.
- Phase 3: the runner also renames `BlaxZones_CleanFirst` and `BlaxZones_HaulFirst` in the save, as it renames the component class, and expects exactly one "Could not load reference" error per job a pawn had from them, and no NRE.
- Performance in `-Compat`, with Pick Up And Haul active: time 2500 ticks with 60 colonists, the colony size Zones is built for (20 with only Cleaning, 20 with only Hauling, 20 with the quick-test colony's work settings), 300 filth in "No cleaning" areas, 200 filth elsewhere and 500 loose items, half of them in "Don't haul from here" and "Haul first" areas, with and without the areas; median of three runs each. Every rule hook runs inside each pawn's work search, so the cost grows with the number of cleaners and haulers, and 60 pawns measure that. The test fails when the areas add more than 5%, tighter than the beds' 10%.
- Compat: Pick Up And Haul, Prison Labor, Hospitality and Blax Castes (a caste area that leaves out a clean-first area, once Castes' area slot, its 1.2, has code) join the 1.3 tests; Blax Defaults once its forbid rules (its 1.1) have code.
- Compat: Pick Up And Haul, Prison Labor, Hospitality and Blax Castes (a caste area that leaves out a clean-first area, once Castes' area slot, its 1.2, has code) join the 1.6 tests; Blax Defaults once its forbid rules (its 1.1) have code.
- `docs/ingame-check.md` gains: the overlay color and the picker, the manage window, the tooltips.
- Effort: S, half a day.
### 1.4 Stockpiles, shelves, roofs and selling (6 days)
Stockpile deliveries and direct delivery ship together: most freezers and hospital shelves are roofed, so the flag alone does little for orbital goods.
#### Stockpiles and shelves receive deliveries
- **Players get:** A "Receive deliveries" gizmo on any stockpile, shelf, rack or fridge lets bought goods and rewards go straight into it, by its own filter and priority: medicine onto the hospital shelves, food into the freezer, no hauling. Delivery zones and flagged storage compete by priority.
- **How:**
- Flags live in `MapComponent_BlaxZones` as a `HashSet<int>` of stockpile zone IDs and a `HashSet<int>` of storage building ThingIDs, never as fields on `Zone_Stockpile` or `Building_Storage`. Zone IDs and ThingIDs are never reused, so a stale flag can't land on a new storage.
- Gizmos come from postfixes on `Zone_Stockpile.GetGizmos` (Zone_Stockpile.cs:75) and `Building_Storage.GetGizmos` (Building_Storage.cs:227). RimFridge's and Weapon Racks' storage buildings call the base, so they get the gizmo.
- Storage groups: shelves can be linked into a group (Building_Storage.cs:13), whose settings every member reads through `GetStoreSettings()` (Building_Storage.cs:100-107). Group membership changes through vanilla's link gizmos (Building_Storage.cs:241-244) without calling Zones. So a storage building counts as flagged when it or any member of its `StorageGroup` is flagged, and the gizmo on a grouped building sets or clears the flag on every member. A shelf linked into a flagged group later is flagged through the group. A shelf leaving a group keeps its own flag, as vanilla copies the group's settings onto it (StorageGroupUtility.cs:163-184); one that joined after the flag was set has none of its own and leaves unflagged.
- The router adds flagged storage as candidates, with accept from `StorageSettings.AllowedToAccept(thing)` and priority from `StorageSettings.Priority`, both through `GetStoreSettings()`; building cells come from `AllSlotCells()`. Storage targets use the storage rule from the data model and fill mergeable stacks first.
- Pods use only stockpile cells that pass the pod rule. Shelves are edifices, so they get orbital goods only with direct delivery. Caravan placement and direct delivery put the thing on a storage cell with `GenPlace.TryPlaceThing(thing, cell, map, ThingPlaceMode.Direct)` and try the next cell on failure.
- A deleted stockpile or storage building drops its ID on the next lookup. The gizmo tooltip says roofed targets need direct delivery for orbital goods and rewards.
- **Settings:** Global "Stockpiles and shelves may receive deliveries" (on). Per stockpile and storage building: gizmo (off).
- **Save and removal:** The flag sets save in the component. Without the mod they vanish with the component node; the stockpiles and shelves keep their own settings.
- **Replaces:** [DHM]Organized Trade Pod System (3490887589, 1,816 subs, no 1.7), Skipdoor Delivery (3233578663, 2,749, no 1.7) for trade goods.
- **Effort:** M plus S, 2.5 days. The S is the storage rule and storage groups.
- **Tests:** An unroofed flagged food stockpile at Important plus a general delivery zone at Normal: bought rice lands in the stockpile, steel in the zone. A flagged medicine shelf in a roofed hospital with direct delivery on: orbital medicine appears on the shelf. A vanilla shelf cell (PassThroughOnly) receives a direct delivery. Caravan rice goes into a roofed flagged freezer. A linked shelf group: flagging one shelf flags every member, and priority and filter come from the group. A new shelf linked into the flagged group receives a delivery; unlinked again, it doesn't. A shelf that was in the group when it was flagged keeps receiving after it is unlinked. Storage targets fill mergeable stacks before empty cells. Flags survive reload. A deleted stockpile is no longer a target. Phase 3 loads with no errors from the flag sets. `-Compat`: a RimFridge fridge (PassThroughOnly) and a RimFridge wall fridge (Impassable) each receive a delivery; a Weapon Racks rack holds no more than its items per cell.
- **Risks:** Without direct delivery, roofed freezers and shelves get only caravan goods; the tooltip says so. Overlapping mods:
- RimFridge: Now with Shelves! (2898411376, 282,094 subs, 1.6 build): `RimFridge_Building` is a `Building_Storage` (its Source/RimFridge_Building.cs:11) with its own items-per-cell setting, which the storage rule reads through `GetMaxItemsAllowedInCell`. Its fridges are PassThroughOnly and its wall fridge Impassable (its 1.6 Defs/ThingDefs_Buildings/Fridge_Base.xml:25, WallFridge_Building.xml:6), so neither is standable and both need the storage rule.
- Weapon Racks (2788630748, 57,447 subs, 1.7): `Building_WeaponStorage` holds 1 to 4 items per cell (its 1.7/Defs/ThingDefs/ThingDefs_Buildings.xml); the storage rule respects that. Bought weapons can land on a flagged rack.
- Haul to Stack (949498803, 77,412 subs, 1.6 build) makes haulers fill stacks first; storage targets use the same order.
- Vanilla Furniture Expanded's storage furniture is `Building_Storage`, so it is covered.
#### Delivery under a roof
- **Players get:** An option "No drop pods, goods appear here" on delivery zones, flagged stockpiles and flagged storage buildings. Roofed warehouses and rooms then receive orbital goods and rewards. Off by default.
- **How:** For targets with direct delivery, orbital and reward routing skip the pod. Delivery zones use `GenPlace.TryPlaceThing(thing, cell, map, Near, null, validator)` with the placement rule, roof ignored; storage targets use Direct mode with the storage rule. For rewards, the `DropThingGroupsNear` prefix takes the group out of the list and places it, applying the call's forbid flag. A dust fleck marks the arrival. The stockpile and storage flags sit in the MapComponent next to the receive flags, and follow storage groups the same way. No roof punching: `Skyfaller.HitRoof` collapses a 3x3 roof (Skyfaller.cs:399-435).
- **Settings:** Global "Allow direct delivery" (on, makes the per-target option available). Per zone, stockpile and storage building: off.
- **Save and removal:** The flags save in the component and vanish with it.
- **Replaces:** Nothing.
- **Effort:** S, half a day.
- **Tests:** In a fully roofed zone with the option on, orbital steel spawns on a zone cell the same tick with no pod. Without the option, it falls back. A quest reward goes to a roofed direct zone, forbid flag kept.
- **Risks:** Immersion only. Goods arrive either way, so balance is neutral. Dubs Skylights (833899765, 272,595 subs, 1.7): skylights sit in roofed cells, so pods can't land under them; the red overlay shows those cells and direct delivery covers them.
#### Sell zone
- **Players get:** A gizmo "Orbital traders can buy from here" on stockpiles and storage buildings. While at least one powered trade beacon stands on the map, orbital traders see every item in flagged storage and can take payment silver from it, so goods don't have to be hauled to the beacon. The shelves themselves are never for sale. Off by default for balance.
- **How:**
- Flags (zone IDs and storage ThingIDs) in the MapComponent, with the storage-group rule from "Stockpiles and shelves receive deliveries".
- A postfix on `TradeUtility.AllLaunchableThingsForTrade(Map, ITrader)` (TradeUtility.cs:84, an iterator) at `Priority.Last` wraps the result. It yields everything, keeping a HashSet, then appends things on flagged cells whose `def.category` is `Item` and that pass `TradeUtility.PlayerSellableNow` (TradeUtility.cs:43) and aren't in the set. Only when `Building_OrbitalTradeBeacon.AllPowered(map)` is not empty. RimFridge's "fridges act as beacons" postfix appends without deduping (its 1.6 Source/HarmonyPatches.cs, `LaunchItemsFromFridges`), hence the late priority and the full set.
- Items only, as vanilla takes only `ThingCategory.Item` from beacon cells (TradeUtility.cs:134). `EverPlayerSellable` accepts minifiable buildings (TradeUtility.cs:32-39), vanilla shelves are minifiable and tradeable, so without the category check a flagged shelf or fridge, or a lamp standing on a flagged stockpile, would be offered, and selling it removes it from the map (TradeShip.cs:179-197). Pawns fail the check too, so prisoner and slave sales stay with vanilla and Blax Slaves. Bookcases and outfit stands aren't `Building_Storage` and get no gizmo.
- The trade dialog lists and pays from what `TradeShip.ColonyThingsWillingToBuy` collects through that method (TradeShip.cs:89-100; Tradeable.cs:463-471), so the postfix alone lets trades sell from and pay with flagged storage.
- `TradeUtility.LaunchThingsOfType(ThingDef resDef, int debt, Map map, TradeShip trader)` (TradeUtility.cs:185-222) searches beacon cells only. Its only vanilla callers are the ransom fee through `LaunchSilver` (:225) and the AI core information request (FactionDialogMaker.cs:196), and both check affordability through `AllLaunchableThingsForTrade`. A prefix with `ref int debt` (Harmony lets a prefix change a plain argument) pays from flagged cells first, the way vanilla pays from beacon cells, lowers `debt`, and lets vanilla pay the rest. Without it vanilla logs "Could not find any Silver" and underpays (:207-211).
- **Settings:** Global "Sell zones" (off). Per stockpile and storage building: off.
- **Save and removal:** The flags save in the component and vanish with it; trade goes back to beacon range.
- **Replaces:** Covers the use of Map Wide Orbital Trade Beacon (1839069104, 50,625 subs, alive on 1.7), Wall-Mounted Orbital Trade Beacon (3553078564, 15,875, alive on 1.7), Trade Beacon Shapes (3533891331, 610, a drawing shape for placing beacons; a weak overlap) and [DHM]Adjustable Trade Beacon Range (3823054506, 27).
- **Effort:** M, 2 days. Two trade methods change.
- **Tests:** A flagged stockpile far from the beacon holds 100 steel. With a powered beacon the trade dialog lists the steel; with the beacon off it doesn't. Selling it removes it from the stockpile. Buying with silver that sits only in a flagged stockpile pays from it. A ransom fee paid from flagged silver logs no error and takes the full amount. A flagged shelf and a standing lamp on a flagged stockpile never show up in `ColonyThingsWillingToBuy`. A prisoner standing in a flagged stockpile isn't offered. `-Compat`: with RimFridge's beacon setting on and a fridge also flagged as a sell zone, the dialog lists each item once.
- **Risks:** Beacon mods also patch `AllLaunchableThingsForTrade`; our wrapper skips things already in the list, so running Map Wide Orbital Trade Beacon alongside doesn't list items twice. It removes hauling to the beacon, hence off by default. [RH2] Rimdeed (2411722784, 83,107 subs, 1.6 build) reads `AllLaunchableThingsForTrade`, so sell-zone silver may pay its fees, which is harmless.
#### Cargo pod events land in the zone
- **Players get:** Optional: random cargo pod events drop their goods into a delivery zone that has "Cargo pods" ticked, and the letter points there.
- **How:** A DeliveryContext prefix and finalizer on `IncidentWorker_ResourcePodCrash.TryExecuteWorker` (IncidentWorker_ResourcePodCrash.cs:8-16) with source CargoPod. While it is set, a prefix on `DropCellFinder.RandomDropSpot(Map, bool)` (DropCellFinder.cs:16) returns the top cargo-pod zone's overflow center, so the drop center and the letter target (IncidentWorker_ResourcePodCrash.cs:12-14) both point at the zone; with no such zone vanilla runs. The `DropThingGroupsNear` prefix from rewards routes the groups and keeps the call's forbid (default true) and `leaveSlag` (true, :13).
- **Settings:** Global "Route cargo pod events" (off). Per zone: "Cargo pods" (off).
- **Save and removal:** The per-zone flag saves with the zone.
- **Replaces:** Resource Drop Pod Redirection (2944180046, 1,984 subs, no 1.7).
- **Effort:** S, half a day.
- **Tests:** The incident with the toggle on puts forbidden pods in the zone, and the letter's target is a zone cell. With the toggle off, vanilla. Vanilla Events Expanded's ApparelPod and WeaponPod events (`-Compat`) stay vanilla.
- **Risks:** It takes the surprise out of cargo pods, hence off by default. Vanilla Events Expanded (1938420742, 836,672 subs, 1.7) drops apparel and weapon pods through `DropThingsNear` without our context; adding them is in the Backlog.
#### Headless tests in 1.4
- Fixtures: `Shelf(cell)`, `LinkShelves(a, b)`, `UnlinkShelf(a)`, a roofed `Stockpile(rect)`.
- Phase 2: every flag set survives. Phase 3: the flags vanish with no errors.
- `-Compat` adds the RimFridge, Weapon Racks and Vanilla Events Expanded tests above; RimFridge's beacon setting is switched on through its settings for the dedupe test.
### 1.5 People sleeping zones (6 days)
#### Sleeping zones for colonists, slaves and prisoners
- **Players get:** A new "Sleeping zone" for people. Colonists claim cells in a dorm zone. A gizmo switches the zone between colonists, slaves and prisoners, as on a bed; without Ideology "Slaves" shows disabled with "Needs Ideology". A prisoner zone can't be dragged into a closed room that holds colonist or slave beds, and switching a zone to prisoners asks first and names the vanilla beds in its rooms that become prisoner beds.
- **How:**
- `Zone_SleepingPeople : Zone_SleepingBase` with an owner type (Colonist by default), the same `AddCell`, cap and home-area handling as animal zones.
- Defs `BlaxZones_ZoneBed` (`bed_humanlike` true, Comfort 0.4) with the animal def's flags, uiIcon from the vanilla SleepSpot texture. `bed_showSleeperBody` true keeps an adult's body drawn on the 1x1 bed (vanilla has 1x1 beds only for babies, Biotech Buildings_Furniture.xml:165-177). `bed_maxBodySize` stays 9999, so `ForHumanBabies` is false and the owner-type setters work (Building_Bed.cs:52, 80-90, 100).
- The bed search order postfix also moves `BlaxZones_ZoneBed` directly before SleepingSpot.
- Owner-type change: unclaim owners silently, set `ForOwnerType` on every bed with the bypass flag set, then call `District.Notify_RoomShapeOrContainedBedsChanged` and `Room.Notify_RoomShapeChanged` once for each distinct district and room of the zone's beds, as vanilla's `SetBedOwnerTypeByInterface` does (Building_Bed.cs:395-473). The setter only marks the room's stats dirty (Building_Bed.cs:92-108, Room.cs:673-676), so without that call a prisoner zone never becomes a prison cell and `CanUseBedNow` fails on `ForPrisoners && !IsInPrisonCell` (RestUtility.cs:121-124). The slave option is enabled only while `ModsConfig.IdeologyActive`, otherwise it shows disabled with "Needs Ideology". The setter's own `ModLister.CheckIdeology("Slavery")` (Building_Bed.cs:100) checks that Ideology is installed, not active (ModLister.cs:283-287, 361-364), so it isn't the guard.
- Slave zones without Ideology, from a save made with it: the zone keeps Slave, as vanilla slave beds do (Building_Bed.cs:319). Beds spawned for it by reconcile or a drag get the type through `AccessTools.FieldRefAccess<Building_Bed, BedOwnerType>("forOwnerType")` while Ideology is inactive, because the setter refuses Slave and logs an error where Ideology isn't installed (ModLister.cs:347-353). On an unspawned bed that field is all the setter would write. The gizmo still switches the zone to colonists or prisoners.
- Vanilla beds in a prisoner zone's rooms: when a room that can be a prison cell (`Building_Bed.RoomCanBePrisonCell`, Building_Bed.cs:333-340) gets a prisoner bed, `Room.Notify_RoomShapeChanged` marks it a prison cell (Room.cs:704-715) and sets `ForPrisoners` on every bed in it (Room.cs:721-727). Each zone bed spawn triggers that (Building_Bed.cs:277-282), and so does the owner-type change. The vanilla beds' setter unclaims their owners with one message each (Building_Bed.cs:61, 738-751). So:
- Switching a zone to prisoners first collects, in the zone's rooms that can be prison cells, the vanilla beds that aren't for prisoners and their humanlike owners. The confirm names the zone's own owners and those beds and owners, as vanilla's own gizmo asks before such a change (Building_Bed.cs:475-480). On confirm, Zones unclaims all of those owners silently and posts one message naming the count, then switches the zone; the room recalculation makes the vanilla beds prisoner beds, as vanilla's gizmo would.
- Expanding a prisoner zone refuses cells whose room can be a prison cell and holds a vanilla bed that isn't for prisoners, with the reason "This room has colonist or slave beds". A drag can't stop to ask.
- A wall that later closes a room around a prisoner zone and vanilla colonist beds flips them, as it would for a vanilla prisoner bed; accepted.
- A closed room that holds a prisoner zone stays a prison cell, so vanilla beds there stay prisoner beds, as in any vanilla prison cell. The zone's owner type wins until the player switches the zone.
- New zones start as colonist zones. A new colonist zone in an existing prison cell keeps Colonist through the setter prefixes, and the inspect pane warns.
- **Settings:** Per people zone: owner-type gizmo (colonists, slaves with Ideology, prisoners). Global: "Zone cells count for bedroom or barracks" (on, as vanilla spots; written to the people defs' `bed_countsForBedroomOrBarracks` at startup, tooltip "restart required").
- **Save and removal:** The owner type saves with the zone and on each bed. Removal as in 1.2.
- **Replaces:** None directly. It extends 1.2's coverage of Designator Shapes and BuilderTweaksReplica spot grids to dorms and prisons.
- **Effort:** M plus S, 2.5 days. The S is the owner-type protection and the prison-room rules.
- **Tests:**
- A colonist gets a bed in a people zone. Render inputs for the drawn body: once it lies down, `CurrentBed()` is the zone bed, its posture is `LayingInBed` and the bed's def has `bed_showSleeperBody` true. Seeing the body is a step in `docs/ingame-check.md`.
- Switched to slaves (Ideology, skipped without): the colonist is refused, a slave accepted, and zero `MessageBedLostAssignment` appear.
- Without Ideology: the gizmo's "Slaves" entry is disabled with "Needs Ideology". A zone set to Slave through the field, as a save made with Ideology holds it, keeps Slave through phase 2. A drag adds Slave beds to it while a test-only counter on `ModLister.CheckIdeology` stays at 0, and switching it to colonists gives Colonist beds.
- A prisoner zone in a walled room: the room `IsPrisonCell`, and `FindBedFor(prisoner, warden, checkSocialProperness: false)` (RestUtility.cs:235) finds a zone bed.
- A colonist zone in a room that also holds a vanilla prisoner bed keeps its owner type and posts no messages.
- The bed gizmo: a closed room with a colonist zone (one cell owned) and a vanilla colonist bed. Select the vanilla bed (the method reads `Find.Selector`) and call `SetBedOwnerTypeByInterface(Prisoner)`; if vanilla opens its confirm, accept it through the dialog's first button. The zone beds stay Colonist, the owner keeps its cell and no `MessageBedLostAssignment` appears. The reverse, on a later frame (a second call in the same frame returns early, Building_Bed.cs:397-401): a prisoner zone and a vanilla prisoner bed, `SetBedOwnerTypeByInterface(Colonist)` on the vanilla bed; the zone beds stay Prisoner.
- Expanding a prisoner zone into a closed room with an owned vanilla colonist bed refuses those cells, and the bed keeps its owner and type.
- Switching a colonist zone in that room to prisoners: the confirm names 1 vanilla bed and 1 owner; after confirming, the vanilla bed is a prisoner bed and exactly one message appears.
- `Alert_NeedColonistBeds` clears with a large enough people zone; the alert only runs in the first 30 days (Alert_NeedColonistBeds.cs:20), which a quick-test game is.
- Phase 2: owner types and owners survive.
- Phase 3, with occupied beds at save time (a colonist asleep in a zone bed, a prisoner in a prison zone bed, a doctor's tend job on a patient in a medical zone bed): no beds, no zones, every former owner's owned bed is null, warnings only, and beyond the two expected errors per map only CurToil errors that name the colonist, the prisoner or the patient, no NRE.
- **Risks:** Overlapping mods:
- Hospitality (753498552): its `IsValidBedFor` postfix lets a guest use a plain `Building_Bed` when it needs medical rest, has any naturally healing injury, or is a prisoner or slave (its Source/Patches/RestUtility_Patch.cs). So an injured guest who doesn't need medical rest may take, and through `ClaimBedIfNonMedical` (JobDriver_LayDown.cs:58) claim, a free cell in a colonist zone, as with a vanilla colonist bed. Zones doesn't refuse guests; zone beds behave like vanilla beds.
- Prisoner Realism (3760196312, 23,829 subs, 1.6 and 1.7): it adds two zones, `Zone_PrisonCommons` and `Zone_PrisonWork` (its Source/Features/Commons/Zone_PrisonCommons.cs:12, Work/Zone_PrisonWork.cs:13), and `Designator_ZoneAdd` refuses cells of another zone type (Designator_ZoneAdd.cs:72-76), so a sleeping zone can't share cells with them. Its postfix on the `Room.IsPrisonCell` getter makes commons rooms count as prison cells (its Patch_CommonsIntegration.cs:22-40). Bed spawn reads that getter (Building_Bed.cs:272-276), so a colonist zone in a commons room would turn prisoner without the setter prefixes; with them it keeps Colonist. The "colonist zone in a prison cell" warning uses Zones' own test (a room that can be a prison cell and holds a prisoner bed) instead of the getter, so commons rooms don't trigger it. Its gratitude silver drops (its Features/Recidivism/RecidivismUtility.cs:127-138) use `TradeDropSpot` with `DropThingsNear` outside any Zones context, so they land at the vanilla spot.
- Replace Stuff - Continued (3526354009, 539,387 subs, 1.7): it replaces only beds whose def is deconstructible (its NewThingFrame.cs), so it leaves zone beds alone; a real bed built on a zone cell takes the cell through the edifice postfix.
- Prison Labor (1899474310, 174,952 subs, 1.7): its `FindBedFor` postfix nulls a bed a prisoner traveler can't reach, which composes. Its candidate prefix only affects the assign dialog, which zone beds never open.
- Vanilla Furniture Expanded (1718190143, 1,119,241 subs) and its Medical module (1718191613, 933,630): their beds sort before ours in the bed search order. No conflict.
#### Medical, shared and comfort
- **Players get:** A gizmo makes a whole zone medical, so patients and injured animals are brought there; it works on people and animal zones. On people zones another gizmo makes the zone shared: nobody keeps a cell, pawns take the nearest free one each night, and the shared cells don't make the room a barracks. A zone is medical or shared, not both: while one is on, the other gizmo is greyed out with the reason. Cells in people zones give the same comfort as a vanilla sleeping spot.
- **How:**
- Medical: unclaim owners silently, then set `Building_Bed.Medical` on every bed through the vanilla setter (Building_Bed.cs:110-131).
- Shared: vanilla claiming stays. Blocking `ClaimBedIfNonMedical` breaks sleep (see Cut). The component's 250-tick sweep unclaims shared-zone beds whose owner isn't lying in them. It skips owners whose `CurJob` targets the bed: `JobDriver_LayDown` claims the bed first and walks there afterwards (JobDriver_LayDown.cs:58-59), and a pawn that arrives as a non-owner fails `CanUseBedNow` on its sleeping slot (RestUtility.cs:142-146) and gets kicked out. Shared zones use a third def, `BlaxZones_ZoneBedShared`, with `bed_countsForBedroomOrBarracks` false; flipping the toggle unclaims silently and respawns the zone's beds with the other def. I picked the sweep over a `CanUseBedNow` postfix that returns true for an unowned sleeper, because the sweep never overrides a false from vanilla or another mod.
- Comfort: `PawnUtility.GainComfortFromCellIfPossible` (PawnUtility.cs:317-327) reads only the edifice, so a non-edifice bed gives none. A postfix on the private `Toils_LayDown.ApplyBedRelatedEffects(Pawn p, Building_Bed bed, bool asleep, bool gainRest, int delta)` (Toils_LayDown.cs:91), which the LayDown toil calls every tick with the bed (:73), calls `PawnUtility.GainComfortFromThingIfPossible(p, bed, delta)` (PawnUtility.cs:329) when `bed` is a `Building_ZoneBed` with a humanlike def; that uses the def's Comfort 0.4 and checks its own 15-tick interval. The method is larger and runs only while lying down, so it is a safer target than the small, widely called `GainComfortFromCellIfPossible`.
- Everything else already matches vanilla spots: rest effectiveness 0.8 (`BedRestEffectiveness` valueIfMissing, Toils_LayDown.cs:95-96; Stats_Building_Special.xml:36), SleptOnGround -4 when the cost list is empty, SleptOutside outdoors (Toils_LayDown.cs:208-215; Thoughts_Memory_Misc.xml:84-97). `Toils_LayDown.ApplyBedThoughts` (Toils_LayDown.cs:172) is private and not patched. Animals have no mood need, so for them only location, ownership and medical matter.
- Switching medical or shared on a zone that has owners asks first and names the count.
- **Settings:** Per zone: Medical (off); per people zone: Shared (off). Global: "Zone cells give sleeping-spot comfort" (on).
- **Save and removal:** Both flags save with the zone; the medical flag also saves on each bed. Removal leaves owners without a bed, as in 1.2.
- **Replaces:** Nothing.
- **Effort:** M, 2 days.
- **Tests:** Medical zone: `RestUtility.FindPatientBedFor` returns a zone bed for an injured colonist, an injured tamed animal goes to a medical animal zone, and no lost-assignment messages appear. With Medical on, the Shared gizmo is disabled, and the reverse; animal zones show no Shared gizmo. Shared zone: a colonist sleeps a full night without `FailOnBedNoLongerUsable` ending the job; 250 ticks after waking, `ownership.OwnedBed` is null; a pawn whose LayDown job targets a shared bed it doesn't lie in yet keeps its claim through a sweep; no SleptInBarracks thought in a room with only shared cells. Comfort rises over 2500 ticks in a zone bed and stays flat on bare ground. SleptOnGround is present after waking. Toggles persist in phase 2.
- **Risks:** A signature change of `ApplyBedRelatedEffects` breaks only this patch class. A medical prisoner zone still needs a prison cell, as in vanilla. A shared pawn owns its cell while asleep, so bed lists show it as claimed overnight. If the room also holds beds that count, it is still a barracks, and a shared sleeper gets SleptInBarracks, as on a vanilla spot (Toils_LayDown.cs:217-239; RoomRoleWorker_Barracks.cs:17). Priority Treatment Ressurected (3009738919, 135,928 subs, 1.7) carries downed colonists to bed first through the vanilla bed search, so medical zones help it.
#### Visible zone state
- **Players get:** The zone tint shows its type: colonist, slave, prisoner and medical zones each get their own color, and animal zones keep theirs. The inspect pane shows the owner type, claimed and free cells, and a warning when a prisoner zone isn't in a prison cell or a colonist or slave zone sits in one.
- **How:**
- Vanilla shows owner type and medical by sheet color, which `drawerType` None hides. The owner-type and medical gizmos set `Zone.color` from a fixed palette. `Zone.Material` builds its material once and caches it in the private `materialInt` (Zone.cs:26, 86-95), so after setting the color Zones nulls `materialInt` through `AccessTools.FieldRefAccess<Zone, Material>` and marks the zone mesh dirty on every cell (`MapMeshDirty(cell, MapMeshFlagDefOf.Zone)`, as `Zone.Hidden` does, Zone.cs:70-84). Without that the tint changes only after a reload.
- `GetInspectString` counts owners over the zone's beds. The prisoner-zone warning reads `IsPrisonCell` on the zone's rooms (GridsUtility.cs:475-485), the same check `CanUseBedNow` makes. The colonist or slave warning uses Zones' own test, `Building_Bed.RoomCanBePrisonCell(room)` plus a prisoner bed in `room.ContainedBeds`, so a room another mod counts as a prison cell, such as a Prisoner Realism commons, doesn't trigger it. It also shows the filter warning from "Which animals may sleep here" and, from 1.6, the caste warnings.
- **Settings:** None.
- **Save and removal:** The color saves with the zone, like any zone color.
- **Replaces:** Nothing.
- **Effort:** S, half a day.
- **Tests:** Switching a zone to prisoners changes `zone.Material.color`, not only `zone.color`. After 3 chickens sleep in a 16-cell zone, the inspect string says 3 claimed, 13 free. An outdoor prisoner zone shows the warning. A colonist zone in a room with a vanilla prisoner bed shows the prison-cell warning.
- **Risks:** Two colonist zones share a color; the zone label tells them apart.
#### Headless tests in 1.5
- Fixture `SleepingZone(rect, kind, ownerType)`.
- Performance: the 1.2 timing again with 500 people zone beds, same 10% limit.
- Compat (`-Compat`): Replace Stuff builds a real bed blueprint on a zone cell, the cell leaves the zone and no error is logged. Prison Labor: `FindBedFor(prisoner, warden, false)` finds a prison zone bed. Hospitality: a healthy guest is refused a zone cell, a guest with a naturally healing injury who doesn't need medical rest may use a free non-medical colonist zone cell, and one that needs medical rest may use a medical zone cell. Prisoner Realism: a colonist zone spawned in a commons room keeps Colonist and shows no prison-cell warning.
- KnownForeignErrors: add any foreign error found in these runs.
- Effort: S, half a day.
### 1.6 Caste filter (2 days)
Ships once Blax Castes publishes `CastesApi` version 1, planned for Castes 1.1 in both design docs.
#### Sleeping zones by caste
- **Players get:** With Blax Castes active, a people sleeping zone can be limited to castes, for example the field hands' barn dorm or a medical zone for the Miner caste. Without Castes the option doesn't show, and limits you set stay stored for when Castes comes back.
- **How:**
- Binding: in the `[StaticConstructorOnStartup]` patcher, only when `Compat.IsActive("blax.castes")` (`ignorePostfix: true`). `AccessTools.TypeByName("BlaxCastes.CastesApi")`, with `Bind<T>`, `ReadVersion` and `WarnOnce` copied from Blax Slaves' Siblings.cs (Siblings.cs:27, 61, 153-157). It needs Version 1 or higher and `Active`, `CasteIdOf` and `CasteLabels`, bound by exact delegate and return types; otherwise it stays unbound with one log line. A call that throws turns the link off until the next game, with one warning, the rule Castes uses for Weapons Tab Reborn. Calls run on the main thread only.
- Ids: `CasteLabels()` and `CasteIdOf(Pawn)` both return the token-prefixed id `"<token>:<id>"`, so ids picked from the list compare directly with a pawn's id.
- Data on `Zone_SleepingPeople`: `HashSet<string> allowedCasteIds` (empty means any), `bool allowNoCaste` (only used while the set isn't empty) and `Dictionary<string, string> lastLabels`, so the UI can name a caste that has gone. All three are always scribed with `LookMode.Value`, kept while unbound, and never pruned in ExposeData, PostLoadInit or FinalizeInit: `CasteLabels()` can still be empty during map `FinalizeInit` (Game.cs:611-647), because Castes seeds its starter castes in `LoadedGame`.
- The check: in the 1.2 `CanUseBedNow` postfix, after the type and zone checks. It returns early when `__result` is already false, the zone has no caste limit, or the link isn't usable (bound and `Active`, read once per tick). Otherwise it gets the sleeper's id from a one-entry cache keyed by `(thingIDNumber, TicksGame)`. `FindBedFor` asks about one sleeper for hundreds of beds in a row through its `GenClosest` validators (RestUtility.cs:235 onwards), so the cache nearly always hits. It refuses when the id is null and `allowNoCaste` is off, or when the id isn't in the set.
- Caste changes: Castes moves pawns one tick after a join and calls no other mod, so Zones polls. The 250-tick sweep also silently unclaims owners of caste-limited beds who no longer pass, while the link is usable. A pawn asleep at that moment is woken by `Toils_Bed.BedNoLongerUsable` through the same postfix (Toils_Bed.cs:58-69). A pawn with another valid bed re-claims it on its own through `FindBedFor`.
- Filter edits unclaim owners that no longer pass, with one message naming the count.
- UI: a "Castes" section in the people-zone tab, shown only while bound. One checkbox per caste from `CasteLabels()`, sorted by label to match Castes' pickers, plus "Pawns without a caste". Stored ids whose caste is gone show greyed as "Deleted caste (last label)" with a remove button. While unbound with ids stored, the inspect pane says the caste limit is inactive because Blax Castes isn't loaded. The inspect pane also warns when no current pawn of the zone's owner type fits.
- Medical zones: the limit applies to them too. It still composes with Blax Slaves' shared infirmary, because Zones runs at `Priority.Low`.
- Load order: About.xml keeps loadAfter `blax.castes` only.
- **Settings:** Per people zone: caste list (empty, any caste) and "Pawns without a caste" (off), hidden without Castes. No global setting.
- **Save and removal:** Caste ids are strings in the zone, saved in the component. Removing Castes keeps them, unused. Removing Castes and adding it back creates a new caste token, so old ids match no new caste and show as deleted castes instead of silently matching a new caste with the same number. Removing Zones drops them with the component; Castes keeps nothing for Zones.
- **Replaces:** Nothing.
- **Effort:** M, 2 days: the token, the cache, the sweep and the deleted-caste UI.
- **Tests:** Run with Castes in `-Compat`; create castes through reflection on `BlaxCastes.CasteManager`, so the test mod gets no assembly reference to Castes. Skip without Castes.
- Phase 1, with Castes: a zone limited to caste A refuses a caste B pawn and accepts an A pawn. Every id from `CasteLabels()` has the same token prefix as `CasteIdOf` returns. A casteless pawn is refused until "Pawns without a caste" is ticked. A bought slave queued by Castes is refused before `Tick(1)` and accepted after it. Assigning the owner to caste B unclaims its zone bed within 250 ticks, and a sleeping owner is woken. A deleted caste's id stays stored and matches nobody. With Castes' API switched off, the limits are ignored and nobody is evicted. Ids from an older token (simulate a new component) match no new caste. `GC.GetAllocatedBytesForCurrentThread` across 1,000 `CanUseBedNow` calls on a caste-limited bed stays below 1 KB. `FindBedFor` across 500 caste-limited cells fails above 10 ms.
- Phase 1, without Castes: the section is hidden, stored ids are ignored but kept.
- Phase 2: ids and `allowNoCaste` survive the reload, and the binding still works.
- Load hook: a save loaded with Castes just added keeps every stored id, although `CasteLabels()` is empty during map `FinalizeInit`.
- **Risks:** It depends on Castes shipping API version 1 with `Active`, the token and `List<KeyValuePair<string, string>>`. An older or different API means unbound, with one log line.
#### Headless tests in 1.6
- Castes joins the default `-Compat` set; the caste tests skip in plain runs.
- A test helper builds castes through reflection only, so the test mod compiles without Castes.
## Works with the other Blax mods
- Package ids: `blax.slaves`, `blax.castes`, `blax.zones`, `blax.defaults`. No hard dependencies. About.xml has one sibling entry, loadAfter `blax.castes`. Load order is Castes, Zones, Slaves. Slaves lists `blax.zones`, so Zones doesn't list Slaves back, which would form a loadAfter cycle. Defaults lists no sibling and no sibling lists Defaults, so its position doesn't matter.
@ -735,7 +727,7 @@ Ships once Blax Castes publishes `CastesApi` version 1, planned for Castes 1.1 i
- `Version` (static int property), 1.
- `bool TryFindDropSpot(Map map, Thing thing, out IntVec3 cell)`: respects zone filters, priority and drop rules, false if no zone fits. It uses the orbital rules (orbital ticked, pod rule, overflow setting), always returns false for a Pawn, and returns false instead of throwing. The cell is for one pod holding that one thing: the caller spawns it exactly there with `TradeUtility.SpawnDropPod(cell, map, thing)` or `DropPodUtility.MakeDropPodAt`, and calls again per thing, after spawning the last pod, because a falling pod is what marks its cell as taken. `DropThingsNear` would not do: `DropThingGroupsNear` searches a new random cell around the center for every group (DropPodUtility.cs:44), starting within 5 cells (DropCellFinder.cs:271-276), so the pod would usually miss a small zone.
- A member for sleeping zones is added once a sibling needs one, with its meaning written down then.
- Zones reads from Blax Castes, in 1.6 only, through `CastesApi` version 1, which Castes' design plans for its 1.1 with the same table:
- Zones reads from Blax Castes, in 1.5 only, through `CastesApi` version 1, which Castes' design plans for its 1.1 with the same table:
| Member | What Zones expects | Castes version |
|---|---|---|
@ -750,10 +742,10 @@ Ships once Blax Castes publishes `CastesApi` version 1, planned for Castes 1.1 i
- Ownership: Zones owns sleeping spots, beds by zone, every friendly drop location and per-cell work rules (work rule areas); it never changes a pawn's work priorities or allowed area. Castes owns every per-pawn policy default (apparel, food, drug, reading, medical care, schedule, work priorities, weapon loadout, allowed area, hostility, self-tend, carried medicine, fire at will, prisoner interaction); Zones never touches policies. Slaves owns slave status, trade, prices, suppression, rebellion, slave medicine and the slave economy. Defaults: starting settings of vanilla stockpiles and growing zones, storage buildings, production bills, workbenches, buildings, animals and mechs, and what the game forbids when pawns go down, die or are stripped. It writes when something is made or joins, and through its opt-in forbid rules when a pawn goes down, dies or is stripped. It keeps nothing in the save.
- Slaves routes its silver payouts through `ZonesApi.TryFindDropSpot` and spawns the pod at the returned cell with `TradeUtility.SpawnDropPod`, with `DropCellFinder.TradeDropSpot` and `DropThingsNear` as fallback (Blax Slaves docs/roadmap.md, purchase ledger and payouts). Pawns are never routed into zones. Payouts follow the zone's orbital checkbox, and its tooltip says so while Slaves is active.
- Buying: Zones never routes bought people. Slaves' buy-mode sets `guest.joinStatus` before vanilla `Pawn.PreTraded`, and Castes classifies by the final status in its own PreTraded scope. Zones touches neither.
- Slave sleeping zones (1.5) use vanilla `BedOwnerType.Slave`, so `Alert_NeedSlaveBeds` counts them with no patch (Alert_NeedSlaveBeds.cs:43). The alert runs only with Ideology (`requireIdeology`, Alert_NeedSlaveBeds.cs:14).
- Slave sleeping zones (1.4) use vanilla `BedOwnerType.Slave`, so `Alert_NeedSlaveBeds` counts them with no patch (Alert_NeedSlaveBeds.cs:43). The alert runs only with Ideology (`requireIdeology`, Alert_NeedSlaveBeds.cs:14).
- Blax Slaves' shared infirmary (its 1.5) lets slaves use colonist medical beds, so a colonist sleeping zone set to medical takes slaves too. Zone filters and caste limits still apply, because the `CanUseBedNow` postfix runs at `Priority.Low`.
- Blax Defaults ("Starting settings for storage, bills, crops, buildings, animals and mechs"): it hooks only `Designator_ZoneAddStockpile` (its 1.0) and `Designator_ZoneAdd_Growing` (its 1.4), and Zones' zones subclass `Zone` and `Designator_ZoneAdd` directly with their own tabs (`ITab_Delivery`, the animal-zone and people-zone tabs), so no Defaults hook or button reaches a delivery or sleeping zone. A new stockpile or shelf starts unflagged; "Make default" never copies Zones' flags, which live in Zones' component. Defaults' button sits inside the storage tab and Zones' 1.4 gizmos on the gizmo bar. Zone beds come from `AddCell`, not a frame, so Defaults' build scope (its 1.2) never sees them. Neither mod touches the home area. Defaults' forbid rules (its 1.1) act only inside `Pawn.Kill`, `Pawn_HealthTracker.MakeDowned` and `Pawn.Strip` (Pawn.cs:3895; Pawn_HealthTracker.cs:837), never on goods Zones delivers, so arriving goods keep the forbid flag of the vanilla call. If Defaults ever adds a rule for them, it must act where Zones' routed groups also pass, because routed reward groups drop through `MakeDropPodAt` and orbital goods through `SpawnDropPod`, never through `DropThingsNear`.
- Work rule areas (1.3) are per cell and never touch a pawn: Castes keeps the allowed area (its 1.2), and the work search already refuses things outside it (JobGiver_Work.cs:219-226; ForbidUtility.cs:111-118, 157-165), so a caste kept to the fields never walks to a "Clean first" hospital and Zones needs no CastesApi member. They aren't vanilla Areas, so they never show in Castes' area picker or match its area labels (`AreaManager.GetLabeled`, AreaManager.cs:86-96). Slaves are colonists for the work search and follow the rules like anyone. With Defaults the two compose: its forbid rules decide whether dropped gear is forbidden (its 1.1), and allow matched gear only once no enemy that can still fight is on the map; work rule areas decide whether haulers fetch it, so a killbox with "Don't haul from here" keeps allowed loot lying until the rule is unticked, and "Haul first" brings it in before other hauling. Neither mod hooks the other's code.
- Blax Defaults ("Starting settings for storage, bills, crops, buildings, animals and mechs"): it hooks only `Designator_ZoneAddStockpile` (its 1.0) and `Designator_ZoneAdd_Growing` (its 1.4), and Zones' zones subclass `Zone` and `Designator_ZoneAdd` directly with their own tabs (`ITab_Delivery`, the animal-zone and people-zone tabs), so no Defaults hook or button reaches a delivery or sleeping zone. A new stockpile or shelf starts unflagged; "Make default" never copies Zones' flags, which live in Zones' component. Defaults' button sits inside the storage tab and Zones' 1.3 gizmos on the gizmo bar. Zone beds come from `AddCell`, not a frame, so Defaults' build scope (its 1.2) never sees them. Neither mod touches the home area. Defaults' forbid rules (its 1.1) act only inside `Pawn.Kill`, `Pawn_HealthTracker.MakeDowned` and `Pawn.Strip` (Pawn.cs:3895; Pawn_HealthTracker.cs:837), never on goods Zones delivers, so arriving goods keep the forbid flag of the vanilla call. If Defaults ever adds a rule for them, it must act where Zones' routed groups also pass, because routed reward groups drop through `MakeDropPodAt` and orbital goods through `SpawnDropPod`, never through `DropThingsNear`.
- Work rule areas (1.6) are per cell and never touch a pawn: Castes keeps the allowed area (its 1.2), and the work search already refuses things outside it (JobGiver_Work.cs:219-226; ForbidUtility.cs:111-118, 157-165), so a caste kept to the fields never walks to a "Clean first" hospital and Zones needs no CastesApi member. They aren't vanilla Areas, so they never show in Castes' area picker or match its area labels (`AreaManager.GetLabeled`, AreaManager.cs:86-96). Slaves are colonists for the work search and follow the rules like anyone. With Defaults the two compose: its forbid rules decide whether dropped gear is forbidden (its 1.1), and allow matched gear only once no enemy that can still fight is on the map; work rule areas decide whether haulers fetch it, so a killbox with "Don't haul from here" keeps allowed loot lying until the rule is unticked, and "Haul first" brings it in before other hauling. Neither mod hooks the other's code.
- Each mod keeps its state in its own Map or Game components, or none (Defaults), so removing one leaves the others' saves intact.
- Shared conventions: patches applied one class at a time from a `[StaticConstructorOnStartup]` class, logging "[Blax Zones] N patches applied"; a ModSettings toggle for every feature (zone storage has none, it is the save format); any DLC combination, core only included (see "DLC support"); every hook body in try/catch with a one-time log; the headless in-game test mod copied from blax-castes/Tests (BlaxCastesTests harness, run-tests.ps1) as Tests/BlaxZonesTests, plus a phase 3 that simulates removing the mod.
@ -770,7 +762,7 @@ Ships once Blax Castes publishes `CastesApi` version 1, planned for Castes 1.1 i
- Ally drop pods and aid land next to a chosen zone (Allies Spot 2067847359, 3,678 subs): needs a faction check so hostile drops are never affected; small demand.
- Vanilla Events Expanded's apparel and weapon pods in the cargo-pod context (S): the same context on those two incident workers, bound by reflection.
- A full removal test (`-Removal`, S): relaunch the game without blax.zones in ModsConfig plus a small verifier mod that loads the phase-3 save at the main menu and writes the error and warning counts.
- Blax zones fly with Odyssey gravships (`GravshipPlacementUtility`): Odyssey isn't installed on the test machine to build or test it. If built, behind `ModsConfig.OdysseyActive`. Work rule areas (1.3) would move with the same code, as vanilla moves the home area (GravshipPlacementUtility.cs:388).
- Blax zones fly with Odyssey gravships (`GravshipPlacementUtility`): Odyssey isn't installed on the test machine to build or test it. If built, behind `ModsConfig.OdysseyActive`. Work rule areas (1.6) would move with the same code, as vanilla moves the home area (GravshipPlacementUtility.cs:388).
- Construction first (M): a work rule "Build first" needs one wrapped giver per construction giver (finish frames, deliver to frames, deliver to blueprints; Core WorkGiverDefs/WorkGivers.xml:689-736), and frame order has build-order effects (roofs, walls closing a room). Smarter Construction (2202185773, 1,023,962 subs, 1.7) already reorders construction. Build it when players ask.
- Plant work first (M): sowing and harvesting first by area, wrapping `GrowerSow` and `GrowerHarvest`. Growing zones already split fields, and Growing Zone Priorities (Continued) (2026571920, 4,639, 1.7) ranks them.
- "Don't haul from here" with an item filter (S), for example leave weapons and apparel but haul corpses and food: a vanilla `ThingFilter` per area, checked in the same `ShouldBeHaulable` postfix. Wait for players to ask; Defaults' forbid rules cover what enemies drop.
@ -781,7 +773,7 @@ Ships once Blax Castes publishes `CastesApi` version 1, planned for Castes 1.1 i
## Cut
- Pack animals walk purchases to the zone (L): many exit paths (lord transitions, duty reassignment, `ExitMap`, death, hostility), owed items must be hidden from the next trade, and nobody asked. Goods appearing plus caravan camping covers it.
- Stockpile flags instead of a delivery zone in 1.0: most stockpiles are roofed, so pods couldn't use them without direct delivery, and a flagged outdoor stockpile mixes landing pods with stored goods. The delivery zone is a landing pad with its own source checkboxes and the camp option. It wouldn't spare the zone save work either, which sleeping zones need in 1.2 anyway. Flags arrive in 1.4 together with direct delivery.
- Stockpile flags instead of a delivery zone in 1.0: most stockpiles are roofed, so pods couldn't use them without direct delivery, and a flagged outdoor stockpile mixes landing pods with stored goods. The delivery zone is a landing pad with its own source checkboxes and the camp option. It wouldn't spare the zone save work either, which sleeping zones need in 1.2 anyway. Flags arrive in 1.3 together with direct delivery.
- Shared zones by blocking `Pawn_Ownership.ClaimBedIfNonMedical`: the unowned sleeper fails `CanUseBedNow` (RestUtility.cs:142-146) and gets kicked out of bed in a loop.
- Letter-target postfix on `QuestPart_DropPods.GetRandomDropSpot`: vanilla already points the letter at the first dropped thing, and the postfix would pull refugees and quest prisoners next to the zone.
- Defeat-all-enemies rewards (`DefeatAllEnemiesQuestComp.GiveRewardsAndSendLetter`): nothing in vanilla 1.7 calls its `StartQuest`, so it never becomes active (RimWorld.Planet/DefeatAllEnemiesQuestComp.cs:25-55), and its letter would point at the trade spot (:74-81).
@ -804,7 +796,7 @@ Ships once Blax Castes publishes `CastesApi` version 1, planned for Castes 1.1 i
- Per-cell spot graphics and owner labels in sleeping zones: clutter, the reason Hidden Spots exists. The zone tint and inspect pane carry the state.
- Routing visitor and trader parting gifts: rare, and harmless next to the giver.
- Work rules as a Zone: one zone per cell, so a rule couldn't lie on a stockpile, a growing field or a delivery or sleeping zone, and the barn holds all of those.
- Work rules as vanilla `Area` subclasses: a plain unsubscribe would leave `map.areaManager` null, taking the home area and every allowed area with it (see "Why this shape" in 1.3), and a work rule area could shadow an allowed area of the same name for Blax Castes.
- Work rules as vanilla `Area` subclasses: a plain unsubscribe would leave `map.areaManager` null, taking the home area and every allowed area with it (see "Why this shape" in 1.6), and a work rule area could shadow an allowed area of the same name for Blax Castes.
- One layer per rule with its own designators: 12 designators in the Zone menu, and switching a rule off for a while means erasing and repainting.
- "Clean first" by making vanilla cleaning prioritized with a `GetPriority` from the area: the prioritized path validates every candidate on the map with a reachability check (JobGiver_Work.cs:118-121) instead of the 4-region search, for every cleaner, even on maps with no area, and switching it on means patching the `Prioritized` getter every scanner shares.
- "Clean first" by sorting the filth list: the search picks by distance, not list order (GenClosest.cs:149-232), so a sort changes nothing.

View File

@ -1,4 +1,4 @@
# In-game check for 1.0 and 1.1
# 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.
@ -39,24 +39,8 @@ The headless suite covers the logic but draws nothing. These are the checks only
## 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.
## Caravan purchases (1.1)
- [ ] Select a delivery zone: the Delivery tab shows "Quest rewards land here" and "Caravan purchases land here" below the orbital row, both ticked, and the item filter still fits the window. Hover each: the tooltip reads well, and with its routing setting off it adds the off note.
- [ ] Force a trader caravan (dev mode) and buy steel and medicine in one trade. Both appear in the delivery zone, also a roofed one, not at the pack animals' feet. One message names the zone; clicking it jumps to the goods.
- [ ] With every zone cell full, bought goods appear right next to the zone, and the message says they were delivered next to it, which is full. With "Overflow lands next to the zone" off they appear at the pack animals' feet.
- [ ] Sell a caravan more than you buy from it: the silver appears in the delivery zone, and the message reads "Goods from the trade were delivered to" the zone.
- [ ] Buy an animal: it stays with the caravan, as in vanilla. The traders don't pick the bought goods back up before they leave.
- [ ] With Hospitality, buy something from a guest: it appears in the zone and the message names it.
## Quest rewards (1.1)
- [ ] Accept a quest with an item reward that drops by pod (dev mode: a quest with Reward_Items, or the debug "drop pods" quest part). The pods fall into the delivery zone, one per stack, and the quest letter jumps to the zone.
- [ ] A refugee or prisoner from a quest lands at the trade beacon, as in vanilla.
- [ ] Mod settings: "Route quest rewards", "Route caravan purchases" and "Message when goods arrive" show with their tooltips, and Reset to defaults ticks all three.
- [ ] 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.
- [ ] Load a save made with 1.0.0: every delivery zone has "Quest rewards land here" and "Caravan purchases land here" ticked, and the log shows nothing from Blax Zones.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 KiB

View File

@ -1,56 +1,54 @@
[b]Choose where deliveries land.[/b] Drag a delivery zone and what you buy from orbital traders and trader caravans, plus quest rewards, lands in it, sorted by item filter and priority: medicine by the hospital, steel by the workshop. Trader caravans camp next to a zone you pick.
[b]Choose where deliveries land.[/b] Drag a delivery zone and what you buy from orbital traders drops into it, sorted by item filter and priority: medicine by the hospital, steel by the workshop. Trader caravans camp next to a zone you pick.
✅ RimWorld 1.7 🔧 Needs [url=https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077]Harmony[/url] 🧩 Works with any DLC combination 💾 Safe to add to a running save
[img]https://cdn.blax.at/blax-gaming/zones/deliveries.png[/img]
[img]https://cdn.blax.at/blax-gaming/zones/delivery-zone.jpg[/img]
[list]
[*]📦 [b]Delivery zones.[/b] "Delivery zone" sits in the Zone menu right after "Growing zone". Drag it like a stockpile. It shows amber on the map and grows with "Expand zone".
[*]🛰️ [b]Orbital trade lands in the zone.[/b] Every item you buy from an orbital trader, plus the silver from selling, drops into the best matching delivery zone instead of next to the trade beacon.
[*]🐪 [b]Caravan purchases appear in the zone.[/b] What you buy from a visiting trader caravan or a Hospitality guest, and the silver from selling to them, appears in the best matching delivery zone instead of at the pack animals' feet. Nothing falls, so a roofed zone works too: a medicine zone inside the hospital. One message per trade names the zone.
[*]🎁 [b]Quest rewards land in the zone.[/b] Item rewards that quests drop at the trade beacon fall into the best matching delivery zone, one pod per stack, and the quest letter points there.
[*]🏷️ [b]Filter and priority.[/b] The zone's Delivery tab has an item filter, a priority from Low to Critical and "Orbital trade lands here", "Quest rewards land here" and "Caravan purchases land here" (all on by default). The filter decides what fits, then the highest priority wins, then the oldest zone.
[*]🏷️ [b]Filter and priority.[/b] The zone's Delivery tab has an item filter, a priority from Low to Critical and "Orbital trade lands here" (on by default). The filter decides what fits, then the highest priority wins, then the oldest zone.
[*]🎯 [b]Pods spread out.[/b] They use the 400 cells nearest the middle of a zone: the free ones first, from the middle out, then a matching stack.
[*]👣 [b]Overflow you can reach.[/b] When every fitting zone is full, pods and caravan purchases land next to the top one, on a cell your colonists can reach, within 16 cells (5 to 30 in the settings). A zone your colonists can't reach sends its overflow to the vanilla spot.
[*]👣 [b]Overflow you can reach.[/b] When every fitting zone is full, pods land next to the top one, on a cell your colonists can reach, within 16 cells (5 to 30 in the settings). A zone your colonists can't reach sends its overflow to the vanilla spot.
[*]🟥 [b]Bad cells marked.[/b] 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.
[*]📋 [b]Copy settings and Paste settings[/b] move the filter, the priority and every checkbox from one delivery zone to another.
[*]🛡️ [b]Nothing gets lost.[/b] Bought people and animals, refugees, prisoners and Wastepack from quests, raids, colonists you ransom back and lent colonists coming home land as before. With no fitting zone, or if anything in Blax Zones goes wrong, goods land at the vanilla spot.
[*]📋 [b]Copy settings and Paste settings[/b] move the filter, the priority and both checkboxes from one delivery zone to another.
[*]🛡️ [b]Nothing gets lost.[/b] Bought people and animals, raids, colonists you ransom back and lent colonists coming home land as before. With no fitting zone, or if anything in Blax Zones goes wrong, the pod lands at the vanilla spot.
[*]🔌 [b]For modders.[/b] ZonesApi hands other mods a cell in or next to a delivery zone for a drop pod, by the zone's filter, priority and "Orbital trade lands here" checkbox. [url=https://steamcommunity.com/sharedfiles/filedetails/?id=3847282171]Blax Slaves[/url] binds it for its planned silver payouts.
[/list]
[img]https://cdn.blax.at/blax-gaming/zones/camps.png[/img]
[list]
[*]⛺ [b]Caravans camp here.[/b] Tick "Caravans camp here" on a delivery zone (off by default). Visiting trader caravans and, with Royalty, tribute collectors gather within 6 cells of it, on open ground they can all reach.
[*]🐪 [b]Easy to reach.[/b] The trader stands next to the zone, and with "Route caravan purchases" off, what you buy drops at the pack animals' feet, so it still ends up next to the zone.
[*]🐪 [b]Goods stay close.[/b] What you buy from them drops at their pack animals' feet, so it ends up next to the zone.
[*]🚶 [b]Visitors pick their own spot.[/b] Visitor groups and Hospitality guests ignore the camp zone.
[/list]
⚙️ The mod settings switch each part off: "Delivery zones" hides the designator (existing zones keep working), "Route orbital trade", "Route quest rewards", "Overflow lands next to the zone" with its radius, "Route caravan purchases", "Message when goods arrive" and "Caravans may camp at zones".
⚙️ The mod settings switch each part off: "Delivery zones" hides the designator (existing zones keep working), "Route orbital trade", "Overflow lands next to the zone" with its radius, and "Caravans may camp at zones".
💾 [b]Safe to add and remove.[/b] Add Blax Zones to a running save. Delivery zones live in Blax Zones' own save data, never in the game's zone list, so after you unsubscribe the save still loads: the delivery zones are gone, vanilla zones stay, and the log shows two errors per map.
🧩 [b]Any DLC combination works,[/b] core only included. Nothing in this version needs a DLC. With Royalty, tribute collectors camp at the zone too, and Empire quest rewards land in it. With Biotech, Wastepack never lands in a zone.
🧩 [b]Any DLC combination works,[/b] core only included. Nothing in this version needs a DLC. With Royalty, tribute collectors camp at the zone too. With Biotech, Wastepack never lands in a zone.
[img]https://cdn.blax.at/blax-gaming/zones/planned.png[/img]
Not in this version yet. Planned for the next releases:
[list]
[*]🎁 Quest rewards land in the zone, and goods bought from trader caravans and Hospitality guests appear in it.
[*]🐔 Animal sleeping zones: every cell is a sleeping spot, with species and body-size filters.
[*]🧹 Work rule areas: paint areas where nobody cleans, fights fires, repairs or hauls from, or that get cleaned and hauled first.
[*]🗄️ Deliveries straight into stockpiles and shelves, sell zones for orbital traders, cargo pods into a zone.
[*]🛏️ Sleeping zones for colonists, prisoners and slaves (slaves need Ideology).
[*]🧹 Work rule areas: paint areas where nobody cleans, fights fires, repairs or hauls from, or that get cleaned and hauled first.
[/list]
[img]https://cdn.blax.at/blax-gaming/zones/replaces.png[/img]
Blax Zones does what these mods do for orbital trade, quest rewards and caravan spots, so you can unsubscribe them.
Blax Zones does what these mods do for orbital trade and caravan spots, so you can unsubscribe them.
[list]
[*]♻️ Trade Ships Drop Spot (while it's active, a one-time message says you can unsubscribe it, once you have a delivery zone)
[*]♻️ Trading Control (while it's active, caravan camps stand down)
[*]♻️ Trade Ships Drop Spot (quest rewards follow in a later release)
[*]♻️ Trading Control (quest rewards follow in a later release; while it's active, caravan camps stand down)
[*]♻️ [KV] Trading Spot and [GMT] Trading Spot (while one is active, caravan camps stand down)
[/list]
[img]https://cdn.blax.at/blax-gaming/zones/compatibility.png[/img]
[list]
[*]✔️ Hospitality guests pick their own spot and never camp at the zone. What you buy from them lands in the zone.
[*]✔️ Hospitality guests pick their own spot and never camp at the zone.
[*]✔️ Trading Spot Rewritten: while it's active, caravan camps stand down and leave caravans to it, with one log line.
[*]✔️ A mod that moves the vanilla trade drop spot keeps working: pods that fit no zone land at its spot.
[*]✔️ Tested in one game with Hospitality, Prison Labor, Pick Up And Haul, Haul to Stack, RimFridge, Weapon Racks, Prisoner Realism, Replace Stuff, Vanilla Expanded Framework, Vanilla Furniture Expanded, Dubs Skylights, Vanilla Events Expanded and the other Blax mods, with no errors from Blax Zones.

View File

@ -4,7 +4,6 @@ The Steam description shows GIFs inline (`[img]`), the same way as the section h
| File | Shows | How to set it up |
|---|---|---|
| `delivery-zone.jpg` (done, on the page and in the README) | Orbital purchases lying in a delivery zone, with the zone's panel and Delivery tab | Screenshot from Fabian's colony, 2026-11-30 |
| `orbital-delivery.gif` | Buy medicine and steel from an orbital trader. The pods fall into a medicine-only zone by the hospital and a general zone by the workshop | Two delivery zones (the medicine one at Important), a powered comms console and trade beacon; dev mode can run "orbital trader arrival" |
| `drag-zone.gif` | Zone menu, "Delivery zone", drag it, then the Delivery tab: priority, "Orbital trade lands here", "Caravans camp here" and the item filter | Any colony |
| `caravan-camp.gif` | Tick "Caravans camp here", a trader caravan walks in and sets up next to the zone | An open spot next to the zone; dev mode can run "trader caravan arrival" |