feat: works with any DLC combination (1.2.1)

Without Ideology the trade features that need no slaves keep working (every trader buys captives, slaver caravans), and the slave features switch off: buy mode, branding, slave-harm moods, runaways and time as a slave. Their settings show disabled with "Needs Ideology", and tab resets keep them. A pawn bought without Ideology always joins as a colonist. Slaves and brands left from an Ideology save get no slave features and log nothing. Runaway records save the interaction mode by name.

Tests: run-tests.ps1 takes -NoDlc and -Dlc <list>; DLC tests skip with "needs <DLC>"; new DLC-off tests; fixtures spawn on open cells. Full matrix green: core 50/0/81, Ideology 128 to 131, all 130/0/1, compat 112/0/18. The publish guard wants a green all-DLC run and a green -NoDlc run newer than the DLL.
This commit is contained in:
Fabian @ Blax Software 2026-11-29 17:07:37 +01:00
parent cf59c02590
commit b40429286b
28 changed files with 1195 additions and 146 deletions

Binary file not shown.

Binary file not shown.

View File

@ -21,24 +21,24 @@
<li>blax.castes</li>
<li>blax.zones</li>
</loadAfter>
<description>Slavery as an everyday part of the rim. Needs Ideology for slaves.
<description>Slavery as an everyday part of the rim. Works with any DLC combination, core only included. Slaves need Ideology, so the features marked (Ideology) switch off without it.
&lt;color=#19C63C&gt;Trade&lt;/color&gt;
- Choose slave or colonist when you buy a pawn from a trader: click "Joins as slave / Joins as colonist" in the trade window.
- Every trader buys your slaves and prisoners, visitors included. Optionally, factions that reject slavery refuse, except to ransom their own people.
- Price sliders for buying slaves and selling captives (vanilla 60% each), with a cap so buy-low-sell-high doesn't pay.
- Slavers (caravans and orbital slave ships) show up far more often and bring more slaves.
- Choose slave or colonist when you buy a pawn from a trader (Ideology): click "Joins as slave / Joins as colonist" in the trade window.
- Every trader buys your prisoners and slaves, visitors included, and with Royalty the Empire's caravans too. Optionally, factions that reject slavery refuse, except to ransom their own people (Ideology).
- Price sliders for buying slaves and selling captives (Ideology): vanilla 60% each, with a cap so buy-low-sell-high doesn't pay.
- Slavers (caravans and orbital slave ships) show up far more often and bring more slaves. Without Ideology, the pawns you buy from them join as colonists.
- Allied outlanders and tribes send a slaver caravan on request (comms console).
- Every caravan and orbital trader may have a slave or two for sale, and settlements keep selling slaves however big your colony gets.
&lt;color=#19C63C&gt;Slaves&lt;/color&gt;
&lt;color=#19C63C&gt;Slaves (Ideology)&lt;/color&gt;
- Brand your slaves: a burn mark that shows who owns them. Branded slaves' suppression falls slower.
- Branded runaways come back: a non-hostile faction that finds one returns them after a few days. Hostile factions keep them.
- Some slaves you buy already carry a previous owner's brand. Rebrand them with your own mark.
- Harming slaves (execution, organ harvesting, selling, banishing, butchering) doesn't upset your colonists, except pacifists: Kind pawns and those incapable of violence still mind. Family still grieves.
- Time as a slave in the Records tab and the slave tab.
Everything is adjustable in the mod settings.
Everything is adjustable in the mod settings. Without Ideology, the settings that need it show greyed out with a note.
&lt;color=#19C63C&gt;Made by Blax&lt;/color&gt;
Blax Gaming is a project of Blax Software, an Austrian software practice. We write Austrian-quality code in many fields: web platforms, mobile apps, backends, infrastructure, and the mods we play in our own colonies. www.blax.at</description>

View File

@ -1,5 +1,11 @@
# Changelog
## 1.2.1
- Works with any DLC combination, core only included. Without Ideology the slave features stay off and their settings show greyed out with a "needs Ideology" note; every trader still buys your prisoners, and the slaver changes still apply.
- A save made with Ideology loads without it: no error for a runaway who was due to be returned, and leftover slaves get no branding surgery, Branded mood, runaway letters, mood protection or slave time. Trader stock from that save that was set to join as a slave joins as a colonist when bought.
- The Records tab no longer shows "Time as a slave" without Ideology.
## 1.2.0
- Buy as slave or colonist: click "Joins as slave / Joins as colonist" on a pawn in a trader's stock to switch it. A setting picks what new stock starts as (vanilla roll, always slave, always colonist). Replaces Trade as Slave or Colonist.

View File

@ -33,7 +33,10 @@
<BlaxSlaves_TabGeneral>General</BlaxSlaves_TabGeneral>
<BlaxSlaves_TabCompat>Compat</BlaxSlaves_TabCompat>
<BlaxSlaves_ResetTab>Reset this tab</BlaxSlaves_ResetTab>
<BlaxSlaves_SettingNeedsIdeology>Slaves need the Ideology DLC. Without it, most of this tab does nothing.</BlaxSlaves_SettingNeedsIdeology>
<BlaxSlaves_SettingNeedsIdeology>Slaves need the Ideology DLC, so the greyed-out options are off without it. Traders still buy your prisoners, and slavers still come more often.</BlaxSlaves_SettingNeedsIdeology>
<BlaxSlaves_SettingGeneralNeedsIdeology>Everything on this tab is about slaves and needs the Ideology DLC.</BlaxSlaves_SettingGeneralNeedsIdeology>
<!-- A setting that does nothing without a DLC: {0} is the setting's label, {1} the DLC (Ideology) -->
<BlaxSlaves_NeedsDlc>{0} (needs {1})</BlaxSlaves_NeedsDlc>
<!-- Trade tab -->
<BlaxSlaves_SettingBuyMode>Choose slave or colonist when buying</BlaxSlaves_SettingBuyMode>
@ -44,7 +47,7 @@
<BlaxSlaves_SettingPurchaseSlave>Always slave</BlaxSlaves_SettingPurchaseSlave>
<BlaxSlaves_SettingPurchaseColonist>Always colonist</BlaxSlaves_SettingPurchaseColonist>
<BlaxSlaves_SettingAllTradersBuy>Every trader buys slaves and prisoners</BlaxSlaves_SettingAllTradersBuy>
<BlaxSlaves_SettingAllTradersBuyTip>Settlements, the Empire and modded traders buy captives too, not only slavers and caravans.</BlaxSlaves_SettingAllTradersBuyTip>
<BlaxSlaves_SettingAllTradersBuyTip>Settlements, modded traders and, with Royalty, the Empire buy captives too, not only slavers and caravans.</BlaxSlaves_SettingAllTradersBuyTip>
<BlaxSlaves_SettingVisitorsBuy>Visitor groups buy slaves and prisoners</BlaxSlaves_SettingVisitorsBuy>
<BlaxSlaves_SettingVisitorsBuyTip>Visiting groups from other factions buy captives when you trade with them.</BlaxSlaves_SettingVisitorsBuyTip>
<BlaxSlaves_SettingAntiSlavery>Traders whose ideoligion rejects slavery:</BlaxSlaves_SettingAntiSlavery>

View File

