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 Verse ;
namespace BlaxSlavesTests
{
/// <summary>
/// Slavers, slave stock and trader branding: Patches/BlaxSlaves_Traders.xml and
/// Patch_TraderSlaveBrand (postfix on ThingWithComps.PostGeneratedForTrader).
/// Stock is generated through vanilla's ThingSetMakerDefOf.TraderStock (what caravans use)
/// or a real TradeShip (what the orbital trader incident uses), then discarded again.
/// </summary>
public static class TradersTests
{
// ---- expected values, copied from Patches/BlaxSlaves_Traders.xml ----------------
private static readonly string [ ] Slavers =
{ "Caravan_Outlander_PirateMerchant" , "Caravan_Neolithic_Slaver" , "Orbital_PirateMerchant" } ;
private const float SlaverCommonality = 2f ;
private static readonly ( float x , float y ) [ ] SlaverPopulationCurve = { ( 0f , 0.5f ) , ( 1f , 1f ) , ( 2f , 2f ) } ;
private static readonly Dictionary < string , IntRange > SlaverSlaveCount = new Dictionary < string , IntRange >
{
{ "Caravan_Outlander_PirateMerchant" , new IntRange ( 5 , 9 ) } ,
{ "Caravan_Neolithic_Slaver" , new IntRange ( 4 , 7 ) } ,
{ "Orbital_PirateMerchant" , new IntRange ( 6 , 10 ) } ,
} ;
private static readonly IntRange OtherTraderSlaveCount = new IntRange ( - 1 , 2 ) ;
private static readonly IntRange SettlementSlaveCount = new IntRange ( 1 , 4 ) ;
private const string HarmonyId = "blax.slaves" ;
// ---- patch and defs --------------------------------------------------------------
[BlaxTest("traders: brand postfix sits on PostGeneratedForTrader and reaches pawns")]
public static void BrandPatchApplied ( )
{
MethodInfo target = AccessTools . Method ( typeof ( ThingWithComps ) , nameof ( ThingWithComps . PostGeneratedForTrader ) ) ;
T . NotNull ( target , "ThingWithComps.PostGeneratedForTrader" ) ;
var info = Harmony . GetPatchInfo ( target ) ;
bool ours = info ! = null & & info . Postfixes . Any ( p = > p . owner = = HarmonyId & & p . PatchMethod ? . DeclaringType = = typeof ( Patch_TraderSlaveBrand ) ) ;
T . Check ( ours , "no blax.slaves postfix from Patch_TraderSlaveBrand on ThingWithComps.PostGeneratedForTrader (postfix owners: "
+ ( info = = null ? "none" : string . Join ( ", " , info . Postfixes . Select ( p = > p . owner ) ) ) + ")" ) ;
MethodInfo onPawn = typeof ( Pawn ) . GetMethod ( nameof ( Pawn . PostGeneratedForTrader ) , BindingFlags . Public | BindingFlags . Instance ) ;
T . Check ( onPawn ! = null & & onPawn . DeclaringType = = typeof ( ThingWithComps ) ,
"Pawn.PostGeneratedForTrader resolves to " + ( onPawn ? . DeclaringType ? . Name ? ? "nothing" ) + ", expected the patched ThingWithComps method" ) ;
}
[BlaxTest("traders: allies can request the slaver caravans")]
public static void SlaverCaravansRequestable ( )
{
foreach ( string name in new [ ] { "Caravan_Outlander_PirateMerchant" , "Caravan_Neolithic_Slaver" } )
{
TraderKindDef def = TraderDef ( name ) ;
T . Check ( def . requestable , name + ".requestable is false, so the comms console hides it" ) ;
T . Check ( DefDatabase < FactionDef > . AllDefs . Any ( f = > f . caravanTraderKinds ! = null & & f . caravanTraderKinds . Contains ( def ) ) ,
"no faction lists " + name + " in caravanTraderKinds" ) ;
}
}
[BlaxTest("traders: slavers have commonality 2 and the softened population curve")]
public static void SlaverCommonalityPatched ( )
{
var problems = new List < string > ( ) ;
string expectedCurve = string . Join ( " " , SlaverPopulationCurve . Select ( p = > $"({p.x}, {p.y})" ) ) ;
foreach ( string name in Slavers )
{
TraderKindDef def = TraderDef ( name ) ;
if ( ! Near ( def . commonality , SlaverCommonality ) )
problems . Add ( $"{name}.commonality = {def.commonality}, expected {SlaverCommonality}" ) ;
SimpleCurve curve = def . commonalityMultFromPopulationIntent ;
if ( curve = = null )
{
problems . Add ( name + " has no commonalityMultFromPopulationIntent" ) ;
continue ;
}
bool same = curve . PointsCount = = SlaverPopulationCurve . Length ;
for ( int i = 0 ; same & & i < SlaverPopulationCurve . Length ; i + + )
same = Near ( curve . Points [ i ] . x , SlaverPopulationCurve [ i ] . x ) & & Near ( curve . Points [ i ] . y , SlaverPopulationCurve [ i ] . y ) ;
if ( ! same )
problems . Add ( $"{name} population curve is {string.Join(" ", curve.Points.Select(p => $" ( { p . x } , { p . y } ) "))}, expected {expectedCurve}" ) ;
}
T . Check ( problems . Count = = 0 , string . Join ( "; " , problems ) ) ;
}
[BlaxTest("traders: slaver slave stock countRange matches the patch")]
public static void SlaverSlaveCountPatched ( )
{
var problems = new List < string > ( ) ;
foreach ( var kv in SlaverSlaveCount )
{
List < StockGenerator_Slaves > gens = SlaveGenerators ( TraderDef ( kv . Key ) ) ;
if ( gens . Count ! = 1 )
problems . Add ( $"{kv.Key} has {gens.Count} StockGenerator_Slaves, expected exactly 1" ) ;
foreach ( StockGenerator_Slaves g in gens )
if ( ! SameRange ( g . countRange , kv . Value ) )
problems . Add ( $"{kv.Key} slave countRange {Show(g.countRange)}, expected {Show(kv.Value)}" ) ;
}
T . Check ( problems . Count = = 0 , string . Join ( "; " , problems ) ) ;
}
[BlaxTest("traders: every caravan and orbital trader carries a slave generator")]
public static void EveryCaravanAndOrbitalHasSlaves ( )
{
List < TraderKindDef > defs = DefDatabase < TraderKindDef > . AllDefsListForReading
. Where ( d = > d . defName . StartsWith ( "Caravan_" , StringComparison . Ordinal ) | | d . defName . StartsWith ( "Orbital_" , StringComparison . Ordinal ) )
. ToList ( ) ;
T . Check ( defs . Count > = Slavers . Length , "found only " + defs . Count + " Caravan_*/Orbital_* trader kinds" ) ;
var problems = new List < string > ( ) ;
foreach ( TraderKindDef def in defs )
{
List < StockGenerator_Slaves > gens = SlaveGenerators ( def ) ;
if ( gens . Count = = 0 )
{
problems . Add ( def . defName + " has no StockGenerator_Slaves" ) ;
continue ;
}
foreach ( StockGenerator_Slaves g in gens )
if ( g . trader ! = def )
problems . Add ( $"{def.defName}: slave generator's trader is {g.trader?.defName ?? " null "} (ResolveReferences missed it; GenerateThings reads trader.orbital)" ) ;
if ( ! SlaverSlaveCount . ContainsKey ( def . defName ) & & ! gens . Any ( g = > SameRange ( g . countRange , OtherTraderSlaveCount ) ) )
problems . Add ( $"{def.defName} slave countRange {string.Join(" / ", gens.Select(g => Show(g.countRange)))}, expected the patch's {Show(OtherTraderSlaveCount)}" ) ;
}
T . Info ( "checked " + defs . Count + " trader kinds: " + string . Join ( ", " , defs . Select ( d = > d . defName ) ) ) ;
T . Check ( problems . Count = = 0 , string . Join ( "; " , problems ) ) ;
}
[BlaxTest("traders: settlement slave countRange matches the patch")]
public static void SettlementSlaveCountPatched ( )
{
List < TraderKindDef > withSlaves = DefDatabase < TraderKindDef > . AllDefsListForReading
. Where ( d = > d . defName . StartsWith ( "Base_" , StringComparison . Ordinal ) & & SlaveGenerators ( d ) . Count > 0 )
. ToList ( ) ;
foreach ( string must in new [ ] { "Base_Outlander_Standard" , "Base_Neolithic_Standard" } )
T . Check ( withSlaves . Any ( d = > d . defName = = must ) , must + " has no StockGenerator_Slaves, but vanilla gives it one" ) ;
var problems = new List < string > ( ) ;
foreach ( TraderKindDef def in withSlaves )
foreach ( StockGenerator_Slaves g in SlaveGenerators ( def ) )
if ( ! SameRange ( g . countRange , SettlementSlaveCount ) )
problems . Add ( $"{def.defName} slave countRange {Show(g.countRange)}, expected {Show(SettlementSlaveCount)}" ) ;
TraderKindDef empire = DefDatabase < TraderKindDef > . GetNamedSilentFail ( "Base_Empire_Standard" ) ;
if ( empire ! = null & & ! SlaveGenerators ( empire ) . Any ( g = > g . slaveKindDef ! = null & & g . slaveKindDef . defName = = "Slave_Empire" ) )
2026-11-28 18:33:08 +00:00
{
if ( Compat . IsActive ( Compat . SyrMoreSlaves ) )
T . Info ( "Base_Empire_Standard has no Slave_Empire slaveKindDef: [SYR] More Slaves replaces every StockGenerator_Slaves without one" ) ;
else
problems . Add ( "Base_Empire_Standard lost its Slave_Empire slaveKindDef (the patch should only replace countRange)" ) ;
}
2026-11-28 18:33:08 +00:00
T . Info ( "settlement trader kinds with slaves: " + string . Join ( ", " , withSlaves . Select ( d = > d . defName ) ) ) ;
T . Check ( problems . Count = = 0 , string . Join ( "; " , problems ) ) ;
}
// ---- stock generation ------------------------------------------------------------
[BlaxTest("traders: generated slaver stock holds the patched number of slaves")]
public static void SlaverStockCountInRange ( )
{
var problems = new List < string > ( ) ;
var seen = new List < string > ( ) ;
2026-11-28 18:33:08 +00:00
int syrExtra = 0 ;
if ( Compat . IsActive ( Compat . SyrMoreSlaves ) )
{
syrExtra = SyrExtraSlavesMax ( out string source ) ;
T . Info ( $"[SYR] More Slaves active: its own generator adds up to {syrExtra} slaves per slaver ({source}), upper bound widened by that" ) ;
}
2026-11-28 18:33:08 +00:00
foreach ( var kv in SlaverSlaveCount )
{
TraderKindDef def = TraderDef ( kv . Key ) ;
2026-11-28 18:33:08 +00:00
IntRange expected = new IntRange ( kv . Value . min , kv . Value . max + syrExtra ) ;
2026-11-28 18:33:08 +00:00
for ( int seed = 1 ; seed < = 3 ; seed + + )
{
TradeShip ship = null ;
List < Thing > stock = null ;
HashSet < Pawn > worldBefore = WorldSnapshot ( ) ;
try
{
string how ;
if ( def . orbital )
{
ship = SlaveShip ( def , 4100 + seed ) ;
stock = Goods ( ship ) ;
how = "trade ship" ;
}
else
{
stock = CaravanStock ( def , CaravanFaction ( def ) , 4100 + seed , out how ) ;
}
int slaves = stock . OfType < Pawn > ( ) . Count ( p = > p . RaceProps . Humanlike ) ;
seen . Add ( $"{def.defName}#{seed}={slaves} ({how})" ) ;
2026-11-28 18:33:08 +00:00
if ( slaves < expected . min | | slaves > expected . max )
problems . Add ( $"{def.defName} seed {seed}: {slaves} slaves via {how}, expected {Show(expected)}" ) ;
2026-11-28 18:33:08 +00:00
}
finally
{
if ( ship ! = null ) RemoveShip ( ship , worldBefore ) ;
else DiscardAll ( stock , worldBefore ) ;
}
}
}
T . Info ( string . Join ( ", " , seen ) ) ;
T . Check ( problems . Count = = 0 , string . Join ( "; " , problems ) ) ;
}
// ---- trader branding on generated stock ------------------------------------------
[BlaxTest("traders: brand chance 1 marks every slave in slaver caravan stock as the trading faction's")]
public static void CaravanStockBrandedForTrader ( )
{
Fixtures . Settings . traderBrandChance = 1f ;
var problems = new List < string > ( ) ;
int exempt = 0 , reused = 0 ;
var brandedPer = new Dictionary < string , int > ( ) ;
string [ ] caravanSlavers = Slavers . Where ( n = > ! TraderDef ( n ) . orbital ) . ToArray ( ) ;
for ( int k = 0 ; k < caravanSlavers . Length ; k + + )
{
TraderKindDef def = TraderDef ( caravanSlavers [ k ] ) ;
Faction trading = CaravanFaction ( def ) ;
if ( trading = = null ) T . Skip ( "no visible non-player humanlike faction to trade as" ) ;
brandedPer [ def . defName ] = 0 ;
for ( int seed = 1 ; seed < = 2 ; seed + + )
{
List < Thing > stock = null ;
HashSet < Pawn > worldBefore = WorldSnapshot ( ) ;
try
{
stock = CaravanStock ( def , trading , 4200 + 10 * k + seed , out string how ) ;
if ( seed = = 1 ) T . Info ( $"{def.defName}: trading faction {trading.Name} ({trading.def.defName}), stock via {how}" ) ;
foreach ( Pawn p in stock . OfType < Pawn > ( ) . Where ( x = > x . RaceProps . Humanlike ) )
{
if ( worldBefore . Contains ( p ) ) { reused + + ; continue ; }
if ( ! BrandEligible ( p , def ) )
{
exempt + + ;
if ( BrandUtility . IsBranded ( p ) )
problems . Add ( $"{def.defName}: {Who(p)} is exempt ({ExemptReason(p, def)}) but got branded" ) ;
continue ;
}
HediffComp_BrandOwner brand = BrandUtility . BrandOf ( p ) ;
if ( brand = = null ) { problems . Add ( $"{def.defName}: {Who(p)} is unbranded at traderBrandChance = 1" ) ; continue ; }
brandedPer [ def . defName ] + + ;
if ( brand . owner ! = trading )
problems . Add ( $"{def.defName}: {Who(p)} brand owner is {brand.owner?.Name ?? " null "}, expected the trading faction {trading.Name}" ) ;
if ( brand . OwnerName ! = trading . Name )
problems . Add ( $"{def.defName}: {Who(p)} brand owner name is '{brand.OwnerName}', expected '{trading.Name}'" ) ;
problems . AddRange ( BurnProblems ( p ) ) ;
}
}
finally
{
DiscardAll ( stock , worldBefore ) ;
}
}
}
T . Info ( $"branded {string.Join(" , ", brandedPer.Select(kv => kv.Key + " = " + kv.Value))}, exempt {exempt}, redressed world pawns skipped {reused}" ) ;
T . Check ( problems . Count = = 0 , string . Join ( "; " , problems . Take ( 6 ) ) ) ;
foreach ( var kv in brandedPer )
T . Check ( kv . Value > 0 , kv . Key + " stock held no freshly generated brandable slave in 2 generations, so nothing was checked" ) ;
}
[BlaxTest("traders: brand chance 0 leaves every slave in slaver stock unbranded")]
public static void ChanceZeroBrandsNobody ( )
{
Fixtures . Settings . traderBrandChance = 0f ;
TraderKindDef caravanDef = TraderDef ( "Caravan_Outlander_PirateMerchant" ) ;
TraderKindDef shipDef = TraderDef ( "Orbital_PirateMerchant" ) ;
var problems = new List < string > ( ) ;
int slaves = 0 ;
List < Thing > stock = null ;
TradeShip ship = null ;
HashSet < Pawn > worldBefore = WorldSnapshot ( ) ;
try
{
stock = CaravanStock ( caravanDef , CaravanFaction ( caravanDef ) , 4301 , out _ ) ;
ship = SlaveShip ( shipDef , 4302 ) ;
foreach ( Pawn p in stock . Concat ( Goods ( ship ) ) . OfType < Pawn > ( ) . Where ( x = > x . RaceProps . Humanlike & & ! worldBefore . Contains ( x ) ) )
{
slaves + + ;
if ( BrandUtility . IsBranded ( p ) )
problems . Add ( $"{Who(p)} branded by {BrandUtility.BrandOf(p)?.OwnerName ?? " ? "} although traderBrandChance = 0" ) ;
}
}
finally
{
DiscardAll ( stock , worldBefore ) ;
if ( ship ! = null ) RemoveShip ( ship , worldBefore ) ;
}
T . Check ( slaves > 0 , "caravan and ship stock held no freshly generated slaves, so nothing was checked" ) ;
T . Check ( problems . Count = = 0 , string . Join ( "; " , problems . Take ( 6 ) ) ) ;
// Control: the same ship seed at chance 1 must brand someone, or "nobody branded" above proves nothing.
Fixtures . Settings . traderBrandChance = 1f ;
int controlBranded = 0 ;
ship = null ;
worldBefore = WorldSnapshot ( ) ;
try
{
ship = SlaveShip ( shipDef , 4302 ) ;
controlBranded = Goods ( ship ) . OfType < Pawn > ( ) . Count ( p = > p . RaceProps . Humanlike & & ! worldBefore . Contains ( p ) & & BrandUtility . IsBranded ( p ) ) ;
}
finally
{
if ( ship ! = null ) RemoveShip ( ship , worldBefore ) ;
}
T . Check ( controlBranded > 0 , "control: the same slave ship seed at traderBrandChance = 1 branded nobody either, so chance 0 was not what kept them unbranded" ) ;
}
[BlaxTest("traders: orbital slave ship has no trading faction, its slaves get a fallback owner")]
public static void SlaveShipFallbackOwner ( )
{
Fixtures . Settings . traderBrandChance = 1f ;
TraderKindDef def = TraderDef ( "Orbital_PirateMerchant" ) ;
var problems = new List < string > ( ) ;
int branded = 0 ;
var owners = new HashSet < string > ( ) ;
for ( int seed = 1 ; seed < = 2 ; seed + + )
{
TradeShip ship = null ;
HashSet < Pawn > worldBefore = WorldSnapshot ( ) ;
try
{
ship = SlaveShip ( def , 4400 + seed ) ;
foreach ( Pawn p in Goods ( ship ) . OfType < Pawn > ( ) . Where ( x = > x . RaceProps . Humanlike & & ! worldBefore . Contains ( x ) ) )
{
if ( ! BrandEligible ( p , def ) )
{
if ( BrandUtility . IsBranded ( p ) ) problems . Add ( $"{Who(p)} is exempt ({ExemptReason(p, def)}) but got branded" ) ;
continue ;
}
HediffComp_BrandOwner brand = BrandUtility . BrandOf ( p ) ;
if ( brand = = null ) { problems . Add ( Who ( p ) + " is unbranded although the ship passed no faction and the fallback should pick one" ) ; continue ; }
branded + + ;
Faction o = brand . owner ;
if ( o = = null ) { problems . Add ( Who ( p ) + " brand has no owner" ) ; continue ; }
owners . Add ( o . Name ) ;
if ( o . IsPlayer ) problems . Add ( Who ( p ) + " fallback owner is the player" ) ;
if ( o . temporary ) problems . Add ( $"{Who(p)} fallback owner {o.Name} is a temporary faction" ) ;
if ( ! o . def . humanlikeFaction ) problems . Add ( $"{Who(p)} fallback owner {o.Name} is not humanlike" ) ;
if ( o . Hidden ) problems . Add ( $"{Who(p)} fallback owner {o.Name} is a hidden faction" ) ;
if ( o = = p . Faction ) problems . Add ( $"{Who(p)} fallback owner {o.Name} is the slave's own faction" ) ;
problems . AddRange ( BurnProblems ( p ) ) ;
}
}
finally
{
if ( ship ! = null ) RemoveShip ( ship , worldBefore ) ;
}
}
T . Info ( $"branded {branded}, fallback owners: {string.Join(" , ", owners)}" ) ;
T . Check ( problems . Count = = 0 , string . Join ( "; " , problems . Take ( 6 ) ) ) ;
T . Check ( branded > 0 , "slave ship stock held no brandable slave in 2 generations, so nothing was checked" ) ;
}
[BlaxTest("traders: animals in slaver stock never get a brand")]
public static void AnimalsNeverBranded ( )
{
Fixtures . Settings . traderBrandChance = 1f ;
TraderKindDef caravanDef = TraderDef ( "Caravan_Outlander_PirateMerchant" ) ;
TraderKindDef shipDef = TraderDef ( "Orbital_PirateMerchant" ) ;
var problems = new List < string > ( ) ;
int animals = 0 , items = 0 , brandedSlaves = 0 ;
for ( int seed = 1 ; seed < = 2 ; seed + + )
{
List < Thing > stock = null ;
TradeShip ship = null ;
HashSet < Pawn > worldBefore = WorldSnapshot ( ) ;
try
{
stock = CaravanStock ( caravanDef , CaravanFaction ( caravanDef ) , 4500 + seed , out _ ) ;
ship = SlaveShip ( shipDef , 4510 + seed ) ;
foreach ( Thing t in stock . Concat ( Goods ( ship ) ) )
{
if ( ! ( t is Pawn p ) ) { items + + ; continue ; }
if ( p . RaceProps . Humanlike )
{
// Only fresh pawns count as the control: a redressed world pawn may carry an older brand.
if ( ! worldBefore . Contains ( p ) & & BrandUtility . IsBranded ( p ) ) brandedSlaves + + ;
continue ;
}
animals + + ;
if ( BrandUtility . IsBranded ( p ) )
problems . Add ( $"animal {Who(p)} ({p.def.defName}) got a slave brand" ) ;
}
}
finally
{
DiscardAll ( stock , worldBefore ) ;
if ( ship ! = null ) RemoveShip ( ship , worldBefore ) ;
}
}
T . Info ( $"animals {animals}, items {items}, freshly branded slaves in the same stock {brandedSlaves}" ) ;
T . Check ( problems . Count = = 0 , string . Join ( "; " , problems . Take ( 6 ) ) ) ;
if ( brandedSlaves = = 0 ) T . Fail ( "no freshly generated slave in the same stock was branded at traderBrandChance = 1, so the brand patch did not run" ) ;
if ( animals = = 0 ) T . Skip ( "vanilla generated no animals in slaver caravan or slave ship stock, nothing to check" ) ;
}
// ---- 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 ) ;
private static void ExemptPawnsUnbrandedBody ( )
{
Fixtures . Settings . traderBrandChance = 1f ;
TraderKindDef def = TraderDef ( "Caravan_Outlander_PirateMerchant" ) ;
Faction trading = AnyTradingFaction ( ) ;
if ( trading = = null ) T . Skip ( "no visible non-player humanlike faction to trade as" ) ;
PlanetTile tile = Fixtures . Map . Tile ;
Pawn control = Fixtures . Generate ( PawnKindDefOf . Slave , trading ) ;
control . guest . joinStatus = JoinStatus . JoinAsSlave ;
control . PostGeneratedForTrader ( def , tile , trading ) ;
T . Check ( BrandUtility . IsBranded ( control ) , "control: an adult join-as-slave Slave pawn was not branded at traderBrandChance = 1" ) ;
T . Equal ( trading , BrandUtility . BrandOf ( control ) . owner , "control slave's brand owner" ) ;
Pawn joiner = Fixtures . Generate ( PawnKindDefOf . Slave , trading ) ;
joiner . guest . joinStatus = JoinStatus . JoinAsColonist ;
joiner . PostGeneratedForTrader ( def , tile , trading ) ;
T . Check ( ! BrandUtility . IsBranded ( joiner ) , "a Slave pawn that joins as a colonist got branded" ) ;
Pawn villager = Fixtures . Generate ( PawnKindDefOf . Villager , trading ) ;
if ( villager . guest ! = null ) villager . guest . joinStatus = JoinStatus . JoinAsSlave ;
villager . PostGeneratedForTrader ( def , tile , trading ) ;
T . Check ( ! BrandUtility . IsBranded ( villager ) , "a non-slave humanlike (Villager kind) passed through slaver stock got branded" ) ;
if ( ! ModsConfig . BiotechActive )
{
T . Info ( "Biotech inactive, child case not checked" ) ;
return ;
}
Pawn child = null ;
try
{
child = PawnGenerator . GeneratePawn ( new PawnGenerationRequest ( PawnKindDefOf . Slave , trading , PawnGenerationContext . NonPlayer ,
forceGenerateNewPawn : true , canGeneratePawnRelations : false , colonistRelationChanceFactor : 0f ,
developmentalStages : DevelopmentalStage . Child ) ) ;
T . Check ( ! child . ageTracker . Adult , "child request produced an adult (" + child . ageTracker . AgeBiologicalYears + "y)" ) ;
if ( child . guest ! = null ) child . guest . joinStatus = JoinStatus . JoinAsSlave ;
child . PostGeneratedForTrader ( def , tile , trading ) ;
T . Check ( ! BrandUtility . IsBranded ( child ) , $"a child slave ({child.ageTracker.AgeBiologicalYears}y) got branded" ) ;
}
finally
{
DiscardAll ( new List < Thing > { child } ) ;
}
}
[BlaxTest("traders: a trader's custom slave kind counts as stock, a pawn-hire trader does not")]
public static void SlaveStockKindRules ( ) = > Seeded ( 4710 , SlaveStockKindRulesBody ) ;
private static void SlaveStockKindRulesBody ( )
{
Fixtures . Settings . traderBrandChance = 1f ;
Faction trading = AnyTradingFaction ( ) ;
if ( trading = = null ) T . Skip ( "no visible non-player humanlike faction to trade as" ) ;
PlanetTile tile = Fixtures . Map . Tile ;
Pawn control = Fixtures . Generate ( PawnKindDefOf . Slave , trading ) ;
control . guest . joinStatus = JoinStatus . JoinAsSlave ;
control . PostGeneratedForTrader ( TraderDef ( "Caravan_Outlander_PirateMerchant" ) , tile , trading ) ;
T . Check ( BrandUtility . IsBranded ( control ) , "control: a Slave pawn in slaver stock was not branded at traderBrandChance = 1" ) ;
var rimdeed = new TraderKindDef { defName = "RD_PawnTrader" } ;
Pawn hired = Fixtures . Generate ( PawnKindDefOf . Slave , trading ) ;
hired . guest . joinStatus = JoinStatus . JoinAsSlave ;
hired . PostGeneratedForTrader ( rimdeed , tile , trading ) ;
T . Check ( ! BrandUtility . IsBranded ( hired ) , "a Slave pawn from the RD_PawnTrader trader kind got branded" ) ;
PawnKindDef empireSlave = DefDatabase < PawnKindDef > . GetNamedSilentFail ( "Slave_Empire" ) ;
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" ) ;
return ;
}
2026-11-28 18:33:08 +00:00
if ( Compat . IsActive ( Compat . SyrMoreSlaves ) )
T . Info ( "[SYR] More Slaves replaced Base_Empire_Standard's Slave_Empire generator with a plain one; custom slave kind not checked" ) ;
else
{
T . Check ( SlaveGenerators ( empireBase ) . Any ( g = > g . slaveKindDef = = empireSlave ) , "Base_Empire_Standard has no Slave_Empire slave generator" ) ;
2026-11-28 18:33:08 +00:00
2026-11-28 18:33:08 +00:00
Pawn imperial = Fixtures . Generate ( empireSlave , trading ) ;
imperial . guest . joinStatus = JoinStatus . JoinAsSlave ;
imperial . PostGeneratedForTrader ( empireBase , tile , trading ) ;
T . Check ( BrandUtility . IsBranded ( imperial ) , "a Slave_Empire pawn in Base_Empire_Standard stock was not branded" ) ;
T . Equal ( trading , BrandUtility . BrandOf ( imperial ) . owner , "Slave_Empire brand owner" ) ;
}
2026-11-28 18:33:08 +00:00
TraderKindDef generic = TraderDef ( "Caravan_Outlander_BulkGoods" ) ;
Pawn stray = Fixtures . Generate ( empireSlave , trading ) ;
stray . guest . joinStatus = JoinStatus . JoinAsSlave ;
stray . PostGeneratedForTrader ( generic , tile , trading ) ;
T . Check ( ! BrandUtility . IsBranded ( stray ) , "a Slave_Empire pawn got branded by Caravan_Outlander_BulkGoods, whose slave generator uses the plain Slave kind" ) ;
}
[BlaxTest("traders: an existing brand is kept, the player as trader falls back to another owner")]
public static void ExistingBrandAndPlayerFallback ( ) = > Seeded ( 4720 , ExistingBrandAndPlayerFallbackBody ) ;
private static void ExistingBrandAndPlayerFallbackBody ( )
{
Fixtures . Settings . traderBrandChance = 1f ;
TraderKindDef def = TraderDef ( "Caravan_Outlander_PirateMerchant" ) ;
List < Faction > factions = VisibleTradingFactions ( ) ;
if ( factions . Count < 2 ) T . Skip ( "need two visible non-player humanlike factions, found " + factions . Count ) ;
Faction first = factions [ 0 ] , second = factions [ 1 ] ;
PlanetTile tile = Fixtures . Map . Tile ;
// Control: the same call on an unbranded slave brands it for `second`, so keeping `first` below is the patch's choice.
Pawn fresh = Fixtures . Generate ( PawnKindDefOf . Slave , second ) ;
fresh . guest . joinStatus = JoinStatus . JoinAsSlave ;
fresh . PostGeneratedForTrader ( def , tile , second ) ;
T . Equal ( second , BrandUtility . BrandOf ( fresh ) ? . owner , "control: brand owner of an unbranded slave passed through the same call" ) ;
Pawn marked = Fixtures . Generate ( PawnKindDefOf . Slave , second ) ;
marked . guest . joinStatus = JoinStatus . JoinAsSlave ;
BrandUtility . Brand ( marked , first ) ;
marked . PostGeneratedForTrader ( def , tile , second ) ;
T . Equal ( first , BrandUtility . BrandOf ( marked ) ? . owner , "owner of a slave branded before it reached the trader" ) ;
T . Equal ( 1 , marked . health . hediffSet . hediffs . Count ( h = > h . def = = BlaxDefOf . BlaxSlaves_SlaveBrand ) , "brand hediffs on the pre-branded slave" ) ;
Pawn sold = Fixtures . Generate ( PawnKindDefOf . Slave , first ) ;
sold . guest . joinStatus = JoinStatus . JoinAsSlave ;
sold . PostGeneratedForTrader ( def , tile , Faction . OfPlayer ) ;
HediffComp_BrandOwner brand = BrandUtility . BrandOf ( sold ) ;
T . NotNull ( brand , "brand on a slave generated with the player as trading faction" ) ;
Faction o = brand . owner ;
T . NotNull ( o , "fallback brand owner" ) ;
T . Check ( ! o . IsPlayer , "player as trading faction: brand owner is still the player" ) ;
T . Check ( o ! = sold . Faction , $"fallback owner {o.Name} is the slave's own faction" ) ;
T . Check ( ! o . temporary & & o . def . humanlikeFaction & & ! o . Hidden , $"fallback owner {o.Name} ({o.def.defName}) is temporary, hidden or not humanlike" ) ;
}
// ---- save and reload -------------------------------------------------------------
private const string CarryShip = "traders.ship" ;
private const string CarrySlave = "traders.slave" ;
private const string CarryOwner = "traders.owner" ;
private const string CarryOwnerName = "traders.ownerName" ;
[BlaxTest("traders: set up a trader-branded slave on a passing slave ship for reload")]
public static void ReloadSetup ( )
{
Fixtures . Settings . traderBrandChance = 1f ;
TraderKindDef def = TraderDef ( "Orbital_PirateMerchant" ) ;
for ( int seed = 4601 ; seed < = 4603 ; seed + + )
{
HashSet < Pawn > worldBefore = WorldSnapshot ( ) ;
TradeShip ship = SlaveShip ( def , seed ) ;
bool keep = false ;
try
{
// A freshly generated pawn, so the brand is the trader brand and not an older one on a redressed world pawn.
Pawn slave = Goods ( ship ) . OfType < Pawn > ( ) . FirstOrDefault ( p = > p . RaceProps . Humanlike & & ! worldBefore . Contains ( p ) & & BrandUtility . BrandOf ( p ) ? . owner ! = null ) ;
if ( slave = = null ) continue ;
HediffComp_BrandOwner brand = BrandUtility . BrandOf ( slave ) ;
ship . ticksUntilDeparture = 1000 * GenDate . TicksPerDay ;
T . Carry [ CarryShip ] = ship . GetUniqueLoadID ( ) ;
T . Carry [ CarrySlave ] = slave . ThingID ;
T . Carry [ CarryOwner ] = brand . owner . GetUniqueLoadID ( ) ;
T . Carry [ CarryOwnerName ] = brand . OwnerName ;
keep = true ;
T . Info ( $"slave ship {ship.GetUniqueLoadID()} (seed {seed}) keeps {Who(slave)}, branded for {brand.OwnerName}" ) ;
return ;
}
finally
{
if ( ! keep ) RemoveShip ( ship , worldBefore ) ;
}
}
T . Fail ( "no freshly generated slave with an owned brand in 3 slave ship stocks at traderBrandChance = 1" ) ;
}
[BlaxTest("traders: a trader brand in slave ship stock survives save and reload", phase: 2)]
public static void ReloadKeepsTraderBrand ( )
{
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 ) ;
T . NotNull ( ship , "slave ship " + shipId + " after reload" ) ;
try
{
string slaveId = T . Carry [ CarrySlave ] ;
Pawn slave = Goods ( ship ) . OfType < Pawn > ( ) . FirstOrDefault ( p = > p . ThingID = = slaveId ) ;
T . NotNull ( slave , "slave " + slaveId + " in the reloaded ship's stock" ) ;
HediffComp_BrandOwner brand = BrandUtility . BrandOf ( slave ) ;
T . NotNull ( brand , "brand on " + slaveId + " after reload" ) ;
T . NotNull ( brand . owner , "brand owner faction after reload (name cached: '" + brand . ownerName + "')" ) ;
T . Equal ( T . Carry [ CarryOwner ] , brand . owner . GetUniqueLoadID ( ) , "brand owner faction after reload" ) ;
T . Equal ( T . Carry [ CarryOwnerName ] , brand . OwnerName , "brand owner name after reload" ) ;
}
finally
{
RemoveShip ( ship ) ;
}
}
// ---- helpers ---------------------------------------------------------------------
private static TraderKindDef TraderDef ( string defName )
{
TraderKindDef def = DefDatabase < TraderKindDef > . GetNamedSilentFail ( defName ) ;
T . NotNull ( def , "TraderKindDef " + defName ) ;
return def ;
}
private static List < StockGenerator_Slaves > SlaveGenerators ( TraderKindDef def ) = >
def . stockGenerators ? . OfType < StockGenerator_Slaves > ( ) . ToList ( ) ? ? new List < StockGenerator_Slaves > ( ) ;
private static bool Near ( float a , float b ) = > Math . Abs ( a - b ) < 0.0001f ;
private static bool SameRange ( IntRange a , IntRange b ) = > a . min = = b . min & & a . max = = b . max ;
private static string Show ( IntRange r ) = > r . min + "~" + r . max ;
2026-11-28 18:33:08 +00:00
/// <summary>
/// The most slaves [SYR] More Slaves adds per slave-carrying trader on top of the StockGenerator_Slaves. Its
/// patch XML appends a MoreSlaves.StockGenerator_Slaves_IgnorePopCap with countRange 2~4, but the generator
/// draws from the mod's "Additional slave count" setting instead (documented default 3~5).
/// </summary>
private static int SyrExtraSlavesMax ( out string source )
{
const int documentedMax = 5 ;
try
{
ModMetaData meta = ModLister . GetActiveModWithIdentifier ( Compat . SyrMoreSlaves , ignorePostfix : true ) ;
Mod mod = meta = = null ? null : LoadedModManager . ModHandles
. FirstOrDefault ( m = > string . Equals ( m . Content ? . PackageId , meta . PackageId , StringComparison . OrdinalIgnoreCase ) ) ;
object settings = mod = = null ? null : AccessTools . Field ( typeof ( Mod ) , "modSettings" ) ? . GetValue ( mod ) ;
FieldInfo count = settings = = null ? null : AccessTools . Field ( settings . GetType ( ) , "SlaveCount" ) ;
object value = count ? . GetValue ( count . IsStatic ? null : settings ) ;
if ( value is IntRange r )
{
source = "its Additional slave count setting " + Show ( r ) ;
return r . max ;
}
if ( value is FloatRange f )
{
source = $"its Additional slave count setting {f.min}~{f.max}" ;
return ( int ) Math . Ceiling ( f . max ) ;
}
}
catch ( Exception e )
{
source = "its documented default 3~5, setting unreadable: " + e . Message ;
return documentedMax ;
}
source = "its documented default 3~5, setting not found" ;
return documentedMax ;
}
2026-11-28 18:33:08 +00:00
private static string Who ( Pawn p ) = > p . LabelShort + " [" + p . ThingID + "]" ;
private static bool ApprovesSlavery ( Faction f ) = >
f . ideos = = null | | f . ideos . AllIdeos . All ( i = > i . IdeoApprovesOfSlavery ( ) ) ;
private static List < Faction > VisibleTradingFactions ( ) = >
Find . FactionManager . AllFactionsVisible
. Where ( f = > ! f . IsPlayer & & ! f . defeated & & ! f . temporary & & f . def . humanlikeFaction )
. OrderBy ( f = > f . loadID ) . ToList ( ) ;
private static Faction AnyTradingFaction ( ) = > Fixtures . FriendlyFaction ( ) ? ? VisibleTradingFactions ( ) . FirstOrDefault ( ) ;
/// <summary>
/// The faction that sends this caravan. Vanilla's slave generator makes no slaves for a faction
/// whose ideoligions don't all approve of slavery, so one that does is preferred.
/// </summary>
private static Faction CaravanFaction ( TraderKindDef def )
{
List < Faction > all = VisibleTradingFactions ( ) ;
return all . FirstOrDefault ( f = > f . def . caravanTraderKinds . Contains ( def ) & & ApprovesSlavery ( f ) )
? ? all . FirstOrDefault ( ApprovesSlavery )
? ? all . FirstOrDefault ( f = > f . def . caravanTraderKinds . Contains ( def ) )
? ? all . FirstOrDefault ( ) ;
}
/// <summary>
/// Caravan stock as PawnGroupKindWorker_Trader makes it: TraderStock with the caravan's faction.
/// If no faction approves of slavery (vanilla would then make no slaves at all), the generators
/// run without a faction and each thing goes through the hooked PostGeneratedForTrader with the
/// trading faction, as ThingSetMaker_TraderStock does.
/// </summary>
private static List < Thing > CaravanStock ( TraderKindDef def , Faction faction , int seed , out string how )
{
PlanetTile tile = Fixtures . Map . Tile ;
Rand . PushState ( seed ) ;
try
{
if ( faction = = null | | ApprovesSlavery ( faction ) )
{
how = "ThingSetMaker TraderStock, faction " + ( faction ? . def . defName ? ? "none" ) ;
return ThingSetMakerDefOf . TraderStock . root . Generate ( new ThingSetMakerParams
{
traderDef = def ,
tile = tile ,
makingFaction = faction ,
} ) ;
}
how = "generators without faction + PostGeneratedForTrader for " + faction . def . defName + " (no faction approves of slavery)" ;
var list = new List < Thing > ( ) ;
foreach ( StockGenerator gen in def . stockGenerators )
foreach ( Thing t in gen . GenerateThings ( tile , null ) )
{
t . PostGeneratedForTrader ( def , tile , faction ) ;
list . Add ( t ) ;
}
return list ;
}
finally
{
Rand . PopState ( ) ;
}
}
/// <summary>
/// A slave ship as IncidentWorker_OrbitalTraderArrival makes it: new TradeShip, added to the map,
/// GenerateThings (which passes no faction to the stock).
/// </summary>
private static TradeShip SlaveShip ( TraderKindDef def , int seed )
{
Rand . PushState ( seed ) ;
try
{
Faction faction = def . faction = = null ? null : Find . FactionManager . AllFactions . FirstOrDefault ( f = > f . def = = def . faction ) ;
var ship = new TradeShip ( def , faction ) ;
Fixtures . Map . passingShipManager . AddShip ( ship ) ;
try
{
ship . GenerateThings ( ) ;
}
catch
{
RemoveShip ( ship ) ;
throw ;
}
return ship ;
}
finally
{
Rand . PopState ( ) ;
}
}
private static List < Thing > Goods ( TradeShip ship ) = > ship . GetDirectlyHeldThings ( ) . ToList ( ) ;
/// <summary>
/// World pawns before stock generation. StockGenerator_Slaves asks for forceGenerateNewPawn: false,
/// so PawnGenerator may redress one of them (and take it out of WorldPawns) instead of making a new pawn.
/// </summary>
private static HashSet < Pawn > WorldSnapshot ( ) = > new HashSet < Pawn > ( Find . WorldPawns . AllPawnsAliveOrDead ) ;
/// <summary>Runs a test body under a fixed Rand seed (pawn generation and the brand roll use Rand).</summary>
private static void Seeded ( int seed , Action body )
{
Rand . PushState ( seed ) ;
try { body ( ) ; }
finally { Rand . PopState ( ) ; }
}
private static void RemoveShip ( TradeShip ship , HashSet < Pawn > formerWorldPawns = null )
{
if ( ship = = null ) return ;
List < Thing > goods = Goods ( ship ) ;
ship . passingShipManager ? . RemoveShip ( ship ) ;
DiscardAll ( goods , formerWorldPawns ) ;
}
/// <summary>
/// Destroys generated stock: fresh pawns are discarded the vanilla way, items destroyed. A pawn that was
/// a world pawn before generation (redressed into the stock) goes back to the world, as on a trader's
/// departure (ThingUtility.DestroyOrPassToWorld), so tests don't delete pawns other systems may reference.
/// </summary>
private static void DiscardAll ( IEnumerable < Thing > things , HashSet < Pawn > formerWorldPawns = null )
{
if ( things = = null ) return ;
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 = = null | | ! formerWorldPawns . Contains ( p ) ) Find . WorldPawns . RemoveAndDiscardPawnViaGC ( p ) ;
}
else if ( formerWorldPawns ! = null & & 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 ) ;
}
}
}
private static bool IsSlaveKind ( Pawn p , TraderKindDef def ) = >
p . kindDef = = PawnKindDefOf . Slave | | SlaveGenerators ( def ) . Any ( g = > g . slaveKindDef ! = null & & g . slaveKindDef = = p . kindDef ) ;
/// <summary>The pawns Patch_TraderSlaveBrand should brand: adult, slave kind, not joining as a colonist.</summary>
private static bool BrandEligible ( Pawn p , TraderKindDef def ) = > ExemptReason ( p , def ) = = null ;
private static string ExemptReason ( Pawn p , TraderKindDef def )
{
if ( p . Dead ) return "dead" ;
if ( ! p . RaceProps . Humanlike ) return "not humanlike" ;
if ( p . ageTracker = = null | | ! p . ageTracker . Adult ) return "child, " + p . ageTracker ? . AgeBiologicalYears + "y" ;
if ( ! IsSlaveKind ( p , def ) ) return "kind " + p . kindDef ? . defName ;
if ( p . guest ! = null & & p . guest . joinStatus = = JoinStatus . JoinAsColonist ) return "joins as colonist" ;
return null ;
}
/// <summary>A trader brand is an old mark: no fresh burn, no infection.</summary>
private static IEnumerable < string > BurnProblems ( Pawn p )
{
HediffDef burn = DamageDefOf . Burn ? . hediff ;
foreach ( Hediff h in p . health . hediffSet . hediffs )
{
if ( burn ! = null & & h . def = = burn & & ! h . IsPermanent ( ) )
yield return $"{Who(p)} has a fresh burn ({h.Part?.Label ?? " whole body "}, severity {h.Severity:0.#}) with the trader brand" ;
if ( h . def = = HediffDefOf . WoundInfection )
yield return Who ( p ) + " has a wound infection with the trader brand" ;
if ( h . def = = BlaxDefOf . BlaxSlaves_SlaveBrand & & h is HediffWithComps hw & & hw . comps . Any ( c = > c is HediffComp_Infecter ) )
yield return Who ( p ) + " brand hediff carries an infecter comp" ;
}
}
}
}