2026-11-28 18:33:08 +00:00
using System ;
using System.Collections.Generic ;
using System.Linq ;
using System.Reflection ;
using BlaxSlaves ;
using HarmonyLib ;
using RimWorld ;
using RimWorld.Planet ;
using UnityEngine ;
using Verse ;
namespace BlaxSlavesTests
{
/// <summary>
/// A modded generator under an unrelated name that buys humans, like a pawn-broker mod might add.
/// TraderBuyers has to see it through HandlesThingDef and add no buyer of its own next to it.
/// </summary>
public class StockGenerator_BlaxTestPawnBroker : StockGenerator
{
public override IEnumerable < Thing > GenerateThings ( PlanetTile forTile , Faction faction = null ) = > Enumerable . Empty < Thing > ( ) ;
public override bool HandlesThingDef ( ThingDef thingDef ) = > thingDef = = ThingDefOf . Human ;
}
/// <summary>
/// "Every trader buys slaves" and "Slave stock ignores colony size" (TraderBuyers.cs): the buyer
/// generator added to trader kinds, its removal when the settings go off, the Trade tab's notes about
/// Everybody Buys Slaves and Hospitality, the anti-slavery gate on Tradeable.TraderWillTrade with its reason
/// tooltip, and the cleared respectPopulationIntent flag.
/// Settings changes go through the handler TraderBuyers subscribed to BlaxSlavesMod.SettingsChanged,
/// the event closing the settings window raises (invoked directly, so no settings file is written).
/// Every test re-applies the restored settings at the end: the runner restores setting values, not
/// the defs they changed.
/// </summary>
public static class TraderBuyersTests
{
/// <summary>Vanilla and Royalty kinds with no humanlike generator, even after Patches/BlaxSlaves_Traders.xml.</summary>
private static readonly string [ ] VanillaGainers = { "Visitor_Outlander_Standard" , "Visitor_Neolithic_Standard" , "Empire_Caravan_TraderGeneral" } ;
private const int StockRounds = 20 ;
// ---- every trader buys slaves ----------------------------------------------------
[BlaxTest("trader buyers: every trader kind buys captives, our generator only where nothing else does")]
public static void EveryKindBuys ( )
{
Change ( s = > { s . allTradersBuySlaves = true ; s . visitorsBuySlaves = true ; } , ( ) = >
{
var problems = new List < string > ( ) ;
var gained = new List < string > ( ) ;
int checkedKinds = 0 ;
foreach ( TraderKindDef def in DefDatabase < TraderKindDef > . AllDefsListForReading )
{
List < StockGenerator_BlaxBuySlaves > ours = Ours ( def ) ;
if ( TraderBuyers . IsExcluded ( def ) | | def . stockGenerators = = null )
{
if ( ours . Count > 0 )
problems . Add ( def . defName + " is excluded but carries our generator" ) ;
continue ;
}
checkedKinds + + ;
if ( ! def . WillTrade ( ThingDefOf . Human ) )
problems . Add ( def . defName + " still won't trade humans" ) ;
int expected = TraderBuyers . OthersBuyHumans ( def ) ? 0 : 1 ;
if ( ours . Count ! = expected )
problems . Add ( $"{def.defName} carries {ours.Count} of our generators, expected {expected} ({Describe(def.stockGenerators)})" ) ;
foreach ( StockGenerator_BlaxBuySlaves g in ours )
if ( g . trader ! = def )
problems . Add ( $"{def.defName}: our generator's trader is {g.trader?.defName ?? " null "} (ResolveReferences missed it)" ) ;
if ( ours . Count > 0 )
gained . Add ( def . defName ) ;
}
T . Info ( $"checked {checkedKinds} trader kinds, our buyer on: {string.Join(" , ", gained)}" ) ;
if ( Compat . IsActive ( Compat . EverybodyBuysSlaves ) )
T . Info ( "Everybody Buys Slaves active: its buyers count as other generators, vanilla gainers not checked by name" ) ;
else
foreach ( string name in VanillaGainers )
{
TraderKindDef def = DefDatabase < TraderKindDef > . GetNamedSilentFail ( name ) ;
if ( def ! = null & & Ours ( def ) . Count ! = 1 )
problems . Add ( name + " has no humanlike generator in vanilla, so it should carry ours" ) ;
}
T . Check ( problems . Count = = 0 , string . Join ( "; " , problems . Take ( 8 ) ) ) ;
} ) ;
}
[BlaxTest("trader buyers: both settings off restore every generator list, on again re-adds without duplicates")]
public static void OffRestoresOnReadds ( )
{
Change ( s = > { s . allTradersBuySlaves = true ; s . visitorsBuySlaves = true ; } , ( ) = >
{
Dictionary < TraderKindDef , List < StockGenerator > > on = Snapshot ( ) ;
int ourCount = on . Values . Sum ( l = > l . Count ( g = > g is StockGenerator_BlaxBuySlaves ) ) ;
if ( ourCount = = 0 & & Compat . IsActive ( Compat . EverybodyBuysSlaves ) )
T . Skip ( "no trader kind carries our generator, nothing to restore (Everybody Buys Slaves gives every kind a buyer)" ) ;
T . Check ( ourCount > 0 , "no trader kind carries our generator with both settings on, so there is nothing to restore" ) ;
Set ( s = > { s . allTradersBuySlaves = false ; s . visitorsBuySlaves = false ; } ) ;
var problems = new List < string > ( ) ;
foreach ( var kv in on )
{
List < StockGenerator > original = kv . Value . Where ( g = > ! ( g is StockGenerator_BlaxBuySlaves ) ) . ToList ( ) ;
if ( ! SameRefs ( original , kv . Key . stockGenerators ) )
problems . Add ( $"{kv.Key.defName} has {Describe(kv.Key.stockGenerators)} with both settings off, expected the original {Describe(original)}" ) ;
}
T . Check ( problems . Count = = 0 , "off: " + string . Join ( "; " , problems . Take ( 6 ) ) ) ;
// Three raises in a row: the window can be closed any number of times.
for ( int i = 0 ; i < 3 ; i + + )
Set ( s = > { s . allTradersBuySlaves = true ; s . visitorsBuySlaves = true ; } ) ;
foreach ( var kv in on )
{
List < StockGenerator > now = kv . Key . stockGenerators ;
List < StockGenerator > theirsBefore = kv . Value . Where ( g = > ! ( g is StockGenerator_BlaxBuySlaves ) ) . ToList ( ) ;
List < StockGenerator > theirsNow = now . Where ( g = > ! ( g is StockGenerator_BlaxBuySlaves ) ) . ToList ( ) ;
int oursBefore = kv . Value . Count - theirsBefore . Count , oursNow = now . Count - theirsNow . Count ;
if ( ! SameRefs ( theirsBefore , theirsNow ) | | oursBefore ! = oursNow )
problems . Add ( $"{kv.Key.defName} has {Describe(now)} after turning back on, expected {Describe(kv.Value)}" ) ;
}
T . Check ( problems . Count = = 0 , "on again: " + string . Join ( "; " , problems . Take ( 6 ) ) ) ;
T . Info ( $"{ourCount} buyers removed and re-added, {on.Count} trader kinds compared" ) ;
} ) ;
}
[BlaxTest("trader buyers: visitor kinds follow the visitor setting, other kinds the every-trader setting")]
public static void VisitorsFollowOwnSetting ( )
{
HashSet < TraderKindDef > visitors = TraderBuyers . VisitorKinds ( ) ;
T . Check ( visitors . Count > 0 , "no FactionDef lists visitorTraderKinds" ) ;
List < TraderKindDef > bare = DefDatabase < TraderKindDef > . AllDefsListForReading
. Where ( d = > d . stockGenerators ! = null & & ! TraderBuyers . IsExcluded ( d ) & & ! TraderBuyers . OthersBuyHumans ( d ) ) . ToList ( ) ;
List < TraderKindDef > bareVisitors = bare . Where ( visitors . Contains ) . ToList ( ) ;
List < TraderKindDef > bareOthers = bare . Where ( d = > ! visitors . Contains ( d ) ) . ToList ( ) ;
if ( bareVisitors . Count = = 0 )
T . Skip ( "every visitor kind already buys humans through another generator (Everybody Buys Slaves?)" ) ;
T . Info ( $"visitor kinds without a humanlike generator: {string.Join(" , ", bareVisitors.Select(d => d.defName))}; others: {string.Join(" , ", bareOthers.Select(d => d.defName))}" ) ;
Change ( s = > { s . allTradersBuySlaves = true ; s . visitorsBuySlaves = false ; } , ( ) = >
{
var problems = new List < string > ( ) ;
foreach ( TraderKindDef d in bareVisitors )
if ( Ours ( d ) . Count ! = 0 | | d . WillTrade ( ThingDefOf . Human ) )
problems . Add ( d . defName + " buys humans with visitorsBuySlaves off" ) ;
foreach ( TraderKindDef d in bareOthers )
if ( Ours ( d ) . Count ! = 1 )
problems . Add ( $"{d.defName} carries {Ours(d).Count} of our generators with allTradersBuySlaves on, expected 1" ) ;
T . Check ( problems . Count = = 0 , "visitors off: " + string . Join ( "; " , problems . Take ( 6 ) ) ) ;
Set ( s = > { s . allTradersBuySlaves = false ; s . visitorsBuySlaves = true ; } ) ;
foreach ( TraderKindDef d in bareVisitors )
if ( Ours ( d ) . Count ! = 1 | | ! d . WillTrade ( ThingDefOf . Human ) )
problems . Add ( $"{d.defName} carries {Ours(d).Count} of our generators with visitorsBuySlaves on, expected 1" ) ;
foreach ( TraderKindDef d in bareOthers )
if ( Ours ( d ) . Count ! = 0 )
problems . Add ( d . defName + " keeps our generator with allTradersBuySlaves off" ) ;
T . Check ( problems . Count = = 0 , "every-trader off: " + string . Join ( "; " , problems . Take ( 6 ) ) ) ;
} ) ;
}
[BlaxTest("trader buyers: another humanlike generator, vanilla or modded under any name, means no second buyer")]
public static void OtherGeneratorsPreventDuplicates ( )
{
Change ( s = > { s . allTradersBuySlaves = true ; s . visitorsBuySlaves = true ; } , ( ) = >
{
TraderKindDef def = DefDatabase < TraderKindDef > . AllDefsListForReading . FirstOrDefault ( d = > Ours ( d ) . Count = = 1 ) ;
if ( def = = null )
T . Skip ( "no trader kind carries our generator, nothing to compete with" ) ;
// What Everybody Buys Slaves adds through XML, and a modded class whose name says nothing.
var ebs = new StockGenerator_BuySlaves ( ) ;
ebs . ResolveReferences ( def ) ;
var broker = new StockGenerator_BlaxTestPawnBroker ( ) ;
broker . ResolveReferences ( def ) ;
try
{
foreach ( StockGenerator other in new StockGenerator [ ] { ebs , broker } )
{
string what = other . GetType ( ) . Name ;
def . stockGenerators . Add ( other ) ;
RaiseSettingsChanged ( ) ;
T . Equal ( 0 , Ours ( def ) . Count , $"our generators on {def.defName} next to a {what}" ) ;
T . Check ( def . WillTrade ( ThingDefOf . Human ) , $"{def.defName} stopped trading humans with a {what} in place of ours" ) ;
def . stockGenerators . Remove ( other ) ;
RaiseSettingsChanged ( ) ;
T . Equal ( 1 , Ours ( def ) . Count , $"our generators on {def.defName} once the {what} is gone" ) ;
}
T . Info ( "checked on " + def . defName ) ;
}
finally
{
def . stockGenerators . Remove ( ebs ) ;
def . stockGenerators . Remove ( broker ) ;
}
} ) ;
}
[BlaxTest("trader buyers: Hospitality's guest kind never gets a buyer")]
public static void HospitalityGuestSkipped ( )
{
var fakeGuest = new TraderKindDef { defName = TraderBuyers . HospitalityGuestKind } ;
T . Check ( TraderBuyers . IsExcluded ( fakeGuest ) , "a TraderKindDef named Guest is not excluded" ) ;
T . Check ( ! TraderBuyers . WantsOurBuyer ( fakeGuest , Fixtures . Settings , new HashSet < TraderKindDef > ( ) ) , "Apply would give a Guest kind with no generators our buyer" ) ;
T . Check ( ! TraderBuyers . IsExcluded ( TraderDef ( "Visitor_Outlander_Standard" ) ) , "Visitor_Outlander_Standard counts as excluded" ) ;
TraderKindDef guest = DefDatabase < TraderKindDef > . GetNamedSilentFail ( TraderBuyers . HospitalityGuestKind ) ;
if ( guest = = null )
{
T . Info ( "Hospitality not loaded; checked the exclusion rule only" ) ;
return ;
}
Change ( s = > { s . allTradersBuySlaves = true ; s . visitorsBuySlaves = true ; } , ( ) = >
T . Equal ( 0 , Ours ( guest ) . Count , "our generators on Hospitality's Guest kind" ) ) ;
}
// ---- settings-window notes -------------------------------------------------------
[BlaxTest("trader buyers: Trade tab notes follow Everybody Buys Slaves' buyers per group of kinds, and Hospitality")]
public static void SettingNotesFromDefs ( )
{
List < string > missing = new [ ]
{
"BlaxSlaves_SettingAllTradersBuyEverybodyBuys" , "BlaxSlaves_SettingVisitorsBuyEverybodyBuys" ,
"BlaxSlaves_SettingVisitorsBuyHospitality" , "BlaxSlaves_CompatNoteEverybodyBuys" ,
} . Where ( k = > ! k . CanTranslate ( ) ) . ToList ( ) ;
T . Check ( missing . Count = = 0 , "Trade tab note strings missing from Keyed: " + string . Join ( ", " , missing ) ) ;
// Only a generator of exactly StockGenerator_BuySlaves counts: not ours, not the slavers' stock generator.
T . Check ( TraderBuyers . HasPlainBuyer ( FakeKind ( new StockGenerator_BuySlaves ( ) ) ) , "a plain StockGenerator_BuySlaves doesn't count as Everybody Buys Slaves' buyer" ) ;
T . Check ( ! TraderBuyers . HasPlainBuyer ( FakeKind ( new StockGenerator_BlaxBuySlaves ( ) ) ) , "our own StockGenerator_BlaxBuySlaves counts as Everybody Buys Slaves' buyer" ) ;
T . Check ( ! TraderBuyers . HasPlainBuyer ( FakeKind ( new StockGenerator_Slaves ( ) ) ) , "a slaver's StockGenerator_Slaves counts as Everybody Buys Slaves' buyer" ) ;
// The cached notes match a fresh walk for the mods actually loaded, and Apply clears the cache.
bool ebs = Compat . IsActive ( Compat . EverybodyBuysSlaves ) , hospitality = Compat . IsActive ( TraderBuyers . HospitalityPackageId ) ;
TraderBuyers . Apply ( ) ;
TraderBuyers . SettingNotes cached = TraderBuyers . Notes , fresh = TraderBuyers . FindNotes ( ebs , hospitality ) ;
T . Info ( $"Everybody Buys Slaves {(ebs ? " active " : " inactive ")}, Hospitality {(hospitality ? " active " : " inactive ")}; notes: {Describe(cached)}" ) ;
T . Check ( Same ( cached , fresh ) , $"cached notes {Describe(cached)} differ from the defs {Describe(fresh)}" ) ;
T . Equal ( hospitality , cached . hospitality , "Hospitality note shown" ) ;
if ( ebs )
T . Check ( cached . everybodyBuysTraders , "Everybody Buys Slaves is active but no non-visitor kind carries its StockGenerator_BuySlaves, so the 'every trader' note is missing" ) ;
TraderBuyers . SettingNotes none = TraderBuyers . FindNotes ( false , false ) ;
T . Check ( ! none . everybodyBuysTraders & & ! none . everybodyBuysVisitors & & ! none . hospitality , "notes without Everybody Buys Slaves or Hospitality: " + Describe ( none ) ) ;
T . Check ( TraderBuyers . FindNotes ( false , true ) . hospitality , "no Hospitality note with Hospitality active" ) ;
// A plain buyer on a visitor kind sets only the visitors note, one on another kind only the traders note.
HashSet < TraderKindDef > visitors = TraderBuyers . VisitorKinds ( ) ;
List < TraderKindDef > clean = DefDatabase < TraderKindDef > . AllDefsListForReading
. Where ( d = > d . stockGenerators ! = null & & ! TraderBuyers . IsExcluded ( d ) & & ! TraderBuyers . HasPlainBuyer ( d ) ) . ToList ( ) ;
TraderKindDef visitor = clean . FirstOrDefault ( visitors . Contains ) ;
TraderKindDef other = clean . FirstOrDefault ( d = > ! visitors . Contains ( d ) ) ;
if ( visitor = = null | | other = = null )
{
T . Info ( "every visitor or every other kind already carries a plain StockGenerator_BuySlaves; per-group check skipped" ) ;
return ;
}
TraderBuyers . SettingNotes baseline = TraderBuyers . FindNotes ( true , false ) ;
T . Info ( $"as if Everybody Buys Slaves were active, without injected buyers: {Describe(baseline)}; injecting on {visitor.defName} and {other.defName}" ) ;
T . Check ( ! baseline . everybodyBuysVisitors | | ebs , "a visitor kind carries a plain StockGenerator_BuySlaves without Everybody Buys Slaves" ) ;
foreach ( TraderKindDef def in new [ ] { visitor , other } )
{
var plain = new StockGenerator_BuySlaves ( ) ;
plain . ResolveReferences ( def ) ;
// No Apply while it sits there: Apply would take our buyer off this kind.
def . stockGenerators . Add ( plain ) ;
try
{
TraderBuyers . SettingNotes n = TraderBuyers . FindNotes ( true , false ) ;
bool isVisitor = def = = visitor ;
T . Check ( isVisitor ? n . everybodyBuysVisitors : n . everybodyBuysTraders ,
$"a plain buyer on {def.defName} doesn't set the {(isVisitor ? " visitors " : " every trader ")} note: {Describe(n)}" ) ;
T . Equal ( isVisitor ? baseline . everybodyBuysTraders : baseline . everybodyBuysVisitors ,
isVisitor ? n . everybodyBuysTraders : n . everybodyBuysVisitors ,
$"the {(isVisitor ? " every trader " : " visitors ")} note with a plain buyer only on {def.defName}" ) ;
}
finally
{
def . stockGenerators . Remove ( plain ) ;
}
}
T . Check ( Same ( baseline , TraderBuyers . FindNotes ( true , false ) ) , "notes didn't return to the baseline once the injected buyers were gone" ) ;
}
// ---- anti-slavery traders --------------------------------------------------------
[BlaxTest("trader buyers: refuse mode, an anti-slavery faction turns down colony captives but buys back its own")]
public static void RefuseModeGate ( )
{
if ( ! ModsConfig . IdeologyActive )
2026-11-29 16:07:37 +00:00
T . Skip ( "needs Ideology (the gate only acts with it)" ) ;
2026-11-28 18:33:08 +00:00
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 ) ;
Ideo pro = IdeoThat ( true , out string proSource ) ;
T . Info ( $"buyer {buyer.Name}, captives from {origin.Name}; against: {againstSource}; pro: {proSource}" ) ;
T . Check ( "BlaxSlaves_TraderRefusesCaptive" . CanTranslate ( ) , "Keyed string BlaxSlaves_TraderRefusesCaptive (the refusal reason) is missing" ) ;
WithIdeos ( buyer , against , ( ) = >
{
T . Check ( TraderBuyers . RejectsSlavery ( buyer ) , buyer . Name + " with an anti-slavery ideoligion doesn't count as rejecting slavery" ) ;
T . Check ( ! WillTrade ( trader , slave ) , "an anti-slavery trader still takes a colony slave from " + origin . Name ) ;
T . Check ( ! WillTrade ( trader , prisoner ) , "an anti-slavery trader still takes a colony prisoner from " + origin . Name ) ;
T . Check ( TraderBuyers . TraderRefusesCaptive ( slave , trader ) , "TraderRefusesCaptive is false for the refused slave (the trade window's reason line reads it)" ) ;
T . Check ( WillTrade ( trader , ownSlave ) , "an anti-slavery trader refuses to buy back its own member (ransom)" ) ;
T . Check ( WillTrade ( ship , slave ) , "a factionless trade ship refuses a colony slave" ) ;
T . Check ( WillTrade ( trader , slave , gift : true ) , "gift mode: an anti-slavery faction refuses a slave given as a gift" ) ;
// The reason line: only on the rows the gate greyed out.
T . Check ( Explains ( trader , slave ) , "the refused slave's row gets no reason tooltip" ) ;
T . Check ( Explains ( trader , prisoner ) , "the refused prisoner's row gets no reason tooltip" ) ;
T . Check ( ! Explains ( trader , ownSlave ) , "the faction's own member (ransom) gets a refusal reason" ) ;
T . Check ( ! Explains ( ship , slave ) , "a factionless trade ship's row gets a refusal reason" ) ;
T . Check ( ! Explains ( trader , slave , gift : true ) , "gift mode: the slave's row gets a refusal reason" ) ;
string reason = Patch_TraderRefusesCaptiveReason . Reason ( slave , trader ) . Resolve ( ) . StripTags ( ) ;
string pawnName = slave . Name ? . ToStringShort ? ? slave . LabelShort ;
T . Check ( reason . Contains ( buyer . Name ) & & reason . Contains ( pawnName ) & & ! reason . Contains ( "{" ) ,
$"reason line doesn't name {buyer.Name} and {pawnName}: {reason}" ) ;
T . Info ( "reason line: " + reason ) ;
} ) ;
WithIdeos ( buyer , pro , ( ) = >
{
T . Check ( WillTrade ( trader , slave ) , "a pro-slavery trader refuses a colony slave in refuse mode" ) ;
T . Check ( ! Explains ( trader , slave ) , "a pro-slavery trader's row gets a refusal reason" ) ;
} ) ;
}
[BlaxTest("trader buyers: refuse mode's reason is a postfix on DrawCaptiveTradeInfo that never skips it, also with Trade as Slave or Colonist")]
public static void RefuseReasonPatched ( )
{
if ( ! ModsConfig . IdeologyActive )
2026-11-29 16:07:37 +00:00
T . Skip ( "needs Ideology (TradeUI never calls DrawCaptiveTradeInfo without it, so the reason patch stays out)" ) ;
2026-11-28 18:33:08 +00:00
MethodInfo target = AccessTools . Method ( typeof ( TransferableUIUtility ) , nameof ( TransferableUIUtility . DrawCaptiveTradeInfo ) ) ;
T . NotNull ( target , "TransferableUIUtility.DrawCaptiveTradeInfo" ) ;
HarmonyLib . Patches info = Harmony . GetPatchInfo ( target ) ;
T . NotNull ( info , "patch info on DrawCaptiveTradeInfo" ) ;
bool postfix = info . Postfixes . Any ( p = > p . owner = = BlaxSlavesStartup . Harmony . Id & & p . PatchMethod ? . DeclaringType = = typeof ( Patch_TraderRefusesCaptiveReason ) ) ;
T . Check ( postfix , "no blax.slaves postfix from Patch_TraderRefusesCaptiveReason on DrawCaptiveTradeInfo (postfix owners: "
+ string . Join ( ", " , info . Postfixes . Select ( p = > p . owner ) . Distinct ( ) ) + ")" ) ;
List < HarmonyLib . Patch > prefixes = info . Prefixes . Where ( p = > p . PatchMethod ? . DeclaringType = = typeof ( Patch_TraderRefusesCaptiveReason ) ) . ToList ( ) ;
T . Check ( prefixes . All ( p = > p . PatchMethod . ReturnType = = typeof ( void ) ) , "Patch_TraderRefusesCaptiveReason has a prefix that can skip the original" ) ;
T . Info ( Compat . IsActive ( Compat . TradeAsSlaveOrColonist )
? "Trade as Slave or Colonist active: the reason patch is applied anyway"
: "Trade as Slave or Colonist inactive" ) ;
// Same column as TradeUI's "won't trade" text: 175 px trader columns, then 240 px, in row coordinates.
Rect willNot = Patch_TraderRefusesCaptiveReason . WillNotTradeRect ( new Rect ( 0f , 0f , 1000f , 30f ) ) ;
T . Check ( Mathf . Approximately ( willNot . x , 585f ) & & Mathf . Approximately ( willNot . width , 240f ) & & willNot . y = = 0f & & Mathf . Approximately ( willNot . height , 30f ) ,
"reason rect for a 1000x30 row is " + willNot + ", expected (585, 0, 240, 30)" ) ;
}
[BlaxTest("trader buyers: buy-anyway mode, every trader takes colony captives as in vanilla")]
public static void BuyAnywayModeGate ( )
{
if ( ! ModsConfig . IdeologyActive )
2026-11-29 16:07:37 +00:00
T . Skip ( "needs Ideology (the gate only acts with it)" ) ;
2026-11-28 18:33:08 +00:00
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 ) ;
T . Info ( $"buyer {buyer.Name}, captives from {origin.Name}; against: {againstSource}" ) ;
WithIdeos ( buyer , against , ( ) = >
{
T . Check ( WillTrade ( trader , slave ) , "buy-anyway: an anti-slavery trader refuses a colony slave" ) ;
T . Check ( WillTrade ( trader , prisoner ) , "buy-anyway: an anti-slavery trader refuses a colony prisoner" ) ;
T . Check ( WillTrade ( trader , ownSlave ) , "buy-anyway: an anti-slavery trader refuses its own member" ) ;
T . Check ( WillTrade ( ship , slave ) , "buy-anyway: a factionless trade ship refuses a colony slave" ) ;
T . Check ( ! TraderBuyers . TraderRefusesCaptive ( slave , trader ) , "TraderRefusesCaptive is true in buy-anyway mode" ) ;
} ) ;
}
2026-11-29 16:07:37 +00:00
[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 ( ) ;
} ) ;
}
2026-11-28 18:33:08 +00:00
// ---- slave stock ignores colony size ---------------------------------------------
[BlaxTest("slave stock: colony-size flag cleared on every slave generator, originals back when off, Slave_Empire kept")]
public static void StockFlagClearedAndRestored ( )
{
T . Check ( TraderBuyers . StockFeatureAvailable , "TraderBuyers could not bind StockGenerator_Slaves.respectPopulationIntent" ) ;
FieldInfo field = RespectField ( ) ;
List < ( TraderKindDef def , StockGenerator_Slaves gen ) > gens = AllSlaveGenerators ( ) ;
T . Check ( gens . Count > 0 , "no StockGenerator_Slaves on any trader kind" ) ;
Change ( s = > s . slaveStockIgnoresColonySize = false , ( ) = >
{
var original = new Dictionary < StockGenerator_Slaves , bool > ( ) ;
foreach ( var x in gens )
original [ x . gen ] = ( bool ) field . GetValue ( x . gen ) ;
bool syr = Compat . IsActive ( Compat . SyrMoreSlaves ) ;
if ( syr )
{
// [SYR] More Slaves replaces vanilla's StockGenerator_Slaves through XML, without respectPopulationIntent
// or slaveKindDef, so vanilla's XML says nothing here. Check against what TraderBuyers recorded at startup.
var startup = ( Dictionary < StockGenerator_Slaves , bool > ) AccessTools . Field ( typeof ( TraderBuyers ) , "originalRespect" ) ? . GetValue ( null ) ;
T . NotNull ( startup , "TraderBuyers.originalRespect" ) ;
List < string > lost = gens . Where ( x = > startup . TryGetValue ( x . gen , out bool was ) & & was & & ! original [ x . gen ] )
. Select ( x = > x . def . defName ) . ToList ( ) ;
T . Check ( lost . Count = = 0 , "respected population intent at startup but not with the setting off (not restored?): " + string . Join ( ", " , lost ) ) ;
T . Info ( $"[SYR] More Slaves active: vanilla's settlement XML not expected, {startup.Count(kv => kv.Value)} generators respected population intent at startup" ) ;
}
else
foreach ( string name in new [ ] { "Base_Outlander_Standard" , "Base_Neolithic_Standard" , "Base_Empire_Standard" } )
{
TraderKindDef def = DefDatabase < TraderKindDef > . GetNamedSilentFail ( name ) ;
if ( def ! = null & & ! SlaveGenerators ( def ) . Any ( g = > original [ g ] ) )
T . Fail ( name + " doesn't respect population intent with the setting off, but vanilla's XML sets it (not restored?)" ) ;
}
Set ( s = > s . slaveStockIgnoresColonySize = true ) ;
List < string > stillSet = gens . Where ( x = > ( bool ) field . GetValue ( x . gen ) ) . Select ( x = > x . def . defName ) . ToList ( ) ;
T . Check ( stillSet . Count = = 0 , "respectPopulationIntent still set with the setting on: " + string . Join ( ", " , stillSet ) ) ;
TraderKindDef empire = DefDatabase < TraderKindDef > . GetNamedSilentFail ( "Base_Empire_Standard" ) ;
if ( empire ! = null & & syr )
T . Info ( "[SYR] More Slaves replaced Base_Empire_Standard's slave generator without Slave_Empire; Slave_Empire check skipped" ) ;
else if ( empire ! = null )
T . Check ( SlaveGenerators ( empire ) . Any ( g = > g . slaveKindDef ! = null & & g . slaveKindDef . defName = = "Slave_Empire" ) ,
"Base_Empire_Standard lost its Slave_Empire slaveKindDef" ) ;
Set ( s = > s . slaveStockIgnoresColonySize = false ) ;
List < string > wrong = gens . Where ( x = > ( bool ) field . GetValue ( x . gen ) ! = original [ x . gen ] )
. Select ( x = > $"{x.def.defName} {field.GetValue(x.gen)} (was {original[x.gen]})" ) . ToList ( ) ;
T . Check ( wrong . Count = = 0 , "setting off did not restore respectPopulationIntent: " + string . Join ( ", " , wrong ) ) ;
Set ( s = > s . slaveStockIgnoresColonySize = true ) ;
Set ( s = > s . slaveStockIgnoresColonySize = true ) ;
T . Check ( gens . All ( x = > ! ( bool ) field . GetValue ( x . gen ) ) , "respectPopulationIntent set again after turning the setting back on twice" ) ;
T . Info ( $"{gens.Count} slave generators, {original.Count(kv => kv.Value)} respect population intent in vanilla: "
+ string . Join ( ", " , gens . Where ( x = > original [ x . gen ] ) . Select ( x = > x . def . defName ) ) ) ;
} ) ;
}
[BlaxTest("slave stock: at population intent 0 settlement stock still holds slaves, with the setting off none")]
public static void StockAtZeroPopulationIntent ( )
{
TraderKindDef def = TraderDef ( "Base_Outlander_Standard" ) ;
StockGenerator_Slaves gen = SlaveGenerators ( def ) . FirstOrDefault ( ) ;
T . NotNull ( gen , "Base_Outlander_Standard's StockGenerator_Slaves" ) ;
StorytellerDef teller = Find . Storyteller ? . def ;
T . NotNull ( teller , "storyteller def" ) ;
Faction pro = Find . FactionManager . AllFactionsVisible
. Where ( f = > ! f . IsPlayer & & ! f . defeated & & ! f . temporary & & f . def . humanlikeFaction & & f . ideos ! = null & & ApprovesSlavery ( f ) )
. OrderBy ( f = > f . loadID ) . FirstOrDefault ( ) ;
int onHits = 0 , proHits = 0 , proRounds = 0 , offHits = 0 ;
var generated = new List < Thing > ( ) ;
HashSet < Pawn > worldBefore = WorldSnapshot ( ) ;
SimpleCurve oldCurve = teller . populationIntentFactorFromPopCurve ;
Change ( s = > s . slaveStockIgnoresColonySize = true , ( ) = >
{
try
{
// Forced through the storyteller's own curve, not a Harmony patch: the PopulationIntent getter
// and CalculatePopulationIntent are tiny enough for the JIT to inline, which a patch would miss.
teller . populationIntentFactorFromPopCurve = new SimpleCurve ( new [ ] { new CurvePoint ( 0f , 0f ) , new CurvePoint ( 1000f , 0f ) } ) ;
float intent = StorytellerUtilityPopulation . PopulationIntent ;
T . Check ( intent < = 0f , "population intent is " + intent + " with an all-zero curve, so it can't be forced low" ) ;
for ( int i = 0 ; i < StockRounds ; i + + )
if ( FirstSlave ( gen , null , 9100 + i , generated ) )
onHits + + ;
if ( pro ! = null )
for ( int i = 0 ; i < 5 ; i + + , proRounds + + )
if ( FirstSlave ( gen , pro , 9200 + i , generated ) )
proHits + + ;
Set ( s = > s . slaveStockIgnoresColonySize = false ) ;
for ( int i = 0 ; i < StockRounds ; i + + )
if ( FirstSlave ( gen , null , 9300 + i , generated ) )
offHits + + ;
}
finally
{
teller . populationIntentFactorFromPopCurve = oldCurve ;
DiscardAll ( generated , worldBefore ) ;
}
} ) ;
T . Info ( $"population intent 0: setting on {onHits}/{StockRounds} factionless stocks with slaves"
+ ( pro ! = null ? $", {proHits}/{proRounds} for pro-slavery {pro.Name}" : ", no pro-slavery faction to check" )
+ $"; setting off {offHits}/{StockRounds}" ) ;
T . Equal ( StockRounds , onHits , "factionless Base_Outlander_Standard stocks holding a slave at population intent 0, setting on" ) ;
if ( pro ! = null )
T . Equal ( proRounds , proHits , "stocks for pro-slavery " + pro . Name + " holding a slave at population intent 0, setting on" ) ;
if ( Compat . IsActive ( Compat . SyrMoreSlaves ) )
{
T . Info ( "[SYR] More Slaves replaced vanilla's generator with one that ignores population intent; 'setting off: none' check skipped" ) ;
return ;
}
T . Equal ( 0 , offHits , "factionless stocks holding a slave at population intent 0, setting off (vanilla's colony-size rule)" ) ;
}
// ---- save and reload -------------------------------------------------------------
[BlaxTest("trader buyers: buyers and stock flags still match the settings after reload", phase: 2)]
public static void StateAfterReload ( )
{
BlaxSlavesSettings s = Fixtures . Settings ;
HashSet < TraderKindDef > visitors = TraderBuyers . VisitorKinds ( ) ;
var problems = new List < string > ( ) ;
foreach ( TraderKindDef def in DefDatabase < TraderKindDef > . AllDefsListForReading )
{
int expected = TraderBuyers . WantsOurBuyer ( def , s , visitors ) ? 1 : 0 ;
int actual = Ours ( def ) . Count ;
if ( actual ! = expected )
problems . Add ( $"{def.defName} carries {actual} of our generators, expected {expected}" ) ;
}
if ( s . slaveStockIgnoresColonySize & & TraderBuyers . StockFeatureAvailable )
{
FieldInfo field = RespectField ( ) ;
foreach ( var x in AllSlaveGenerators ( ) )
if ( ( bool ) field . GetValue ( x . gen ) )
problems . Add ( x . def . defName + " respects population intent although the setting is on" ) ;
}
T . Check ( problems . Count = = 0 , string . Join ( "; " , problems . Take ( 8 ) ) ) ;
}
// ---- helpers: settings and defs --------------------------------------------------
/// <summary>Changes settings, raises SettingsChanged, runs the body, then restores and re-applies.</summary>
private static void Change ( Action < BlaxSlavesSettings > set , Action body )
{
Dictionary < FieldInfo , object > snapshot = Fixtures . SnapshotSettings ( ) ;
try
{
Set ( set ) ;
body ( ) ;
}
finally
{
Fixtures . RestoreSettings ( snapshot ) ;
TraderBuyers . Apply ( ) ;
}
}
private static void Set ( Action < BlaxSlavesSettings > set )
{
set ( Fixtures . Settings ) ;
RaiseSettingsChanged ( ) ;
}
/// <summary>
/// What closing the settings window does for TraderBuyers: invokes its SettingsChanged handler. Only
/// ours, so other features' handlers don't run, and not through WriteSettings, which writes the file.
/// </summary>
private static void RaiseSettingsChanged ( )
{
FieldInfo field = AccessTools . Field ( typeof ( BlaxSlavesMod ) , nameof ( BlaxSlavesMod . SettingsChanged ) ) ;
T . NotNull ( field , "backing field of BlaxSlavesMod.SettingsChanged" ) ;
List < Delegate > ours = ( ( field . GetValue ( null ) as Action ) ? . GetInvocationList ( ) ? ? new Delegate [ 0 ] )
. Where ( d = > d . Method . DeclaringType = = typeof ( TraderBuyers ) ) . ToList ( ) ;
T . Equal ( 1 , ours . Count , "TraderBuyers handlers on BlaxSlavesMod.SettingsChanged" ) ;
foreach ( Delegate d in ours )
( ( Action ) d ) ( ) ;
}
private static TraderKindDef TraderDef ( string defName )
{
TraderKindDef def = DefDatabase < TraderKindDef > . GetNamedSilentFail ( defName ) ;
T . NotNull ( def , "TraderKindDef " + defName ) ;
return def ;
}
private static List < StockGenerator_BlaxBuySlaves > Ours ( TraderKindDef def ) = >
def ? . stockGenerators ? . OfType < StockGenerator_BlaxBuySlaves > ( ) . ToList ( ) ? ? new List < StockGenerator_BlaxBuySlaves > ( ) ;
private static List < StockGenerator_Slaves > SlaveGenerators ( TraderKindDef def ) = >
def ? . stockGenerators ? . OfType < StockGenerator_Slaves > ( ) . ToList ( ) ? ? new List < StockGenerator_Slaves > ( ) ;
private static List < ( TraderKindDef def , StockGenerator_Slaves gen ) > AllSlaveGenerators ( ) = >
DefDatabase < TraderKindDef > . AllDefsListForReading . SelectMany ( d = > SlaveGenerators ( d ) . Select ( g = > ( d , g ) ) ) . ToList ( ) ;
private static FieldInfo RespectField ( )
{
FieldInfo field = AccessTools . Field ( typeof ( StockGenerator_Slaves ) , "respectPopulationIntent" ) ;
T . NotNull ( field , "StockGenerator_Slaves.respectPopulationIntent" ) ;
return field ;
}
private static Dictionary < TraderKindDef , List < StockGenerator > > Snapshot ( ) = >
DefDatabase < TraderKindDef > . AllDefsListForReading . Where ( d = > d . stockGenerators ! = null )
. ToDictionary ( d = > d , d = > d . stockGenerators . ToList ( ) ) ;
private static bool SameRefs ( List < StockGenerator > a , List < StockGenerator > b ) = >
a . Count = = b . Count & & a . Zip ( b , ( x , y ) = > ReferenceEquals ( x , y ) ) . All ( same = > same ) ;
private static string Describe ( List < StockGenerator > gens ) = >
"[" + string . Join ( ", " , gens . Select ( g = > g ? . GetType ( ) . Name ? ? "null" ) ) + "]" ;
private static bool ApprovesSlavery ( Faction f ) = >
f . ideos = = null | | f . ideos . AllIdeos . All ( i = > i . IdeoApprovesOfSlavery ( ) ) ;
/// <summary>A trader kind that exists only for the test, never in the DefDatabase.</summary>
private static TraderKindDef FakeKind ( StockGenerator gen ) = >
new TraderKindDef { defName = "BlaxTestKind" , stockGenerators = new List < StockGenerator > { gen } } ;
private static bool Same ( TraderBuyers . SettingNotes a , TraderBuyers . SettingNotes b ) = >
a . everybodyBuysTraders = = b . everybodyBuysTraders & & a . everybodyBuysVisitors = = b . everybodyBuysVisitors & & a . hospitality = = b . hospitality ;
private static string Describe ( TraderBuyers . SettingNotes n ) = >
$"[every trader {n.everybodyBuysTraders}, visitors {n.everybodyBuysVisitors}, Hospitality {n.hospitality}]" ;
// ---- helpers: the trade gate -----------------------------------------------------
/// <summary>A trader with a chosen faction and kind, nothing else. Never spawned, never traded with.</summary>
private sealed class StubTrader : ITrader
{
private readonly TraderKindDef kind ;
private readonly Faction faction ;
public StubTrader ( TraderKindDef kind , Faction faction )
{
this . kind = kind ;
this . faction = faction ;
}
public TraderKindDef TraderKind = > kind ;
public IEnumerable < Thing > Goods = > Enumerable . Empty < Thing > ( ) ;
public int RandomPriceFactorSeed = > 1 ;
public string TraderName = > "Blax test trader" ;
public bool CanTradeNow = > true ;
public float TradePriceImprovementOffsetForPlayer = > 0f ;
public Faction Faction = > faction ;
public TradeCurrency TradeCurrency = > TradeCurrency . Silver ;
public IEnumerable < Thing > ColonyThingsWillingToBuy ( Pawn playerNegotiator ) = > Enumerable . Empty < Thing > ( ) ;
public void GiveSoldThingToTrader ( Thing toGive , int countToGive , Pawn playerNegotiator ) { }
public void GiveSoldThingToPlayer ( Thing toGive , int countToGive , Pawn playerNegotiator ) { }
}
/// <summary>
/// Buyer and origin factions, a colony slave and a colony prisoner from the origin, a colony slave whose
/// home is the buyer, a settlement-kind trader of the buyer's faction and a factionless slave ship.
/// </summary>
private static void GateSetup ( out Faction buyer , out Faction origin , out Pawn slave , out Pawn prisoner , out Pawn ownSlave , out StubTrader trader , out TradeShip ship )
{
List < Faction > factions = Find . FactionManager . AllFactionsVisible
. Where ( f = > ! f . IsPlayer & & ! f . defeated & & ! f . temporary & & f . def . humanlikeFaction & & f . ideos ! = null )
. OrderBy ( f = > f . HostileTo ( Faction . OfPlayer ) ) . ThenBy ( f = > f . loadID ) . ToList ( ) ;
if ( factions . Count < 2 )
T . Skip ( "need two visible humanlike factions with ideoligions, found " + factions . Count ) ;
buyer = factions [ 0 ] ;
origin = factions [ 1 ] ;
TraderKindDef kind = TraderDef ( "Base_Outlander_Standard" ) ;
T . Check ( kind . WillTrade ( ThingDefOf . Human ) , "Base_Outlander_Standard won't trade humans, so the gate can't be seen" ) ;
trader = new StubTrader ( kind , buyer ) ;
ship = new TradeShip ( TraderDef ( "Orbital_PirateMerchant" ) ) ;
T . Check ( ship . Faction = = null , "Orbital_PirateMerchant trade ship has a faction" ) ;
slave = Fixtures . ColonySlave ( origin ) ;
T . Check ( slave . IsSlaveOfColony & & slave . HomeFaction = = origin , "slave fixture is not a colony slave from " + origin . Name ) ;
prisoner = Fixtures . Spawn ( Fixtures . Generate ( PawnKindDefOf . Slave , origin ) ) ;
prisoner . guest . SetGuestStatus ( Faction . OfPlayer , GuestStatus . Prisoner ) ;
T . Check ( prisoner . IsPrisonerOfColony & & prisoner . HomeFaction = = origin , "prisoner fixture is not a colony prisoner from " + origin . Name ) ;
ownSlave = Fixtures . ColonySlave ( buyer ) ;
T . Check ( ownSlave . IsSlaveOfColony & & ownSlave . HomeFaction = = buyer , "own-member fixture is not a colony slave from " + buyer . Name ) ;
}
/// <summary>Tradeable_Pawn.TraderWillTrade for a colony pawn, read inside a trade session with this trader.</summary>
private static bool WillTrade ( ITrader trader , Pawn pawn , bool gift = false ) = >
InSession ( trader , pawn , gift , row = > row . TraderWillTrade ) ;
/// <summary>Whether the trade window's reason patch explains this colony pawn's row, inside a trade session with this trader.</summary>
private static bool Explains ( ITrader trader , Pawn pawn , bool gift = false ) = >
InSession ( trader , pawn , gift , row = > Patch_TraderRefusesCaptiveReason . Explains ( row , trader , out _ ) ) ;
/// <summary>Reads a trade row for a colony pawn with TradeSession.trader and giftMode set, then puts both back.</summary>
private static TR InSession < TR > ( ITrader trader , Pawn pawn , bool gift , Func < Tradeable_Pawn , TR > read )
{
ITrader oldTrader = TradeSession . trader ;
bool oldGift = TradeSession . giftMode ;
try
{
TradeSession . trader = trader ;
TradeSession . giftMode = gift ;
var row = new Tradeable_Pawn ( ) ;
row . thingsColony . Add ( pawn ) ;
return read ( row ) ;
}
finally
{
TradeSession . trader = oldTrader ;
TradeSession . giftMode = oldGift ;
}
}
/// <summary>
/// A world ideoligion that approves (or rejects) slavery. If the world has none, a bare one that exists
/// only for this test: without precepts it rejects, with Slavery_Honorable it approves.
/// </summary>
private static Ideo IdeoThat ( bool approves , out string source )
{
Ideo real = Find . IdeoManager . IdeosListForReading . FirstOrDefault ( i = > i ! = null & & i . IdeoApprovesOfSlavery ( ) = = approves ) ;
if ( real ! = null )
{
source = "world ideoligion '" + real . name + "'" ;
return real ;
}
var made = new Ideo { name = approves ? "Blax test slavers" : "Blax test abolitionists" } ;
if ( approves )
{
PreceptDef def = DefDatabase < PreceptDef > . GetNamedSilentFail ( "Slavery_Honorable" )
? ? DefDatabase < PreceptDef > . AllDefsListForReading . FirstOrDefault ( d = > d . approvesOfSlavery ) ;
T . NotNull ( def , "a PreceptDef that approves of slavery" ) ;
Precept precept = PreceptMaker . MakePrecept ( def ) ;
precept . ideo = made ;
made . PreceptsListForReading . Add ( precept ) ;
}
T . Check ( made . IdeoApprovesOfSlavery ( ) = = approves , "synthetic ideoligion approves of slavery: " + made . IdeoApprovesOfSlavery ( ) ) ;
source = "synthetic ideoligion '" + made . name + "' (no world ideoligion " + ( approves ? "approves of" : "rejects" ) + " slavery)" ;
return made ;
}
/// <summary>Runs the body with the faction following only this ideoligion, then puts its own back.</summary>
private static void WithIdeos ( Faction faction , Ideo ideo , Action body )
{
Ideo oldPrimary = faction . ideos . PrimaryIdeo ;
List < Ideo > minor = faction . ideos . IdeosMinorListForReading ;
List < Ideo > oldMinor = minor . ToList ( ) ;
try
{
faction . ideos . SetPrimary ( ideo ) ;
minor . Clear ( ) ;
body ( ) ;
}
finally
{
faction . ideos . SetPrimary ( oldPrimary ) ;
minor . Clear ( ) ;
minor . AddRange ( oldMinor ) ;
}
}
// ---- helpers: generated stock ----------------------------------------------------
/// <summary>Only the generator's first item, so a round costs one pawn at most. True if it is a humanlike pawn.</summary>
private static bool FirstSlave ( StockGenerator_Slaves gen , Faction faction , int seed , List < Thing > sink )
{
Rand . PushState ( seed ) ;
try
{
Thing first = gen . GenerateThings ( Fixtures . Map . Tile , faction ) . FirstOrDefault ( ) ;
if ( first = = null )
return false ;
sink . Add ( first ) ;
return first is Pawn p & & p . RaceProps . Humanlike ;
}
finally
{
Rand . PopState ( ) ;
}
}
/// <summary>
/// World pawns before generation. StockGenerator_Slaves asks for forceGenerateNewPawn: false, so
/// PawnGenerator may redress one of them instead of making a new pawn.
/// </summary>
private static HashSet < Pawn > WorldSnapshot ( ) = > new HashSet < Pawn > ( Find . WorldPawns . AllPawnsAliveOrDead ) ;
/// <summary>Fresh pawns are discarded, redressed world pawns go back to the world, as TradersTests does.</summary>
private static void DiscardAll ( IEnumerable < Thing > things , HashSet < Pawn > formerWorldPawns )
{
foreach ( Thing t in things . Where ( x = > x ! = null ) . ToList ( ) )
{
try
{
if ( t . Spawned )
continue ;
t . holdingOwner ? . Remove ( t ) ;
if ( t is Pawn p )
{
if ( p . Discarded )
continue ;
if ( Find . WorldPawns . Contains ( p ) )
{
if ( ! formerWorldPawns . Contains ( p ) )
Find . WorldPawns . RemoveAndDiscardPawnViaGC ( p ) ;
}
else if ( formerWorldPawns . Contains ( p ) )
Find . WorldPawns . PassToWorld ( p ) ;
else
Find . WorldPawns . PassToWorld ( p , PawnDiscardDecideMode . Discard ) ;
}
else if ( ! t . Destroyed )
{
t . Destroy ( DestroyMode . Vanish ) ;
}
}
catch ( Exception e )
{
T . Info ( "cleanup of " + t + " threw: " + e . Message ) ;
}
}
}
}
}