@ -5,29 +5,41 @@
[![RimWorld 1.7](https://img.shields.io/badge/RimWorld-1.7-19C63C)](https://rimworldgame.com)
[![Steam Workshop](https://img.shields.io/badge/Steam_Workshop-subscribe-1b2838?logo=steam)](https://steamcommunity.com/sharedfiles/filedetails/?id=3847282171)
[![Needs Harmony](https://img.shields.io/badge/needs-Harmony-050805)](https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077)
[![Slaves need Ideology](https://img.shields.io/badge/slaves_need-Ideology-5a6b5d)](https://store.steampowered.com/app/1392840/)
[![Any DLC combination](https://img.shields.io/badge/DLCs-any_combination-5a6b5d)](#dlc-support)
RimWorld mod (1.7) that makes slavery an everyday part of the rim. First mod under the Blax Gaming label. Needs Harmony; slaves need Ideology.
RimWorld mod (1.7) that makes slavery an everyday part of the rim. First mod under the Blax Gaming label. Needs Harmony. Works with any DLC combination, core only included; the slave features need Ideology.
## Features
### Trade
- 🔁 **Buy as slave or colonist (1.2).** In the trade window, "Joins as slave / Joins as colonist" on a pawn the trader sells is a button: click to switch, and the price updates (a slave costs 60% of the colonist price, as in vanilla). Unwaveringly loyal pawns can only be bought as slaves. A setting picks what new stock starts as: the vanilla 25/75 roll, always slave or always colonist. Stands down while Trade as Slave or Colonist is active. `Source/BlaxSlaves/BuyMode.cs`
- 🤝 **Every trader buys captives (1.2).** Visitor groups, the Empire's caravans and modded traders without a humanlike stock generator get one, so anyone you trade with buys your slaves and prisoners. Optional: factions whose ideoligion rejects slavery refuse, except their own people (ransom). Slave stock ignores colony size, so settlements keep selling slaves to big colonies. `Source/BlaxSlaves/TraderBuyers.cs`
- 💰 **Price sliders (1.2).** What slaves cost and what captives fetch, both vanilla 60% by default (30 to 100%). Above vanilla, a captive's sale price is capped at 90% of what the same trader would charge you for that pawn as a slave, so buy-low-sell-high loops don't pay. `Source/BlaxSlaves/SlavePrices.cs`
- 🐪 **Slavers are common.** The three vanilla slavers (outlander "slaver" caravan, tribal "slaver" caravan, orbital "slave ship") get commonality 2 instead of 1, and big colonies keep seeing them at half weight instead of zero. They carry more: outlander 5~9, tribal 4~7, slave ship 6~10 (vanilla 2~4). Every other caravan and orbital trader has a ~50% chance of 1~2 slaves, settlements stock 1~4. `Patches/BlaxSlaves_Traders.xml`
- 🔁 **Buy as slave or colonist (1.2).** In the trade window, "Joins as slave / Joins as colonist" on a pawn the trader sells is a button: click to switch, and the price updates (a slave costs 60% of the colonist price, as in vanilla). Unwaveringly loyal pawns can only be bought as slaves. A setting picks what new stock starts as: the vanilla 25/75 roll, always slave or always colonist. Stands down while Trade as Slave or Colonist is active. Needs Ideology. `Source/BlaxSlaves/BuyMode.cs`
- 🤝 **Every trader buys captives (1.2).** Visitor groups, the Empire's caravans (Royalty) and modded traders without a humanlike stock generator get one, so anyone you trade with buys your slaves and prisoners. Works without any DLC (then for prisoners). Optional, needs Ideology: factions whose ideoligion rejects slavery refuse, except their own people (ransom). Slave stock ignores colony size, so settlements keep selling slaves to big colonies. `Source/BlaxSlaves/TraderBuyers.cs`
- 💰 **Price sliders (1.2).** What slaves cost and what captives fetch, both vanilla 60% by default (30 to 100%). Above vanilla, a captive's sale price is capped at 90% of what the same trader would charge you for that pawn as a slave, so buy-low-sell-high loops don't pay. Needs Ideology: without it vanilla prices captives at full value, so there is no slave price to adjust. `Source/BlaxSlaves/SlavePrices.cs`
- 🐪 **Slavers are common.** The three vanilla slavers (outlander "slaver" caravan, tribal "slaver" caravan, orbital "slave ship") get commonality 2 instead of 1, and big colonies keep seeing them at half weight instead of zero. They carry more: outlander 5~9, tribal 4~7, slave ship 6~10 (vanilla 2~4). Every other caravan and orbital trader has a ~50% chance of 1~2 slaves, settlements stock 1~4. Works without any DLC; without Ideology the pawns you buy join as colonists. `Patches/BlaxSlaves_Traders.xml`
- 📡 **Request a slaver caravan.** Allied outlanders and tribes send one on request at the comms console (vanilla hides slavers from that list).
### Slaves
Everything in this section needs Ideology.
- 🔥 **Branding.** "Brand" surgery for colony slaves (adults, Medicine 2, never fails). The brand remembers its owner (shown as "slave brand (Owner)"), slows suppression loss by 15%, gives the slave a -3 "branded" mood and a fresh torso burn. "Rebrand" burns your mark over another owner's. `Defs/BlaxSlaves_Brand.xml`, `Source/BlaxSlaves/Brand.cs`
- 🏷️ **Trader slaves come branded.** 35% of adult slaves in trader stock carry the trader faction's brand (orbital ships: a random faction).
- 🏃 **Runaways come back.** A slave with your brand who escapes (slave rebellion, or a caravan whose last free member dies) is tracked. If the faction they end up with is hostile, they keep them. Otherwise, after 3~10 days (80% chance) a non-hostile faction returns them as your slave, walking in (tribal/medieval) or by drop pod. `Source/BlaxSlaves/Runaways.cs`
- 😌 **Harming slaves doesn't upset colonists.** Executing, harvesting, selling (trade or gift pod), banishing, butchering, blinding, gibbeting a slave gives free colonists no negative thoughts. Deaths only count when the colony caused them: a slave killed by raiders, animals or disease is mourned normally. Branded pawns count too unless they became free colonists. Pacifists (Kind, or incapable of violence) still mind, family still grieves, and the banish dialog shows the reduced cost. `Source/BlaxSlaves/SlaveHarm.cs`
- ⏳ **Time as a slave (1.2).** A Records tab entry, and "Enslaved for ..." in the slave tab (counted from the moment 1.2 is installed). `Source/BlaxSlaves/TimeAsSlave.cs`
⚙️ Mod settings for all the numbers and toggles, in tabs (Trade, General, Compat). The Compat tab lists active mods that Blax Slaves replaces, so you know what you can unsubscribe.
⚙️ Mod settings for all the numbers and toggles, in tabs (Trade, General, Compat). Without Ideology, the settings that need it show greyed out with a "needs Ideology" note. The Compat tab lists active mods that Blax Slaves replaces, so you know what you can unsubscribe.
### DLC support
Blax Slaves works with any combination of DLCs, core only included, and lists none as a dependency.
- **Ideology** is what makes slaves. Without it, buying as slave or colonist, the anti-slavery refusal, the price sliders and everything under Slaves stay off, and their settings show greyed out with a "needs Ideology" note. Every trader still buys your prisoners, and the slaver changes still apply.
- **A save made with Ideology** loads without it. Leftover slaves and brands are treated the way vanilla treats them: no branding, no runaway returns or letters, no mood protection, no time counting. A pawn a trader still holds from that save joins as a colonist when you buy it, never as a slave.
- **Royalty** adds the Empire: its caravans buy captives too, and its orbital and settlement traders carry slaves.
- **Biotech** adds children: "always slave" covers them, brands are for adults only.
- **Anomaly** and **Odyssey**: Blax Slaves uses none of their content.
### Compatibility
@ -74,7 +86,7 @@ RimWorld 1.7 no longer runs on Unity/Mono. It runs on .NET 10 (CoreCLR) with Lud
.\Tools\workshop-upload.ps1 -Publish -DescriptionFile docs\workshop-description.txt # also replace the description
```
It stages only what players need (About, 1.7, Defs, Patches, Languages) in `%TEMP%`, sets the tags the game would (Mod plus the supported versions), and writes every CHANGELOG.md entry since the version in `Tools/workshop-published.txt` as the change note. `-Publish` refuses unless the shipped files are committed and pushed, the top CHANGELOG entry matches `modVersion`, and the last test run passed after the last build. It leaves the title and preview alone; the game's uploader resets the title from About.xml and never updates the description. The in-game route still works: `Tools/workshop-stage.ps1` swaps the junction for a clean copy, upload from Mods > Blax Slaves > More actions (dev mode), then `workshop-stage.ps1 -Done`.
It stages only what players need (About, 1.7, Defs, Patches, Languages) in `%TEMP%`, sets the tags the game would (Mod plus the supported versions), and writes every CHANGELOG.md entry since the version in `Tools/workshop-published.txt` as the change note. `-Publish` refuses unless the shipped files are committed and pushed, the top CHANGELOG entry matches `modVersion`, and two test runs passed after the last build: one with every installed DLC and one with `-NoDlc`. It leaves the title and preview alone; the game's uploader resets the title from About.xml and never updates the description. The in-game route still works: `Tools/workshop-stage.ps1` swaps the junction for a clean copy, upload from Mods > Blax Slaves > More actions (dev mode), then `workshop-stage.ps1 -Done`.
The Workshop description is `docs/workshop-description.txt` (Steam BBCode); `-DescriptionOnly -DescriptionFile docs\workshop-description.txt` replaces just the text, with no build, no content upload and no change note. Steam loads description images as cross-origin requests, so every `[img]` host must send an `Access-Control-Allow-Origin` header or the image shows broken; the script checks each one and `-Publish` refuses otherwise. Forgejo's raw URLs send no such header, so the Steam images are served from `cdn.blax.at/blax-gaming/`, which does. `Source/Art/README.md` has the render and upload commands.
@ -84,9 +96,11 @@ The Workshop description is `docs/workshop-description.txt` (Steam BBCode); `-De
```powershell
.\Tests\run-tests.ps1
.\Tests\run-tests.ps1 -NoDlc
.\Tests\run-tests.ps1 -Dlc Ideology
```
`-Compat` also loads the installed mods Blax Slaves has compat code for (Hospitality, Harvest Organs Post Mortem, War Crimes Expanded 2, SYR More Slaves, Everybody Buys Slaves, Trade as Slave or Colonist); tests whose assumptions those mods change skip or relax only that assertion and say why. `-AllowWhileRunning` runs it next to an open RimWorld, with the test game at below-normal priority; a lock file keeps two runs from overlapping. Exit code 0 means all passed, 1 failures, 2 the run didn't finish (see `game.log` in the data folder).
`-Compat` also loads the installed mods Blax Slaves has compat code for (Hospitality, Harvest Organs Post Mortem, War Crimes Expanded 2, SYR More Slaves, Everybody Buys Slaves, Trade as Slave or Colonist); tests whose assumptions those mods change skip or relax only that assertion and say why. By default every installed DLC is loaded; `-NoDlc` runs core only and `-Dlc Royalty,Biotech` loads only the DLCs named. A test that needs a DLC skips with "needs Ideology" (or the DLC it needs) when it is off, and the DLC-off tests check that those features stay off. The results file has a `DLCS` line right after `BEGIN`, and each run also leaves a copy per DLC set (`BlaxSlavesTestResults.all.txt`, `.nodlc.txt`, `.dlc-<names>.txt`). `-AllowWhileRunning` runs it next to an open RimWorld, with the test game at below-normal priority; a lock file keeps two runs from overlapping. Exit code 0 means all passed, 1 failures, 2 the run didn't finish (see `game.log` in the data folder).
Tests are `public static void` methods marked `[BlaxTest("area: what", phase: 1)]`, using `T` for assertions and `Fixtures` for pawns, ticks and memories. Phase 2 runs after the save and reload; carry ThingIDs through `T.Carry`.

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using RimWorld;
using UnityEngine;
@ -72,30 +73,38 @@ namespace BlaxSlaves
slaveBuyFactor = Mathf.Clamp(slaveBuyFactor, 0.3f, 1f);
}
public void ResetGeneral()
// The settings each tab draws and its "Reset this tab" button restores (SettingsTests pins both to the tabs).
public static readonly string[] GeneralFields =
{
var d = new BlaxSlavesSettings();
returnRunaways = d.returnRunaways;
returnChance = d.returnChance;
returnDelayMinDays = d.returnDelayMinDays;
returnDelayMaxDays = d.returnDelayMaxDays;
suppressSlaveHarmMood = d.suppressSlaveHarmMood;
keepRelationGrief = d.keepRelationGrief;
showTimeInSlaveTab = d.showTimeInSlaveTab;
}
nameof(returnRunaways), nameof(returnChance), nameof(returnDelayMinDays), nameof(returnDelayMaxDays),
nameof(suppressSlaveHarmMood), nameof(keepRelationGrief), nameof(showTimeInSlaveTab),
};
public void ResetTrade()
public static readonly string[] TradeFields =
{
var d = new BlaxSlavesSettings();
traderBrandChance = d.traderBrandChance;
buyModeEnabled = d.buyModeEnabled;
defaultPurchaseMode = d.defaultPurchaseMode;
allTradersBuySlaves = d.allTradersBuySlaves;
visitorsBuySlaves = d.visitorsBuySlaves;
antiSlaveryTraders = d.antiSlaveryTraders;
slaveStockIgnoresColonySize = d.slaveStockIgnoresColonySize;
slaveSellFactor = d.slaveSellFactor;
slaveBuyFactor = d.slaveBuyFactor;
nameof(traderBrandChance), nameof(buyModeEnabled), nameof(defaultPurchaseMode), nameof(allTradersBuySlaves),
nameof(visitorsBuySlaves), nameof(antiSlaveryTraders), nameof(slaveStockIgnoresColonySize),
nameof(slaveSellFactor), nameof(slaveBuyFactor),
};
public void ResetGeneral() => Reset(GeneralFields);
public void ResetTrade() => Reset(TradeFields);
/// <summary>
/// Puts these settings back to their defaults, except the ones that need a missing DLC: the window draws
/// those greyed out and never changes them, so they keep their values for when the DLC is back.
/// </summary>
private void Reset(string[] fields)
{
var defaults = new BlaxSlavesSettings();
foreach (string name in fields)
{
if (BlaxSlavesMod.MissingDlc(name) != null)
continue;
FieldInfo field = typeof(BlaxSlavesSettings).GetField(name);
field.SetValue(this, field.GetValue(defaults));
}
}
}
@ -173,6 +182,165 @@ namespace BlaxSlaves
Widgets.EndScrollView();
}
// ---- DLC-dependent settings ---------------------------------------------------------------
public const string Ideology = "Ideology";
/// <summary>
/// Settings that only do something with a DLC: field name to the DLC it needs. Without that DLC the
/// settings window draws them greyed out with a "needs ..." note and leaves their values alone. Every
/// field missing here works with any DLC combination.
/// </summary>
public static readonly Dictionary<string, string> NeedsDlc = new Dictionary<string, string>
{
// Trade tab: buying as slave or colonist, refusing captives over the ideoligion, trader brands and
// the slave price factors all need slaves (vanilla prices captives at 100% without Ideology).
{ nameof(BlaxSlavesSettings.buyModeEnabled), Ideology },
{ nameof(BlaxSlavesSettings.defaultPurchaseMode), Ideology },
{ nameof(BlaxSlavesSettings.antiSlaveryTraders), Ideology },
{ nameof(BlaxSlavesSettings.traderBrandChance), Ideology },
{ nameof(BlaxSlavesSettings.slaveSellFactor), Ideology },
{ nameof(BlaxSlavesSettings.slaveBuyFactor), Ideology },
// General tab: runaways, the slave harm mood gate and time as a slave.
{ nameof(BlaxSlavesSettings.returnRunaways), Ideology },
{ nameof(BlaxSlavesSettings.returnChance), Ideology },
{ nameof(BlaxSlavesSettings.returnDelayMinDays), Ideology },
{ nameof(BlaxSlavesSettings.returnDelayMaxDays), Ideology },
{ nameof(BlaxSlavesSettings.suppressSlaveHarmMood), Ideology },
{ nameof(BlaxSlavesSettings.keepRelationGrief), Ideology },
{ nameof(BlaxSlavesSettings.showTimeInSlaveTab), Ideology },
};
/// <summary>Whether a DLC (by the names NeedsDlc uses) is active. Unknown names count as active.</summary>
public static bool DlcActive(string dlc)
{
switch (dlc)
{
case "Royalty": return ModsConfig.RoyaltyActive;
case Ideology: return ModsConfig.IdeologyActive;
case "Biotech": return ModsConfig.BiotechActive;
case "Anomaly": return ModsConfig.AnomalyActive;
case "Odyssey": return ModsConfig.OdysseyActive;
default: return true;
}
}
/// <summary>The DLC a setting needs and that is not active, or null when the setting works now.</summary>
public static string MissingDlc(string field) =>
field != null && NeedsDlc.TryGetValue(field, out string dlc) && !DlcActive(dlc) ? dlc : null;
/// <summary>The DLC every one of these settings is missing (the first one's), or null when any of them works now.</summary>
public static string MissingDlcForAll(IEnumerable<string> fields)
{
string missing = null;
foreach (string field in fields)
{
string dlc = MissingDlc(field);
if (dlc == null)
return null;
missing ??= dlc;
}
return missing;
}
/// <summary>"Label (needs Ideology)".</summary>
public static string WithDlcNote(string label, string dlc) => "BlaxSlaves_NeedsDlc".Translate(label, dlc);
// With the DLC active these draw exactly what Listing_Standard draws. Without it: the same row greyed
// out, with the note, taking no input. Fields go in by ref, so the tab methods still read every field
// directly (SettingsTests reads their IL to pin each tab's reset button to what it draws).
private static void Checkbox(Listing_Standard l, string label, ref bool value, string field, string tooltip)
{
string dlc = MissingDlc(field);
if (dlc == null)
{
l.CheckboxLabeled(label, ref value, tooltip);
return;
}
label = WithDlcNote(label, dlc);
Rect rect = l.GetRect(Text.CalcHeight(label, l.ColumnWidth));
if (!tooltip.NullOrEmpty())
TooltipHandler.TipRegion(rect, tooltip);
Color old = GUI.color;
GUI.color = ColoredText.SubtleGrayColor;
bool shown = value;
Widgets.CheckboxLabeled(rect, label, ref shown, disabled: true);
GUI.color = old;
l.Gap(l.verticalSpacing);
}
/// <summary>A radio group's heading; gets the note when the group's setting needs a missing DLC.</summary>
private static void Heading(Listing_Standard l, string label, string field)
{
string dlc = MissingDlc(field);
if (dlc == null)
{
l.Label(label);
return;
}
Grey(l, WithDlcNote(label, dlc), null);
}
/// <summary>True when the player picked this option; never while its setting needs a missing DLC.</summary>
private static bool Radio(Listing_Standard l, string label, bool active, string field)
{
if (MissingDlc(field) == null)
return l.RadioButton(label, active, 12f);
// RadioButtonLabeled still reports clicks when disabled, so they are dropped here.
l.RadioButton(label, active, 12f, null, null, disabled: true);
return false;
}
/// <summary>
/// A slider row under its label. Without the DLC only the label shows, greyed out with the note and the
/// current value, and the value comes back unchanged.
/// </summary>
private static float Slider(Listing_Standard l, string label, float value, float min, float max, string field, string tooltip = null)
{
string dlc = MissingDlc(field);
if (dlc != null)
{
Grey(l, WithDlcNote(label, dlc), tooltip);
return value;
}
if (tooltip == null)
l.Label(label);
else
l.Label(label, tooltip: tooltip);
return l.Slider(value, min, max);
}
/// <summary>
/// "Reset this tab". The reset itself skips settings that need a missing DLC; when every setting on the
/// tab needs one, the button is greyed out with the note and takes no click.
/// </summary>
private static bool ResetButton(Listing_Standard l, string[] fields)
{
string label = "BlaxSlaves_ResetTab".Translate();
string dlc = MissingDlcForAll(fields);
if (dlc == null)
return l.ButtonText(label);
Rect rect = l.GetRect(30f);
Color old = GUI.color;
GUI.color = ColoredText.SubtleGrayColor;
Widgets.ButtonText(rect, WithDlcNote(label, dlc), active: false);
GUI.color = old;
l.Gap(l.verticalSpacing);
return false;
}
private static void Grey(Listing_Standard l, string text, string tooltip)
{
Color old = GUI.color;
GUI.color = ColoredText.SubtleGrayColor;
if (tooltip == null)
l.Label(text);
else
l.Label(text, tooltip: tooltip);
GUI.color = old;
}
private static void DoTrade(Listing_Standard l)
{
BlaxSlavesSettings s = Settings;
@ -182,71 +350,77 @@ namespace BlaxSlaves
l.GapLine();
}
l.CheckboxLabeled("BlaxSlaves_SettingBuyMode".Translate(), ref s.buyModeEnabled, "BlaxSlaves_SettingBuyModeTip".Translate());
Checkbox(l, "BlaxSlaves_SettingBuyMode".Translate(), ref s.buyModeEnabled, nameof(BlaxSlavesSettings.buyModeEnabled), "BlaxSlaves_SettingBuyModeTip".Translate());
if (Compat.IsActive(Compat.TradeAsSlaveOrColonist))
l.Label("BlaxSlaves_SettingBuyModeStandsDown".Translate());
l.Label("BlaxSlaves_SettingPurchaseMode".Translate());
if (l.RadioButton("BlaxSlaves_SettingPurchaseVanilla".Translate(), s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseVanilla, 12f))
Heading(l, "BlaxSlaves_SettingPurchaseMode".Translate(), nameof(BlaxSlavesSettings.defaultPurchaseMode));
if (Radio(l, "BlaxSlaves_SettingPurchaseVanilla".Translate(), s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseVanilla, nameof(BlaxSlavesSettings.defaultPurchaseMode)))
s.defaultPurchaseMode = BlaxSlavesSettings.PurchaseVanilla;
if (l.RadioButton("BlaxSlaves_SettingPurchaseSlave".Translate(), s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseAlwaysSlave, 12f))
if (Radio(l, "BlaxSlaves_SettingPurchaseSlave".Translate(), s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseAlwaysSlave, nameof(BlaxSlavesSettings.defaultPurchaseMode)))
s.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysSlave;
if (l.RadioButton("BlaxSlaves_SettingPurchaseColonist".Translate(), s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseAlwaysColonist, 12f))
if (Radio(l, "BlaxSlaves_SettingPurchaseColonist".Translate(), s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseAlwaysColonist, nameof(BlaxSlavesSettings.defaultPurchaseMode)))
s.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysColonist;
l.GapLine();
TraderBuyers.SettingNotes buyerNotes = TraderBuyers.Notes; // cached, DoTrade runs every frame
l.CheckboxLabeled("BlaxSlaves_SettingAllTradersBuy".Translate(), ref s.allTradersBuySlaves, "BlaxSlaves_SettingAllTradersBuyTip".Translate());
Checkbox(l, "BlaxSlaves_SettingAllTradersBuy".Translate(), ref s.allTradersBuySlaves, nameof(BlaxSlavesSettings.allTradersBuySlaves), "BlaxSlaves_SettingAllTradersBuyTip".Translate());
if (buyerNotes.everybodyBuysTraders)
l.Label("BlaxSlaves_SettingAllTradersBuyEverybodyBuys".Translate());
l.CheckboxLabeled("BlaxSlaves_SettingVisitorsBuy".Translate(), ref s.visitorsBuySlaves, "BlaxSlaves_SettingVisitorsBuyTip".Translate());
Checkbox(l, "BlaxSlaves_SettingVisitorsBuy".Translate(), ref s.visitorsBuySlaves, nameof(BlaxSlavesSettings.visitorsBuySlaves), "BlaxSlaves_SettingVisitorsBuyTip".Translate());
if (buyerNotes.everybodyBuysVisitors)
l.Label("BlaxSlaves_SettingVisitorsBuyEverybodyBuys".Translate());
if (buyerNotes.hospitality)
l.Label("BlaxSlaves_SettingVisitorsBuyHospitality".Translate());
l.Label("BlaxSlaves_SettingAntiSlavery".Translate());
if (l.RadioButton("BlaxSlaves_SettingAntiSlaveryBuy".Translate(), s.antiSlaveryTraders == BlaxSlavesSettings.AntiSlaveryBuyAnyway, 12f))
Heading(l, "BlaxSlaves_SettingAntiSlavery".Translate(), nameof(BlaxSlavesSettings.antiSlaveryTraders));
if (Radio(l, "BlaxSlaves_SettingAntiSlaveryBuy".Translate(), s.antiSlaveryTraders == BlaxSlavesSettings.AntiSlaveryBuyAnyway, nameof(BlaxSlavesSettings.antiSlaveryTraders)))
s.antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryBuyAnyway;
if (l.RadioButton("BlaxSlaves_SettingAntiSlaveryRefuse".Translate(), s.antiSlaveryTraders == BlaxSlavesSettings.AntiSlaveryRefuse, 12f))
if (Radio(l, "BlaxSlaves_SettingAntiSlaveryRefuse".Translate(), s.antiSlaveryTraders == BlaxSlavesSettings.AntiSlaveryRefuse, nameof(BlaxSlavesSettings.antiSlaveryTraders)))
s.antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryRefuse;
l.GapLine();
l.CheckboxLabeled("BlaxSlaves_SettingStockAnySize".Translate(), ref s.slaveStockIgnoresColonySize, "BlaxSlaves_SettingStockAnySizeTip".Translate());
l.Label("BlaxSlaves_SettingTraderBrand".Translate(s.traderBrandChance.ToStringPercent()));
s.traderBrandChance = l.Slider(s.traderBrandChance, 0f, 1f);
Checkbox(l, "BlaxSlaves_SettingStockAnySize".Translate(), ref s.slaveStockIgnoresColonySize, nameof(BlaxSlavesSettings.slaveStockIgnoresColonySize), "BlaxSlaves_SettingStockAnySizeTip".Translate());
s.traderBrandChance = Slider(l, "BlaxSlaves_SettingTraderBrand".Translate(s.traderBrandChance.ToStringPercent()), s.traderBrandChance, 0f, 1f,
nameof(BlaxSlavesSettings.traderBrandChance));
l.GapLine();
l.Label("BlaxSlaves_SettingSellFactor".Translate(s.slaveSellFactor.ToStringPercent()), tooltip: "BlaxSlaves_SettingSellFactorTip".Translate());
s.slaveSellFactor = Mathf.Round(l.Slider(s.slaveSellFactor, 0.3f, 1f) * 20f) / 20f;
l.Label("BlaxSlaves_SettingBuyFactor".Translate(s.slaveBuyFactor.ToStringPercent()), tooltip: "BlaxSlaves_SettingBuyFactorTip".Translate());
s.slaveBuyFactor = Mathf.Round(l.Slider(s.slaveBuyFactor, 0.3f, 1f) * 20f) / 20f;
s.slaveSellFactor = Mathf.Round(Slider(l, "BlaxSlaves_SettingSellFactor".Translate(s.slaveSellFactor.ToStringPercent()), s.slaveSellFactor, 0.3f, 1f,
nameof(BlaxSlavesSettings.slaveSellFactor), "BlaxSlaves_SettingSellFactorTip".Translate()) * 20f) / 20f;
s.slaveBuyFactor = Mathf.Round(Slider(l, "BlaxSlaves_SettingBuyFactor".Translate(s.slaveBuyFactor.ToStringPercent()), s.slaveBuyFactor, 0.3f, 1f,
nameof(BlaxSlavesSettings.slaveBuyFactor), "BlaxSlaves_SettingBuyFactorTip".Translate()) * 20f) / 20f;
l.Gap();
if (l.ButtonText("BlaxSlaves_ResetTab".Translate()))
if (ResetButton(l, BlaxSlavesSettings.TradeFields))
s.ResetTrade();
}
private static void DoGeneral(Listing_Standard l)
{
BlaxSlavesSettings s = Settings;
l.CheckboxLabeled("BlaxSlaves_SettingReturn".Translate(), ref s.returnRunaways, "BlaxSlaves_SettingReturnTip".Translate());
l.Label("BlaxSlaves_SettingReturnChance".Translate(s.returnChance.ToStringPercent()));
s.returnChance = l.Slider(s.returnChance, 0f, 1f);
l.Label("BlaxSlaves_SettingReturnDelayMin".Translate(s.returnDelayMinDays));
s.returnDelayMinDays = Mathf.RoundToInt(l.Slider(s.returnDelayMinDays, 1f, 30f));
l.Label("BlaxSlaves_SettingReturnDelayMax".Translate(s.returnDelayMaxDays));
s.returnDelayMaxDays = Mathf.RoundToInt(l.Slider(s.returnDelayMaxDays, 1f, 60f));
if (!ModsConfig.IdeologyActive)
{
l.Label("BlaxSlaves_SettingGeneralNeedsIdeology".Translate());
l.GapLine();
}
Checkbox(l, "BlaxSlaves_SettingReturn".Translate(), ref s.returnRunaways, nameof(BlaxSlavesSettings.returnRunaways), "BlaxSlaves_SettingReturnTip".Translate());
s.returnChance = Slider(l, "BlaxSlaves_SettingReturnChance".Translate(s.returnChance.ToStringPercent()), s.returnChance, 0f, 1f,
nameof(BlaxSlavesSettings.returnChance));
s.returnDelayMinDays = Mathf.RoundToInt(Slider(l, "BlaxSlaves_SettingReturnDelayMin".Translate(s.returnDelayMinDays), s.returnDelayMinDays, 1f, 30f,
nameof(BlaxSlavesSettings.returnDelayMinDays)));
s.returnDelayMaxDays = Mathf.RoundToInt(Slider(l, "BlaxSlaves_SettingReturnDelayMax".Translate(s.returnDelayMaxDays), s.returnDelayMaxDays, 1f, 60f,
nameof(BlaxSlavesSettings.returnDelayMaxDays)));
if (s.returnDelayMaxDays < s.returnDelayMinDays)
s.returnDelayMaxDays = s.returnDelayMinDays;
l.GapLine();
l.CheckboxLabeled("BlaxSlaves_SettingMood".Translate(), ref s.suppressSlaveHarmMood, "BlaxSlaves_SettingMoodTip".Translate());
l.CheckboxLabeled("BlaxSlaves_SettingGrief".Translate(), ref s.keepRelationGrief, "BlaxSlaves_SettingGriefTip".Translate());
Checkbox(l, "BlaxSlaves_SettingMood".Translate(), ref s.suppressSlaveHarmMood, nameof(BlaxSlavesSettings.suppressSlaveHarmMood), "BlaxSlaves_SettingMoodTip".Translate());
Checkbox(l, "BlaxSlaves_SettingGrief".Translate(), ref s.keepRelationGrief, nameof(BlaxSlavesSettings.keepRelationGrief), "BlaxSlaves_SettingGriefTip".Translate());
l.GapLine();
l.CheckboxLabeled("BlaxSlaves_SettingTimeAsSlave".Translate(), ref s.showTimeInSlaveTab, "BlaxSlaves_SettingTimeAsSlaveTip".Translate());
Checkbox(l, "BlaxSlaves_SettingTimeAsSlave".Translate(), ref s.showTimeInSlaveTab, nameof(BlaxSlavesSettings.showTimeInSlaveTab), "BlaxSlaves_SettingTimeAsSlaveTip".Translate());
l.Gap();
if (l.ButtonText("BlaxSlaves_ResetTab".Translate()))
if (ResetButton(l, BlaxSlavesSettings.GeneralFields))
s.ResetGeneral();
}

View File

@ -113,23 +113,29 @@ namespace BlaxSlaves
}
}
/// <summary>"Branded" mood only while they're someone's slave; a freed pawn keeps the scar, not the shame.</summary>
/// <summary>
/// "Branded" mood only while they're someone's slave; a freed pawn keeps the scar, not the shame.
/// Off without Ideology, also for slaves left over from a save made with it.
/// </summary>
public class ThoughtWorker_Branded : ThoughtWorker_Hediff
{
protected override ThoughtState CurrentStateInternal(Pawn p) =>
p.IsSlave ? base.CurrentStateInternal(p) : ThoughtState.Inactive;
ModsConfig.IdeologyActive && p.IsSlave ? base.CurrentStateInternal(p) : ThoughtState.Inactive;
}
/// <summary>Branding surgery: colony slaves only. Never fails, marks them as the player's.</summary>
/// <summary>
/// Branding surgery: colony slaves only. Never fails, marks them as the player's. Never offered without
/// Ideology; the def stays loaded so a save with a queued brand bill still loads.
/// </summary>
public class Recipe_BrandSlave : Recipe_AddHediff
{
public override bool AvailableOnNow(Thing thing, BodyPartRecord part = null) =>
thing is Pawn pawn && pawn.IsSlaveOfColony && base.AvailableOnNow(thing, part);
ModsConfig.IdeologyActive && thing is Pawn pawn && pawn.IsSlaveOfColony && base.AvailableOnNow(thing, part);
// A bill queued before the slave got branded (bought back, handed over) must not stack a second
// brand on top; taking over someone else's brand is the rebrand surgery.
public override bool CompletableEver(Pawn surgeryTarget) =>
base.CompletableEver(surgeryTarget) && surgeryTarget.IsSlaveOfColony && !BrandUtility.IsBranded(surgeryTarget);
ModsConfig.IdeologyActive && base.CompletableEver(surgeryTarget) && surgeryTarget.IsSlaveOfColony && !BrandUtility.IsBranded(surgeryTarget);
public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
{
@ -148,12 +154,12 @@ namespace BlaxSlaves
}
}
/// <summary>Burns the colony's mark over another owner's brand.</summary>
/// <summary>Burns the colony's mark over another owner's brand. Never offered without Ideology.</summary>
public class Recipe_RebrandSlave : Recipe_Surgery
{
public override bool AvailableOnNow(Thing thing, BodyPartRecord part = null)
{
if (!(thing is Pawn pawn) || !pawn.IsSlaveOfColony)
if (!ModsConfig.IdeologyActive || !(thing is Pawn pawn) || !pawn.IsSlaveOfColony)
return false;
HediffComp_BrandOwner brand = BrandUtility.BrandOf(pawn);
return brand != null && brand.owner != Faction.OfPlayer
@ -162,7 +168,7 @@ namespace BlaxSlaves
}
public override bool CompletableEver(Pawn surgeryTarget) =>
base.CompletableEver(surgeryTarget) && surgeryTarget.IsSlaveOfColony
ModsConfig.IdeologyActive && base.CompletableEver(surgeryTarget) && surgeryTarget.IsSlaveOfColony
&& BrandUtility.BrandOf(surgeryTarget) is HediffComp_BrandOwner brand && brand.owner != Faction.OfPlayer;
public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
@ -189,6 +195,10 @@ namespace BlaxSlaves
{
BuyMode.ApplyDefaultPurchaseMode(__instance, trader);
// Brands mark slaves, which need Ideology. Without it vanilla makes new stock join as colonists, and
// Patch_BuyAsColonistWithoutIdeology buys any pawn still set to join as a slave as a colonist.
if (!ModsConfig.IdeologyActive)
return;
if (!(__instance is Pawn pawn) || pawn.Dead || pawn.RaceProps == null || !pawn.RaceProps.Humanlike)
return;
if (pawn.ageTracker == null || !pawn.ageTracker.Adult || BrandUtility.IsBranded(pawn))

View File

@ -394,4 +394,21 @@ namespace BlaxSlaves
public static void Postfix(Lord __result) => BuyMode.ApplyColonistDefaultUnderTradeLord(__result);
}
/// <summary>
/// Without Ideology, every pawn bought from a trader joins as a colonist. Vanilla rolls new stock that way,
/// but stock from a save made with Ideology can still be set to join as a slave (orbital traders and
/// settlements keep their stock in the save), and Pawn.PreTraded enslaves such a pawn without checking for
/// Ideology, while the trade window shows no join status to switch. Patched with any DLC set; the check runs
/// at purchase, so with Ideology nothing changes.
/// </summary>
[HarmonyPatch(typeof(Pawn), nameof(Pawn.PreTraded))]
public static class Patch_BuyAsColonistWithoutIdeology
{
public static void Prefix(Pawn __instance, TradeAction action)
{
if (action == TradeAction.PlayerBuys && !ModsConfig.IdeologyActive && BuyMode.WouldJoinAsSlave(__instance))
__instance.guest.joinStatus = JoinStatus.JoinAsColonist;
}
}
}

View File

@ -33,7 +33,14 @@ namespace BlaxSlaves
Scribe_References.Look(ref pawn, "pawn");
Scribe_References.Look(ref origin, "origin");
Scribe_References.Look(ref finder, "finder");
Scribe_Defs.Look(ref mode, "mode");
// Saved as the def name, the same XML Scribe_Defs writes. Slave interaction modes are Ideology defs,
// and Scribe_Defs logs an error for a name it can't find (a save made with Ideology, loaded without);
// here a missing mode just loads as null, which delivery treats as Suppress.
string modeName = mode?.defName ?? "null";
Scribe_Values.Look(ref modeName, "mode", "null");
if (Scribe.mode == LoadSaveMode.LoadingVars)
mode = modeName.NullOrEmpty() || modeName == "null" ? null
: DefDatabase<SlaveInteractionModeDef>.GetNamedSilentFail(BackCompatibility.BackCompatibleDefName(typeof(SlaveInteractionModeDef), modeName));
Scribe_References.Look(ref map, "map");
Scribe_Values.Look(ref dueTick, "dueTick");
Scribe_Values.Look(ref pinnedByUs, "pinnedByUs");
@ -60,9 +67,13 @@ namespace BlaxSlaves
Siblings.ClearQueue();
}
/// <summary>
/// Tracks an escaped branded slave. Without Ideology it does nothing and says nothing: a slave left
/// over from a save made with Ideology leaves the way vanilla lets them.
/// </summary>
public void Register(Pawn pawn, Faction origin, SlaveInteractionModeDef mode, Map map)
{
if (pawn == null || IsPending(pawn))
if (!ModsConfig.IdeologyActive || pawn == null || IsPending(pawn))
return;
BlaxSlavesSettings settings = BlaxSlavesMod.Settings;
Faction finder = pawn.Faction;
@ -79,7 +90,7 @@ namespace BlaxSlaves
if (finder == null || finder.IsPlayer || finder.defeated || finder.Hidden)
finder = Find.FactionManager.RandomNonHostileFaction(allowHidden: false, allowDefeated: false, allowNonHumanlike: false);
if (!settings.returnRunaways || finder == null || !ModsConfig.IdeologyActive || !Rand.Chance(settings.returnChance))
if (!settings.returnRunaways || finder == null || !Rand.Chance(settings.returnChance))
{
Messages.Message("BlaxSlaves_RunawayGoneMessage".Translate(pawn.Named("PAWN")), MessageTypeDefOf.NegativeEvent);
return;
@ -111,7 +122,9 @@ namespace BlaxSlaves
for (int i = records.Count - 1; i >= 0; i--)
{
RunawayRecord r = records[i];
if (r.pawn == null || r.pawn.Destroyed || r.pawn.Dead || r.pawn.Discarded)
// A record from a save made with Ideology, loaded without it: nobody brings slaves back,
// so let the pawn go now (pending and pin released) instead of at its due tick.
if (r.pawn == null || r.pawn.Destroyed || r.pawn.Dead || r.pawn.Discarded || !ModsConfig.IdeologyActive)
{
Drop(i);
continue;
@ -177,6 +190,9 @@ namespace BlaxSlaves
{
public static DeliveryResult TryDeliver(RunawayRecord r)
{
// Without Ideology there are no slaves to return: cancel before any letter.
if (!ModsConfig.IdeologyActive)
return DeliveryResult.Cancel;
Pawn pawn = r.pawn;
if (!pawn.IsWorldPawn())
{
@ -203,7 +219,7 @@ namespace BlaxSlaves
Faction deliverer = r.finder;
if (deliverer == null || !factions.Contains(deliverer) || deliverer.HostileTo(Faction.OfPlayer) || deliverer.defeated)
deliverer = holder != null && !holder.IsPlayer && !holder.Hidden ? holder : Find.FactionManager.RandomNonHostileFaction(allowNonHumanlike: false);
if (deliverer == null || !ModsConfig.IdeologyActive)
if (deliverer == null)
return DeliveryResult.Cancel;
Map map = r.map != null && Find.Maps.Contains(r.map) && r.map.IsPlayerHome ? r.map : Find.AnyPlayerHomeMap;
@ -278,7 +294,7 @@ namespace BlaxSlaves
{
__state = null;
Pawn pawn = __instance;
if (!pawn.IsSlaveOfColony || pawn.guest == null || pawn.guest.Released || pawn.teleporting || !pawn.Spawned)
if (!ModsConfig.IdeologyActive || !pawn.IsSlaveOfColony || pawn.guest == null || pawn.guest.Released || pawn.teleporting || !pawn.Spawned)
return;
if (pawn.IsCaravanMember() || pawn.IsQuestLodger()
|| ThingOwnerUtility.AnyParentIs<ActiveTransporterInfo>(pawn)
@ -312,7 +328,8 @@ namespace BlaxSlaves
public static void Prefix(Caravan __instance, Pawn member, out List<Pawn> __state)
{
__state = null;
if (__instance.Faction != Faction.OfPlayer)
// Without Ideology, slaves left over from an Ideology save stay with vanilla's handling.
if (!ModsConfig.IdeologyActive || __instance.Faction != Faction.OfPlayer)
return;
List<Pawn> pawns = __instance.PawnsListForReading;
for (int i = 0; i < pawns.Count; i++)

View File

@ -31,10 +31,11 @@ namespace BlaxSlaves
/// <summary>
/// Slaves, and branded pawns who aren't free members of the colony (runaways, prisoners, sold
/// slaves). A branded pawn who became a free colonist is mourned like anyone else.
/// slaves). A branded pawn who became a free colonist is mourned like anyone else. Nobody without
/// Ideology: slaves and brands left over from a save made with it are mourned as vanilla does.
/// </summary>
public static bool IsProtected(Pawn pawn) =>
pawn != null && pawn.RaceProps != null && pawn.RaceProps.Humanlike
ModsConfig.IdeologyActive && pawn != null && pawn.RaceProps != null && pawn.RaceProps.Humanlike
&& (pawn.IsSlave || (pawn.Faction != Faction.OfPlayer && BrandUtility.IsBranded(pawn)));
public static Frame Push(Pawn victim, bool forceProtected = false)

View File

@ -40,7 +40,8 @@ namespace BlaxSlaves
public override void GameComponentTick()
{
if (Find.TickManager.TicksGame % TimeAsSlave.CountInterval == 0)
// Without Ideology nothing counts, also not slaves left over from a save made with it. Saved counters stay.
if (Find.TickManager.TicksGame % TimeAsSlave.CountInterval == 0 && ModsConfig.IdeologyActive)
Count(TimeAsSlave.CountInterval);
}
@ -118,12 +119,15 @@ namespace BlaxSlaves
public static string RecordTooltip => "BlaxSlaves_TimeAsSlaveRecordDesc".Translate();
// The counter always counts; the setting only hides the line.
/// <summary>Whether the Records tab shows the row for this pawn: every pawn with Ideology, nobody without it.</summary>
public static bool ShowsRecordRow(Pawn pawn) => pawn != null && ModsConfig.IdeologyActive;
// The counter always counts (with Ideology); the setting only hides the line.
internal static readonly SlaveTabLine Line = new SlaveTabLine(
LineId,
Label,
tooltip: _ => "BlaxSlaves_TimeAsSlaveLineTip".Translate(),
visible: _ => BlaxSlavesMod.Settings == null || BlaxSlavesMod.Settings.showTimeInSlaveTab);
visible: _ => ModsConfig.IdeologyActive && (BlaxSlavesMod.Settings == null || BlaxSlavesMod.Settings.showTimeInSlaveTab));
}
/// <summary>
@ -131,7 +135,8 @@ namespace BlaxSlaves
/// laid out like vanilla's private DrawRecord (8 px indent, value in the right 45 percent, highlight and
/// tooltip on hover). DrawTimeRecords draws inside the card's scroll view and returns the column height,
/// which DrawRecordsCard turns into the scroll height, so the postfix draws right under the last row and
/// adds its own height to the result. Shown for every pawn, like vanilla's time records.
/// adds its own height to the result. Shown for every pawn, like vanilla's time records, but only with
/// Ideology: without it no pawn can be a slave, so the row would read 0 for everyone.
/// </summary>
[HarmonyPatch(typeof(RecordsCardUtility), "DrawTimeRecords")]
public static class Patch_RecordsCardTimeAsSlave
@ -141,7 +146,7 @@ namespace BlaxSlaves
public static void Postfix(Rect leftRect, Pawn pawn, ref float __result)
{
if (pawn == null)
if (!TimeAsSlave.ShowsRecordRow(pawn))
return;
try
{

View File

@ -10,6 +10,7 @@
<li>
<packageId>blax.slaves</packageId>
<displayName>Blax Slaves</displayName>
<steamWorkshopUrl>steam://url/CommunityFilePage/3847282171</steamWorkshopUrl>
</li>
</modDependencies>
<loadAfter>

View File

@ -193,6 +193,7 @@ namespace BlaxSlavesTests
[BlaxTest("brand: Branded mood while a slave, gone once emancipated")]
public static void BrandedThoughtFollowsSlaveStatus()
{
Fixtures.RequireIdeology();
ThoughtDef thought = BrandedThought;
T.Check(thought.Worker is ThoughtWorker_Branded, "BlaxSlaves_Branded worker is " + thought.Worker?.GetType().Name + ", not ThoughtWorker_Branded");
@ -228,7 +229,7 @@ namespace BlaxSlavesTests
[BlaxTest("brand: slave suppression falls slower with the brand")]
public static void BrandSlowsSuppressionFall()
{
if (!ModsConfig.IdeologyActive) T.Skip("Ideology inactive: no suppression");
if (!ModsConfig.IdeologyActive) T.Skip("needs Ideology (no suppression without it)");
StatDef stat = StatDefOf.SlaveSuppressionFallRate;
T.NotNull(stat, "StatDefOf.SlaveSuppressionFallRate");
@ -278,6 +279,44 @@ namespace BlaxSlavesTests
return drop;
}
[BlaxTest("brand: without Ideology neither surgery is offered and the Branded mood is off, also for slaves from an Ideology save")]
public static void OffWithoutIdeology()
{
RecipeDef brand = BrandRecipe, rebrand = RebrandRecipe;
T.NotNull(BrandedThought, "thought BlaxSlaves_Branded (stays loaded without Ideology, so saves with it load)");
Pawn slave = Fixtures.LeftoverSlave();
Pawn ours = Fixtures.LeftoverSlave();
BrandUtility.Brand(ours, Faction.OfPlayer);
Pawn foreign = Fixtures.LeftoverSlave();
Faction other = OtherFaction(foreign.SlaveFaction);
if (other != null)
BrandUtility.Brand(foreign, other);
else
T.Info("no second non-player faction; the rebrand case is checked without a foreign brand");
Pawn colonist = Fixtures.Colonist();
Pawn prisoner = Prisoner();
Fixtures.AsIfIdeologyOff(() =>
{
foreach (Pawn p in new[] { slave, colonist, prisoner })
{
T.Check(!Offered(brand, p), "brand surgery offered without Ideology for " + p.LabelShort);
T.Check(!((Recipe_Surgery)brand.Worker).CompletableEver(p), "a queued brand bill could complete without Ideology for " + p.LabelShort);
}
T.Check(!Offered(rebrand, foreign), "rebrand surgery offered without Ideology");
T.Check(!((Recipe_Surgery)rebrand.Worker).CompletableEver(foreign), "a queued rebrand bill could complete without Ideology");
T.Check(!BrandedThought.Worker.CurrentState(ours).Active, "Branded mood active without Ideology for a branded colony slave");
});
if (!ModsConfig.IdeologyActive)
return;
// Control: the same pawns with Ideology.
T.Check(Offered(brand, slave), "control: brand surgery not offered with Ideology for an unbranded colony slave");
if (other != null)
T.Check(Offered(rebrand, foreign), "control: rebrand surgery not offered with Ideology for " + other.Name + "'s brand");
T.Check(BrandedThought.Worker.CurrentState(ours).Active, "control: Branded mood inactive with Ideology for a branded colony slave");
}
// ---- owner name ------------------------------------------------------------------
[BlaxTest("brand: owner name in label and tooltip, cached name once the faction is gone")]
@ -601,6 +640,7 @@ namespace BlaxSlavesTests
private static Pawn CarriedPawn(string key)
{
Fixtures.RequireIdeology();
if (!T.Carry.TryGetValue(key, out string id))
T.Skip("phase-1 setup did not carry '" + key + "' (setup failed or skipped)");
Pawn pawn = Fixtures.FindPawnById(id);

View File

@ -40,6 +40,17 @@ namespace BlaxSlavesTests
string owners = info == null ? "none" : string.Join(", ", info.Prefixes.Select(p => p.owner).Distinct());
T.Info("DrawCaptiveTradeInfo prefix owners: " + owners);
if (!ModsConfig.IdeologyActive)
{
// No slaves, so neither patch goes in (their Prepare checks Ideology) and the feature is off.
T.Check(!ours, "Ideology is off, but Patch_BuyModeButton patched DrawCaptiveTradeInfo");
var lordPatches = Harmony.GetPatchInfo(AccessTools.Method(typeof(LordMaker), nameof(LordMaker.MakeNewLord)));
T.Check(lordPatches == null || !lordPatches.Postfixes.Any(p => p.PatchMethod?.DeclaringType == typeof(Patch_BuyModeTradeLord)),
"Ideology is off, but Patch_BuyModeTradeLord patched LordMaker.MakeNewLord");
T.Check(!BuyMode.Available && !BuyMode.Enabled, "BuyMode reports itself available without Ideology");
T.Info("Ideology off: buy-mode is not patched in");
return;
}
if (Compat.IsActive(Compat.TradeAsSlaveOrColonist))
{
T.Check(!ours, "Trade as Slave or Colonist is active, but Patch_BuyModeButton still patched DrawCaptiveTradeInfo");
@ -65,6 +76,34 @@ namespace BlaxSlavesTests
"no blax.slaves postfix from Patch_BuyModeTradeLord on LordMaker.MakeNewLord ('always colonist' for caravan chattel)");
}
[BlaxTest("buy-mode: without Ideology the switch is off and 'always slave' makes no slaves")]
public static void OffWithoutIdeology()
{
// Without Ideology the trade window shows no join status, so the default purchase mode must never set
// JoinAsSlave there (Patch_BuyAsColonistWithoutIdeology would only undo it at purchase).
Faction trading = AnyFaction();
if (trading == null) T.Skip("no visible non-player humanlike faction to trade as");
Pawn stock = StockPawn(JoinStatus.JoinAsColonist, trading);
Pawn other = StockPawn(JoinStatus.JoinAsColonist, trading);
Fixtures.Settings.buyModeEnabled = true;
Fixtures.Settings.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysSlave;
Fixtures.AsIfIdeologyOff(() =>
{
T.Check(!BuyMode.Available && !BuyMode.Enabled, "BuyMode reports itself available without Ideology");
stock.PostGeneratedForTrader(Def(CaravanSlaverDef), Fixtures.Map.Tile, trading);
T.Equal(JoinStatus.JoinAsColonist, stock.guest.joinStatus, "joinStatus of new stock under 'always slave' without Ideology");
T.Check(!BuyMode.Toggle(LooseTradeable(other)), "Toggle switched a stock pawn without Ideology");
T.Equal(JoinStatus.JoinAsColonist, other.guest.joinStatus, "joinStatus after a refused switch without Ideology");
});
if (ModsConfig.IdeologyActive && !BuyMode.StandsDown)
{
// Control: the same call with Ideology on does apply 'always slave'.
Pawn control = StockPawn(JoinStatus.JoinAsColonist, trading);
control.PostGeneratedForTrader(Def(CaravanSlaverDef), Fixtures.Map.Tile, trading);
T.Equal(JoinStatus.JoinAsSlave, control.guest.joinStatus, "control: joinStatus under 'always slave' with Ideology");
}
}
// ---- the switch in a real trade session ------------------------------------------
[BlaxTest("buy-mode: switching a slave ship pawn flips joinStatus, reprices it at 1/0.6 and updates the silver")]
@ -223,6 +262,38 @@ namespace BlaxSlavesTests
}
}
[BlaxTest("buy-mode: without Ideology a stock pawn still set to join as a slave (an Ideology save's stock) is bought as a colonist")]
public static void BuysAsColonistWithoutIdeology()
{
// Vanilla's Pawn.PreTraded enslaves a JoinAsSlave pawn without checking for Ideology, and ships and
// settlements keep their stock in the save, so stock rolled with Ideology can reach a game without it.
var info = Harmony.GetPatchInfo(AccessTools.DeclaredMethod(typeof(Pawn), nameof(Pawn.PreTraded)));
T.Check(info != null && info.Prefixes.Any(p => p.owner == HarmonyId && p.PatchMethod?.DeclaringType == typeof(Patch_BuyAsColonistWithoutIdeology)),
"no blax.slaves prefix from Patch_BuyAsColonistWithoutIdeology on Pawn.PreTraded");
var bought = new List<Pawn>();
try
{
WithSlaveShip(5107, (ship, stock) => InSession(ship, deal =>
{
if (stock.Count == 0) T.Skip("slave ship stock holds no humanlike pawn");
Pawn pawn = stock[0];
pawn.guest.joinStatus = JoinStatus.JoinAsSlave;
Tradeable tr = TradeableOf(deal, pawn);
tr.ForceToSource(1);
T.Equal(TradeAction.PlayerBuys, tr.ActionToDo, "trade action for the stock pawn moved to the colony");
bought.Add(pawn);
List<string> problems = Fixtures.LoggedProblems(() => Fixtures.AsIfIdeologyOff(() => tr.ResolveTrade()));
T.Check(problems.Count == 0, "buying without Ideology logged: " + string.Join(" | ", problems));
T.Check(!pawn.IsSlave, Who(pawn) + " bought without Ideology is a slave (faction " + (pawn.Faction?.Name ?? "none") + ")");
T.Equal(Faction.OfPlayer, pawn.Faction, Who(pawn) + " faction after buying without Ideology");
}));
}
finally
{
foreach (Pawn p in bought) DiscardBought(p);
}
}
[BlaxTest("buy-mode: switch off, a colony captive or a pawn-hire trader: nothing changes")]
public static void ToggleRefusedOutsideStock()
{
@ -386,7 +457,7 @@ namespace BlaxSlavesTests
if (!ModsConfig.BiotechActive)
{
T.Info("Biotech inactive, child case not checked");
T.Info("child case needs Biotech, not checked");
return;
}
Pawn child = null;
@ -596,6 +667,7 @@ namespace BlaxSlavesTests
[BlaxTest("buy-mode: a switched stock pawn keeps its joinStatus after save and reload", phase: 2)]
public static void ReloadKeepsSwitch()
{
Fixtures.RequireIdeology();
if (Compat.IsActive(Compat.TradeAsSlaveOrColonist))
T.Skip("Trade as Slave or Colonist is active, buy-mode stands down, so phase 1 set up no switched pawn");
T.Check(T.Carry.TryGetValue(CarryShip, out string shipId), "phase 1 setup did not run or failed");
@ -619,7 +691,7 @@ namespace BlaxSlavesTests
private static void RequireAvailable()
{
if (!ModsConfig.IdeologyActive) T.Skip("Ideology inactive, buy-mode is hidden");
if (!ModsConfig.IdeologyActive) T.Skip("needs Ideology (buy-mode is hidden without it)");
if (BuyMode.StandsDown) T.Skip("Trade as Slave or Colonist is active, buy-mode stands down");
}

View File

@ -48,13 +48,56 @@ namespace BlaxSlavesTests
return p;
}
/// <summary>
/// Spawns the pawn on a random open cell near the map's anchor. Vanilla's RandomClosewalkCellNear
/// falls back to its root when it finds nothing, so on a map whose center lies in rock the pawn
/// would stand inside the rock with no district: vanilla AI then throws (a prisoner's escape check
/// reads the district) and the mood gate scenes find no room around the victim.
/// </summary>
public static Pawn Spawn(Pawn p)
{
IntVec3 cell = CellFinder.RandomClosewalkCellNear(Map.Center, Map, 12);
GenSpawn.Spawn(p, cell, Map);
Map map = Map;
IntVec3 root = Anchor(map);
if (!CellFinder.TryRandomClosewalkCellNear(root, map, 12, out IntVec3 cell, c => IsOpen(c, map)))
cell = root;
GenSpawn.Spawn(p, cell, map);
return p;
}
private static Map anchorMap;
private static IntVec3 anchor = IntVec3.Invalid;
/// <summary>Standable, not fogged and inside a district: a cell vanilla AI and the scenes can work with.</summary>
public static bool IsOpen(IntVec3 c, Map map) =>
c.InBounds(map) && c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) != null;
/// <summary>The map center when it is open, else the open cell closest to it. Skips the test when the map has none.</summary>
private static IntVec3 Anchor(Map map)
{
IntVec3 center = map.Center;
if (IsOpen(center, map))
return center;
if (map == anchorMap && anchor.IsValid && IsOpen(anchor, map))
return anchor;
IntVec3 best = IntVec3.Invalid;
int bestDist = int.MaxValue;
foreach (IntVec3 c in map.AllCells)
{
int dist = (c - center).LengthHorizontalSquared;
if (dist < bestDist && IsOpen(c, map))
{
best = c;
bestDist = dist;
}
}
if (!best.IsValid)
T.Skip("setup: no standable, unfogged cell on the map to spawn test pawns on");
T.Info("map center " + center + " is not open (rock, fog or no district), test pawns spawn near " + best);
anchorMap = map;
anchor = best;
return best;
}
/// <summary>A spawned free colonist. pacifist = has the Kind trait; otherwise Kind is removed.</summary>
public static Pawn Colonist(bool pacifist = false)
{
@ -65,15 +108,111 @@ namespace BlaxSlavesTests
return Spawn(p);
}
/// <summary>A spawned slave of the colony, enslaved from origin (default: a friendly faction).</summary>
/// <summary>A spawned slave of the colony, enslaved from origin (default: a friendly faction). Skips the test without Ideology.</summary>
public static Pawn ColonySlave(Faction origin = null)
{
RequireIdeology();
Pawn p = Generate(PawnKindDefOf.Slave, origin ?? FriendlyFaction());
Spawn(p);
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
return p;
}
/// <summary>A spawned prisoner of the colony, from a hostile faction when there is one.</summary>
public static Pawn ColonyPrisoner(Faction from = null)
{
Pawn p = Spawn(Generate(PawnKindDefOf.Slave, from ?? HostileFaction() ?? FriendlyFaction()));
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner);
T.Check(p.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony");
return p;
}
/// <summary>
/// A spawned colony slave even without Ideology, as a save made with Ideology and loaded without it
/// leaves one: vanilla keeps the slave status, but there is no suppression and no interaction mode.
/// With Ideology it is a normal colony slave.
/// </summary>
public static Pawn LeftoverSlave()
{
if (ModsConfig.IdeologyActive)
return ColonySlave();
Pawn p = Spawn(Generate(PawnKindDefOf.Slave, FriendlyFaction()));
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
T.Check(p.IsSlaveOfColony, "setup: vanilla refused to make a colony slave without Ideology");
return p;
}
// ---- DLCs ------------------------------------------------------------------------
/// <summary>Skips the test without Ideology: slaves, brands and everything that acts on them need it.</summary>
public static void RequireIdeology()
{
if (!ModsConfig.IdeologyActive)
T.Skip("needs Ideology");
}
/// <summary>The active DLCs for the DLCS line of the results file, "none" for core only.</summary>
public static string ActiveDlcs()
{
var dlcs = new List<string>();
if (ModsConfig.RoyaltyActive) dlcs.Add("Royalty");
if (ModsConfig.IdeologyActive) dlcs.Add("Ideology");
if (ModsConfig.BiotechActive) dlcs.Add("Biotech");
if (ModsConfig.AnomalyActive) dlcs.Add("Anomaly");
if (ModsConfig.OdysseyActive) dlcs.Add("Odyssey");
return dlcs.Count == 0 ? "none" : string.Join(",", dlcs);
}
private static readonly FieldInfo IdeologyActiveField = typeof(ModsConfig).GetField("ideologyActive", BindingFlags.NonPublic | BindingFlags.Static);
/// <summary>
/// Runs a DLC-off check. Without Ideology it simply runs. With Ideology loaded, ModsConfig.IdeologyActive
/// reads false for the body only, so the same check also guards the mod's own Ideology gates in a
/// full run (a real -NoDlc run is still what proves the game loads and plays without it). Keep the body
/// to direct calls into Blax Slaves and plain reads: never tick the game or run vanilla systems inside.
/// </summary>
public static void AsIfIdeologyOff(System.Action body)
{
if (!ModsConfig.IdeologyActive)
{
body();
return;
}
if (IdeologyActiveField == null || IdeologyActiveField.FieldType != typeof(bool))
T.Skip("ModsConfig.ideologyActive not found (renamed in this game version?), so Ideology can't be switched off for this check; a -NoDlc run covers it");
IdeologyActiveField.SetValue(null, false);
try
{
T.Check(!ModsConfig.IdeologyActive, "setup: ModsConfig.IdeologyActive still true after switching ideologyActive off");
body();
}
finally
{
IdeologyActiveField.SetValue(null, true);
}
}
/// <summary>Errors and warnings the game logs while the body runs (any source), one line each.</summary>
public static List<string> LoggedProblems(System.Action body)
{
var found = new List<string>();
UnityEngine.Application.LogCallback handler = (text, stack, type) =>
{
if (type == UnityEngine.LogType.Error || type == UnityEngine.LogType.Exception || type == UnityEngine.LogType.Warning)
lock (found) found.Add(type + ": " + text);
};
UnityEngine.Application.logMessageReceivedThreaded += handler;
try
{
body();
}
finally
{
UnityEngine.Application.logMessageReceivedThreaded -= handler;
}
return found;
}
/// <summary>Exclude a pawn from the per-test cleanup (phase-1 setup for phase-2 checks).</summary>
public static Pawn Keep(Pawn p)
{

View File

@ -134,6 +134,7 @@ namespace BlaxSlavesTests
try { File.Delete(ResultPath); } catch { }
HookLog();
Line("BEGIN Blax Slaves in-game tests, RimWorld " + VersionControl.CurrentVersionStringWithRev);
Line("DLCS " + Fixtures.ActiveDlcs());
Fixtures.QuietStoryteller();
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
}

View File

@ -163,6 +163,7 @@ namespace BlaxSlavesTests
[BlaxTest("mood gate: executing a branded prisoner, not an unbranded one")]
public static void BrandedPrisoner()
{
Fixtures.RequireIdeology();
Faction hostile = Fixtures.HostileFaction();
if (hostile == null)
T.Skip("no hostile humanlike faction to take a prisoner from");
@ -200,9 +201,10 @@ namespace BlaxSlavesTests
[BlaxTest("mood gate: a slave's corpse in a gibbet cage")]
public static void GibbetCageCorpse()
{
Fixtures.RequireIdeology();
ThingDef cageDef = DefDatabase<ThingDef>.GetNamedSilentFail("GibbetCage");
if (cageDef == null)
T.Skip("no GibbetCage def (Ideology inactive?)");
T.Skip("no GibbetCage def although Ideology is active");
Pawn plain = Watcher();
Pawn pacifist = Watcher(pacifist: true);
if (plain.Ideo != null && plain.Ideo.IdeoApprovesOfSlavery())
@ -281,6 +283,51 @@ namespace BlaxSlavesTests
}, s => KillBy(s.victim, s["killer"]));
}
[BlaxTest("mood gate: without Ideology nobody is protected, branded prisoners and slaves from an Ideology save included")]
public static void NobodyProtectedWithoutIdeology()
{
Settings.suppressSlaveHarmMood = true;
Pawn prisoner = Fixtures.ColonyPrisoner();
BrandUtility.Brand(prisoner, Faction.OfPlayer);
Pawn slave = Fixtures.LeftoverSlave();
Fixtures.AsIfIdeologyOff(() =>
{
foreach (Pawn p in new[] { prisoner, slave })
{
string who = (p == slave ? "colony slave " : "branded prisoner ") + p.LabelShort;
T.Check(!SlaveHarm.IsProtected(p), who + " counts as protected without Ideology");
SlaveHarm.Frame frame = SlaveHarm.Push(p);
try
{
T.Check(!frame.protectedVictim, who + ": the harm frame is protected without Ideology");
}
finally
{
SlaveHarm.Pop(frame);
}
}
});
if (ModsConfig.IdeologyActive)
{
T.Check(SlaveHarm.IsProtected(prisoner) && SlaveHarm.IsProtected(slave), "control: with Ideology the branded prisoner and the slave are protected");
return;
}
// Core only: executing the branded prisoner is mourned as in vanilla.
Scene s = Run(() =>
{
var scene = new Scene(prisoner);
scene.Add("executioner", Watcher());
Befriend(scene.Add("friend", Watcher()), prisoner);
scene.Add("bystander", Watcher());
PlaceAround(scene);
return scene;
}, scene => ExecuteLikeWarden(scene.victim, scene["executioner"]), "executing a branded prisoner without Ideology");
T.Info(s.Report());
T.Check(s.Has("friend", ThoughtDefOf.PawnWithGoodOpinionDied),
"executing a branded prisoner without Ideology: friend expected " + ThoughtDefOf.PawnWithGoodOpinionDied.defName + ", got: " + s.Report());
}
[BlaxTest("mood gate: a pacifist observer still takes the bad memory")]
public static void PacifistKeepsMemory()
{
@ -360,6 +407,7 @@ namespace BlaxSlavesTests
[BlaxTest("mood gate: executing a slave loaded from the save", phase: 2)]
public static void ExecuteReloadedSlave()
{
Fixtures.RequireIdeology();
Pawn main = KeptSlave(KeptMainKey);
Pawn control = KeptSlave(KeptControlKey);
var victims = new Queue<Pawn>(new[] { main, control });
@ -425,9 +473,13 @@ namespace BlaxSlavesTests
if (!control.AnyBad)
T.Skip("vanilla gives no thought here in this setup: " + what + " gave no bad memories even with suppressSlaveHarmMood off. " + IdeoNote());
T.Check(main.AnyBad, what + ": expected bad memories with suppressSlaveHarmMood on (nothing to suppress here), got none. Control: " + control.Report());
var steady = new[] { ThoughtDefOf.WitnessedDeathNonAlly, ThoughtDefOf.WitnessedDeathAlly, ThoughtDefOf.PawnWithGoodOpinionDied };
// Seeing the death is steady for every observer. "My friend died" is steady only for the
// befriended "friend" role: the other observers are fresh pawns in each run, so their opinion
// of the victim, and with it that thought, is random.
var witnessed = new[] { ThoughtDefOf.WitnessedDeathNonAlly, ThoughtDefOf.WitnessedDeathAlly };
var befriended = witnessed.Concat(new[] { ThoughtDefOf.PawnWithGoodOpinionDied }).ToArray();
foreach (string role in control.Roles)
foreach (ThoughtDef def in steady)
foreach (ThoughtDef def in role == "friend" ? befriended : witnessed)
if (control.Has(role, def))
T.Check(main.Has(role, def), what + ": " + role + " got " + def.defName + " with suppressSlaveHarmMood off but not with it on. On: "
+ main.Report() + "; off: " + control.Report());

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using BlaxSlaves;
@ -276,6 +277,7 @@ namespace BlaxSlavesTests
[BlaxTest("runaways: pending runaway survives save and reload, then is returned", phase: 2)]
public static void PendingRunawaySurvivesReload()
{
Fixtures.RequireIdeology();
if (!T.Carry.TryGetValue(CarryPawn, out string id))
T.Skip("phase 1 stored no pending runaway; see 'runaways: set up a pending runaway for the reload check'");
Pawn pawn = Fixtures.FindPawnById(id);
@ -327,6 +329,162 @@ namespace BlaxSlavesTests
}
}
// ---- any DLC set --------------------------------------------------------------------
[BlaxTest("runaways: a saved record whose interaction mode is missing (save made with Ideology) loads quietly without a mode")]
public static void RecordWithMissingModeLoads()
{
// The mode is written as Scribe_Defs always wrote it, so old saves and new ones read the same.
if (ModsConfig.IdeologyActive)
{
string saved = SaveRecord(new RunawayRecord { mode = SlaveInteractionModeDefOf.NoInteraction, dueTick = 7 });
T.Check(saved.Contains("<mode>NoInteraction</mode>"), "a saved record does not write its mode as <mode>NoInteraction</mode>: " + saved);
}
// Suppress is an Ideology def: without Ideology this is a save made with it, loaded without it.
var cases = new[]
{
("Suppress", ModsConfig.IdeologyActive ? SlaveInteractionModeDefOf.Suppress : null),
("BlaxTestMissingMode", (SlaveInteractionModeDef)null),
("null", (SlaveInteractionModeDef)null),
};
foreach (var (name, expected) in cases)
{
RunawayRecord loaded = null;
List<string> logged = Fixtures.LoggedProblems(() => loaded = LoadRecord("<mode>" + name + "</mode><dueTick>12345</dueTick><pinnedByUs>True</pinnedByUs>"));
T.Check(logged.Count == 0, $"loading a record with mode '{name}' logged: " + string.Join(" | ", logged.Take(3)));
T.NotNull(loaded, $"record with mode '{name}'");
T.Equal(expected, loaded.mode, $"mode loaded from '{name}'");
T.Equal(12345, loaded.dueTick, $"dueTick of the record with mode '{name}'");
T.Check(loaded.pinnedByUs && loaded.pawn == null, $"record with mode '{name}': other fields loaded wrong");
}
}
[BlaxTest("runaways: without Ideology nothing is registered or delivered, and a record from an Ideology save is let go")]
public static void NothingWithoutIdeology()
{
GameComponent_BlaxRunaways comp = GameComponent_BlaxRunaways.Instance;
T.NotNull(comp, "GameComponent_BlaxRunaways.Instance");
Faction holder = Fixtures.HostileFaction();
bool hostile = holder != null;
holder = holder ?? Fixtures.FriendlyFaction();
if (holder == null)
T.Skip("no visible non-player humanlike faction to hold the runaway");
Pawn pawn = Fixtures.Generate(PawnKindDefOf.Slave, holder);
Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.KeepForever);
BrandUtility.Brand(pawn, Faction.OfPlayer);
var record = new RunawayRecord
{
pawn = pawn,
finder = holder,
map = Fixtures.Map,
// Far off, so the check only drops it because Ideology is off.
dueTick = Find.TickManager.TicksGame + 60 * GenDate.TicksPerDay,
pinnedByUs = Find.WorldPawns.ForcefullyKeptPawns.Add(pawn),
};
escapees.Add(pawn);
try
{
var since = new Snapshot();
DeliveryResult result = DeliveryResult.Delivered;
Fixtures.AsIfIdeologyOff(() =>
{
// A hostile holder would get the "Runaway kept" letter with Ideology.
result = RunawayDelivery.TryDeliver(record);
comp.Register(pawn, holder, null, Fixtures.Map);
T.Check(!GameComponent_BlaxRunaways.IsPending(pawn), "Register made a runaway pending without Ideology");
});
T.Equal(DeliveryResult.Cancel, result, "TryDeliver without Ideology (" + (hostile ? "hostile" : "friendly") + " holder)");
int letters = Find.LetterStack.LettersListForReading.Count(l => !since.letters.Contains(l));
int messages = Find.Archive.ArchivablesListForReading.OfType<Message>().Count(m => !since.messages.Contains(m));
T.Equal(0, letters, "letters sent by TryDeliver and Register without Ideology");
T.Equal(0, messages, "messages sent by TryDeliver and Register without Ideology");
// A record loaded from a save made with Ideology: the next check lets the pawn go.
Records().Add(record);
PendingSet().Add(pawn);
// The component checks every 250 ticks; line up so a direct call is a check tick.
while (Find.TickManager.TicksGame % CheckInterval != 0)
Fixtures.Tick(1);
if (ModsConfig.IdeologyActive)
T.Check(RecordOf(pawn) != null && GameComponent_BlaxRunaways.IsPending(pawn),
"control: with Ideology the record was dropped before its due tick");
// Only this record goes through the check: the one kept for the reload test must stay.
List<RunawayRecord> others = Records().Where(r => r != record).ToList();
Records().RemoveAll(r => r != record);
try
{
Fixtures.AsIfIdeologyOff(() => comp.GameComponentTick());
}
finally
{
Records().AddRange(others);
}
T.Check(RecordOf(pawn) == null, "the record is still there after a check without Ideology");
T.Check(!GameComponent_BlaxRunaways.IsPending(pawn), $"{pawn} is still pending after a check without Ideology");
if (record.pinnedByUs)
T.Check(!Find.WorldPawns.ForcefullyKeptPawns.Contains(pawn), $"{pawn} is still pinned in ForcefullyKeptPawns after the record was dropped");
}
finally
{
ForgetEscapees();
if (record.pinnedByUs)
Find.WorldPawns.ForcefullyKeptPawns.Remove(pawn);
}
}
/// <summary>Writes the record the way a save does and returns the file's text.</summary>
private static string SaveRecord(RunawayRecord record)
{
string path = Path.Combine(GenFilePaths.SaveDataFolderPath, "BlaxSlavesRunawayRecordTest.xml");
try
{
Scribe.saver.InitSaving(path, "root");
try
{
Scribe_Deep.Look(ref record, "record");
}
finally
{
Scribe.saver.FinalizeSaving();
}
return File.ReadAllText(path);
}
finally
{
if (Scribe.mode != LoadSaveMode.Inactive)
Scribe.ForceStop();
File.Delete(path);
}
}
/// <summary>Loads a record from these child nodes the way a save loads it (vars, cross-references, post-load).</summary>
private static RunawayRecord LoadRecord(string innerXml)
{
string path = Path.Combine(GenFilePaths.SaveDataFolderPath, "BlaxSlavesRunawayRecordTest.xml");
RunawayRecord record = null;
try
{
File.WriteAllText(path, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n<record>" + innerXml + "</record>\n</root>\n");
Scribe.loader.InitLoading(path);
try
{
Scribe_Deep.Look(ref record, "record");
}
finally
{
Scribe.loader.FinalizeLoading();
}
return record;
}
finally
{
if (Scribe.mode != LoadSaveMode.Inactive)
Scribe.ForceStop();
File.Delete(path);
}
}
// ---- escape helpers -----------------------------------------------------------------
private sealed class Escapee

View File

@ -48,7 +48,7 @@ namespace BlaxSlavesTests
private static readonly string[] SettingsUiKeys =
{
"BlaxSlaves_TabTrade", "BlaxSlaves_TabGeneral", "BlaxSlaves_TabCompat", "BlaxSlaves_ResetTab",
"BlaxSlaves_SettingNeedsIdeology", "BlaxSlaves_SettingBuyMode", "BlaxSlaves_SettingBuyModeTip",
"BlaxSlaves_SettingNeedsIdeology", "BlaxSlaves_SettingGeneralNeedsIdeology", "BlaxSlaves_NeedsDlc", "BlaxSlaves_SettingBuyMode", "BlaxSlaves_SettingBuyModeTip",
"BlaxSlaves_SettingBuyModeStandsDown", "BlaxSlaves_SettingPurchaseMode", "BlaxSlaves_SettingPurchaseVanilla",
"BlaxSlaves_SettingPurchaseSlave", "BlaxSlaves_SettingPurchaseColonist", "BlaxSlaves_SettingAllTradersBuy",
"BlaxSlaves_SettingAllTradersBuyTip", "BlaxSlaves_SettingVisitorsBuy", "BlaxSlaves_SettingVisitorsBuyTip",
@ -281,31 +281,87 @@ namespace BlaxSlavesTests
T.Check(unknown.Count == 0, "test lists fields BlaxSlavesSettings doesn't have (renamed?): " + string.Join(", ", unknown));
T.Check(unlisted.Count == 0, "new settings fields not assigned to a tab in this test (and maybe in no Reset method): " + string.Join(", ", unlisted));
T.Check(onBothTabs.Count == 0, "test assigns fields to both tabs, but each has one owner: " + string.Join(", ", onBothTabs));
T.Check(SameSet(BlaxSlavesSettings.TradeFields, TradeFields), "BlaxSlavesSettings.TradeFields is not this test's Trade tab: " + string.Join(", ", BlaxSlavesSettings.TradeFields));
T.Check(SameSet(BlaxSlavesSettings.GeneralFields, GeneralFields), "BlaxSlavesSettings.GeneralFields is not this test's General tab: " + string.Join(", ", BlaxSlavesSettings.GeneralFields));
// A setting that needs a missing DLC is kept by its tab's reset (ResetKeepsDlcSettings); with every DLC
// on, none is, so this checks the full reset.
string[] kept = AllNames().Where(n => BlaxSlavesMod.MissingDlc(n) != null).ToArray();
if (kept.Length > 0)
T.Info("reset keeps the settings that need a missing DLC: " + string.Join(", ", kept));
string[] tradeReset = TradeFields.Except(kept).ToArray();
string[] generalReset = GeneralFields.Except(kept).ToArray();
BlaxSlavesSettings defaults = new BlaxSlavesSettings();
BlaxSlavesSettings varied = Varied();
BlaxSlavesSettings trade = Copy(varied);
trade.ResetTrade();
List<string> notReset = Diff(defaults, trade, TradeFields);
List<string> wronglyReset = Diff(varied, trade, GeneralFields);
List<string> notReset = Diff(defaults, trade, tradeReset);
List<string> wronglyReset = Diff(varied, trade, GeneralFields.Concat(kept));
T.Check(notReset.Count == 0, "ResetTrade left Trade fields changed: " + string.Join("; ", notReset));
T.Check(wronglyReset.Count == 0, "ResetTrade touched General fields: " + string.Join("; ", wronglyReset));
T.Check(wronglyReset.Count == 0, "ResetTrade touched General fields or kept ones: " + string.Join("; ", wronglyReset));
BlaxSlavesSettings general = Copy(varied);
general.ResetGeneral();
notReset = Diff(defaults, general, GeneralFields);
wronglyReset = Diff(varied, general, TradeFields);
notReset = Diff(defaults, general, generalReset);
wronglyReset = Diff(varied, general, TradeFields.Concat(kept));
T.Check(notReset.Count == 0, "ResetGeneral left General fields changed: " + string.Join("; ", notReset));
T.Check(wronglyReset.Count == 0, "ResetGeneral touched Trade fields: " + string.Join("; ", wronglyReset));
T.Check(wronglyReset.Count == 0, "ResetGeneral touched Trade fields or kept ones: " + string.Join("; ", wronglyReset));
BlaxSlavesSettings both = Copy(varied);
both.ResetTrade();
both.ResetGeneral();
List<string> left = Diff(defaults, both, AllNames());
List<string> left = Diff(defaults, both, AllNames().Except(kept));
T.Check(left.Count == 0, "both reset buttons together leave fields changed: " + string.Join("; ", left));
}
[BlaxTest("settings: without Ideology the reset buttons keep the greyed-out settings, and General's is off")]
public static void ResetKeepsDlcSettings()
{
BlaxSlavesSettings defaults = new BlaxSlavesSettings();
BlaxSlavesSettings varied = Varied();
if (ModsConfig.IdeologyActive)
{
T.Equal((string)null, BlaxSlavesMod.MissingDlcForAll(BlaxSlavesSettings.GeneralFields), "General reset button's missing DLC with Ideology");
T.Equal((string)null, BlaxSlavesMod.MissingDlcForAll(BlaxSlavesSettings.TradeFields), "Trade reset button's missing DLC with Ideology");
}
Fixtures.AsIfIdeologyOff(() =>
{
var problems = new List<string>();
foreach (var (reset, fields, run) in new (string, string[], Action<BlaxSlavesSettings>)[]
{
("ResetTrade", TradeFields, x => x.ResetTrade()),
("ResetGeneral", GeneralFields, x => x.ResetGeneral()),
})
{
string[] greyed = fields.Where(f => BlaxSlavesMod.MissingDlc(f) != null).ToArray();
string[] working = fields.Except(greyed).ToArray();
BlaxSlavesSettings s = Copy(varied);
run(s);
problems.AddRange(Diff(varied, s, greyed).Select(d => reset + " changed a setting that needs Ideology, " + d));
problems.AddRange(Diff(defaults, s, working).Select(d => reset + " didn't restore " + d));
}
T.Check(problems.Count == 0, string.Join("; ", problems));
// Every General setting needs Ideology, so its button has nothing to reset; the Trade tab still has
// the captive buyer settings.
T.Equal(BlaxSlavesMod.Ideology, BlaxSlavesMod.MissingDlcForAll(BlaxSlavesSettings.GeneralFields), "General reset button's missing DLC without Ideology");
T.Equal((string)null, BlaxSlavesMod.MissingDlcForAll(BlaxSlavesSettings.TradeFields), "Trade reset button's missing DLC without Ideology");
});
// Both tabs draw their reset button through ResetButton, which greys it out; never a bare ButtonText.
MethodInfo resetButton = AccessTools.DeclaredMethod(typeof(BlaxSlavesMod), "ResetButton");
T.NotNull(resetButton, "BlaxSlavesMod.ResetButton (renamed?)");
foreach (string draw in new[] { "DoTrade", "DoGeneral" })
{
List<MethodBase> calls = PatchProcessor.ReadMethodBody(AccessTools.DeclaredMethod(typeof(BlaxSlavesMod), draw))
.Select(op => op.Value).OfType<MethodBase>().ToList();
T.Check(calls.Any(m => m.DeclaringType == typeof(BlaxSlavesMod) && m.Name == resetButton.Name), draw + " doesn't draw its reset button through ResetButton");
T.Check(!calls.Any(m => m.Name == nameof(Listing_Standard.ButtonText)), draw + " draws a ButtonText of its own, which stays live without the DLC");
}
}
[BlaxTest("settings: every setting a tab draws is one its own reset button restores")]
public static void ResetOwnsDrawnFields()
{
@ -323,6 +379,47 @@ namespace BlaxSlavesTests
T.Check(problems.Count == 0, string.Join("; ", problems));
}
[BlaxTest("settings: exactly the slave options need Ideology, and without it they say so instead of working")]
public static void DlcNeedsTable()
{
string[] needIdeology =
{
"buyModeEnabled", "defaultPurchaseMode", "antiSlaveryTraders", "traderBrandChance", "slaveSellFactor", "slaveBuyFactor",
"returnRunaways", "returnChance", "returnDelayMinDays", "returnDelayMaxDays", "suppressSlaveHarmMood", "keepRelationGrief", "showTimeInSlaveTab",
};
string[] anyDlc = { "allTradersBuySlaves", "visitorsBuySlaves", "slaveStockIgnoresColonySize" };
Dictionary<string, string> table = BlaxSlavesMod.NeedsDlc;
var problems = new List<string>();
problems.AddRange(table.Keys.Where(k => typeof(BlaxSlavesSettings).GetField(k) == null).Select(k => "NeedsDlc lists " + k + ", which BlaxSlavesSettings doesn't have"));
problems.AddRange(AllNames().Where(n => !needIdeology.Contains(n) && !anyDlc.Contains(n)).Select(n => "new setting " + n + " is not sorted into 'needs Ideology' or 'any DLC' in this test"));
foreach (string f in needIdeology)
if (!table.TryGetValue(f, out string dlc) || dlc != BlaxSlavesMod.Ideology)
problems.Add(f + " should need Ideology, NeedsDlc says " + (dlc ?? "nothing"));
foreach (string f in anyDlc)
if (table.ContainsKey(f))
problems.Add(f + " works without any DLC, but NeedsDlc says it needs " + table[f]);
// Every listed field is one a tab draws, so the greyed-out row is really shown.
var drawn = new HashSet<string>(SettingsFieldsUsedBy(AccessTools.DeclaredMethod(typeof(BlaxSlavesMod), "DoTrade"))
.Concat(SettingsFieldsUsedBy(AccessTools.DeclaredMethod(typeof(BlaxSlavesMod), "DoGeneral"))));
problems.AddRange(table.Keys.Where(k => !drawn.Contains(k)).Select(k => "NeedsDlc lists " + k + ", but no tab draws it"));
T.Check(problems.Count == 0, string.Join("; ", problems));
T.Equal(ModsConfig.RoyaltyActive, BlaxSlavesMod.DlcActive("Royalty"), "DlcActive(Royalty)");
T.Equal(ModsConfig.BiotechActive, BlaxSlavesMod.DlcActive("Biotech"), "DlcActive(Biotech)");
T.Equal(ModsConfig.IdeologyActive, BlaxSlavesMod.DlcActive(BlaxSlavesMod.Ideology), "DlcActive(Ideology)");
if (ModsConfig.IdeologyActive)
T.Check(needIdeology.All(f => BlaxSlavesMod.MissingDlc(f) == null), "with Ideology a setting still reports a missing DLC");
Fixtures.AsIfIdeologyOff(() =>
{
foreach (string f in needIdeology)
T.Equal(BlaxSlavesMod.Ideology, BlaxSlavesMod.MissingDlc(f), "missing DLC of " + f + " without Ideology");
foreach (string f in anyDlc)
T.Equal((string)null, BlaxSlavesMod.MissingDlc(f), "missing DLC of " + f + " without Ideology");
});
string note = BlaxSlavesMod.WithDlcNote("Some option", BlaxSlavesMod.Ideology);
T.Check(note.Contains("Some option") && note.Contains("Ideology") && !note.Contains("{"), "note for a setting that needs Ideology: " + note);
}
[BlaxTest("settings: the window's listing stays one column, so the scroll height counts every row after a tab switch")]
public static void SettingsListingOneColumn()
{
@ -440,7 +537,7 @@ namespace BlaxSlavesTests
if (!castes && !zones)
T.Equal((string)"BlaxSlaves_CompatNoSiblings".Translate(), described, "Describe() without siblings");
Pawn slave = Fixtures.ColonySlave();
Pawn slave = Fixtures.Colonist(); // any pawn: the calls must be no-ops for it
// Null arguments are no-ops whether or not the siblings are bound.
Siblings.CastesNotifyJoined(null, Siblings.ReasonRunawayReturned);
Siblings.CastesHintJoinReason(null, null);
@ -535,6 +632,8 @@ namespace BlaxSlavesTests
return s;
}
private static bool SameSet(IEnumerable<string> a, IEnumerable<string> b) => new HashSet<string>(a).SetEquals(b);
private static bool Same(object a, object b) =>
a is float fa && b is float fb ? Math.Abs(fa - fb) < 1e-4f : Equals(a, b);

View File

@ -295,6 +295,36 @@ namespace BlaxSlavesTests
});
}
[BlaxTest("slave prices: without Ideology the sliders change nothing, prisoners and stock keep vanilla's full price")]
public static void UntouchedWithoutIdeology()
{
// Vanilla sets its 60% slave and captive factors only with Ideology; the sliders replace those, so
// without it there is nothing to replace and prices stay at vanilla's 100%.
Fixtures.Settings.slaveSellFactor = 0.8f;
Fixtures.Settings.slaveBuyFactor = 0.5f;
WithTrade(4808, 10, c =>
{
Fixtures.AsIfIdeologyOff(() =>
{
foreach (Tradeable t in new[] { c.captiveT, c.stockT })
{
Invalidate(t);
CheckUntouched(t, Who((Pawn)t.AnyThing) + " without Ideology");
}
});
if (ModsConfig.IdeologyActive)
{
// Control: the same tradeables with Ideology get the slider factors.
Invalidate(c.captiveT);
Invalidate(c.stockT);
Sell(c.captiveT);
Buy(c.stockT);
T.Check(Near(F(c.captiveT, "priceFactorSell_HumanPawn"), 0.8f, 0.0001f), "control: captive sell factor with Ideology " + F(c.captiveT, "priceFactorSell_HumanPawn"));
T.Check(Near(F(c.stockT, "priceFactorBuy_JoinAs"), 0.5f, 0.0001f), "control: slave stock buy factor with Ideology " + F(c.stockT, "priceFactorBuy_JoinAs"));
}
}, captive: () => Fixtures.ColonyPrisoner(), needsIdeology: false);
}
// ---- setup -----------------------------------------------------------------------
private sealed class TradeCtx
@ -333,20 +363,20 @@ namespace BlaxSlavesTests
}
/// <summary>
/// A slave ship with fresh stock, a colony slave and a colonist negotiator with the given Social level,
/// A slave ship with fresh stock, a colony slave (or the given captive) and a colonist negotiator with the given Social level,
/// joined by TradeSession.SetupWith as the comms console does. Prices are invalidated before the body,
/// so the first GetPriceFor runs a real compute with the settings the test set. The session is closed
/// and the stock discarded afterwards.
/// </summary>
private static void WithTrade(int seed, int socialLevel, Action<TradeCtx> body)
private static void WithTrade(int seed, int socialLevel, Action<TradeCtx> body, Func<Pawn> captive = null, bool needsIdeology = true)
{
if (!ModsConfig.IdeologyActive)
T.Skip("Ideology inactive: vanilla has no slave price factors");
if (needsIdeology && !ModsConfig.IdeologyActive)
T.Skip("needs Ideology (vanilla has no slave price factors without it)");
TraderKindDef def = DefDatabase<TraderKindDef>.GetNamedSilentFail(ShipDefName);
T.NotNull(def, "TraderKindDef " + ShipDefName);
var c = new TradeCtx { negotiator = Negotiator(socialLevel), captive = Fixtures.ColonySlave() };
T.NotNull(c.captive.guest, "colony slave guest tracker");
var c = new TradeCtx { negotiator = Negotiator(socialLevel), captive = (captive ?? (() => Fixtures.ColonySlave()))() };
T.NotNull(c.captive.guest, "colony captive guest tracker");
HashSet<Pawn> worldBefore = new HashSet<Pawn>(Find.WorldPawns.AllPawnsAliveOrDead);
TradeShip ship = null;

View File

@ -16,12 +16,16 @@ namespace BlaxSlavesTests
.Where(info => info != null)
.SelectMany(info => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers).Concat(info.Transpilers))
.Count(p => p.owner == "blax.slaves");
T.Info("Harmony patches owned by blax.slaves: " + ours);
T.Info("Harmony patches owned by blax.slaves: " + ours + ", DLCs: " + Fixtures.ActiveDlcs());
T.Check(ours >= 17, "expected at least 17 patches from blax.slaves, found " + ours);
bool logged = Log.Messages.Any(m => m.text != null && m.text.Contains("[Blax Slaves]") && m.text.Contains("patches applied"));
T.Check(logged, "startup line '[Blax Slaves] N patches applied' not in the log");
var errors = Log.Messages.Where(m => m.type == LogMessageType.Error && m.text != null && m.text.Contains("Blax")).ToList();
T.Check(errors.Count == 0, "errors mentioning Blax at startup: " + string.Join(" | ", errors.Take(3).Select(e => e.text)));
// Any DLC combination loads quietly: no warning from the mod or about its defs either.
var warnings = Log.Messages.Where(m => m.type == LogMessageType.Warning && m.text != null
&& (m.text.Contains("Blax Slaves") || m.text.Contains("BlaxSlaves"))).ToList();
T.Check(warnings.Count == 0, "warnings mentioning Blax Slaves at startup: " + string.Join(" | ", warnings.Take(3).Select(e => e.text)));
}
[BlaxTest("startup: settings and defs loaded")]
@ -43,20 +47,61 @@ namespace BlaxSlavesTests
T.Check(slave.IsSlaveOfColony, "fixture pawn is not a slave of the colony");
}
/// <summary>
/// A pawn left inside rock has no district, and vanilla AI throws when it ticks (a prisoner's
/// escape check). Random quick-test maps sometimes have rock at the center, so a wall stands in for it.
/// </summary>
[BlaxTest("harness: test pawns spawn on an open cell, also when the map center is blocked")]
public static void SpawnOnOpenCell()
{
Map map = Fixtures.Map;
Pawn first = Fixtures.Colonist();
T.Check(Fixtures.IsOpen(first.Position, map), "test pawn " + first.LabelShort + " spawned on " + first.Position + ", which is not open (rock, fog or no district)");
IntVec3 center = map.Center;
if (!Fixtures.IsOpen(center, map))
{
T.Info("map center " + center + " is blocked on this map, so the spawn above already took the fallback");
return;
}
if (center.GetFirstPawn(map) != null || center.GetFirstItem(map) != null || center.GetEdifice(map) != null || center.Roofed(map))
T.Skip("setup: something stands on the map center " + center + " or it is roofed, so no wall can block it");
ThingDef wallDef = ThingDefOf.Wall;
Thing wall = GenSpawn.Spawn(ThingMaker.MakeThing(wallDef, GenStuff.DefaultStuffFor(wallDef)), center, map);
try
{
T.Check(!Fixtures.IsOpen(center, map), "setup: the map center " + center + " is still open with a wall on it");
Pawn p = Fixtures.Colonist();
T.Check(p.Position != center && Fixtures.IsOpen(p.Position, map),
"with the map center walled off, test pawn " + p.LabelShort + " spawned on " + p.Position + ", which is not open");
}
finally
{
if (!wall.Destroyed)
wall.Destroy(DestroyMode.Vanish);
}
}
[BlaxTest("harness: save and reload kept a marker pawn", phase: 2)]
public static void ReloadWorked()
{
T.Check(T.Carry.TryGetValue("marker", out string id), "phase 1 marker missing");
T.Check(T.Carry.TryGetValue("marker.kind", out string kind), "phase 1 marker kind missing");
Pawn p = Fixtures.FindPawnById(id);
T.NotNull(p, "marker pawn " + id + " after reload");
T.Check(p.IsSlaveOfColony, "marker pawn lost slave status over save and load");
if (kind == "slave")
T.Check(p.IsSlaveOfColony, "marker pawn lost slave status over save and load");
else
T.Check(p.IsPrisonerOfColony, "marker pawn lost prisoner status over save and load");
}
/// <summary>With Ideology a colony slave, without it a prisoner, so the save and reload check runs in every DLC set.</summary>
[BlaxTest("harness: set up marker pawn for reload")]
public static void MarkerSetup()
{
Pawn slave = Fixtures.Keep(Fixtures.ColonySlave());
T.Carry["marker"] = slave.ThingID;
Pawn marker = Fixtures.Keep(ModsConfig.IdeologyActive ? Fixtures.ColonySlave() : Fixtures.ColonyPrisoner());
T.Carry["marker"] = marker.ThingID;
T.Carry["marker.kind"] = ModsConfig.IdeologyActive ? "slave" : "prisoner";
}
}
}

View File

@ -77,6 +77,41 @@ namespace BlaxSlavesTests
T.Equal(TimeAsSlave.Ticks(slave).ToStringTicksToPeriod(), value, "Records tab value");
}
[BlaxTest("time as slave: without Ideology no Records row, no slave tab line and no counting, also for a slave from an Ideology save")]
public static void OffWithoutIdeology()
{
Pawn slave = Fixtures.LeftoverSlave();
Pawn colonist = Fixtures.Colonist();
Pawn prisoner = Prisoner();
Fixtures.Settings.showTimeInSlaveTab = true;
// Line up on a counting tick, so a direct call to the component counts (or would).
Fixtures.Tick(1);
while (Find.TickManager.TicksGame % Interval != 0)
Fixtures.Tick(1);
int before = TimeAsSlave.Ticks(slave);
Fixtures.AsIfIdeologyOff(() =>
{
foreach (Pawn p in new[] { slave, colonist, prisoner })
T.Check(!TimeAsSlave.ShowsRecordRow(p), "the Records tab shows the time-as-slave row for " + p.LabelShort + " without Ideology");
List<string> lines = SlaveTabLines.LabelsFor(slave);
T.Check(!lines.Contains(TimeAsSlave.Label(slave)), "the slave tab shows the time-as-slave line without Ideology: " + string.Join(", ", lines));
Counter.GameComponentTick();
});
T.Equal(before, TimeAsSlave.Ticks(slave), "counter of a colony slave after a counting tick without Ideology");
if (ModsConfig.IdeologyActive)
{
// Control: the same pawns and the same call with Ideology.
T.Check(TimeAsSlave.ShowsRecordRow(colonist) && TimeAsSlave.ShowsRecordRow(slave), "control: with Ideology the Records row is hidden");
T.Check(SlaveTabLines.LabelsFor(slave).Contains(TimeAsSlave.Label(slave)), "control: with Ideology the slave tab line is missing");
Counter.GameComponentTick();
T.Check(TimeAsSlave.Ticks(slave) > before, "control: with Ideology a counting tick did not count the slave");
return;
}
Fixtures.Tick(Interval * 2);
T.Equal(0, TimeAsSlave.Ticks(slave), "counter of a colony slave after two counting passes without Ideology");
}
// ---- counting ---------------------------------------------------------------------
[BlaxTest("time as slave: a colony slave's counter grows, a free colonist's and a prisoner's stay 0")]
@ -268,6 +303,7 @@ namespace BlaxSlavesTests
T.Carry.TryGetValue("timeAsSlave.pawn", out string id);
T.Carry.TryGetValue("timeAsSlave.ticks", out string carried);
bool parsed = int.TryParse(carried, out int before);
Fixtures.RequireIdeology();
if (id == null || !parsed)
T.Skip("phase-1 counting test did not carry its slave (failed or skipped)");
T.NotNull(Counter, "GameComponent_TimeAsSlave after reload");
@ -292,7 +328,7 @@ namespace BlaxSlavesTests
T.Info($"{destroyed} pawns destroyed by earlier phase-2 tests, cleared by Purge");
T.Carry.TryGetValue("timeAsSlave.destroyed", out string goneId);
if (goneId == null)
T.Skip("phase-1 purge test did not carry its destroyed slave (failed or skipped)");
T.Skip(ModsConfig.IdeologyActive ? "phase-1 purge test did not carry its destroyed slave (failed or skipped)" : "needs Ideology for the destroyed-slave check; the rest passed");
T.Check(!Counter.TrackedPawns.Any(p => p.ThingID == goneId), $"destroyed slave {goneId} is tracked again after the reload");
T.Info($"{Counter.TrackedPawns.Count} pawns tracked after the reload");
}

View File

@ -288,7 +288,7 @@ namespace BlaxSlavesTests
public static void RefuseModeGate()
{
if (!ModsConfig.IdeologyActive)
T.Skip("Ideology inactive: the gate only acts with Ideology");
T.Skip("needs Ideology (the gate only acts with it)");
Fixtures.Settings.antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryRefuse;
GateSetup(out Faction buyer, out Faction origin, out Pawn slave, out Pawn prisoner, out Pawn ownSlave, out StubTrader trader, out TradeShip ship);
Ideo against = IdeoThat(false, out string againstSource);
@ -329,7 +329,7 @@ namespace BlaxSlavesTests
public static void RefuseReasonPatched()
{
if (!ModsConfig.IdeologyActive)
T.Skip("Ideology inactive: TradeUI never calls DrawCaptiveTradeInfo, so the reason patch stays out");
T.Skip("needs Ideology (TradeUI never calls DrawCaptiveTradeInfo without it, so the reason patch stays out)");
MethodInfo target = AccessTools.Method(typeof(TransferableUIUtility), nameof(TransferableUIUtility.DrawCaptiveTradeInfo));
T.NotNull(target, "TransferableUIUtility.DrawCaptiveTradeInfo");
HarmonyLib.Patches info = Harmony.GetPatchInfo(target);
@ -353,7 +353,7 @@ namespace BlaxSlavesTests
public static void BuyAnywayModeGate()
{
if (!ModsConfig.IdeologyActive)
T.Skip("Ideology inactive: the gate only acts with Ideology");
T.Skip("needs Ideology (the gate only acts with it)");
Fixtures.Settings.antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryBuyAnyway;
GateSetup(out Faction buyer, out Faction origin, out Pawn slave, out Pawn prisoner, out Pawn ownSlave, out StubTrader trader, out TradeShip ship);
Ideo against = IdeoThat(false, out string againstSource);
@ -369,6 +369,40 @@ namespace BlaxSlavesTests
});
}
[BlaxTest("trader buyers: without Ideology refuse mode does nothing, every trader takes colony prisoners")]
public static void RefuseModeOffWithoutIdeology()
{
Fixtures.Settings.antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryRefuse;
List<Faction> factions = Find.FactionManager.AllFactionsVisible
.Where(f => !f.IsPlayer && !f.defeated && !f.temporary && f.def.humanlikeFaction)
.OrderBy(f => f.HostileTo(Faction.OfPlayer)).ThenBy(f => f.loadID).ToList();
if (factions.Count < 2)
T.Skip("need two visible humanlike factions, found " + factions.Count);
Faction buyer = factions[0], origin = factions[1];
var trader = new StubTrader(TraderDef("Base_Outlander_Standard"), buyer);
Pawn prisoner = Fixtures.ColonyPrisoner(origin);
Action check = () => Fixtures.AsIfIdeologyOff(() =>
{
T.Check(!TraderBuyers.TraderRefusesCaptive(prisoner, trader), "TraderRefusesCaptive is true without Ideology");
T.Check(WillTrade(trader, prisoner), buyer.Name + " refuses a colony prisoner in refuse mode without Ideology");
T.Check(!Explains(trader, prisoner), "the prisoner's row gets a refusal reason without Ideology");
});
if (!ModsConfig.IdeologyActive || buyer.ideos == null)
{
check();
return;
}
// With Ideology loaded the buyer is made to reject slavery, so only the Ideology gate can let it buy.
Ideo against = IdeoThat(false, out string againstSource);
T.Info($"buyer {buyer.Name}, prisoner from {origin.Name}; against: {againstSource}");
WithIdeos(buyer, against, () =>
{
T.Check(!WillTrade(trader, prisoner), "control: with Ideology an anti-slavery trader in refuse mode still takes the colony prisoner");
check();
});
}
// ---- slave stock ignores colony size ---------------------------------------------
[BlaxTest("slave stock: colony-size flag cleared on every slave generator, originals back when off, Slave_Empire kept")]

View File

@ -222,6 +222,7 @@ namespace BlaxSlavesTests
[BlaxTest("traders: brand chance 1 marks every slave in slaver caravan stock as the trading faction's")]
public static void CaravanStockBrandedForTrader()
{
Fixtures.RequireIdeology();
Fixtures.Settings.traderBrandChance = 1f;
var problems = new List<string>();
int exempt = 0, reused = 0;
@ -276,6 +277,7 @@ namespace BlaxSlavesTests
[BlaxTest("traders: brand chance 0 leaves every slave in slaver stock unbranded")]
public static void ChanceZeroBrandsNobody()
{
Fixtures.RequireIdeology();
Fixtures.Settings.traderBrandChance = 0f;
TraderKindDef caravanDef = TraderDef("Caravan_Outlander_PirateMerchant");
TraderKindDef shipDef = TraderDef("Orbital_PirateMerchant");
@ -324,6 +326,7 @@ namespace BlaxSlavesTests
[BlaxTest("traders: orbital slave ship has no trading faction, its slaves get a fallback owner")]
public static void SlaveShipFallbackOwner()
{
Fixtures.RequireIdeology();
Fixtures.Settings.traderBrandChance = 1f;
TraderKindDef def = TraderDef("Orbital_PirateMerchant");
var problems = new List<string>();
@ -370,6 +373,7 @@ namespace BlaxSlavesTests
[BlaxTest("traders: animals in slaver stock never get a brand")]
public static void AnimalsNeverBranded()
{
Fixtures.RequireIdeology();
Fixtures.Settings.traderBrandChance = 1f;
TraderKindDef caravanDef = TraderDef("Caravan_Outlander_PirateMerchant");
TraderKindDef shipDef = TraderDef("Orbital_PirateMerchant");
@ -413,7 +417,11 @@ namespace BlaxSlavesTests
// ---- brand rules on the hooked vanilla method ------------------------------------
[BlaxTest("traders: join-as-colonist, child and non-slave pawns in stock stay unbranded")]
public static void ExemptPawnsUnbranded() => Seeded(4700, ExemptPawnsUnbrandedBody);
public static void ExemptPawnsUnbranded()
{
Fixtures.RequireIdeology();
Seeded(4700, ExemptPawnsUnbrandedBody);
}
private static void ExemptPawnsUnbrandedBody()
{
@ -441,7 +449,7 @@ namespace BlaxSlavesTests
if (!ModsConfig.BiotechActive)
{
T.Info("Biotech inactive, child case not checked");
T.Info("child case needs Biotech, not checked");
return;
}
Pawn child = null;
@ -462,7 +470,11 @@ namespace BlaxSlavesTests
}
[BlaxTest("traders: a trader's custom slave kind counts as stock, a pawn-hire trader does not")]
public static void SlaveStockKindRules() => Seeded(4710, SlaveStockKindRulesBody);
public static void SlaveStockKindRules()
{
Fixtures.RequireIdeology();
Seeded(4710, SlaveStockKindRulesBody);
}
private static void SlaveStockKindRulesBody()
{
@ -486,7 +498,7 @@ namespace BlaxSlavesTests
TraderKindDef empireBase = DefDatabase<TraderKindDef>.GetNamedSilentFail("Base_Empire_Standard");
if (empireSlave == null || empireBase == null)
{
T.Info("Royalty's Slave_Empire or Base_Empire_Standard missing, custom slave kind not checked");
T.Info("custom slave kind case needs Royalty (Slave_Empire, Base_Empire_Standard), not checked");
return;
}
if (Compat.IsActive(Compat.SyrMoreSlaves))
@ -510,7 +522,11 @@ namespace BlaxSlavesTests
}
[BlaxTest("traders: an existing brand is kept, the player as trader falls back to another owner")]
public static void ExistingBrandAndPlayerFallback() => Seeded(4720, ExistingBrandAndPlayerFallbackBody);
public static void ExistingBrandAndPlayerFallback()
{
Fixtures.RequireIdeology();
Seeded(4720, ExistingBrandAndPlayerFallbackBody);
}
private static void ExistingBrandAndPlayerFallbackBody()
{
@ -546,6 +562,58 @@ namespace BlaxSlavesTests
T.Check(!o.temporary && o.def.humanlikeFaction && !o.Hidden, $"fallback owner {o.Name} ({o.def.defName}) is temporary, hidden or not humanlike");
}
[BlaxTest("traders: without Ideology slaver stock still comes, joins as colonists and nobody gets a brand")]
public static void NoBrandsWithoutIdeology() => Seeded(4730, NoBrandsWithoutIdeologyBody);
private static void NoBrandsWithoutIdeologyBody()
{
Fixtures.Settings.traderBrandChance = 1f;
TraderKindDef caravanDef = TraderDef("Caravan_Outlander_PirateMerchant");
Faction trading = AnyTradingFaction();
if (trading == null) T.Skip("no visible non-player humanlike faction to trade as");
// Another mod may still set JoinAsSlave without Ideology: the brand roll must not run then.
Pawn forced = Fixtures.Generate(PawnKindDefOf.Slave, trading);
forced.guest.joinStatus = JoinStatus.JoinAsSlave;
Fixtures.AsIfIdeologyOff(() => forced.PostGeneratedForTrader(caravanDef, Fixtures.Map.Tile, trading));
T.Check(!BrandUtility.IsBranded(forced), "an adult join-as-slave Slave pawn got a trader brand without Ideology at traderBrandChance = 1");
if (ModsConfig.IdeologyActive)
{
T.Info("Ideology active: freshly generated stock without it is checked in -NoDlc runs");
return;
}
// Core only: vanilla makes every stock pawn join as a colonist, and the slaver patches still add them.
TraderKindDef shipDef = TraderDef("Orbital_PirateMerchant");
var problems = new List<string>();
int humans = 0;
List<Thing> stock = null;
TradeShip ship = null;
HashSet<Pawn> worldBefore = WorldSnapshot();
try
{
stock = CaravanStock(caravanDef, CaravanFaction(caravanDef), 4731, out string how);
ship = SlaveShip(shipDef, 4732);
T.Info("caravan stock via " + how);
foreach (Pawn p in stock.Concat(Goods(ship)).OfType<Pawn>().Where(x => x.RaceProps.Humanlike && !worldBefore.Contains(x)))
{
humans++;
if (p.guest != null && p.guest.joinStatus != JoinStatus.JoinAsColonist)
problems.Add($"{Who(p)} joins as {p.guest.joinStatus} without Ideology");
if (BrandUtility.IsBranded(p))
problems.Add($"{Who(p)} got a brand without Ideology");
}
}
finally
{
DiscardAll(stock, worldBefore);
if (ship != null) RemoveShip(ship, worldBefore);
}
T.Info("fresh humanlike stock pawns: " + humans);
T.Check(humans > 0, "slaver caravan and slave ship stock held no fresh humanlike pawn without Ideology, so the slaver patches did nothing");
T.Check(problems.Count == 0, string.Join("; ", problems.Take(6)));
}
// ---- save and reload -------------------------------------------------------------
private const string CarryShip = "traders.ship";
@ -556,6 +624,7 @@ namespace BlaxSlavesTests
[BlaxTest("traders: set up a trader-branded slave on a passing slave ship for reload")]
public static void ReloadSetup()
{
Fixtures.RequireIdeology();
Fixtures.Settings.traderBrandChance = 1f;
TraderKindDef def = TraderDef("Orbital_PirateMerchant");
for (int seed = 4601; seed <= 4603; seed++)
@ -589,6 +658,7 @@ namespace BlaxSlavesTests
[BlaxTest("traders: a trader brand in slave ship stock survives save and reload", phase: 2)]
public static void ReloadKeepsTraderBrand()
{
Fixtures.RequireIdeology();
T.Check(T.Carry.TryGetValue(CarryShip, out string shipId), "phase 1 slave ship setup did not run or failed");
TradeShip ship = Find.Maps.SelectMany(m => m.passingShipManager.passingShips).OfType<TradeShip>()
.FirstOrDefault(s => s.GetUniqueLoadID() == shipId);

View File

@ -5,16 +5,23 @@ the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures, 2 the ru
.\Tests\run-tests.ps1 Harmony, the installed DLCs, Blax Slaves
.\Tests\run-tests.ps1 -Compat also the installed mods Blax Slaves has compat code for
.\Tests\run-tests.ps1 -NoDlc core only, no DLC (tests that need a DLC skip with "needs <DLC>")
.\Tests\run-tests.ps1 -Dlc Royalty,Biotech only these installed DLCs
.\Tests\run-tests.ps1 -NoBuild skip dotnet build
.\Tests\run-tests.ps1 -AllowWhileRunning run next to an open RimWorld (the test game runs at below-normal priority)
While it runs, the test mod is linked into the game's Mods folder; the link is removed afterwards.
Only one run at a time: a lock file in the data folder holds the running script's process id.
The results go to BlaxSlavesTestResults.txt in the data folder, and a copy per DLC set next to it:
BlaxSlavesTestResults.all.txt (every installed DLC), .nodlc.txt, or .dlc-<names>.txt. The Workshop
upload checks the "all" and "nodlc" copies.
#>
param(
[string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld',
[string]$DataDir = (Join-Path $env:TEMP 'BlaxSlavesTest'),
[switch]$Compat,
[switch]$NoDlc,
[string[]]$Dlc,
[switch]$NoBuild,
[switch]$AllowWhileRunning,
[int]$TimeoutSeconds = 900
@ -81,13 +88,24 @@ try {
[void]$list.Add($id)
}
# Every installed DLC is listed as known, so the game does not switch on a left-out DLC as "new".
$installedDlcs = @(@('Royalty', 'Ideology', 'Biotech', 'Anomaly', 'Odyssey') | Where-Object { Test-Path (Join-Path $RimWorldDir "Data\$_") })
if ($NoDlc) { $loadDlcs = @() }
elseif ($Dlc) {
$wanted = @($Dlc | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
foreach ($w in $wanted) { if ($installedDlcs -notcontains $w) { Write-Warning "DLC not installed or unknown, skipped: $w" } }
$loadDlcs = @($installedDlcs | Where-Object { $wanted -contains $_ })
}
else { $loadDlcs = @($installedDlcs) }
$mods = New-Object System.Collections.ArrayList
$expansions = @()
$expansions = @($installedDlcs | ForEach-Object { 'ludeon.rimworld.' + $_.ToLower() })
[void]$mods.Add('brrainz.harmony')
[void]$mods.Add('ludeon.rimworld')
foreach ($dlc in 'Royalty', 'Ideology', 'Biotech', 'Anomaly', 'Odyssey') {
if (Test-Path (Join-Path $RimWorldDir "Data\$dlc")) { $id = 'ludeon.rimworld.' + $dlc.ToLower(); [void]$mods.Add($id); $expansions += $id }
}
foreach ($d in $loadDlcs) { [void]$mods.Add('ludeon.rimworld.' + $d.ToLower()) }
Write-Host ("DLCs: " + $(if ($loadDlcs.Count) { $loadDlcs -join ', ' } else { 'none' }))
# Name of this DLC set for the per-set copy of the results.
$dlcSet = if ($loadDlcs.Count -eq 0) { 'nodlc' } elseif ($loadDlcs.Count -eq $installedDlcs.Count) { 'all' } else { 'dlc-' + ($loadDlcs -join '-').ToLower() }
$setResults = Join-Path $DataDir "BlaxSlavesTestResults.$dlcSet.txt"
if ($Compat) {
foreach ($id in 'unlimitedhugs.hugslib', 'orion.hospitality', 'smuffle.harvestorganspostmortem',
'mersid.wce2updated.core', 'mlie.syrmoreslaves', 'bblkepling.everybodybuysslaves',
@ -100,7 +118,7 @@ try {
# fresh test data folder: mod list only, no old save, results or mod settings
New-Item -ItemType Directory -Force (Join-Path $DataDir 'Config') | Out-Null
Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxSlavesTest.rws'), (Join-Path $DataDir 'BlaxSlavesTestResults.txt'), (Join-Path $DataDir 'Config\Mod_blax.slaves_*.xml')
Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxSlavesTest.rws'), (Join-Path $DataDir 'BlaxSlavesTestResults.txt'), $setResults, (Join-Path $DataDir 'Config\Mod_blax.slaves_*.xml')
$li = { param($ids) ($ids | ForEach-Object { " <li>$_</li>" }) -join "`n" }
$modsConfig = "<?xml version=`"1.0`" encoding=`"utf-8`"?>`n<ModsConfigData>`n <version>1.7</version>`n <activeMods>`n" +
(& $li $mods) + "`n </activeMods>`n <knownExpansions>`n" + (& $li $expansions) + "`n </knownExpansions>`n</ModsConfigData>`n"
@ -137,6 +155,7 @@ finally {
$results = Join-Path $DataDir 'BlaxSlavesTestResults.txt'
if (-not (Test-Path $results)) { Write-Host 'No results file: the suite never started. See game.log.'; exit 2 }
Copy-Item -LiteralPath $results -Destination $setResults -Force
$lines = Get-Content -LiteralPath $results -Encoding UTF8
$lines | ForEach-Object { Write-Host $_ }
if (-not ($lines -match '^END$')) { Write-Host 'The run did not finish.'; exit 2 }

View File

@ -15,7 +15,8 @@ description images as cross-origin requests and shows a broken image otherwise.
when one doesn't.
-Publish refuses unless the shipped files are committed and pushed, the top CHANGELOG.md entry matches
About.xml's modVersion, and the last Tests\run-tests.ps1 run passed after the last build.
About.xml's modVersion, and two Tests\run-tests.ps1 runs passed after the last build: one with every
installed DLC (BlaxSlavesTestResults.all.txt) and one with -NoDlc (BlaxSlavesTestResults.nodlc.txt).
-SkipChecks skips those checks. The in-game button (Tools\workshop-stage.ps1) still works as a fallback.
#>
param(
@ -23,7 +24,7 @@ param(
[switch]$Publish,
[string]$DescriptionFile,
[switch]$DescriptionOnly,
[string]$TestResults = (Join-Path $env:TEMP 'BlaxSlavesTest\BlaxSlavesTestResults.txt'),
[string]$TestResultsDir = (Join-Path $env:TEMP 'BlaxSlavesTest'),
[switch]$SkipChecks
)
$ErrorActionPreference = 'Stop'
@ -109,12 +110,14 @@ if ($Publish -and -not $SkipChecks) {
$dirty = & git -C $repo status --porcelain -- $ship
if ($dirty) { $problems += "Uncommitted changes in shipped files:`n$($dirty -join "`n")" }
$dll = Get-ChildItem (Join-Path $repo '1.7\Assemblies\*.dll') | Sort-Object LastWriteTime -Descending | Select-Object -First 1
if (-not (Test-Path $TestResults)) { $problems += "No test results at $TestResults. Run .\Tests\run-tests.ps1 first." }
else {
$res = Get-Item $TestResults
$lines = Get-Content -LiteralPath $TestResults -Encoding UTF8
if (-not ($lines -match '^END$') -or ($lines -match '^FAIL ')) { $problems += 'The last test run failed or did not finish.' }
elseif ($dll -and $res.LastWriteTime -lt $dll.LastWriteTime) { $problems += "The last test run ($($res.LastWriteTime)) is older than the build ($($dll.LastWriteTime)). Run .\Tests\run-tests.ps1 again." }
# The mod must work with and without DLCs: a passing run with every installed DLC and one with none.
foreach ($set in @(@{ name = 'all'; run = '.\Tests\run-tests.ps1' }, @{ name = 'nodlc'; run = '.\Tests\run-tests.ps1 -NoDlc' })) {
$file = Join-Path $TestResultsDir "BlaxSlavesTestResults.$($set.name).txt"
if (-not (Test-Path $file)) { $problems += "No test results at $file. Run $($set.run) first."; continue }
$res = Get-Item $file
$lines = Get-Content -LiteralPath $file -Encoding UTF8
if (-not ($lines -match '^END$') -or ($lines -match '^FAIL ')) { $problems += "The last $($set.run) run failed or did not finish." }
elseif ($dll -and $res.LastWriteTime -lt $dll.LastWriteTime) { $problems += "The last $($set.run) run ($($res.LastWriteTime)) is older than the build ($($dll.LastWriteTime)). Run it again." }
}
}
if ($problems) { throw ("Not publishing:`n- " + ($problems -join "`n- ")) }

View File

@ -1,17 +1,18 @@
[b]Slavery as an everyday part of the rim.[/b] Buy pawns as slaves or colonists, sell your captives to anyone, brand your slaves and get your runaways back.
✅ RimWorld 1.7 🔧 Needs [url=https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077]Harmony[/url] ⛓️ Slaves need Ideology ⚙️ Every feature can be switched off
✅ RimWorld 1.7 🔧 Needs [url=https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077]Harmony[/url] 🧩 Works with any DLC combination ⚙️ Every feature can be switched off
[img]https://cdn.blax.at/blax-gaming/slaves/trade.png[/img]
[list]
[*]🔁 [b]Buy as slave or colonist.[/b] In the trade window, click "Joins as slave / Joins as colonist" on a pawn the trader sells. The price updates (a slave costs 60% of a colonist, as in vanilla). A setting picks what new stock starts as: the vanilla roll, always slave or always colonist.
[*]🤝 [b]Every trader buys captives,[/b] visitor groups and the Empire's caravans included. Optionally, factions whose ideoligion rejects slavery refuse, except to ransom their own people.
[*]💰 [b]Price sliders[/b] for buying slaves and selling captives (vanilla 60% each), capped so buy-low-sell-high doesn't pay.
[*]🐪 [b]Slavers are common.[/b] Slaver caravans and orbital slave ships show up twice as often, bring more slaves and keep coming when your colony grows. Other caravans and orbital traders may have a slave or two, and settlements keep selling slaves however big your colony is.
[*]🔁 [b]Buy as slave or colonist.[/b] In the trade window, click "Joins as slave / Joins as colonist" on a pawn the trader sells. The price updates (a slave costs 60% of a colonist, as in vanilla). A setting picks what new stock starts as: the vanilla roll, always slave or always colonist. (needs Ideology)
[*]🤝 [b]Every trader buys captives,[/b] visitor groups and the Empire's caravans (Royalty) included. Optionally, factions whose ideoligion rejects slavery refuse, except to ransom their own people (needs Ideology).
[*]💰 [b]Price sliders[/b] for buying slaves and selling captives (vanilla 60% each), capped so buy-low-sell-high doesn't pay. (needs Ideology)
[*]🐪 [b]Slavers are common.[/b] Slaver caravans and orbital slave ships show up twice as often, bring more slaves and keep coming when your colony grows. Other caravans and orbital traders may have a slave or two, and settlements keep selling slaves however big your colony is. Without Ideology, the pawns you buy join as colonists.
[*]📡 [b]Request a slaver caravan[/b] from allied outlanders and tribes at the comms console. Vanilla hides slavers from that list.
[/list]
[img]https://cdn.blax.at/blax-gaming/slaves/slaves.png[/img]
Everything in this part needs Ideology.
[list]
[*]🔥 [b]Branding.[/b] A surgery burns your colony's mark into a slave. Branded slaves lose suppression 15% slower. Rebrand a slave who carries another owner's mark.
[*]🏷️ [b]Trader slaves come branded.[/b] About a third of the slaves you buy carry a previous owner's brand.
@ -20,7 +21,9 @@
[*]⏳ [b]Time as a slave[/b] in the Records tab and the slave tab.
[/list]
⚙️ Every feature has its own switch or number in the mod settings, sorted into Trade, General and Compat tabs.
⚙️ Every feature has its own switch or number in the mod settings, sorted into Trade, General and Compat tabs. Without Ideology, the settings that need it show greyed out with a note.
🧩 [b]Any DLC combination works,[/b] core only included. Without Ideology there are no slaves, so the slave features stay off, while every trader still buys your prisoners and slavers still come more often. A save made with Ideology also loads without it.
[img]https://cdn.blax.at/blax-gaming/slaves/replaces.png[/img]
Blax Slaves does what these mods do, so you can unsubscribe them. The Compat tab in the settings lists the ones you have active.