diff --git a/1.7/Assemblies/BlaxSlaves.dll b/1.7/Assemblies/BlaxSlaves.dll index 0766e0f..f37b007 100644 Binary files a/1.7/Assemblies/BlaxSlaves.dll and b/1.7/Assemblies/BlaxSlaves.dll differ diff --git a/1.7/Assemblies/BlaxSlaves.pdb b/1.7/Assemblies/BlaxSlaves.pdb index ab846a3..5c750ee 100644 Binary files a/1.7/Assemblies/BlaxSlaves.pdb and b/1.7/Assemblies/BlaxSlaves.pdb differ diff --git a/About/About.xml b/About/About.xml index 6ea1850..1c4f5c2 100644 --- a/About/About.xml +++ b/About/About.xml @@ -3,6 +3,7 @@ Blax Slaves Blax Gaming blax.slaves + 1.2.0
  • 1.7
  • @@ -17,12 +18,18 @@
  • brrainz.harmony
  • Mlie.SYRMoreSlaves
  • +
  • blax.castes
  • +
  • blax.zones
  • Slavery as an everyday part of the rim. Needs Ideology for slaves. +- 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. - 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 more. +- Every caravan and orbital trader may have a slave or two for sale, and settlements keep selling slaves however big your colony gets. +- Time as a slave in the Records tab and the slave tab. - 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. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c978517 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,18 @@ +# Changelog + +## 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. +- Every trader buys captives, visitor groups included. Optional: factions whose ideoligion rejects slavery refuse, except their own people. Replaces Everybody Buys Slaves. +- Settlements keep selling slaves however big your colony gets. Replaces [SYR] More Slaves. +- Price sliders for buying slaves and selling captives (vanilla 60% each), capped so buy-low-sell-high doesn't pay. +- Time as a slave in the Records tab and the slave tab. +- Settings in tabs (Trade, General, Compat). The Compat tab lists active mods Blax Slaves replaces. + +## 1.1.0 + +- Allied outlanders and tribes send a slaver caravan on request at the comms console (vanilla hides slavers from the request list). + +## 1.0.0 + +- First Workshop release: common slavers with more slaves, branding, branded runaways returned, harming slaves doesn't upset colonists. diff --git a/Languages/English/Keyed/BlaxSlaves.xml b/Languages/English/Keyed/BlaxSlaves.xml index ff79153..ec90e9e 100644 --- a/Languages/English/Keyed/BlaxSlaves.xml +++ b/Languages/English/Keyed/BlaxSlaves.xml @@ -25,5 +25,45 @@ Family still grieves Colonists related to the slave (family, lovers) keep their thoughts. Trader slaves with a previous owner's brand: {0} + Show time as a slave in the slave tab + The Records tab always counts it. This only hides the line in the slave tab. + + + Trade + General + Compat + Reset this tab + Slaves need the Ideology DLC. Without it, most of this tab does nothing. + + + Choose slave or colonist when buying + In the trade window, click "Joins as slave" or "Joins as colonist" on a pawn the trader sells to switch it. A slave costs less. + Trade as Slave or Colonist is active, so it handles this instead. + New pawns in trader stock start as: + Vanilla roll (25% colonist, 75% slave) + Always slave + Always colonist + Every trader buys slaves and prisoners + Settlements, the Empire and modded traders buy captives too, not only slavers and caravans. + Visitor groups buy slaves and prisoners + Visiting groups from other factions buy captives when you trade with them. + Traders whose ideoligion rejects slavery: + Buy captives anyway (vanilla) + Refuse, except their own people (ransom) + Slave stock ignores colony size + Vanilla settlements stop selling slaves as your colony grows. With this on, they keep selling. + Captives sell for {0} of their colonist price (vanilla 60%) + Applies to slaves and prisoners you sell. Capped below what a trader would charge you for the same pawn as a slave, so you can't buy low and sell high. + Slaves cost {0} of the colonist price (vanilla 60%) + Applies to pawns you buy as slaves. + + + Other Blax mods found: + none + Active mods that Blax Slaves replaces: + none, nothing to unsubscribe + Blax Slaves' "choose slave or colonist" stands down while it is active. Unsubscribe it to use ours. + Its buyers stay even when Blax Slaves' "every trader" and "visitors" settings are off. Unsubscribe it to control buying from here. + Its extra 3 to 5 slaves per trader stack on top of ours. You can unsubscribe it. diff --git a/Languages/English/Keyed/BlaxSlaves_BuyMode.xml b/Languages/English/Keyed/BlaxSlaves_BuyMode.xml new file mode 100644 index 0000000..50f9680 --- /dev/null +++ b/Languages/English/Keyed/BlaxSlaves_BuyMode.xml @@ -0,0 +1,11 @@ + + + + + As a colonist: {0}\nAs a slave: {1} + Click to buy {PAWN_objective} as a slave instead. + Click to buy {PAWN_objective} as a colonist instead. + {PAWN_nameDef} is unwaveringly loyal to {PAWN_possessive} home and refuses to join as a colonist. You can only buy {PAWN_objective} as a slave. + {PAWN_nameDef} is unwaveringly loyal to {PAWN_possessive} home, so the trader's terms for {PAWN_objective} can't be changed. + + diff --git a/Languages/English/Keyed/BlaxSlaves_TimeAsSlave.xml b/Languages/English/Keyed/BlaxSlaves_TimeAsSlave.xml new file mode 100644 index 0000000..f2b477d --- /dev/null +++ b/Languages/English/Keyed/BlaxSlaves_TimeAsSlave.xml @@ -0,0 +1,12 @@ + + + + + Enslaved for {0} (tracked since install) + Total time as our slave, counted since Blax Slaves was installed. The Records tab lists it as "time as a slave". + + + time as a slave + Total time spent as a slave of your community. Counted since Blax Slaves was installed. + + diff --git a/Languages/English/Keyed/BlaxSlaves_TraderBuyers.xml b/Languages/English/Keyed/BlaxSlaves_TraderBuyers.xml new file mode 100644 index 0000000..d719acc --- /dev/null +++ b/Languages/English/Keyed/BlaxSlaves_TraderBuyers.xml @@ -0,0 +1,12 @@ + + + + + {FACTION_name} rejects slavery and won't buy {PAWN_nameDef}. They only buy back their own people. + + + Everybody Buys Slaves adds its own buyers to these traders. They keep buying while it is active, even with this off. + Everybody Buys Slaves adds its own buyers to visitor groups. They keep buying while it is active, even with this off. + With Hospitality, visitor groups are its guests, who don't buy captives. This setting only reaches other visitors, such as Ideology's skylantern wanderers. + + diff --git a/README.md b/README.md index abdd001..3311e07 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,15 @@ RimWorld mod (1.7) that makes slavery an everyday part of the rim. First mod und - **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` -- Mod settings for all the numbers and toggles. +- **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` +- **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. -Compat: War Crimes Expanded 2 torture and Harvest Organs Post Mortem autopsies count as slave harm when their mods are active. Hospitality visitor groups never take a runaway who is due to be returned. No Sympathy For Prisoners already removes slavery and execution precept thoughts for everyone, pacifists included. Load after [SYR] More Slaves, or every trader gets its extra 3~5 slaves on top of ours. +Compat: War Crimes Expanded 2 torture and Harvest Organs Post Mortem autopsies count as slave harm when their mods are active. Hospitality visitor groups never take a runaway who is due to be returned. No Sympathy For Prisoners already removes slavery and execution precept thoughts for everyone, pacifists included. Everybody Buys Slaves and [SYR] More Slaves can stay installed but aren't needed any more; with More Slaves, its extra 3~5 slaves per trader stack on ours. Blax Castes and Blax Zones (planned, see `docs/`) are optional companions; Blax Slaves binds their APIs by reflection when they are loaded. + +Roadmap: `docs/roadmap.md`. Not covered: eating slave meat, slave-leather apparel, slaves lost when a map closes or kidnapped by raiders (vanilla ransom handles those). @@ -46,7 +52,7 @@ RimWorld 1.7 no longer runs on Unity/Mono. It runs on .NET 10 (CoreCLR) with Lud .\Tests\run-tests.ps1 ``` -`-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). 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. 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`. diff --git a/Source/BlaxSlaves/BlaxSlavesMod.cs b/Source/BlaxSlaves/BlaxSlavesMod.cs index b18b224..8abe030 100644 --- a/Source/BlaxSlaves/BlaxSlavesMod.cs +++ b/Source/BlaxSlaves/BlaxSlavesMod.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using HarmonyLib; using RimWorld; using UnityEngine; @@ -8,13 +9,31 @@ namespace BlaxSlaves { public class BlaxSlavesSettings : ModSettings { + // How "buy as slave or colonist" picks the default for recruitable pawns in trader stock. + public const int PurchaseVanilla = 0, PurchaseAlwaysSlave = 1, PurchaseAlwaysColonist = 2; + // What traders whose ideoligion rejects slavery do with colony slaves and prisoners. + public const int AntiSlaveryBuyAnyway = 0, AntiSlaveryRefuse = 1; + + // General (1.0/1.1) public bool returnRunaways = true; public float returnChance = 0.8f; public int returnDelayMinDays = 3; public int returnDelayMaxDays = 10; public bool suppressSlaveHarmMood = true; public bool keepRelationGrief = true; + public bool showTimeInSlaveTab = true; + + // Trade (1.2) + // A 1.1 setting, drawn and reset on the Trade tab; its Scribe key is unchanged, so saved values load. public float traderBrandChance = 0.35f; + public bool buyModeEnabled = true; + public int defaultPurchaseMode = PurchaseVanilla; + public bool allTradersBuySlaves = true; + public bool visitorsBuySlaves = true; + public int antiSlaveryTraders = AntiSlaveryBuyAnyway; + public bool slaveStockIgnoresColonySize = true; + public float slaveSellFactor = 0.6f; + public float slaveBuyFactor = 0.6f; public override void ExposeData() { @@ -26,6 +45,57 @@ namespace BlaxSlaves Scribe_Values.Look(ref suppressSlaveHarmMood, "suppressSlaveHarmMood", true); Scribe_Values.Look(ref keepRelationGrief, "keepRelationGrief", true); Scribe_Values.Look(ref traderBrandChance, "traderBrandChance", 0.35f); + Scribe_Values.Look(ref showTimeInSlaveTab, "showTimeInSlaveTab", true); + + Scribe_Values.Look(ref buyModeEnabled, "buyModeEnabled", true); + Scribe_Values.Look(ref defaultPurchaseMode, "defaultPurchaseMode", PurchaseVanilla); + Scribe_Values.Look(ref allTradersBuySlaves, "allTradersBuySlaves", true); + Scribe_Values.Look(ref visitorsBuySlaves, "visitorsBuySlaves", true); + Scribe_Values.Look(ref antiSlaveryTraders, "antiSlaveryTraders", AntiSlaveryBuyAnyway); + Scribe_Values.Look(ref slaveStockIgnoresColonySize, "slaveStockIgnoresColonySize", true); + Scribe_Values.Look(ref slaveSellFactor, "slaveSellFactor", 0.6f); + Scribe_Values.Look(ref slaveBuyFactor, "slaveBuyFactor", 0.6f); + + if (Scribe.mode == LoadSaveMode.PostLoadInit) + Clamp(); + } + + public void Clamp() + { + returnChance = Mathf.Clamp01(returnChance); + returnDelayMinDays = Mathf.Clamp(returnDelayMinDays, 1, 30); + returnDelayMaxDays = Mathf.Clamp(returnDelayMaxDays, returnDelayMinDays, 60); + traderBrandChance = Mathf.Clamp01(traderBrandChance); + defaultPurchaseMode = Mathf.Clamp(defaultPurchaseMode, PurchaseVanilla, PurchaseAlwaysColonist); + antiSlaveryTraders = Mathf.Clamp(antiSlaveryTraders, AntiSlaveryBuyAnyway, AntiSlaveryRefuse); + slaveSellFactor = Mathf.Clamp(slaveSellFactor, 0.3f, 1f); + slaveBuyFactor = Mathf.Clamp(slaveBuyFactor, 0.3f, 1f); + } + + public void ResetGeneral() + { + 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; + } + + public void ResetTrade() + { + 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; } } @@ -33,6 +103,18 @@ namespace BlaxSlaves { public static BlaxSlavesSettings Settings; + /// + /// Raised after the settings window closes and the settings are written. Features that + /// change defs at startup (trader generators, stock flags) re-apply themselves here. + /// Never raised during a trade session: the settings window can't open while trading. + /// + public static event Action SettingsChanged; + + private enum Tab { Trade, General, Compat } + private static Tab tab = Tab.Trade; + private static Vector2 scroll; + private static float viewHeight = 900f; + public BlaxSlavesMod(ModContentPack content) : base(content) { Settings = GetSettings(); @@ -40,30 +122,151 @@ namespace BlaxSlaves public override string SettingsCategory() => "Blax Slaves"; + public override void WriteSettings() + { + Settings.Clamp(); + base.WriteSettings(); + try + { + SettingsChanged?.Invoke(); + } + catch (Exception e) + { + Log.Error("[Blax Slaves] Re-applying settings failed: " + e); + } + } + public override void DoSettingsWindowContents(Rect inRect) { + var tabs = new List + { + new TabRecord("BlaxSlaves_TabTrade".Translate(), () => tab = Tab.Trade, tab == Tab.Trade), + new TabRecord("BlaxSlaves_TabGeneral".Translate(), () => tab = Tab.General, tab == Tab.General), + new TabRecord("BlaxSlaves_TabCompat".Translate(), () => tab = Tab.Compat, tab == Tab.Compat), + }; + Rect body = inRect; + body.yMin += 32f; + TabDrawer.DrawTabs(body, tabs); + + Rect outRect = body.ContractedBy(4f); + Rect viewRect = new Rect(0f, 0f, outRect.width - 16f, viewHeight); + Widgets.BeginScrollView(outRect, ref scroll, viewRect); + // One column: otherwise rows past last frame's viewHeight wrap into a second column outside the + // scroll group, CurHeight counts only that column, and viewHeight never grows back after a tab switch. var l = new Listing_Standard(); - l.Begin(inRect); - - l.CheckboxLabeled("BlaxSlaves_SettingReturn".Translate(), ref Settings.returnRunaways, "BlaxSlaves_SettingReturnTip".Translate()); - l.Label("BlaxSlaves_SettingReturnChance".Translate(Settings.returnChance.ToStringPercent())); - Settings.returnChance = l.Slider(Settings.returnChance, 0f, 1f); - l.Label("BlaxSlaves_SettingReturnDelayMin".Translate(Settings.returnDelayMinDays)); - Settings.returnDelayMinDays = Mathf.RoundToInt(l.Slider(Settings.returnDelayMinDays, 1f, 30f)); - l.Label("BlaxSlaves_SettingReturnDelayMax".Translate(Settings.returnDelayMaxDays)); - Settings.returnDelayMaxDays = Mathf.RoundToInt(l.Slider(Settings.returnDelayMaxDays, 1f, 60f)); - if (Settings.returnDelayMaxDays < Settings.returnDelayMinDays) - Settings.returnDelayMaxDays = Settings.returnDelayMinDays; - - l.GapLine(); - l.CheckboxLabeled("BlaxSlaves_SettingMood".Translate(), ref Settings.suppressSlaveHarmMood, "BlaxSlaves_SettingMoodTip".Translate()); - l.CheckboxLabeled("BlaxSlaves_SettingGrief".Translate(), ref Settings.keepRelationGrief, "BlaxSlaves_SettingGriefTip".Translate()); - - l.GapLine(); - l.Label("BlaxSlaves_SettingTraderBrand".Translate(Settings.traderBrandChance.ToStringPercent())); - Settings.traderBrandChance = l.Slider(Settings.traderBrandChance, 0f, 1f); - + l.maxOneColumn = true; + l.Begin(viewRect); + switch (tab) + { + case Tab.Trade: + DoTrade(l); + break; + case Tab.General: + DoGeneral(l); + break; + case Tab.Compat: + DoCompat(l); + break; + } + viewHeight = Mathf.Max(outRect.height, l.CurHeight + 12f); l.End(); + Widgets.EndScrollView(); + } + + private static void DoTrade(Listing_Standard l) + { + BlaxSlavesSettings s = Settings; + if (!ModsConfig.IdeologyActive) + { + l.Label("BlaxSlaves_SettingNeedsIdeology".Translate()); + l.GapLine(); + } + + l.CheckboxLabeled("BlaxSlaves_SettingBuyMode".Translate(), ref s.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)) + s.defaultPurchaseMode = BlaxSlavesSettings.PurchaseVanilla; + if (l.RadioButton("BlaxSlaves_SettingPurchaseSlave".Translate(), s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseAlwaysSlave, 12f)) + s.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysSlave; + if (l.RadioButton("BlaxSlaves_SettingPurchaseColonist".Translate(), s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseAlwaysColonist, 12f)) + 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()); + if (buyerNotes.everybodyBuysTraders) + l.Label("BlaxSlaves_SettingAllTradersBuyEverybodyBuys".Translate()); + l.CheckboxLabeled("BlaxSlaves_SettingVisitorsBuy".Translate(), ref s.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)) + s.antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryBuyAnyway; + if (l.RadioButton("BlaxSlaves_SettingAntiSlaveryRefuse".Translate(), s.antiSlaveryTraders == BlaxSlavesSettings.AntiSlaveryRefuse, 12f)) + 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); + + 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; + + l.Gap(); + if (l.ButtonText("BlaxSlaves_ResetTab".Translate())) + 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 (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()); + + l.GapLine(); + l.CheckboxLabeled("BlaxSlaves_SettingTimeAsSlave".Translate(), ref s.showTimeInSlaveTab, "BlaxSlaves_SettingTimeAsSlaveTip".Translate()); + + l.Gap(); + if (l.ButtonText("BlaxSlaves_ResetTab".Translate())) + s.ResetGeneral(); + } + + private static void DoCompat(Listing_Standard l) + { + l.Label("BlaxSlaves_CompatSiblings".Translate()); + l.Label(" " + Siblings.Describe()); + l.GapLine(); + + l.Label("BlaxSlaves_CompatReplaced".Translate()); + int shown = 0; + foreach (Compat.ReplacedMod m in Compat.Replaced) + { + if (!Compat.IsActive(m.packageId)) + continue; + shown++; + l.Label(" " + m.name + " (" + m.packageId + "): " + m.note.Translate()); + } + if (shown == 0) + l.Label(" " + "BlaxSlaves_CompatNoneActive".Translate()); } } @@ -96,6 +299,7 @@ namespace BlaxSlaves } ok += Compat.Apply(Harmony); Log.Message("[Blax Slaves] " + ok + " patches applied" + (failed > 0 ? ", " + failed + " failed" : "")); + Siblings.Init(); } } diff --git a/Source/BlaxSlaves/Brand.cs b/Source/BlaxSlaves/Brand.cs index 5a504f1..24eb680 100644 --- a/Source/BlaxSlaves/Brand.cs +++ b/Source/BlaxSlaves/Brand.cs @@ -177,12 +177,18 @@ namespace BlaxSlaves } } - /// Some slaves in trader stock already carry an owner's brand: the trader's faction, or another one. + /// + /// Some slaves in trader stock already carry an owner's brand: the trader's faction, or another one. + /// First applies the default purchase mode (buy as slave or colonist), before any early return, so + /// children, non-slave stock and pre-branded pawns get it too and the brand roll sees the final joinStatus. + /// [HarmonyPatch(typeof(ThingWithComps), nameof(ThingWithComps.PostGeneratedForTrader))] public static class Patch_TraderSlaveBrand { public static void Postfix(ThingWithComps __instance, TraderKindDef trader, Faction forFaction) { + BuyMode.ApplyDefaultPurchaseMode(__instance, trader); + if (!(__instance is Pawn pawn) || pawn.Dead || pawn.RaceProps == null || !pawn.RaceProps.Humanlike) return; if (pawn.ageTracker == null || !pawn.ageTracker.Adult || BrandUtility.IsBranded(pawn)) diff --git a/Source/BlaxSlaves/BuyMode.cs b/Source/BlaxSlaves/BuyMode.cs new file mode 100644 index 0000000..3194698 --- /dev/null +++ b/Source/BlaxSlaves/BuyMode.cs @@ -0,0 +1,397 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.CompilerServices; +using HarmonyLib; +using RimWorld; +using UnityEngine; +using Verse; +using Verse.AI.Group; +using Verse.Sound; + +namespace BlaxSlaves +{ + /// + /// "Buy as slave or colonist": the "Joins as slave / Joins as colonist" label on a pawn a trader + /// sells becomes a button that switches it, and new trader stock can start as one or the other. + /// Purchase itself stays vanilla: Pawn.PreTraded(PlayerBuys) reads guest.joinStatus, so flipping + /// joinStatus is all a switch needs. Replaces Trade as Slave or Colonist (Rhajiit.tradepurchasemode) + /// and stands down completely while that mod is active. + /// + public static class BuyMode + { + /// Vanilla's label rect in the trade row is 140 px wide; the button is never narrower. + public const float ButtonWidth = 140f; + + /// + /// The widest the button gets. Trader stock leaves the row's 75 px colony-count and 100 px sell-price + /// columns empty, so a long translation may grow the button into those 175 px, never past them. + /// + public const float MaxButtonWidth = 170f; + + // Room the label keeps from the button's edges: when sizing the button, and when cutting a label down. + private const float LabelPadding = 16f, TruncateMargin = 8f; + + // Rimdeed's pawn-hire trader: its pawns are hired, not bought, so joinStatus means nothing there. + private const string RimdeedTrader = "RD_PawnTrader"; + + // Vanilla caches both prices per Tradeable and only recomputes them while pricePlayerBuy <= 0. + // Null if a game update renamed the fields: then the button stays off rather than show stale prices. + private static readonly AccessTools.FieldRef PricePlayerBuy = PriceField("pricePlayerBuy"); + private static readonly AccessTools.FieldRef PricePlayerSell = PriceField("pricePlayerSell"); + + private static bool? standsDown; + + /// Trade as Slave or Colonist is active. The mod list can't change without a restart, so this is cached. + public static bool StandsDown => standsDown ??= Compat.IsActive(Compat.TradeAsSlaveOrColonist); + + /// The feature can work at all: Ideology active (no slaves otherwise) and no replaced mod in charge. + public static bool Available => ModsConfig.IdeologyActive && !StandsDown; + + /// The trade-window switch is on. + public static bool Enabled => Available && BlaxSlavesMod.Settings != null && BlaxSlavesMod.Settings.buyModeEnabled; + + private static AccessTools.FieldRef PriceField(string name) + { + try + { + return AccessTools.FieldRefAccess(name); + } + catch (Exception e) + { + Log.Warning("[Blax Slaves] Tradeable." + name + " not found, buying as slave or colonist is off: " + e.Message); + return null; + } + } + + // ---- trade window -------------------------------------------------------------------------- + + /// + /// A humanlike pawn the trader sells (held only by the trader, not a colony slave or prisoner). + /// Colony captives keep vanilla's ransom and slave icons. + /// + public static bool IsTraderStockPawn(Transferable trad, out Pawn pawn) + { + pawn = null; + if (!(trad is Tradeable t) || t.thingsColony.Count > 0 || t.thingsTrader.Count == 0) + return false; + if (!(t.thingsTrader[0].GetInnerIfMinified() is Pawn p) || p.guest == null || p.RaceProps == null || !p.RaceProps.Humanlike) + return false; + if (p.IsSlaveOfColony || p.IsPrisonerOfColony) + return false; + pawn = p; + return true; + } + + /// Traders whose pawns aren't bought into the colony the vanilla way. + public static bool TraderExcluded(ITrader trader) => TraderExcluded(trader?.TraderKind); + + public static bool TraderExcluded(TraderKindDef kind) => kind != null && kind.defName == RimdeedTrader; + + /// + /// Whether a click may switch this pawn. An unrecruitable pawn (unwavering loyalty on orbital and + /// settlement stock; vanilla makes caravan chattel recruitable through LordJob_TradeWithColony) is + /// refused in both directions, with a reason. Not only slave to colonist: vanilla rolls joinStatus + /// before SetupRecruitable, so some unrecruitable pawns are offered as colonists, and switching one + /// to slave could never be switched back (joinStatus is saved on the pawn, Cancel keeps it). + /// + public static AcceptanceReport CanToggle(Tradeable trad) + { + if (!Enabled || PricePlayerBuy == null || PricePlayerSell == null) + return false; + if (!IsTraderStockPawn(trad, out Pawn pawn)) + return false; + if (TradeSession.Active && TraderExcluded(TradeSession.trader)) + return false; + if (!pawn.guest.Recruitable) + { + return WouldJoinAsSlave(pawn) + ? "BlaxSlaves_BuyModeRefusesColonist".Translate(pawn.Named("PAWN")) + : "BlaxSlaves_BuyModeTermsFixed".Translate(pawn.Named("PAWN")); + } + return true; + } + + /// + /// Switches a trader's pawn between joining as slave and as colonist and reprices it. Returns + /// false (and changes nothing) when the switch isn't allowed. Public so tests can drive it without UI. + /// + public static bool Toggle(Tradeable trad) + { + if (!CanToggle(trad).Accepted) + return false; + IsTraderStockPawn(trad, out Pawn pawn); + pawn.guest.joinStatus = WouldJoinAsSlave(pawn) ? JoinStatus.JoinAsColonist : JoinStatus.JoinAsSlave; + InvalidatePrices(trad); + if (TradeSession.Active && TradeSession.deal != null) + TradeSession.deal.UpdateCurrencyCount(); + return true; + } + + /// + /// Drops vanilla's cached prices so the next GetPriceFor runs InitPriceDataIfNeeded again, with + /// every patch on it (the slave price sliders' postfix included). Never computes prices itself. + /// + public static void InvalidatePrices(Tradeable trad) + { + if (trad == null || PricePlayerBuy == null || PricePlayerSell == null) + return; + PricePlayerBuy(trad) = -1f; + PricePlayerSell(trad) = -1f; + } + + /// Pawn.PreTraded only makes JoinAsSlave a slave; anything else joins as a colonist. + public static bool WouldJoinAsSlave(Pawn pawn) => pawn?.guest != null && pawn.guest.joinStatus == JoinStatus.JoinAsSlave; + + private sealed class BothPrices + { + public JoinStatus status; + public float asColonist, asSlave; + } + + // Prices don't change within one deal (vanilla caches them for the whole session), so each + // Tradeable is priced both ways once per join status. Weak keys: a closed deal frees its entries. + private static readonly ConditionalWeakTable bothPrices = new ConditionalWeakTable(); + + /// + /// The buy price as colonist and as slave. The other price comes from a real InitPriceDataIfNeeded + /// run with joinStatus flipped for a moment, so other mods' price patches count. Needs a trade session. + /// + public static bool TryGetBothPrices(Tradeable trad, out float asColonist, out float asSlave) + { + asColonist = asSlave = 0f; + if (!TradeSession.Active || TradeSession.playerNegotiator == null || PricePlayerBuy == null || PricePlayerSell == null) + return false; + if (!IsTraderStockPawn(trad, out Pawn pawn)) + return false; + JoinStatus current = pawn.guest.joinStatus; + if (bothPrices.TryGetValue(trad, out BothPrices cached) && cached.status == current) + { + asColonist = cached.asColonist; + asSlave = cached.asSlave; + return true; + } + + bool slaveNow = WouldJoinAsSlave(pawn); + float now = trad.GetPriceFor(TradeAction.PlayerBuys); + float other; + try + { + pawn.guest.joinStatus = slaveNow ? JoinStatus.JoinAsColonist : JoinStatus.JoinAsSlave; + InvalidatePrices(trad); + other = trad.GetPriceFor(TradeAction.PlayerBuys); + } + finally + { + pawn.guest.joinStatus = current; + InvalidatePrices(trad); + } + trad.GetPriceFor(TradeAction.PlayerBuys); // cache the real status' prices again + + asColonist = slaveNow ? other : now; + asSlave = slaveNow ? now : other; + bothPrices.AddOrUpdate(trad, new BothPrices { status = current, asColonist = asColonist, asSlave = asSlave }); + return true; + } + + /// Vanilla's description, both prices, and what a click does or why it can't. + public static string Tooltip(Tradeable trad) + { + if (!IsTraderStockPawn(trad, out Pawn pawn)) + return null; + bool slave = WouldJoinAsSlave(pawn); + string tip = (slave ? "JoinsAsSlaveDesc" : "JoinsAsColonistDesc").Translate().Resolve(); + if (TryGetBothPrices(trad, out float asColonist, out float asSlave)) + tip += "\n\n" + "BlaxSlaves_BuyModePrices".Translate(asColonist.ToStringMoney(), asSlave.ToStringMoney()).Resolve(); + AcceptanceReport can = CanToggle(trad); + if (can.Accepted) + tip += "\n\n" + (slave ? "BlaxSlaves_BuyModeClickColonist" : "BlaxSlaves_BuyModeClickSlave").Translate(pawn.Named("PAWN")).Resolve(); + else if (!can.Reason.NullOrEmpty()) + tip += "\n\n" + can.Reason; + return tip; + } + + /// + /// The button width for a label this wide (the wider of both labels): label plus padding, at least + /// vanilla's 140 px, at most MaxButtonWidth. + /// + public static float ButtonWidthFor(float widestLabel) => Mathf.Clamp(widestLabel + LabelPadding, ButtonWidth, MaxButtonWidth); + + /// The label as it fits a button this wide, cut with "..." when the translation is too long. Uses the current font. + public static string FitLabel(string label, float buttonWidth) => label.Truncate(buttonWidth - TruncateMargin); + + // Width for the current language's labels and font, and the labels cut to it. Both labels size + // the button, so it doesn't change width when a click switches the label. + private static string sizedSlave, sizedColonist; + private static GameFont sizedFont; + private static float sizedWidth; + private static readonly Dictionary fittedLabels = new Dictionary(); + + /// The button width in the current language and font. Recomputed only when those change. + public static float CurrentButtonWidth() + { + string asSlave = "JoinsAsSlave".Translate(), asColonist = "JoinsAsColonist".Translate(); + if (asSlave != sizedSlave || asColonist != sizedColonist || Text.Font != sizedFont) + { + sizedSlave = asSlave; + sizedColonist = asColonist; + sizedFont = Text.Font; + sizedWidth = ButtonWidthFor(Mathf.Max(Text.CalcSize(asSlave).x, Text.CalcSize(asColonist).x)); + fittedLabels.Clear(); + } + return sizedWidth; + } + + /// + /// Draws the switch at curX, where vanilla draws its label, wide enough for the translation (see + /// MaxButtonWidth). A refused switch is greyed out and says why on click. A cut label shows in full + /// at the top of the tooltip. + /// + internal static void DrawButton(Tradeable trad, Pawn pawn, float x, float height) + { + float width = CurrentButtonWidth(); + string label = (WouldJoinAsSlave(pawn) ? "JoinsAsSlave" : "JoinsAsColonist").Translate(); + if (!fittedLabels.TryGetValue(label, out string shown)) + fittedLabels[label] = shown = FitLabel(label, width); + AcceptanceReport can = CanToggle(trad); + Rect button = new Rect(x, 0f, width, height).ContractedBy(0f, 2f); + + Color oldColor = GUI.color; + if (!can.Accepted) + GUI.color = Color.gray; + bool clicked = Widgets.ButtonText(button, shown); + GUI.color = oldColor; + + if (Mouse.IsOver(button)) + { + bool cut = shown != label; + TooltipHandler.TipRegion(button, () => cut ? label + "\n\n" + (Tooltip(trad) ?? "") : Tooltip(trad) ?? "", 0x5B1A0000 ^ pawn.thingIDNumber); + } + + if (!clicked) + return; + if (Toggle(trad)) + SoundDefOf.Tick_High.PlayOneShotOnCamera(); + else if (!can.Reason.NullOrEmpty()) + Messages.Message(can.Reason, MessageTypeDefOf.RejectInput, historical: false); + } + + // ---- default purchase mode ----------------------------------------------------------------- + + // Stock that "always colonist" skipped because it wasn't recruitable yet. Caravan wares are generated + // before IncidentWorker_TraderCaravanArrival gives the caravan its LordJob_TradeWithColony, and only + // that lord makes chattel recruitable, so Patch_BuyModeTradeLord finishes the job once the lord exists. + // Weak keys: stock that never gets such a lord (orbital, settlement, caravan meeting) is just dropped. + private static readonly ConditionalWeakTable awaitingTradeLord = new ConditionalWeakTable(); + private static readonly object Waiting = new object(); + + /// + /// The "new pawns in trader stock start as" setting. Called first in Patch_TraderSlaveBrand's postfix + /// on ThingWithComps.PostGeneratedForTrader, which runs after PawnGenerator finished (and with it + /// RandomizeJoinStatus and SetupRecruitable), so this overrides vanilla's 25/75 roll. "Always slave" + /// covers every humanlike pawn: being made a slave needs no recruitability. "Always colonist" covers + /// recruitable pawns only, as an unwaveringly loyal pawn won't join freely; one that turns recruitable + /// when its caravan's trade lord is made becomes a colonist then (ApplyColonistDefaultUnderTradeLord). + /// Works whether or not the trade-window switch is on, since it's a setting of its own. + /// + public static void ApplyDefaultPurchaseMode(Thing thing, TraderKindDef trader) + { + if (!(thing is Pawn pawn)) + return; + awaitingTradeLord.Remove(pawn); // regenerated (or redressed) stock is decided afresh + BlaxSlavesSettings s = BlaxSlavesMod.Settings; + if (s == null || s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseVanilla || !Available) + return; + if (pawn.Dead || pawn.guest == null || pawn.RaceProps == null || !pawn.RaceProps.Humanlike) + return; + if (trader != null && trader.defName == RimdeedTrader) + return; + if (s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseAlwaysSlave) + { + pawn.guest.joinStatus = JoinStatus.JoinAsSlave; + } + else if (s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseAlwaysColonist) + { + if (pawn.guest.Recruitable) + pawn.guest.joinStatus = JoinStatus.JoinAsColonist; + else + awaitingTradeLord.AddOrUpdate(pawn, Waiting); + } + } + + /// + /// "Always colonist" for caravan chattel: once a new lord's job is LordJob_TradeWithColony, every + /// owned pawn ApplyDefaultPurchaseMode skipped that the lord made recruitable now joins as a colonist. + /// Runs in the same incident that generated the stock, so it can't overwrite a player's switch. + /// Caravan meetings (Dialog_Trade with a world caravan) make no such lord and keep vanilla's roll. + /// + public static void ApplyColonistDefaultUnderTradeLord(Lord lord) + { + if (lord?.ownedPawns == null || !(lord.LordJob is LordJob_TradeWithColony)) + return; + BlaxSlavesSettings s = BlaxSlavesMod.Settings; + bool alwaysColonist = s != null && s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseAlwaysColonist && Available; + foreach (Pawn pawn in lord.ownedPawns) + { + if (pawn == null || !awaitingTradeLord.TryGetValue(pawn, out _)) + continue; + awaitingTradeLord.Remove(pawn); + if (!alwaysColonist || pawn.guest == null || pawn.IsSlaveOfColony || pawn.IsPrisonerOfColony) + continue; + if (pawn.guest.Recruitable) + pawn.guest.joinStatus = JoinStatus.JoinAsColonist; + } + } + } + + /// + /// Takes over the trader-stock branch of DrawCaptiveTradeInfo (TradeUI calls it only with Ideology) + /// and draws the switch where vanilla draws its label. Colony captives fall through to vanilla's + /// ransom and slave icons, so other mods' hooks on that branch keep working. + /// + [HarmonyPatch(typeof(TransferableUIUtility), nameof(TransferableUIUtility.DrawCaptiveTradeInfo))] + public static class Patch_BuyModeButton + { + private static bool loggedStandDown; + + /// No patch at all while Trade as Slave or Colonist is active, or without Ideology. + public static bool Prepare(MethodBase original) + { + if (BuyMode.StandsDown) + { + if (!loggedStandDown) + { + loggedStandDown = true; + Log.Message("[Blax Slaves] Trade as Slave or Colonist is active, so Blax Slaves' buy as slave or colonist stands down."); + } + return false; + } + return ModsConfig.IdeologyActive; + } + + public static bool Prefix(Transferable trad, ITrader trader, Rect rect, ref float curX) + { + if (!BuyMode.Enabled || BuyMode.TraderExcluded(trader)) + return true; + if (!BuyMode.IsTraderStockPawn(trad, out Pawn pawn)) + return true; + // Vanilla's label sits at curX without moving it; the colony-count and sell-price columns to its + // right are empty for stock, which is the room the button may grow into. + BuyMode.DrawButton((Tradeable)trad, pawn, curX, rect.height); + return false; + } + } + + /// + /// Finishes "always colonist" for caravan chattel once the caravan's LordJob_TradeWithColony exists + /// (see BuyMode.ApplyColonistDefaultUnderTradeLord). Not patched while Trade as Slave or Colonist is + /// active, or without Ideology. + /// + [HarmonyPatch(typeof(LordMaker), nameof(LordMaker.MakeNewLord))] + public static class Patch_BuyModeTradeLord + { + public static bool Prepare(MethodBase original) => !BuyMode.StandsDown && ModsConfig.IdeologyActive; + + public static void Postfix(Lord __result) => BuyMode.ApplyColonistDefaultUnderTradeLord(__result); + } +} diff --git a/Source/BlaxSlaves/Compat.cs b/Source/BlaxSlaves/Compat.cs new file mode 100644 index 0000000..f6f0aae --- /dev/null +++ b/Source/BlaxSlaves/Compat.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; +using Verse; + +namespace BlaxSlaves +{ + /// + /// Shared mod detection and the list of mods Blax Slaves replaces. The third-party patches for + /// slave harm (War Crimes Expanded 2, Harvest Organs Post Mortem, Hospitality) live in SlaveHarm.cs. + /// + public static partial class Compat + { + public const string TradeAsSlaveOrColonist = "Rhajiit.tradepurchasemode"; + public const string EverybodyBuysSlaves = "bblkepling.EverybodyBuysSlaves"; + public const string SyrMoreSlaves = "Mlie.SYRMoreSlaves"; + + /// + /// Active by packageId, local or Steam copy. ModsConfig.IsActive misses a mod that is installed + /// both ways (the Steam copy gets a "_steam" postfix), so nothing in Blax Slaves uses it. + /// + public static bool IsActive(string packageId) => ModLister.GetActiveModWithIdentifier(packageId, ignorePostfix: true) != null; + + public struct ReplacedMod + { + public string packageId; + public string name; + public string note; // translation key + + public ReplacedMod(string packageId, string name, string note) + { + this.packageId = packageId; + this.name = name; + this.note = note; + } + } + + /// Mods a Blax Slaves feature replaces, shown in the Compat tab when they are active. + public static readonly List Replaced = new List + { + new ReplacedMod(TradeAsSlaveOrColonist, "Trade as Slave or Colonist", "BlaxSlaves_CompatNoteBuyMode"), + new ReplacedMod(EverybodyBuysSlaves, "Everybody Buys Slaves", "BlaxSlaves_CompatNoteEverybodyBuys"), + new ReplacedMod(SyrMoreSlaves, "[SYR] More Slaves", "BlaxSlaves_CompatNoteMoreSlaves"), + }; + } +} diff --git a/Source/BlaxSlaves/Runaways.cs b/Source/BlaxSlaves/Runaways.cs index ad146f6..fd6dc10 100644 --- a/Source/BlaxSlaves/Runaways.cs +++ b/Source/BlaxSlaves/Runaways.cs @@ -57,6 +57,7 @@ namespace BlaxSlaves public GameComponent_BlaxRunaways(Game game) { pending.Clear(); + Siblings.ClearQueue(); } public void Register(Pawn pawn, Faction origin, SlaveInteractionModeDef mode, Map map) @@ -103,6 +104,7 @@ namespace BlaxSlaves public override void GameComponentTick() { + Siblings.Tick(); if (records.Count == 0 || Find.TickManager.TicksGame % CheckInterval != 0) return; int now = Find.TickManager.TicksGame; @@ -123,6 +125,7 @@ namespace BlaxSlaves { case DeliveryResult.Delivered: pending.Remove(r.pawn); + Siblings.CastesNotifyJoinedNextTick(r.pawn, Siblings.ReasonRunawayReturned); records.RemoveAt(i); break; case DeliveryResult.Retry: diff --git a/Source/BlaxSlaves/Siblings.cs b/Source/BlaxSlaves/Siblings.cs new file mode 100644 index 0000000..42de78d --- /dev/null +++ b/Source/BlaxSlaves/Siblings.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using HarmonyLib; +using Verse; + +namespace BlaxSlaves +{ + /// + /// Optional links to the other Blax mods (Blax Castes, Blax Zones). No assembly reference and no + /// hard dependency: their static APIs are bound by reflection at startup. A missing mod or method + /// leaves the delegate null and every call a silent no-op. The APIs only ever grow. + /// + public static class Siblings + { + public const string CastesId = "blax.castes"; + public const string ZonesId = "blax.zones"; + + public const string ReasonRunawayReturned = "blax.slaves.runawayReturned"; + + public static int CastesVersion { get; private set; } + public static int ZonesVersion { get; private set; } + + private static Action castesNotifyJoined; + private static Action castesHintJoinReason; + + public delegate bool TryFindDropSpotFn(Map map, Thing thing, out IntVec3 cell); + private static TryFindDropSpotFn zonesTryFindDropSpot; + + private static readonly List<(Verse.Pawn pawn, string reason, int tick)> notifyQueue = new List<(Verse.Pawn, string, int)>(); + private static bool warned; + + public static bool CastesBound => castesNotifyJoined != null || castesHintJoinReason != null; + public static bool ZonesBound => zonesTryFindDropSpot != null; + + public static void Init() + { + castesNotifyJoined = null; + castesHintJoinReason = null; + zonesTryFindDropSpot = null; + CastesVersion = 0; + ZonesVersion = 0; + try + { + if (Compat.IsActive(CastesId)) + { + Type api = AccessTools.TypeByName("BlaxCastes.CastesApi"); + if (api != null) + { + CastesVersion = ReadVersion(api); + castesNotifyJoined = Bind>(api, "NotifyJoined", typeof(Verse.Pawn), typeof(string)); + castesHintJoinReason = Bind>(api, "HintJoinReason", typeof(Verse.Pawn), typeof(string)); + } + } + if (Compat.IsActive(ZonesId)) + { + Type api = AccessTools.TypeByName("BlaxZones.ZonesApi"); + if (api != null) + { + ZonesVersion = ReadVersion(api); + zonesTryFindDropSpot = Bind(api, "TryFindDropSpot", typeof(Map), typeof(Thing), typeof(IntVec3).MakeByRefType()); + } + } + } + catch (Exception e) + { + Log.Warning("[Blax Slaves] Binding the other Blax mods failed, they stay unlinked: " + e.Message); + } + } + + public static string Describe() + { + string castes = Compat.IsActive(CastesId) ? (CastesBound ? "Blax Castes v" + CastesVersion : "Blax Castes (no API yet)") : null; + string zones = Compat.IsActive(ZonesId) ? (ZonesBound ? "Blax Zones v" + ZonesVersion : "Blax Zones (no API yet)") : null; + if (castes == null && zones == null) + return "BlaxSlaves_CompatNoSiblings".Translate(); + return castes != null && zones != null ? castes + ", " + zones : castes ?? zones; + } + + /// Tell Blax Castes about a join it can't see itself. Called one tick after the status is final. + public static void CastesNotifyJoined(Verse.Pawn pawn, string reason) => Call(castesNotifyJoined, pawn, reason); + + /// Tell Blax Castes why the next join of this pawn (this tick) happens. + public static void CastesHintJoinReason(Verse.Pawn pawn, string reason) => Call(castesHintJoinReason, pawn, reason); + + /// Queue a NotifyJoined for the next tick, after vanilla's status-change resets have run. + public static void CastesNotifyJoinedNextTick(Verse.Pawn pawn, string reason) + { + if (castesNotifyJoined == null || pawn == null || Find.TickManager == null) + return; + notifyQueue.Add((pawn, reason, Find.TickManager.TicksGame)); + } + + /// Drains the NotifyJoined queue. Called every tick from GameComponent_BlaxRunaways. + public static void Tick() + { + if (notifyQueue.Count == 0) + return; + int now = Find.TickManager.TicksGame; + for (int i = 0; i < notifyQueue.Count; i++) + { + var (pawn, reason, tick) = notifyQueue[i]; + if (tick >= now) + continue; + notifyQueue.RemoveAt(i--); + if (pawn != null && !pawn.Destroyed && !pawn.Dead) + CastesNotifyJoined(pawn, reason); + } + } + + public static void ClearQueue() => notifyQueue.Clear(); + + /// A delivery zone cell for this thing from Blax Zones, if it has one. + public static bool ZonesTryFindDropSpot(Map map, Thing thing, out IntVec3 cell) + { + cell = IntVec3.Invalid; + if (zonesTryFindDropSpot == null || map == null || thing == null) + return false; + try + { + return zonesTryFindDropSpot(map, thing, out cell) && cell.IsValid; + } + catch (Exception e) + { + WarnOnce(e); + cell = IntVec3.Invalid; + return false; + } + } + + private static void Call(Action fn, Verse.Pawn pawn, string reason) + { + if (fn == null || pawn == null) + return; + try + { + fn(pawn, reason); + } + catch (Exception e) + { + WarnOnce(e); + } + } + + private static void WarnOnce(Exception e) + { + if (warned) + return; + warned = true; + Log.Warning("[Blax Slaves] A call into another Blax mod failed (shown once): " + e); + } + + private static int ReadVersion(Type api) + { + object v = AccessTools.Property(api, "Version")?.GetValue(null) ?? AccessTools.Field(api, "Version")?.GetValue(null); + return v is int i ? i : 0; + } + + private static T Bind(Type api, string name, params Type[] args) where T : Delegate + { + MethodInfo m = AccessTools.Method(api, name, args); + if (m == null || !m.IsStatic) + return null; + try + { + return (T)Delegate.CreateDelegate(typeof(T), m); + } + catch (ArgumentException) + { + return null; + } + } + } +} diff --git a/Source/BlaxSlaves/SlaveHarm.cs b/Source/BlaxSlaves/SlaveHarm.cs index 46155bc..cbf9636 100644 --- a/Source/BlaxSlaves/SlaveHarm.cs +++ b/Source/BlaxSlaves/SlaveHarm.cs @@ -368,7 +368,7 @@ namespace BlaxSlaves // ---- other mods ------------------------------------------------------------------------------ - public static class Compat + public static partial class Compat { public static int Apply(Harmony harmony) { @@ -398,7 +398,6 @@ namespace BlaxSlaves return applied; } - private static bool IsActive(string packageId) => ModLister.GetActiveModWithIdentifier(packageId, ignorePostfix: true) != null; private static bool TryPatch(Harmony harmony, System.Reflection.MethodBase target, HarmonyMethod prefix, HarmonyMethod postfix, HarmonyMethod finalizer, string label) { diff --git a/Source/BlaxSlaves/SlavePrices.cs b/Source/BlaxSlaves/SlavePrices.cs new file mode 100644 index 0000000..93b4944 --- /dev/null +++ b/Source/BlaxSlaves/SlavePrices.cs @@ -0,0 +1,163 @@ +using System; +using HarmonyLib; +using RimWorld; +using UnityEngine; +using Verse; + +namespace BlaxSlaves +{ + /// + /// Slave price sliders (1.2). With Ideology, vanilla charges 60% of the colonist price for a pawn + /// that joins as a slave and pays 60% for any humanlike pawn the player sells. The settings + /// slaveBuyFactor and slaveSellFactor replace those two factors, and a hard cap keeps a captive's + /// sale price below what the best possible negotiator would pay for that pawn as a slave, so the + /// sliders never make buying low and selling high pay, between traders or by switching negotiators. + /// Raising only the sell slider never pays less than vanilla. Later pricing (appraisal, abolitionist buyers, + /// indenture) extends Patch_SlavePrices rather than adding another patch on the same method. + /// + public static class SlavePrices + { + /// Vanilla's slave factor (Tradeable.PriceFactor_JoinAsSlaveOrColonyPawn, private). + public const float VanillaFactor = 0.6f; + + /// + /// A captive sells for at most this share of what the best possible negotiator would pay for it as a + /// slave (see SellCap). + /// + public const float CapShareOfSlaveBuyPrice = 0.9f; + + /// Above this, vanilla rounds trade prices to whole silver (TradeUtility.GetPricePlayerBuy/Sell). + private const float RoundAbove = 99.5f; + + /// The slider steps by 5%, so a small tolerance is enough to call a factor vanilla. + public static bool IsVanilla(float factor) => Mathf.Abs(factor - VanillaFactor) < 0.001f; + + /// + /// True when either slider is off vanilla. At 60%/60% nothing is touched, cap included: vanilla's own + /// prices can exceed the cap (a negotiator's trade gain above about 21% at a settlement or 27% at a ship, + /// or a trader that sells humans cheap), and the defaults must stay exactly vanilla. + /// + public static bool AnyFactorChanged(BlaxSlavesSettings s) => + s != null && !(IsVanilla(s.slaveSellFactor) && IsVanilla(s.slaveBuyFactor)); + + /// + /// True when the buy slider is at vanilla or above. There a sale at vanilla's own price faces purchase prices + /// at or above vanilla's, so it opens no loop that vanilla doesn't already have. + /// + public static bool BuyAtOrAboveVanilla(float slaveBuyFactor) => + IsVanilla(slaveBuyFactor) || slaveBuyFactor > VanillaFactor; + + /// + /// The best trade gain any negotiator can reach: TradePriceImprovement's maxValue (39.5% in Core, where + /// StatWorker.FinalizeValue clamps the stat), or the current negotiator's gain if a mod pushes it past that. + /// + public static float BestNegotiatorGain(float priceGain_PlayerNegotiator) => + Mathf.Max(StatDefOf.TradePriceImprovement.maxValue, priceGain_PlayerNegotiator); + + /// + /// The most the player gets for selling this humanlike pawn: CapShareOfSlaveBuyPrice x what the best + /// possible negotiator (BestNegotiatorGain) would pay this trader for it as a slave at slaveBuyFactor, + /// with this trader's settlement gain. The trader's buy price type counts at most Normal, so a trader + /// that sells humans expensive doesn't lift the cap above a Normal trader's slave price. Independent of + /// who negotiates, so buying with a skilled negotiator and selling with a poor one gains nothing, and a + /// better negotiator never gets less. Whole silver above 99.5 like vanilla's prices, rounded down so it + /// never exceeds the share. + /// + public static float SellCap(Thing pawn, float priceFactorBuy_TraderPriceType, float priceGain_PlayerNegotiator, + float priceGain_Settlement, float slaveBuyFactor) + { + float priceType = Mathf.Min(priceFactorBuy_TraderPriceType, PriceType.Normal.PriceMultiplier()); + float slaveBuy = TradeUtility.GetPricePlayerBuy(pawn, priceType, slaveBuyFactor, + BestNegotiatorGain(priceGain_PlayerNegotiator), priceGain_Settlement); + float cap = slaveBuy * CapShareOfSlaveBuyPrice; + if (cap > RoundAbove) + cap = Mathf.Floor(cap); + return Mathf.Max(cap, TradeUtility.MinimumSellPrice); + } + } + + /// + /// Applies the slave price sliders where vanilla computes trade prices. Vanilla stores both prices already + /// clamped and rounded, so they are recomputed from the stored price types and gains with the new factors + /// instead of being scaled. The factor fields are what vanilla's GetPriceTooltip prints ("Slave: x50%" on + /// the buy side, "x 0.80 (Slave)" on the sell side), so the tooltip follows with no extra patch. + /// Fields are bound by Harmony's ___name injection: a renamed field fails this class at patch time + /// instead of throwing on every price lookup. + /// + [HarmonyPatch(typeof(Tradeable), "InitPriceDataIfNeeded")] + public static class Patch_SlavePrices + { + /// + /// Vanilla returns at once while pricePlayerBuy is above 0 (cached). Only a real compute resets the + /// factor fields, so the postfix acts only then. That keeps it idempotent: buy mode invalidates the + /// prices (sets them to -1) and calls in again, which runs vanilla and this postfix once more from scratch. + /// + public static void Prefix(float ___pricePlayerBuy, out bool __state) + { + __state = ___pricePlayerBuy <= 0f; + } + + public static void Postfix(Tradeable __instance, bool __state, + ref float ___pricePlayerBuy, ref float ___pricePlayerSell, + ref float ___priceFactorBuy_JoinAs, ref float ___priceFactorSell_HumanPawn, + float ___priceFactorBuy_TraderPriceType, float ___priceFactorSell_TraderPriceType, + float ___priceGain_PlayerNegotiator, float ___priceGain_Settlement, + float ___priceGain_DrugBonus, float ___priceGain_AnimalProduceBonus) + { + if (!__state || !ModsConfig.IdeologyActive || !TradeSession.Active) + return; + BlaxSlavesSettings s = BlaxSlavesMod.Settings; + if (!SlavePrices.AnyFactorChanged(s)) + return; + try + { + // AnyThing without its "lacks AnyThing" error for thing-less tradeables (royal favor). + if (!((__instance.FirstThingColony ?? __instance.FirstThingTrader) is Pawn pawn) + || pawn.RaceProps == null || !pawn.RaceProps.Humanlike) + return; + + // Only the factors vanilla just set to its slave value: a pawn joining as a colonist keeps 1 on the + // buy side, a humanlike without a guest tracker keeps 1 on the sell side. + bool slaveBuy = SlavePrices.IsVanilla(___priceFactorBuy_JoinAs); + bool humanSell = SlavePrices.IsVanilla(___priceFactorSell_HumanPawn); + if (!slaveBuy && !humanSell) + return; + float joinAs = slaveBuy ? s.slaveBuyFactor : ___priceFactorBuy_JoinAs; + float human = humanSell ? s.slaveSellFactor : ___priceFactorSell_HumanPawn; + + TradeCurrency currency = TradeSession.TradeCurrency; + float buy = TradeUtility.GetPricePlayerBuy(pawn, ___priceFactorBuy_TraderPriceType, joinAs, + ___priceGain_PlayerNegotiator, ___priceGain_Settlement); + float sell = TradeUtility.GetPricePlayerSell(pawn, ___priceFactorSell_TraderPriceType, human, + ___priceGain_PlayerNegotiator, ___priceGain_Settlement, ___priceGain_DrugBonus, + ___priceGain_AnimalProduceBonus, currency); + if (sell >= buy) + sell = buy; + // Favor traders pay in favor (RoyalFavorValue), which a silver cap can't bound. + if (humanSell && currency == TradeCurrency.Silver) + { + float cap = SlavePrices.SellCap(pawn, ___priceFactorBuy_TraderPriceType, + ___priceGain_PlayerNegotiator, ___priceGain_Settlement, s.slaveBuyFactor); + // A skilled seller's vanilla price can sit above the cap, so raising only the sell slider + // would pay less than vanilla. Vanilla's own 60% sale is the floor while slaves cost vanilla + // or more (it adds no loop vanilla lacks); below that the floor would reopen the loop. + if (SlavePrices.BuyAtOrAboveVanilla(s.slaveBuyFactor)) + cap = Mathf.Max(cap, TradeUtility.GetPricePlayerSell(pawn, ___priceFactorSell_TraderPriceType, + SlavePrices.VanillaFactor, ___priceGain_PlayerNegotiator, ___priceGain_Settlement, + ___priceGain_DrugBonus, ___priceGain_AnimalProduceBonus, currency)); + sell = Mathf.Min(sell, cap); + } + + ___priceFactorBuy_JoinAs = joinAs; + ___priceFactorSell_HumanPawn = human; + ___pricePlayerBuy = buy; + ___pricePlayerSell = sell; + } + catch (Exception e) + { + // The trade window asks for prices every frame; log once and leave vanilla's prices. + Log.ErrorOnce("[Blax Slaves] Slave price sliders failed, vanilla prices kept: " + e, 0x51A7E0); + } + } + } +} diff --git a/Source/BlaxSlaves/TimeAsSlave.cs b/Source/BlaxSlaves/TimeAsSlave.cs new file mode 100644 index 0000000..5519f3c --- /dev/null +++ b/Source/BlaxSlaves/TimeAsSlave.cs @@ -0,0 +1,337 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using HarmonyLib; +using RimWorld; +using UnityEngine; +using Verse; + +namespace BlaxSlaves +{ + /// + /// Counts time as a slave of the player's colony, per pawn, in ticks. This is deliberately not a RecordDef: + /// Pawn_RecordsTracker saves records as a list ordered by def index (DefMap), and def indices follow the + /// load order, so any RecordDef added by this mod would shift the records of every mod loaded after it + /// when Blax Slaves is added to or removed from a running save. Here the counter lives in its own save + /// node, keyed by pawn reference: adding the mod starts at zero, removing it drops only this node. + /// + /// Every CountInterval ticks it adds the whole interval to each living colony slave on any map (pawns in + /// containers, transporters on the ground and cryptosleep included), in a caravan, in a travelling + /// transporter or aboard a gravship in flight: the set PawnsFinder already keeps for colony slaves. + /// + public class GameComponent_TimeAsSlave : GameComponent + { + private Dictionary ticks = new Dictionary(); + private List keysWorkingList; + private List valuesWorkingList; + private readonly HashSet counted = new HashSet(); + private readonly List purgeList = new List(); + + public GameComponent_TimeAsSlave(Game game) + { + } + + public static GameComponent_TimeAsSlave Instance => Current.Game?.GetComponent(); + + /// Pawns with a counter: colony slaves now or earlier. Read-only, for tests and other mods. + public IReadOnlyCollection TrackedPawns => ticks.Keys; + + public int TicksOf(Pawn pawn) => pawn != null && ticks.TryGetValue(pawn, out int t) ? t : 0; + + public override void GameComponentTick() + { + if (Find.TickManager.TicksGame % TimeAsSlave.CountInterval == 0) + Count(TimeAsSlave.CountInterval); + } + + private void Count(int interval) + { + List slaves = PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_SlavesOfColony; + counted.Clear(); + for (int i = 0; i < slaves.Count; i++) + { + Pawn pawn = slaves[i]; + // The finder joins several lists; never count one pawn twice in a pass. + if (pawn == null || pawn.Dead || !counted.Add(pawn)) + continue; + ticks.TryGetValue(pawn, out int t); + ticks[pawn] = t + interval; + } + counted.Clear(); + } + + /// + /// Drops the counters of destroyed pawns (discarded ones included). They are saved nowhere, so their + /// references could not be loaded back. Dead slaves keep theirs while their corpse or world pawn exists. + /// Runs before every save and after every load; returns how many it dropped. + /// + public int Purge() + { + purgeList.Clear(); + foreach (KeyValuePair entry in ticks) + { + if (entry.Key == null || entry.Key.Destroyed) + purgeList.Add(entry.Key); + } + for (int i = 0; i < purgeList.Count; i++) + ticks.Remove(purgeList[i]); + int dropped = purgeList.Count; + purgeList.Clear(); + return dropped; + } + + public override void ExposeData() + { + if (Scribe.mode == LoadSaveMode.Saving) + Purge(); + // A reference that can't be resolved on load (a pawn lost without being destroyed) comes back as a + // null key. BuildDictionary skips null keys; logNullErrors: false keeps that out of the error log. + Scribe_Collections.Look(ref ticks, "ticks", LookMode.Reference, LookMode.Value, + ref keysWorkingList, ref valuesWorkingList, logNullErrors: false); + if (Scribe.mode == LoadSaveMode.PostLoadInit) + { + if (ticks == null) + ticks = new Dictionary(); + Purge(); + } + } + } + + public static class TimeAsSlave + { + public const string LineId = "blax.slaves.timeAsSlave"; + + /// Ticks between two counting passes (GenTicks.TickRareInterval); each pass adds the whole interval. + public const int CountInterval = 250; + + /// Ticks this pawn has spent as a slave of the colony since Blax Slaves was installed. + public static int Ticks(Pawn pawn) => GameComponent_TimeAsSlave.Instance?.TicksOf(pawn) ?? 0; + + /// "Enslaved for 23 days (tracked since install)", formatted like the Records tab. + public static string Label(Pawn pawn) => + "BlaxSlaves_TimeAsSlaveLine".Translate(Ticks(pawn).ToStringTicksToPeriod()); + + /// The Records tab row: label, value as vanilla formats time records, and tooltip. + public static string RecordLabel => "BlaxSlaves_TimeAsSlaveRecord".Translate().CapitalizeFirst(); + + public static string RecordValue(Pawn pawn) => Ticks(pawn).ToStringTicksToPeriod(); + + public static string RecordTooltip => "BlaxSlaves_TimeAsSlaveRecordDesc".Translate(); + + // The counter always counts; 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); + } + + /// + /// Adds "Time as a slave" at the end of the Records tab's time column, where a RecordDef row would sit, + /// 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. + /// + [HarmonyPatch(typeof(RecordsCardUtility), "DrawTimeRecords")] + public static class Patch_RecordsCardTimeAsSlave + { + private const float Indent = 8f; + private const float ValueShare = 0.45f; + + public static void Postfix(Rect leftRect, Pawn pawn, ref float __result) + { + if (pawn == null) + return; + try + { + __result += DrawRow(leftRect, __result, pawn); + } + catch (Exception e) + { + Log.ErrorOnce("[Blax Slaves] Records tab row failed: " + e, 0x6B1A61); + } + } + + private static float DrawRow(Rect column, float curY, Pawn pawn) + { + float width = column.width - Indent; + float valueWidth = width * ValueShare; + string value = TimeAsSlave.RecordValue(pawn); + var row = new Rect(column.x + Indent, column.y + curY, width, Text.CalcHeight(value, valueWidth)); + bool over = Mouse.IsOver(row); + if (over) + Widgets.DrawHighlight(row); + Rect labelRect = row; + labelRect.width -= valueWidth; + Widgets.Label(labelRect, TimeAsSlave.RecordLabel); + Rect valueRect = row; + valueRect.x = labelRect.xMax; + valueRect.width = valueWidth; + Widgets.Label(valueRect, value); + if (over) + TooltipHandler.TipRegion(row, new TipSignal(TimeAsSlave.RecordTooltip, 0x6B1A62)); + return row.height; + } + } + + /// + /// One extra line in the slave tab, drawn under "Slave price". Shown for colony slaves only unless + /// prisonersToo is set, because vanilla draws the slave price in the prisoner tab as well. + /// + public sealed class SlaveTabLine + { + public readonly string id; + public readonly Func label; + public readonly Func tooltip; + public readonly Func visible; + public readonly bool prisonersToo; + + public SlaveTabLine(string id, Func label, Func tooltip = null, + Func visible = null, bool prisonersToo = false) + { + this.id = id; + this.label = label; + this.tooltip = tooltip; + this.visible = visible; + this.prisonersToo = prisonersToo; + } + } + + /// + /// The one place that adds lines to the slave tab (time as a slave now; appraised value, persuasion, + /// loyalty and indenture term in later releases). Add a line once at startup; Add replaces a line with + /// the same id, so registering twice never doubles it. Each line runs in its own try/catch, so a broken + /// line logs once and the rest of the tab still draws. + /// + public static class SlaveTabLines + { + private static readonly List lines = new List { TimeAsSlave.Line }; + + public static IReadOnlyList All => lines; + + public static void Add(SlaveTabLine line) + { + if (line?.id == null || line.label == null) + return; + int i = lines.FindIndex(l => l.id == line.id); + if (i >= 0) + lines[i] = line; + else + lines.Add(line); + } + + public static bool Remove(string id) => lines.RemoveAll(l => l.id == id) > 0; + + public static bool Shows(SlaveTabLine line, Pawn pawn) + { + if (line == null || pawn?.guest == null) + return false; + bool colonySlave = pawn.guest.IsSlave && pawn.Faction != null && pawn.Faction.IsPlayer; + bool colonyPrisoner = pawn.guest.IsPrisoner && pawn.guest.HostFaction != null && pawn.guest.HostFaction.IsPlayer; + if (!colonySlave && !(line.prisonersToo && colonyPrisoner)) + return false; + return line.visible == null || line.visible(pawn); + } + + /// The labels the tab would show for this pawn, in order. Needs no GUI, so tests can read it. + public static List LabelsFor(Pawn pawn) + { + var result = new List(); + foreach (SlaveTabLine line in lines) + { + try + { + if (!Shows(line, pawn)) + continue; + string label = line.label(pawn); + if (!label.NullOrEmpty()) + result.Add(label); + } + catch (Exception e) + { + LogOnce(line, e); + } + } + return result; + } + + internal static void Draw(Listing_Standard listing, Pawn pawn) + { + if (listing == null || pawn == null) + return; + for (int i = 0; i < lines.Count; i++) + { + SlaveTabLine line = lines[i]; + try + { + if (!Shows(line, pawn)) + continue; + string label = line.label(pawn); + if (label.NullOrEmpty()) + continue; + // Listing_Standard.Label measures the wrapped height, and ITab_Pawn_Visitor.FillTab sizes + // the tab from listing.CurHeight afterwards, so a long translation grows the tab instead + // of being cut off. + Rect rect = listing.Label(label); + if (line.tooltip != null && Mouse.IsOver(rect)) + { + Widgets.DrawHighlight(rect); + string tip = line.tooltip(pawn); + if (!tip.NullOrEmpty()) + TooltipHandler.TipRegion(rect, tip); + } + } + catch (Exception e) + { + LogOnce(line, e); + } + } + } + + private static void LogOnce(SlaveTabLine line, Exception e) => + Log.ErrorOnce("[Blax Slaves] Slave tab line " + line?.id + " failed: " + e, 0x6B1A60 ^ (line?.id?.GetHashCode() ?? 0)); + } + + /// + /// Draws the extra slave tab lines right after vanilla's "Slave price". DoSlavePriceListing is private + /// and also runs in the prisoner tab; SlaveTabLines decides per line who sees it. + /// + [HarmonyPatch(typeof(ITab_Pawn_Visitor), "DoSlavePriceListing")] + public static class Patch_SlaveTabLines + { + private static Func selPawn; + private static bool bound; + + public static void Postfix(ITab_Pawn_Visitor __instance, Listing_Standard listing) + { + SlaveTabLines.Draw(listing, PawnOf(__instance)); + } + + /// + /// The pawn the tab shows. ITab.SelPawn is protected (and virtual), so it is bound once by + /// reflection; if that ever fails, the single selected thing is what vanilla's getter returns. + /// + public static Pawn PawnOf(ITab tab) + { + if (!bound) + { + bound = true; + try + { + MethodInfo getter = AccessTools.PropertyGetter(typeof(ITab), "SelPawn"); + if (getter != null) + selPawn = AccessTools.MethodDelegate>(getter); + } + catch (Exception e) + { + Log.Warning("[Blax Slaves] ITab.SelPawn not found, the slave tab uses the selection instead: " + e.Message); + selPawn = null; + } + } + if (tab != null && selPawn != null) + return selPawn(tab); + return Find.Selector?.SingleSelectedThing as Pawn; + } + } +} diff --git a/Source/BlaxSlaves/TraderBuyers.cs b/Source/BlaxSlaves/TraderBuyers.cs new file mode 100644 index 0000000..ccb2bf3 --- /dev/null +++ b/Source/BlaxSlaves/TraderBuyers.cs @@ -0,0 +1,409 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using HarmonyLib; +using RimWorld; +using UnityEngine; +using Verse; + +namespace BlaxSlaves +{ + /// + /// The buy-only generator Blax Slaves adds to trader kinds that would otherwise turn captives + /// away. Its own subclass so it can be told apart from a vanilla or modded StockGenerator_BuySlaves + /// (Royalty's tribute collector, Everybody Buys Slaves) and removed again without touching theirs. + /// + public class StockGenerator_BlaxBuySlaves : StockGenerator_BuySlaves + { + } + + /// + /// "Every trader buys slaves" and "Slave stock ignores colony size". Both change trader defs: once at + /// startup and again whenever the settings window closes (BlaxSlavesMod.SettingsChanged, never raised + /// during a trade session). Turning a setting off undoes exactly what it changed, so the defs end up + /// as the game and other mods left them. + /// + [StaticConstructorOnStartup] + public static class TraderBuyers + { + /// + /// Hospitality's guest "trader" kind: guests shop in your colony, they don't buy pawns. Matched by + /// defName, the same way Everybody Buys Slaves skips it. + /// + public const string HospitalityGuestKind = "Guest"; + + /// Hospitality's packageId. With it, visitor groups arrive as its guests, who never buy captives. + public const string HospitalityPackageId = "Orion.Hospitality"; + + // Private in vanilla. Null if a game update renames it; the stock feature then stands down. + private static readonly AccessTools.FieldRef respectPopulationIntent = BindRespectPopulationIntent(); + + // Each slave generator's own respectPopulationIntent, recorded the first time Apply sees it. + private static readonly Dictionary originalRespect = new Dictionary(); + + // Generators whose HandlesThingDef threw, so the warning is logged once per generator. + private static readonly HashSet warnedGenerators = new HashSet(); + + static TraderBuyers() + { + Apply(); + BlaxSlavesMod.SettingsChanged += Apply; + } + + /// + /// Brings every TraderKindDef in line with the current settings. Safe to call any number of times: + /// each trader kind ends up with at most one of our generators, and only where nothing else buys humans. + /// + public static void Apply() + { + // The settings window works its notes out again the next time it opens. + notes = null; + BlaxSlavesSettings s = BlaxSlavesMod.Settings; + if (s == null) + return; + int added = 0, removed = 0, flags = 0; + try + { + ApplyBuyers(s, ref added, ref removed); + } + catch (Exception e) + { + Log.Error("[Blax Slaves] Every trader buys slaves: applying failed: " + e); + } + try + { + flags = ApplyStock(s); + } + catch (Exception e) + { + Log.Error("[Blax Slaves] Slave stock ignores colony size: applying failed: " + e); + } + if (added + removed + flags > 0) + Log.Message("[Blax Slaves] Trader kinds: " + added + " now buy captives, " + removed + " stopped, " + + flags + " slave stocks changed their colony-size rule."); + } + + // ---- every trader buys slaves ---------------------------------------------------------------- + + /// Hospitality's guest kind never buys pawns. + public static bool IsExcluded(TraderKindDef def) => def == null || def.defName == HospitalityGuestKind; + + /// Trader kinds some faction sends as visitors. They follow visitorsBuySlaves instead of allTradersBuySlaves. + public static HashSet VisitorKinds() + { + var set = new HashSet(); + foreach (FactionDef f in DefDatabase.AllDefsListForReading) + { + if (f?.visitorTraderKinds == null) + continue; + foreach (TraderKindDef k in f.visitorTraderKinds) + if (k != null) + set.Add(k); + } + return set; + } + + /// + /// Whether any generator other than ours buys humans. Found through HandlesThingDef, never by class + /// name, so modded humanlike generators (and Everybody Buys Slaves' XML) count and we never add a second. + /// + public static bool OthersBuyHumans(TraderKindDef def) + { + List gens = def?.stockGenerators; + if (gens == null) + return false; + for (int i = 0; i < gens.Count; i++) + { + StockGenerator g = gens[i]; + if (g != null && !(g is StockGenerator_BlaxBuySlaves) && Handles(g, ThingDefOf.Human)) + return true; + } + return false; + } + + /// Whether this trader kind should carry our generator under these settings. + public static bool WantsOurBuyer(TraderKindDef def, BlaxSlavesSettings s, HashSet visitorKinds) + { + if (s == null || IsExcluded(def) || def.stockGenerators == null) + return false; + bool on = visitorKinds != null && visitorKinds.Contains(def) ? s.visitorsBuySlaves : s.allTradersBuySlaves; + return on && !OthersBuyHumans(def); + } + + private static void ApplyBuyers(BlaxSlavesSettings s, ref int added, ref int removed) + { + HashSet visitors = VisitorKinds(); + foreach (TraderKindDef def in DefDatabase.AllDefsListForReading) + { + List gens = def?.stockGenerators; + if (gens == null) + continue; + bool want = WantsOurBuyer(def, s, visitors); + int ours = 0; + for (int i = 0; i < gens.Count; i++) + if (gens[i] is StockGenerator_BlaxBuySlaves) + ours++; + if (want && ours == 1) + continue; + if (ours > 0) + removed += gens.RemoveAll(g => g is StockGenerator_BlaxBuySlaves); + if (want) + { + // Appended last, so PriceTypeFor and the stock generators already there keep their order. + var gen = new StockGenerator_BlaxBuySlaves(); + gen.ResolveReferences(def); + gens.Add(gen); + added++; + } + } + } + + private static bool Handles(StockGenerator g, ThingDef td) + { + try + { + return g.HandlesThingDef(td); + } + catch (Exception e) + { + if (warnedGenerators.Add(g)) + Log.Warning("[Blax Slaves] " + g.GetType().FullName + " on " + g.trader?.defName + " threw in HandlesThingDef(" + td?.defName + "): " + e.Message); + return false; + } + } + + // ---- settings-window notes ------------------------------------------------------------------- + + /// When the Trade tab warns that a "buy" checkbox can't take buyers away. + public struct SettingNotes + { + /// Everybody Buys Slaves' own buyers sit on non-visitor kinds, so "every trader" off leaves them buying. + public bool everybodyBuysTraders; + + /// The same on visitor kinds. False when XML Extensions' "exclude visitors" kept them out. + public bool everybodyBuysVisitors; + + /// Hospitality runs visitor groups as its guests, so "visitors" only reaches other visitors. + public bool hospitality; + } + + private static SettingNotes? notes; + + /// + /// The notes for the current defs. DoTrade reads this every frame, so it walks the defs once and keeps + /// the result until Apply runs again (each time the settings window closes). + /// + public static SettingNotes Notes => notes ?? (notes = FindNotes(Compat.IsActive(Compat.EverybodyBuysSlaves), Compat.IsActive(HospitalityPackageId))).Value; + + /// + /// Works the notes out from the defs, not just from which mods are active: a buyer must actually sit on + /// that group of kinds. The mod flags are parameters so the tests can try both. + /// + public static SettingNotes FindNotes(bool everybodyBuysActive, bool hospitalityActive) + { + var n = new SettingNotes { hospitality = hospitalityActive }; + if (!everybodyBuysActive) + return n; + HashSet visitors = VisitorKinds(); + foreach (TraderKindDef def in DefDatabase.AllDefsListForReading) + { + if (IsExcluded(def) || !HasPlainBuyer(def)) + continue; + if (visitors.Contains(def)) + n.everybodyBuysVisitors = true; + else + n.everybodyBuysTraders = true; + } + return n; + } + + /// + /// Carries a generator of exactly StockGenerator_BuySlaves, the class Everybody Buys Slaves' XML adds. + /// Our subclass doesn't count, and neither do other humanlike generators such as the slavers' StockGenerator_Slaves. + /// + public static bool HasPlainBuyer(TraderKindDef def) + { + List gens = def?.stockGenerators; + if (gens == null) + return false; + for (int i = 0; i < gens.Count; i++) + if (gens[i] != null && gens[i].GetType() == typeof(StockGenerator_BuySlaves)) + return true; + return false; + } + + // ---- anti-slavery traders -------------------------------------------------------------------- + + /// + /// Any of the faction's ideoligions rejects slavery, the same rule vanilla's slave stock and slaver + /// caravans use (all ideoligions must approve). Factions without ideoligions don't reject. + /// + public static bool RejectsSlavery(Faction faction) + { + if (faction?.ideos == null) + return false; + foreach (Ideo ideo in faction.ideos.AllIdeos) + if (ideo != null && !ideo.IdeoApprovesOfSlavery()) + return true; + return false; + } + + /// + /// Refuse mode only: true when this trader turns down this colony slave or prisoner because its + /// faction rejects slavery. Their own people are bought back (ransom), factionless traders always + /// buy. Patch_TraderRefusesCaptiveReason reads it to explain the greyed-out row. + /// + public static bool TraderRefusesCaptive(Pawn pawn, ITrader trader) + { + BlaxSlavesSettings s = BlaxSlavesMod.Settings; + if (s == null || s.antiSlaveryTraders != BlaxSlavesSettings.AntiSlaveryRefuse || !ModsConfig.IdeologyActive) + return false; + if (pawn == null || trader == null || pawn.RaceProps == null || !pawn.RaceProps.Humanlike) + return false; + if (!pawn.IsSlaveOfColony && !pawn.IsPrisonerOfColony) + return false; + Faction faction = trader.Faction; + if (faction == null || faction.IsPlayer || pawn.HomeFaction == faction) + return false; + return RejectsSlavery(faction); + } + + // ---- slave stock ignores colony size --------------------------------------------------------- + + /// Whether the colony-size field could be bound (false after a game update renamed it). + public static bool StockFeatureAvailable => respectPopulationIntent != null; + + private static int ApplyStock(BlaxSlavesSettings s) + { + if (respectPopulationIntent == null) + return 0; + int changed = 0; + foreach (TraderKindDef def in DefDatabase.AllDefsListForReading) + { + List gens = def?.stockGenerators; + if (gens == null) + continue; + foreach (StockGenerator g in gens) + { + if (!(g is StockGenerator_Slaves slaves)) + continue; + if (!originalRespect.TryGetValue(slaves, out bool original)) + { + original = respectPopulationIntent(slaves); + originalRespect[slaves] = original; + } + // Only the flag: slaveKindDef (Royalty's Slave_Empire) and vanilla's ideoligion check stay. + bool target = !s.slaveStockIgnoresColonySize && original; + ref bool field = ref respectPopulationIntent(slaves); + if (field != target) + { + field = target; + changed++; + } + } + } + return changed; + } + + private static AccessTools.FieldRef BindRespectPopulationIntent() + { + try + { + return AccessTools.FieldRefAccess("respectPopulationIntent"); + } + catch (Exception e) + { + Log.Warning("[Blax Slaves] StockGenerator_Slaves.respectPopulationIntent not found, slave stock keeps vanilla's colony-size rule: " + e.Message); + return null; + } + } + } + + /// + /// Refuse mode: traders whose faction rejects slavery won't take colony slaves or prisoners, except + /// their own people. Postfix on the base getter (Tradeable_Pawn doesn't override it), so vanilla's + /// trade row greys the pawn out with "won't trade" instead of hiding it. Gifts stay untouched. + /// + [HarmonyPatch(typeof(Tradeable), nameof(Tradeable.TraderWillTrade), MethodType.Getter)] + public static class Patch_AntiSlaveryTradersRefuse + { + public static void Postfix(Tradeable __instance, ref bool __result) + { + // Runs for every trade row each frame: the setting check comes first and is cheap. + if (!__result || BlaxSlavesMod.Settings == null || BlaxSlavesMod.Settings.antiSlaveryTraders != BlaxSlavesSettings.AntiSlaveryRefuse) + return; + if (TradeSession.giftMode) + return; + if (__instance?.FirstThingColony is Pawn pawn && TraderBuyers.TraderRefusesCaptive(pawn, TradeSession.trader)) + __result = false; + } + } + + /// + /// Refuse mode: says why a colony captive's row reads "won't trade". The reason is a tooltip on vanilla's + /// "won't trade" text, the way vanilla explains a negotiator who won't sell slaves, and on vanilla's slave + /// icon next to the name. A postfix, so it still runs when another mod's prefix skips the original, and it + /// never skips anything itself; vanilla's icon and curX stay as they are. No stand-down for Trade as Slave + /// or Colonist: that mod only takes over the trader-stock branch, and the refuse gate never stands down. + /// + [HarmonyPatch(typeof(TransferableUIUtility), nameof(TransferableUIUtility.DrawCaptiveTradeInfo))] + public static class Patch_TraderRefusesCaptiveReason + { + // TradeUI.DrawTradeableRow in row-group coordinates: 175 px of trader count and price at the right edge, + // then the 240 px column where "won't trade" is written. Vanilla's captive icons are 24 px wide. + public const float TraderColumnsWidth = 175f, WillNotTradeWidth = 240f, CaptiveIconWidth = 24f; + + /// TradeUI calls DrawCaptiveTradeInfo only with Ideology, and refuse mode needs it too. + public static bool Prepare(MethodBase original) => ModsConfig.IdeologyActive; + + /// Only records curX, so the postfix can tell whether the original drew its icon. + public static void Prefix(ref float curX, out float __state) => __state = curX; + + public static void Postfix(Transferable trad, ITrader trader, Rect rect, ref float curX, float __state) + { + // Runs for every row each frame: the setting check first, then hover, the ideoligion walk last. + BlaxSlavesSettings s = BlaxSlavesMod.Settings; + if (s == null || s.antiSlaveryTraders != BlaxSlavesSettings.AntiSlaveryRefuse) + return; + Rect willNot = WillNotTradeRect(rect); + // Vanilla's slave icon sits where curX now points, if the original moved it left by one icon. + Rect icon = new Rect(curX, (rect.height - CaptiveIconWidth) / 2f, CaptiveIconWidth, CaptiveIconWidth); + bool overText = Mouse.IsOver(willNot); + bool overIcon = Mathf.Approximately(__state - curX, CaptiveIconWidth) && Mouse.IsOver(icon); + if (!overText && !overIcon) + return; + if (!Explains(trad, trader, out Pawn pawn)) + return; + TaggedString reason = Reason(pawn, trader); + if (overText) + { + Widgets.DrawHighlight(willNot); + TooltipHandler.TipRegion(willNot, reason); + } + if (overIcon) + TooltipHandler.TipRegion(icon, reason); + } + + /// Where TradeUI writes "won't trade" in a row of this size. + public static Rect WillNotTradeRect(Rect row) => + new Rect(row.width - TraderColumnsWidth - WillNotTradeWidth, 0f, WillNotTradeWidth, row.height); + + /// + /// True when this row is a colony captive greyed out because the trader's faction rejects slavery. Not in + /// gift mode, where the gate stays out. Reads TraderWillTrade last, so a row another mod re-enabled gets no reason. + /// + public static bool Explains(Transferable trad, ITrader trader, out Pawn pawn) + { + pawn = null; + if (TradeSession.giftMode || !(trad is Tradeable t) || !(t.FirstThingColony is Pawn p)) + return false; + if (!TraderBuyers.TraderRefusesCaptive(p, trader) || t.TraderWillTrade) + return false; + pawn = p; + return true; + } + + public static TaggedString Reason(Pawn pawn, ITrader trader) => + "BlaxSlaves_TraderRefusesCaptive".Translate(trader.Faction.Named("FACTION"), pawn.Named("PAWN")); + } +} diff --git a/Tests/BlaxSlavesTests/Source/BuyModeTests.cs b/Tests/BlaxSlavesTests/Source/BuyModeTests.cs new file mode 100644 index 0000000..78b98ed --- /dev/null +++ b/Tests/BlaxSlavesTests/Source/BuyModeTests.cs @@ -0,0 +1,823 @@ +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; +using Verse.AI.Group; + +namespace BlaxSlavesTests +{ + /// + /// "Buy as slave or colonist" (BuyMode.cs): the trade-window switch on pawns a trader sells, its + /// repricing through vanilla's InitPriceDataIfNeeded, and the default purchase mode applied first in + /// Patch_TraderSlaveBrand. Stock comes from a real slave ship (Orbital_PirateMerchant) and trades run + /// through TradeSession.SetupWith, as the comms console does. BuyMode.Toggle stands in for the click. + /// + public static class BuyModeTests + { + private const string HarmonyId = "blax.slaves"; + private const string SlaveShipDef = "Orbital_PirateMerchant"; + private const string CaravanSlaverDef = "Caravan_Outlander_PirateMerchant"; + + // Vanilla's Tradeable.InitPriceDataIfNeeded prices a JoinAsSlave pawn at 0.6 of the colonist price. + // slaveBuyFactor 0.6 is the settings default and equals vanilla, so tests pin it there. + private const float VanillaSlaveBuyFactor = 0.6f; + + // ---- patch and stand-down -------------------------------------------------------- + + [BlaxTest("buy-mode: switch prefix sits on DrawCaptiveTradeInfo, or stands down for Trade as Slave or Colonist")] + public static void PatchAppliedOrStandsDown() + { + MethodInfo target = AccessTools.Method(typeof(TransferableUIUtility), nameof(TransferableUIUtility.DrawCaptiveTradeInfo)); + T.NotNull(target, "TransferableUIUtility.DrawCaptiveTradeInfo"); + var info = Harmony.GetPatchInfo(target); + bool ours = info != null && info.Prefixes.Any(p => p.owner == HarmonyId && p.PatchMethod?.DeclaringType == typeof(Patch_BuyModeButton)); + string owners = info == null ? "none" : string.Join(", ", info.Prefixes.Select(p => p.owner).Distinct()); + T.Info("DrawCaptiveTradeInfo prefix owners: " + owners); + + if (Compat.IsActive(Compat.TradeAsSlaveOrColonist)) + { + T.Check(!ours, "Trade as Slave or Colonist is active, but Patch_BuyModeButton still 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)), + "Trade as Slave or Colonist is active, but Patch_BuyModeTradeLord still patched LordMaker.MakeNewLord"); + T.Check(BuyMode.StandsDown && !BuyMode.Available && !BuyMode.Enabled, "BuyMode does not report standing down"); + + Fixtures.Settings.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysSlave; + Pawn p = StockPawn(JoinStatus.JoinAsColonist); + p.PostGeneratedForTrader(Def(CaravanSlaverDef), Fixtures.Map.Tile, AnyFaction()); + T.Equal(JoinStatus.JoinAsColonist, p.guest.joinStatus, "joinStatus after 'always slave' while standing down"); + T.Check(!BuyMode.Toggle(LooseTradeable(p)), "Toggle switched a pawn while standing down"); + return; + } + T.Check(ours, "no blax.slaves prefix from Patch_BuyModeButton on DrawCaptiveTradeInfo (prefix owners: " + owners + ")"); + T.Check(BuyMode.Available && BuyMode.Enabled, "BuyMode not available although Ideology is active and Trade as Slave or Colonist is not"); + + MethodInfo makeLord = AccessTools.Method(typeof(LordMaker), nameof(LordMaker.MakeNewLord)); + T.NotNull(makeLord, "LordMaker.MakeNewLord"); + var lordInfo = Harmony.GetPatchInfo(makeLord); + T.Check(lordInfo != null && lordInfo.Postfixes.Any(p => p.owner == HarmonyId && p.PatchMethod?.DeclaringType == typeof(Patch_BuyModeTradeLord)), + "no blax.slaves postfix from Patch_BuyModeTradeLord on LordMaker.MakeNewLord ('always colonist' for caravan chattel)"); + } + + // ---- 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")] + public static void ToggleRepricesAndUpdatesSilver() + { + RequireAvailable(); + Fixtures.Settings.slaveBuyFactor = VanillaSlaveBuyFactor; + WithSlaveShip(5101, (ship, stock) => InSession(ship, deal => + { + Pawn pawn = PriciestPawn(stock); + Tradeable tr = TradeableOf(deal, pawn); + pawn.guest.Recruitable = true; + pawn.guest.joinStatus = JoinStatus.JoinAsColonist; + BuyMode.InvalidatePrices(tr); + + tr.ForceToSource(1); + T.Equal(TradeAction.PlayerBuys, tr.ActionToDo, "trade action for one trader pawn moved to the colony"); + deal.UpdateCurrencyCount(); + Tradeable silver = deal.CurrencyTradeable; + T.NotNull(silver, "the deal's currency tradeable"); + float asColonist = tr.GetPriceFor(TradeAction.PlayerBuys); + if (asColonist < 100f) T.Skip($"priciest stock pawn {Who(pawn)} costs only {asColonist}, too cheap for a 1% ratio check"); + T.Equal(-silver.CostToInt(asColonist), silver.CountToTransferToSource, "silver to pay before the switch"); + + T.Check(BuyMode.Toggle(tr), "Toggle refused a recruitable colonist-to-be in slave ship stock"); + T.Equal(JoinStatus.JoinAsSlave, pawn.guest.joinStatus, "joinStatus after one switch"); + float asSlave = tr.GetPriceFor(TradeAction.PlayerBuys); + float ratio = asColonist / asSlave, expected = 1f / VanillaSlaveBuyFactor; + T.Info($"{Who(pawn)}: colonist {asColonist}, slave {asSlave}, ratio {ratio:0.0000} (expected {expected:0.0000})"); + T.Check(Math.Abs(ratio / expected - 1f) <= 0.01f, $"colonist/slave price ratio {ratio:0.0000}, expected {expected:0.0000} within 1%"); + T.Equal(-silver.CostToInt(asSlave), silver.CountToTransferToSource, "silver to pay after the switch (UpdateCurrencyCount)"); + + T.Check(BuyMode.Toggle(tr), "Toggle refused switching back to colonist"); + T.Equal(JoinStatus.JoinAsColonist, pawn.guest.joinStatus, "joinStatus after switching back"); + T.Check(Math.Abs(tr.GetPriceFor(TradeAction.PlayerBuys) - asColonist) < 0.01f, "price after switching back differs from the first colonist price"); + T.Equal(-silver.CostToInt(asColonist), silver.CountToTransferToSource, "silver to pay after switching back"); + })); + } + + [BlaxTest("buy-mode: an unwaveringly loyal slave ship pawn can't be switched either way, and says why")] + public static void UnwaveringRefusesColonist() + { + RequireAvailable(); + WithUnwavering(() => WithSlaveShip(5102, (ship, stock) => InSession(ship, deal => + { + Pawn pawn = stock.FirstOrDefault(p => + { + p.guest.Recruitable = false; + return !p.guest.Recruitable; + }); + if (pawn == null) T.Skip("every slave ship pawn stays recruitable (former colonists?), nothing to refuse"); + Tradeable tr = TradeableOf(deal, pawn); + pawn.guest.joinStatus = JoinStatus.JoinAsSlave; + BuyMode.InvalidatePrices(tr); + float price = tr.GetPriceFor(TradeAction.PlayerBuys); + + AcceptanceReport can = BuyMode.CanToggle(tr); + T.Check(!can.Accepted, "CanToggle accepted switching an unrecruitable pawn to colonist"); + T.Check(!can.Reason.NullOrEmpty(), "the refusal has no reason for the tooltip and message"); + T.Check(!BuyMode.Toggle(tr), "Toggle switched an unrecruitable pawn to colonist"); + T.Equal(JoinStatus.JoinAsSlave, pawn.guest.joinStatus, "joinStatus after a refused switch"); + T.Check(Math.Abs(tr.GetPriceFor(TradeAction.PlayerBuys) - price) < 0.01f, "price changed after a refused switch"); + string tip = BuyMode.Tooltip(tr); + T.Check(tip != null && tip.Contains(can.Reason), "tooltip does not say why: " + tip); + + // Vanilla can roll JoinAsColonist before SetupRecruitable runs. Switching such a pawn to slave + // could never be undone (the slave-to-colonist refusal above), so vanilla's offer stays as it is. + pawn.guest.joinStatus = JoinStatus.JoinAsColonist; + BuyMode.InvalidatePrices(tr); + float colonistPrice = tr.GetPriceFor(TradeAction.PlayerBuys); + AcceptanceReport toSlave = BuyMode.CanToggle(tr); + T.Check(!toSlave.Accepted, "CanToggle accepted switching an unrecruitable colonist-to-be to slave, which could not be switched back"); + T.Check(!toSlave.Reason.NullOrEmpty(), "the colonist-to-be's refusal has no reason for the tooltip and message"); + T.Check(toSlave.Reason != can.Reason, "the colonist-to-be's refusal says the pawn refuses to join as a colonist: " + toSlave.Reason); + T.Check(!BuyMode.Toggle(tr), "Toggle switched an unrecruitable colonist-to-be to slave"); + T.Equal(JoinStatus.JoinAsColonist, pawn.guest.joinStatus, "colonist-to-be's joinStatus after a refused switch"); + T.Check(Math.Abs(tr.GetPriceFor(TradeAction.PlayerBuys) - colonistPrice) < 0.01f, "colonist-to-be's price changed after a refused switch"); + string colonistTip = BuyMode.Tooltip(tr); + T.Check(colonistTip != null && colonistTip.Contains(toSlave.Reason), "colonist-to-be's tooltip does not say why: " + colonistTip); + + // Control: the same pawn, recruitable, may switch, so Recruitable was the reason. + pawn.guest.Recruitable = true; + T.Check(BuyMode.CanToggle(tr).Accepted, "control: CanToggle refused the same pawn once recruitable"); + }))); + } + + [BlaxTest("buy-mode: caravan chattel stays recruitable through vanilla's trade lord, so the switch works")] + public static void CaravanChattelRecruitable() + { + RequireAvailable(); + Faction faction = AnyFaction(); + if (faction == null) T.Skip("no visible non-player humanlike faction to send a caravan"); + WithUnwavering(() => + { + Pawn pawn = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, faction)); + pawn.guest.Recruitable = false; + pawn.guest.joinStatus = JoinStatus.JoinAsSlave; + T.Check(!pawn.guest.Recruitable, "setup: the pawn is recruitable before joining a trade caravan"); + + Lord lord = LordMaker.MakeNewLord(faction, new LordJob_TradeWithColony(faction, pawn.Position), Fixtures.Map, new[] { pawn }); + try + { + T.Check(pawn.guest.Recruitable, "vanilla's LordJob_TradeWithColony clause did not make caravan chattel recruitable"); + Tradeable tr = LooseTradeable(pawn); + T.Check(BuyMode.Toggle(tr), "Toggle refused a caravan slave the caravan lord makes recruitable"); + T.Equal(JoinStatus.JoinAsColonist, pawn.guest.joinStatus, "caravan pawn's joinStatus after the switch"); + } + finally + { + lord.RemovePawn(pawn); + Fixtures.Map.lordManager.RemoveLord(lord); + } + }); + } + + [BlaxTest("buy-mode: ResolveTrade as colonist frees and recruits, as slave enslaves to the colony")] + public static void ResolveTradeFollowsSwitch() + { + RequireAvailable(); + var bought = new List(); + try + { + WithSlaveShip(5103, (ship, stock) => InSession(ship, deal => + { + if (stock.Count < 2) T.Skip("slave ship stock holds fewer than 2 humanlike pawns"); + Pawn colonist = stock[0], slave = stock[1]; + + colonist.guest.Recruitable = true; + colonist.guest.joinStatus = JoinStatus.JoinAsSlave; + Tradeable trColonist = TradeableOf(deal, colonist); + T.Check(BuyMode.Toggle(trColonist), "Toggle refused switching a recruitable pawn to colonist"); + trColonist.ForceToSource(1); + bought.Add(colonist); + trColonist.ResolveTrade(); + + slave.guest.Recruitable = true; // an unrecruitable pawn can't be switched either way + slave.guest.joinStatus = JoinStatus.JoinAsColonist; + Tradeable trSlave = TradeableOf(deal, slave); + T.Check(BuyMode.Toggle(trSlave), "Toggle refused switching a pawn to slave"); + trSlave.ForceToSource(1); + bought.Add(slave); + trSlave.ResolveTrade(); + + T.Check(!colonist.IsSlave, Who(colonist) + " bought as colonist is a slave"); + T.Equal(Faction.OfPlayer, colonist.Faction, Who(colonist) + " faction after buying as colonist"); + var memories = colonist.needs?.mood?.thoughts?.memories; + if (memories == null) T.Info(Who(colonist) + " has no mood memories, FreedFromSlavery not checked"); + else T.NotNull(memories.GetFirstMemoryOfDef(ThoughtDefOf.FreedFromSlavery), Who(colonist) + "'s FreedFromSlavery memory"); + + T.Check(slave.IsSlaveOfColony, Who(slave) + " bought as slave is not a slave of the colony (faction " + (slave.Faction?.Name ?? "none") + ", slave " + slave.IsSlave + ")"); + })); + } + 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() + { + RequireAvailable(); + Pawn stock = StockPawn(JoinStatus.JoinAsSlave); + Tradeable tr = LooseTradeable(stock); + + Fixtures.Settings.buyModeEnabled = false; + T.Check(!BuyMode.Enabled, "BuyMode.Enabled with buyModeEnabled off"); + T.Check(!BuyMode.Toggle(tr), "Toggle switched a stock pawn with the setting off"); + T.Equal(JoinStatus.JoinAsSlave, stock.guest.joinStatus, "joinStatus after a switch with the setting off"); + + Fixtures.Settings.buyModeEnabled = true; + T.Check(BuyMode.Toggle(tr), "control: Toggle refused the same stock pawn with the setting on"); + T.Equal(JoinStatus.JoinAsColonist, stock.guest.joinStatus, "control: joinStatus after the switch"); + + Pawn captive = Fixtures.ColonySlave(); + JoinStatus before = captive.guest.joinStatus; + var colonySide = new Tradeable_Pawn(); + colonySide.AddThing(captive, Transactor.Colony); + T.Check(!BuyMode.IsTraderStockPawn(colonySide, out _), "a colony slave on the colony side counts as trader stock"); + T.Check(!BuyMode.Toggle(colonySide), "Toggle switched a colony slave the player would sell"); + T.Equal(before, captive.guest.joinStatus, "colony slave's joinStatus after a refused switch"); + + T.Check(BuyMode.TraderExcluded(new TraderKindDef { defName = "RD_PawnTrader" }), "Rimdeed's RD_PawnTrader is not excluded"); + T.Check(!BuyMode.TraderExcluded(Def(SlaveShipDef)), "the vanilla slave ship is excluded"); + } + + [BlaxTest("buy-mode: tooltip lists both prices and leaves the pawn as it was")] + public static void TooltipBothPrices() + { + RequireAvailable(); + Fixtures.Settings.slaveBuyFactor = VanillaSlaveBuyFactor; + WithSlaveShip(5104, (ship, stock) => InSession(ship, deal => + { + Pawn pawn = PriciestPawn(stock); + Tradeable tr = TradeableOf(deal, pawn); + pawn.guest.Recruitable = true; + pawn.guest.joinStatus = JoinStatus.JoinAsSlave; + BuyMode.InvalidatePrices(tr); + float price = tr.GetPriceFor(TradeAction.PlayerBuys); + + T.Check(BuyMode.TryGetBothPrices(tr, out float asColonist, out float asSlave), "TryGetBothPrices failed in a trade session"); + T.Check(Math.Abs(asSlave - price) < 0.01f, $"slave price {asSlave} differs from the row's price {price}"); + T.Equal(JoinStatus.JoinAsSlave, pawn.guest.joinStatus, "joinStatus after pricing both ways"); + T.Check(Math.Abs(tr.GetPriceFor(TradeAction.PlayerBuys) - price) < 0.01f, "row price changed after pricing both ways"); + if (price >= 100f) + { + float ratio = asColonist / asSlave, expected = 1f / VanillaSlaveBuyFactor; + T.Check(Math.Abs(ratio / expected - 1f) <= 0.01f, $"tooltip colonist/slave ratio {ratio:0.0000}, expected {expected:0.0000}"); + } + + string tip = BuyMode.Tooltip(tr); + T.NotNull(tip, "tooltip"); + T.Check(tip.Contains(asColonist.ToStringMoney()) && tip.Contains(asSlave.ToStringMoney()), "tooltip lacks one of the prices: " + tip); + T.Check(tip.Contains("BlaxSlaves_BuyModeClickColonist".Translate(pawn.Named("PAWN")).Resolve()), "tooltip does not say a click buys as colonist: " + tip); + + T.Check(BuyMode.Toggle(tr), "Toggle refused a recruitable pawn"); + T.Check(BuyMode.TryGetBothPrices(tr, out float c2, out float s2), "TryGetBothPrices failed after the switch"); + T.Check(Math.Abs(c2 - asColonist) < 0.01f && Math.Abs(s2 - asSlave) < 0.01f, $"prices after the switch {c2}/{s2}, before {asColonist}/{asSlave}"); + T.Check(Math.Abs(tr.GetPriceFor(TradeAction.PlayerBuys) - asColonist) < 0.01f, "row price after the switch is not the colonist price"); + })); + } + + [BlaxTest("buy-mode: the switch is sized by the wider label within 140 to 170 px, and a too-long translation is cut with '...'")] + public static void ButtonFitsLabels() + { + RequireAvailable(); + GameFont oldFont = Text.Font; + Text.Font = GameFont.Small; // TradeUI.DrawTradeableRow draws rows in Small + try + { + T.Check(Math.Abs(BuyMode.ButtonWidthFor(0f) - BuyMode.ButtonWidth) < 0.01f, "a short label shrinks the button below vanilla's 140 px"); + T.Check(Math.Abs(BuyMode.ButtonWidthFor(1000f) - BuyMode.MaxButtonWidth) < 0.01f, "a long label grows the button past MaxButtonWidth"); + T.Check(BuyMode.MaxButtonWidth <= 175f, "MaxButtonWidth leaves the 175 px of colony columns that are empty for stock"); + + string asSlave = "JoinsAsSlave".Translate(), asColonist = "JoinsAsColonist".Translate(); + float widest = Mathf.Max(Text.CalcSize(asSlave).x, Text.CalcSize(asColonist).x); + float width = BuyMode.CurrentButtonWidth(); + T.Info($"labels '{asSlave}' / '{asColonist}', widest {widest:0.0} px, button {width:0.0} px"); + T.Check(Math.Abs(width - BuyMode.ButtonWidthFor(widest)) < 0.01f, $"button width {width} not sized by the wider label ({widest} px)"); + foreach (string label in new[] { asSlave, asColonist }) + { + string shown = BuyMode.FitLabel(label, width); + if (BuyMode.ButtonWidthFor(widest) < BuyMode.MaxButtonWidth) + T.Equal(label, shown, "label cut although the button grew to fit it"); + T.Check(Text.CalcSize(shown).x <= width + 0.01f, $"label '{shown}' is wider than the {width} px button"); + } + + // Like the Russian "Joins as colonist" (about 184 px), too long even at MaxButtonWidth. + const string tooLong = "Joins the colony as a free colonist, not as a slave"; + string cut = BuyMode.FitLabel(tooLong, BuyMode.MaxButtonWidth); + T.Check(cut != tooLong && cut.EndsWith("..."), "a too-long label was not cut with '...': " + cut); + T.Check(Text.CalcSize(cut).x <= BuyMode.MaxButtonWidth - 8f + 0.01f, $"cut label '{cut}' still overflows the button"); + } + finally + { + Text.Font = oldFont; + } + } + + // ---- default purchase mode (first step of Patch_TraderSlaveBrand) ---------------- + + [BlaxTest("buy-mode: 'always slave' makes all stock join as slaves, unrecruitable, children and pre-branded included, before the brand roll")] + public static void AlwaysSlaveDefault() => Seeded(5201, AlwaysSlaveDefaultBody); + + private static void AlwaysSlaveDefaultBody() + { + RequireAvailable(); + Fixtures.Settings.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysSlave; + Fixtures.Settings.traderBrandChance = 1f; + TraderKindDef def = Def(CaravanSlaverDef); + Faction trading = AnyFaction(); + if (trading == null) T.Skip("no visible non-player humanlike faction to trade as"); + PlanetTile tile = Fixtures.Map.Tile; + + Pawn adult = StockPawn(JoinStatus.JoinAsColonist, trading); + adult.PostGeneratedForTrader(def, tile, trading); + T.Equal(JoinStatus.JoinAsSlave, adult.guest.joinStatus, "adult slave-kind pawn's joinStatus"); + T.Check(BrandUtility.IsBranded(adult), "the adult turned slave was not branded at traderBrandChance = 1, so the brand roll ran before the purchase mode"); + + Faction other = Find.FactionManager.AllFactionsVisible.FirstOrDefault(f => !f.IsPlayer && !f.temporary && f.def.humanlikeFaction && f != trading) ?? trading; + Pawn marked = StockPawn(JoinStatus.JoinAsColonist, trading); + BrandUtility.Brand(marked, other); + marked.PostGeneratedForTrader(def, tile, trading); + T.Equal(JoinStatus.JoinAsSlave, marked.guest.joinStatus, "pre-branded pawn's joinStatus"); + T.Equal(other, BrandUtility.BrandOf(marked)?.owner, "pre-branded pawn's brand owner"); + + Pawn villager = Fixtures.Generate(PawnKindDefOf.Villager, trading); + villager.guest.Recruitable = true; + villager.guest.joinStatus = JoinStatus.JoinAsColonist; + villager.PostGeneratedForTrader(def, tile, trading); + T.Equal(JoinStatus.JoinAsSlave, villager.guest.joinStatus, "non-slave-kind stock pawn's joinStatus"); + T.Check(!BrandUtility.IsBranded(villager), "non-slave-kind stock pawn got branded"); + + Pawn hired = StockPawn(JoinStatus.JoinAsColonist, trading); + hired.PostGeneratedForTrader(new TraderKindDef { defName = "RD_PawnTrader" }, tile, trading); + T.Equal(JoinStatus.JoinAsColonist, hired.guest.joinStatus, "RD_PawnTrader pawn's joinStatus"); + + WithUnwavering(() => + { + Pawn loyal = StockPawn(JoinStatus.JoinAsColonist, trading); + loyal.guest.Recruitable = false; + if (loyal.guest.Recruitable) + { + T.Info("the fresh pawn stays recruitable with unwavering prisoners on, unrecruitable case not checked"); + return; + } + // Vanilla can roll JoinAsColonist for a pawn SetupRecruitable then makes unrecruitable. Being made + // a slave needs no recruitability, so 'always slave' covers it too. + loyal.PostGeneratedForTrader(def, tile, trading); + T.Equal(JoinStatus.JoinAsSlave, loyal.guest.joinStatus, "unrecruitable colonist-rolled pawn's joinStatus under 'always slave'"); + T.Check(BrandUtility.IsBranded(loyal), "the unrecruitable pawn turned slave was not branded at traderBrandChance = 1, so the brand roll ran before the purchase mode"); + }); + + Fixtures.Settings.buyModeEnabled = false; + Pawn switchOff = StockPawn(JoinStatus.JoinAsColonist, trading); + switchOff.PostGeneratedForTrader(def, tile, trading); + T.Equal(JoinStatus.JoinAsSlave, switchOff.guest.joinStatus, "joinStatus with the trade-window switch off (the default is its own setting)"); + Fixtures.Settings.buyModeEnabled = true; + + 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.guest.Recruitable = true; + child.guest.joinStatus = JoinStatus.JoinAsColonist; + child.PostGeneratedForTrader(def, tile, trading); + T.Equal(JoinStatus.JoinAsSlave, child.guest.joinStatus, "child slave's joinStatus"); + T.Check(!BrandUtility.IsBranded(child), "child slave got branded"); + } + finally + { + if (child != null && !child.Discarded) Find.WorldPawns.PassToWorld(child, PawnDiscardDecideMode.Discard); + } + } + + [BlaxTest("buy-mode: 'always colonist' makes recruitable stock join as colonists, unbranded; unwavering pawns stay slaves")] + public static void AlwaysColonistDefault() => Seeded(5202, AlwaysColonistDefaultBody); + + private static void AlwaysColonistDefaultBody() + { + RequireAvailable(); + Fixtures.Settings.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysColonist; + Fixtures.Settings.traderBrandChance = 1f; + TraderKindDef def = Def(CaravanSlaverDef); + Faction trading = AnyFaction(); + if (trading == null) T.Skip("no visible non-player humanlike faction to trade as"); + PlanetTile tile = Fixtures.Map.Tile; + + Pawn free = StockPawn(JoinStatus.JoinAsSlave, trading); + free.PostGeneratedForTrader(def, tile, trading); + T.Equal(JoinStatus.JoinAsColonist, free.guest.joinStatus, "recruitable slave-kind pawn's joinStatus"); + T.Check(!BrandUtility.IsBranded(free), "a pawn joining as colonist got a trader brand"); + + WithUnwavering(() => + { + Pawn loyal = StockPawn(JoinStatus.JoinAsSlave, trading); + loyal.guest.Recruitable = false; + if (loyal.guest.Recruitable) + { + T.Info("the fresh pawn stays recruitable with unwavering prisoners on, unwavering case not checked"); + return; + } + loyal.PostGeneratedForTrader(def, tile, trading); + T.Equal(JoinStatus.JoinAsSlave, loyal.guest.joinStatus, "unwaveringly loyal pawn's joinStatus"); + T.Check(BrandUtility.IsBranded(loyal), "the unwavering slave was not branded at traderBrandChance = 1"); + }); + } + + [BlaxTest("buy-mode: 'always colonist' frees caravan chattel once the caravan's trade lord makes it recruitable; stock without that lord keeps its roll")] + public static void AlwaysColonistCaravanChattel() => Seeded(5204, AlwaysColonistCaravanChattelBody); + + private static void AlwaysColonistCaravanChattelBody() + { + RequireAvailable(); + Fixtures.Settings.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysColonist; + Fixtures.Settings.traderBrandChance = 0f; + TraderKindDef caravanDef = Def(CaravanSlaverDef); + Faction trading = AnyFaction(); + if (trading == null) T.Skip("no visible non-player humanlike faction to send a caravan"); + PlanetTile tile = Fixtures.Map.Tile; + + WithUnwavering(() => + { + // As PawnGroupKindWorker_Trader makes caravan wares: generated for the trader, before + // IncidentWorker_TraderCaravanArrival gives the caravan its LordJob_TradeWithColony. + Pawn chattel = UnrecruitableStock(trading); + chattel.PostGeneratedForTrader(caravanDef, tile, trading); + T.Equal(JoinStatus.JoinAsSlave, chattel.guest.joinStatus, "unrecruitable caravan chattel's joinStatus before its trade lord exists"); + + // Skipped once, then generated again under 'always slave' (a redressed pawn): no longer waiting. + Pawn regenerated = UnrecruitableStock(trading); + regenerated.PostGeneratedForTrader(caravanDef, tile, trading); + Fixtures.Settings.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysSlave; + regenerated.PostGeneratedForTrader(caravanDef, tile, trading); + Fixtures.Settings.defaultPurchaseMode = BlaxSlavesSettings.PurchaseVanilla; + // Generated under the vanilla roll: the default never skipped it. + Pawn vanillaRolled = UnrecruitableStock(trading); + vanillaRolled.PostGeneratedForTrader(caravanDef, tile, trading); + Fixtures.Settings.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysColonist; + + // Orbital stock (and a caravan met on the world map) never gets a trade lord. + Pawn orbital = UnrecruitableStock(trading); + orbital.PostGeneratedForTrader(Def(SlaveShipDef), tile, trading); + + var caravan = new[] { chattel, regenerated, vanillaRolled }; + foreach (Pawn p in caravan) Fixtures.Spawn(p); + Lord lord = LordMaker.MakeNewLord(trading, new LordJob_TradeWithColony(trading, chattel.Position), Fixtures.Map, caravan); + try + { + T.Check(chattel.guest.Recruitable, "setup: vanilla's LordJob_TradeWithColony clause did not make caravan chattel recruitable"); + T.Equal(JoinStatus.JoinAsColonist, chattel.guest.joinStatus, "caravan chattel's joinStatus after its trade lord was made"); + T.Equal(JoinStatus.JoinAsSlave, regenerated.guest.joinStatus, "regenerated chattel's joinStatus (its last generation was 'always slave')"); + T.Equal(JoinStatus.JoinAsSlave, vanillaRolled.guest.joinStatus, "vanilla-rolled chattel's joinStatus (the default never skipped it)"); + + Tradeable tr = LooseTradeable(chattel); + T.Check(BuyMode.Toggle(tr), "Toggle refused caravan chattel the trade lord makes recruitable"); + T.Equal(JoinStatus.JoinAsSlave, chattel.guest.joinStatus, "caravan chattel's joinStatus after the player switched it"); + } + finally + { + foreach (Pawn p in caravan) lord.RemovePawn(p); + Fixtures.Map.lordManager.RemoveLord(lord); + } + + T.Check(!orbital.guest.Recruitable, "setup: orbital stock turned recruitable"); + T.Equal(JoinStatus.JoinAsSlave, orbital.guest.joinStatus, "unrecruitable orbital stock's joinStatus under 'always colonist'"); + }); + } + + [BlaxTest("buy-mode: vanilla default leaves the rolled joinStatus alone")] + public static void VanillaDefaultUntouched() => Seeded(5203, () => + { + RequireAvailable(); + Fixtures.Settings.defaultPurchaseMode = BlaxSlavesSettings.PurchaseVanilla; + Fixtures.Settings.traderBrandChance = 0f; + TraderKindDef def = Def(CaravanSlaverDef); + Faction trading = AnyFaction(); + if (trading == null) T.Skip("no visible non-player humanlike faction to trade as"); + foreach (JoinStatus rolled in new[] { JoinStatus.JoinAsSlave, JoinStatus.JoinAsColonist }) + { + Pawn p = StockPawn(rolled, trading); + p.PostGeneratedForTrader(def, Fixtures.Map.Tile, trading); + T.Equal(rolled, p.guest.joinStatus, "joinStatus after the vanilla default"); + } + }); + + [BlaxTest("buy-mode: generated slave ship stock follows the default purchase mode")] + public static void GeneratedStockFollowsDefault() + { + RequireAvailable(); + Fixtures.Settings.traderBrandChance = 1f; + var seen = new List(); + foreach (var (mode, want, name) in new[] + { + (BlaxSlavesSettings.PurchaseAlwaysSlave, JoinStatus.JoinAsSlave, "always slave"), + (BlaxSlavesSettings.PurchaseAlwaysColonist, JoinStatus.JoinAsColonist, "always colonist"), + }) + { + Fixtures.Settings.defaultPurchaseMode = mode; + WithSlaveShip(mode == BlaxSlavesSettings.PurchaseAlwaysSlave ? 5301 : 5302, (ship, stock) => + { + // 'Always slave' covers every pawn, 'always colonist' only recruitable ones. + List covered = want == JoinStatus.JoinAsSlave ? stock : stock.Where(p => p.guest.Recruitable).ToList(); + seen.Add($"{name}: {covered.Count}/{stock.Count} covered"); + if (covered.Count == 0) T.Fail(name + ": slave ship stock held no pawn the default covers, nothing was checked"); + var wrong = covered.Where(p => p.guest.joinStatus != want).Select(p => $"{Who(p)} = {p.guest.joinStatus}").ToList(); + T.Check(wrong.Count == 0, $"{name}: covered stock not {want}: {string.Join(", ", wrong.Take(5))}"); + if (want == JoinStatus.JoinAsColonist) + { + var branded = covered.Where(p => BrandUtility.IsBranded(p)).Select(Who).ToList(); + T.Check(branded.Count == 0, name + ": colonists-to-be got a trader brand: " + string.Join(", ", branded.Take(5))); + } + }); + } + T.Info(string.Join("; ", seen)); + } + + // ---- save and reload ------------------------------------------------------------- + + private const string CarryShip = "buymode.ship"; + private const string CarryPawn = "buymode.pawn"; + private const string CarryStatus = "buymode.status"; + + [BlaxTest("buy-mode: set up a switched pawn on a passing slave ship for reload")] + public static void ReloadSetup() + { + RequireAvailable(); + HashSet worldBefore = WorldSnapshot(); + TradeShip ship = SlaveShip(5401); + bool keep = false; + try + { + List stock = FreshStock(ship, worldBefore); + if (stock.Count == 0) T.Fail("slave ship stock held no fresh humanlike pawn"); + InSession(ship, deal => + { + // Only a recruitable pawn can be switched, either way. + Pawn pawn = stock.FirstOrDefault(p => p.guest.Recruitable && !BuyMode.WouldJoinAsSlave(p)) ?? stock.FirstOrDefault(p => p.guest.Recruitable); + if (pawn == null) + { + pawn = stock[0]; + pawn.guest.Recruitable = true; + } + JoinStatus before = pawn.guest.joinStatus; + T.Check(BuyMode.Toggle(TradeableOf(deal, pawn)), "Toggle refused " + Who(pawn)); + T.Check(pawn.guest.joinStatus != before, "joinStatus unchanged by the switch"); + ship.ticksUntilDeparture = 1000 * GenDate.TicksPerDay; + T.Carry[CarryShip] = ship.GetUniqueLoadID(); + T.Carry[CarryPawn] = pawn.ThingID; + T.Carry[CarryStatus] = pawn.guest.joinStatus.ToString(); + keep = true; + T.Info($"slave ship {ship.GetUniqueLoadID()} keeps {Who(pawn)}, switched from {before} to {pawn.guest.joinStatus}"); + }); + } + finally + { + if (!keep) RemoveShip(ship, worldBefore); + } + } + + [BlaxTest("buy-mode: a switched stock pawn keeps its joinStatus after save and reload", phase: 2)] + public static void ReloadKeepsSwitch() + { + 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"); + TradeShip ship = Find.Maps.SelectMany(m => m.passingShipManager.passingShips).OfType() + .FirstOrDefault(s => s.GetUniqueLoadID() == shipId); + T.NotNull(ship, "slave ship " + shipId + " after reload"); + try + { + string pawnId = T.Carry[CarryPawn]; + Pawn pawn = ship.GetDirectlyHeldThings().OfType().FirstOrDefault(p => p.ThingID == pawnId); + T.NotNull(pawn, "pawn " + pawnId + " in the reloaded ship's stock"); + T.Equal(T.Carry[CarryStatus], pawn.guest.joinStatus.ToString(), Who(pawn) + " joinStatus after reload"); + } + finally + { + RemoveShip(ship); + } + } + + // ---- helpers --------------------------------------------------------------------- + + private static void RequireAvailable() + { + if (!ModsConfig.IdeologyActive) T.Skip("Ideology inactive, buy-mode is hidden"); + if (BuyMode.StandsDown) T.Skip("Trade as Slave or Colonist is active, buy-mode stands down"); + } + + private static TraderKindDef Def(string defName) + { + TraderKindDef def = DefDatabase.GetNamedSilentFail(defName); + T.NotNull(def, "TraderKindDef " + defName); + return def; + } + + private static string Who(Pawn p) => p.LabelShort + " [" + p.ThingID + "]"; + + private static Faction AnyFaction() => + Fixtures.FriendlyFaction() ?? Find.FactionManager.AllFactionsVisible + .Where(f => !f.IsPlayer && !f.defeated && !f.temporary && f.def.humanlikeFaction) + .OrderBy(f => f.loadID).FirstOrDefault(); + + /// An unspawned adult Slave-kind pawn as stock generators make it, recruitable, with a fixed joinStatus. + private static Pawn StockPawn(JoinStatus status, Faction faction = null) + { + Pawn p = Fixtures.Generate(PawnKindDefOf.Slave, faction ?? AnyFaction()); + p.guest.Recruitable = true; + p.guest.joinStatus = status; + return p; + } + + /// A StockPawn that joins as slave and isn't recruitable. Call inside WithUnwavering; skips the test if the pawn stays recruitable. + private static Pawn UnrecruitableStock(Faction faction) + { + Pawn p = StockPawn(JoinStatus.JoinAsSlave, faction); + p.guest.Recruitable = false; + if (p.guest.Recruitable) T.Skip("a fresh stock pawn stays recruitable with unwavering prisoners on, nothing to check"); + return p; + } + + /// A trader-side Tradeable_Pawn outside any trade session, as TradeDeal.AddToTradeables builds it. + private static Tradeable LooseTradeable(Pawn p) + { + var tr = new Tradeable_Pawn(); + tr.AddThing(p, Transactor.Trader); + return tr; + } + + private static Pawn PriciestPawn(List stock) + { + if (stock.Count == 0) T.Fail("slave ship stock held no fresh humanlike pawn"); + return stock.OrderByDescending(p => p.MarketValue).First(); + } + + private static Tradeable TradeableOf(TradeDeal deal, Pawn pawn) + { + Tradeable tr = deal.AllTradeables.FirstOrDefault(t => t.thingsTrader.Contains(pawn)); + T.NotNull(tr, "the deal's tradeable for " + Who(pawn)); + return tr; + } + + private static void Seeded(int seed, Action body) + { + Rand.PushState(seed); + try { body(); } + finally { Rand.PopState(); } + } + + private static void WithUnwavering(Action body) + { + Difficulty difficulty = Find.Storyteller.difficulty; + bool old = difficulty.unwaveringPrisoners; + difficulty.unwaveringPrisoners = true; + try { body(); } + finally { difficulty.unwaveringPrisoners = old; } + } + + /// A trade session with a fresh colonist as negotiator, as the comms console opens it. Restores the previous session. + private static void InSession(TradeShip ship, Action body) + { + Pawn negotiator = Fixtures.Colonist(); + ITrader oldTrader = TradeSession.trader; + Pawn oldNegotiator = TradeSession.playerNegotiator; + TradeDeal oldDeal = TradeSession.deal; + bool oldGiftMode = TradeSession.giftMode; + try + { + TradeSession.SetupWith(ship, negotiator, giftMode: false); + T.NotNull(TradeSession.deal, "TradeSession.deal after SetupWith"); + body(TradeSession.deal); + } + finally + { + TradeSession.trader = oldTrader; + TradeSession.playerNegotiator = oldNegotiator; + TradeSession.deal = oldDeal; + TradeSession.giftMode = oldGiftMode; + } + } + + /// A slave ship with fresh stock for one test body, removed afterwards. + private static void WithSlaveShip(int seed, Action> body) + { + HashSet worldBefore = WorldSnapshot(); + TradeShip ship = SlaveShip(seed); + try + { + body(ship, FreshStock(ship, worldBefore)); + } + finally + { + RemoveShip(ship, worldBefore); + } + } + + /// A slave ship as IncidentWorker_OrbitalTraderArrival makes it: added to the map, then GenerateThings. + private static TradeShip SlaveShip(int seed) + { + TraderKindDef def = Def(SlaveShipDef); + 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(); + } + } + + /// Humanlike stock made for this ship, not a world pawn redressed into it (those may be referenced elsewhere). + private static List FreshStock(TradeShip ship, HashSet worldBefore) => + ship.GetDirectlyHeldThings().OfType() + .Where(p => p.RaceProps.Humanlike && p.guest != null && !worldBefore.Contains(p)) + .ToList(); + + private static HashSet WorldSnapshot() => new HashSet(Find.WorldPawns.AllPawnsAliveOrDead); + + /// + /// Removes the ship and its stock: fresh pawns are discarded, redressed former world pawns go back to the + /// world (as when a ship departs), items are destroyed. + /// + private static void RemoveShip(TradeShip ship, HashSet formerWorldPawns = null) + { + if (ship == null) return; + List goods = ship.GetDirectlyHeldThings().ToList(); + ship.passingShipManager?.RemoveShip(ship); + foreach (Thing t in goods) + { + try + { + t.holdingOwner?.Remove(t); + if (t is Pawn p) + { + if (p.Discarded || Find.WorldPawns.Contains(p)) continue; + 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); + } + } + } + + /// A pawn bought from the ship sits in an incoming drop pod: take it out, remove the pod, discard the pawn. + private static void DiscardBought(Pawn p) + { + if (p == null || p.Discarded) return; + try + { + if (p.Spawned) + { + p.Destroy(DestroyMode.Vanish); + return; + } + Thing pod = p.SpawnedParentOrMe; + p.holdingOwner?.Remove(p); + if (pod != null && pod != p && pod.Spawned && !pod.Destroyed) pod.Destroy(DestroyMode.Vanish); + if (Find.WorldPawns.Contains(p)) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p); + else Find.WorldPawns.PassToWorld(p, PawnDiscardDecideMode.Discard); + } + catch (Exception e) + { + T.Info("cleanup of bought " + p + " threw: " + e.Message); + } + } + } +} diff --git a/Tests/BlaxSlavesTests/Source/SettingsTests.cs b/Tests/BlaxSlavesTests/Source/SettingsTests.cs new file mode 100644 index 0000000..0eef9b7 --- /dev/null +++ b/Tests/BlaxSlavesTests/Source/SettingsTests.cs @@ -0,0 +1,606 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using BlaxSlaves; +using HarmonyLib; +using RimWorld; +using Verse; + +namespace BlaxSlavesTests +{ + /// + /// Smoke tests for the tabbed settings (BlaxSlavesSettings, BlaxSlavesMod), the Compat table and the + /// sibling hooks. Settings files go through vanilla's own LoadedModManager.WriteModSettings and + /// ReadModSettings under a test-only mod id, so they land in the test run's Config folder (run-tests.ps1 + /// passes -savedatafolder) and are deleted again. The window itself needs OnGUI, so it isn't drawn. + /// + public static class SettingsTests + { + private const string TestModId = "BlaxSlavesSettingsTest"; + private const string Handle = nameof(BlaxSlavesMod); + + // Each field belongs to exactly one tab: the tab that draws it, whose Reset method restores it. + private static readonly string[] GeneralFields = + { + "returnRunaways", "returnChance", "returnDelayMinDays", "returnDelayMaxDays", + "suppressSlaveHarmMood", "keepRelationGrief", "showTimeInSlaveTab", + }; + + // traderBrandChance is a 1.1 setting (Scribe key unchanged) that the Trade tab draws, so ResetTrade owns it. + private static readonly string[] TradeFields = + { + "traderBrandChance", "buyModeEnabled", "defaultPurchaseMode", "allTradersBuySlaves", "visitorsBuySlaves", + "antiSlaveryTraders", "slaveStockIgnoresColonySize", "slaveSellFactor", "slaveBuyFactor", + }; + + // Workshop folder (published file id) -> packageId in that item's About.xml, checked 2026-11-28. + private static readonly Dictionary ReplacedWorkshopIds = new Dictionary + { + { "3838162426", Compat.TradeAsSlaveOrColonist }, + { "2799461327", Compat.EverybodyBuysSlaves }, + { "3361231919", Compat.SyrMoreSlaves }, + }; + + private static readonly string[] SettingsUiKeys = + { + "BlaxSlaves_TabTrade", "BlaxSlaves_TabGeneral", "BlaxSlaves_TabCompat", "BlaxSlaves_ResetTab", + "BlaxSlaves_SettingNeedsIdeology", "BlaxSlaves_SettingBuyMode", "BlaxSlaves_SettingBuyModeTip", + "BlaxSlaves_SettingBuyModeStandsDown", "BlaxSlaves_SettingPurchaseMode", "BlaxSlaves_SettingPurchaseVanilla", + "BlaxSlaves_SettingPurchaseSlave", "BlaxSlaves_SettingPurchaseColonist", "BlaxSlaves_SettingAllTradersBuy", + "BlaxSlaves_SettingAllTradersBuyTip", "BlaxSlaves_SettingVisitorsBuy", "BlaxSlaves_SettingVisitorsBuyTip", + "BlaxSlaves_SettingAntiSlavery", "BlaxSlaves_SettingAntiSlaveryBuy", "BlaxSlaves_SettingAntiSlaveryRefuse", + "BlaxSlaves_SettingStockAnySize", "BlaxSlaves_SettingStockAnySizeTip", "BlaxSlaves_SettingTraderBrand", + "BlaxSlaves_SettingSellFactor", "BlaxSlaves_SettingSellFactorTip", "BlaxSlaves_SettingBuyFactor", + "BlaxSlaves_SettingBuyFactorTip", "BlaxSlaves_SettingReturn", "BlaxSlaves_SettingReturnTip", + "BlaxSlaves_SettingReturnChance", "BlaxSlaves_SettingReturnDelayMin", "BlaxSlaves_SettingReturnDelayMax", + "BlaxSlaves_SettingMood", "BlaxSlaves_SettingMoodTip", "BlaxSlaves_SettingGrief", "BlaxSlaves_SettingGriefTip", + "BlaxSlaves_SettingTimeAsSlave", "BlaxSlaves_SettingTimeAsSlaveTip", "BlaxSlaves_CompatSiblings", + "BlaxSlaves_CompatNoSiblings", "BlaxSlaves_CompatReplaced", "BlaxSlaves_CompatNoneActive", + }; + + // ---- mod and window --------------------------------------------------------------- + + [BlaxTest("settings: mod has a settings category and Settings is the mod's own instance")] + public static void ModRegistered() + { + BlaxSlavesMod mod = LoadedModManager.GetMod(); + T.NotNull(mod, "LoadedModManager.GetMod()"); + T.Check(!mod.SettingsCategory().NullOrEmpty(), "SettingsCategory() is empty, so the mod gets no settings window"); + T.NotNull(BlaxSlavesMod.Settings, "BlaxSlavesMod.Settings"); + T.Check(ReferenceEquals(mod.GetSettings(), BlaxSlavesMod.Settings), + "BlaxSlavesMod.Settings is not the instance the mod writes on close (GetSettings())"); + var missing = SettingsUiKeys.Where(k => !k.CanTranslate()).ToList(); + T.Check(missing.Count == 0, "settings window strings missing from Keyed: " + string.Join(", ", missing)); + } + + [BlaxTest("settings: closing the window (WriteSettings) raises SettingsChanged once, without errors")] + public static void WriteSettingsRaisesChanged() + { + BlaxSlavesMod mod = LoadedModManager.GetMod(); + T.NotNull(mod, "LoadedModManager.GetMod()"); + BlaxSlavesSettings before = Copy(BlaxSlavesMod.Settings); + int raised = 0; + Action handler = () => raised++; + BlaxSlavesMod.SettingsChanged += handler; + try + { + // Writes the current (startup) values back to the test run's own Config folder and lets every + // feature re-apply itself, as closing the window does. + mod.WriteSettings(); + } + finally + { + BlaxSlavesMod.SettingsChanged -= handler; + StopScribe(); + } + T.Equal(1, raised, "SettingsChanged raised by WriteSettings"); + List changed = Diff(before, BlaxSlavesMod.Settings, AllNames()); + T.Check(changed.Count == 0, "WriteSettings changed in-range settings: " + string.Join("; ", changed)); + } + + // ---- Scribe ----------------------------------------------------------------------- + + [BlaxTest("settings: every field round-trips through the settings file")] + public static void RoundTrip() + { + BlaxSlavesSettings src = Varied(); + BlaxSlavesSettings defaults = new BlaxSlavesSettings(); + var notVaried = Fields.Where(f => Same(f.GetValue(src), f.GetValue(defaults))).Select(f => f.Name).ToList(); + T.Check(notVaried.Count == 0, + "test can't give these fields a valid non-default value, so the round trip proves nothing for them (extend Varied()): " + string.Join(", ", notVaried)); + + string path = SettingsPath(); + try + { + LoadedModManager.WriteModSettings(TestModId, Handle, src); + StopScribe(); + T.Check(File.Exists(path), "WriteModSettings wrote no file at " + path + " (vanilla's settings file name changed?)"); + BlaxSlavesSettings back = LoadedModManager.ReadModSettings(TestModId, Handle); + StopScribe(); + T.NotNull(back, "ReadModSettings result"); + List diff = Diff(src, back, AllNames()); + T.Check(diff.Count == 0, "settings changed over write and read (missing Scribe_Values key or wrong default?): " + string.Join("; ", diff)); + } + finally + { + StopScribe(); + Delete(path); + } + } + + [BlaxTest("settings: a 1.1 settings file loads its values, 1.2 keys get their defaults")] + public static void OldFileLoads() + { + // The 7 keys the published 1.1 DLL scribes, written the way WriteModSettings writes them. + const string xml = + "\n" + + "\n" + + "\t\n" + + "\t\tFalse\n" + + "\t\t0.5\n" + + "\t\t5\n" + + "\t\t20\n" + + "\t\tFalse\n" + + "\t\tFalse\n" + + "\t\t0.1\n" + + "\t\n" + + "\n"; + var expected = new BlaxSlavesSettings + { + returnRunaways = false, + returnChance = 0.5f, + returnDelayMinDays = 5, + returnDelayMaxDays = 20, + suppressSlaveHarmMood = false, + keepRelationGrief = false, + traderBrandChance = 0.1f, + }; + BlaxSlavesSettings loaded = LoadFile(xml); + List diff = Diff(expected, loaded, AllNames()); + T.Check(diff.Count == 0, "1.1 settings file loaded wrong (renamed Scribe key?): " + string.Join("; ", diff)); + } + + [BlaxTest("settings: loading a hand-edited file clamps out-of-range values")] + public static void LoadClamps() + { + const string xml = + "\n" + + "\n" + + "\t\n" + + "\t\t3\n" + + "\t\t0\n" + + "\t\t500\n" + + "\t\t-1\n" + + "\t\t9\n" + + "\t\t-4\n" + + "\t\t5\n" + + "\t\t0.01\n" + + "\t\n" + + "\n"; + var expected = new BlaxSlavesSettings + { + returnChance = 1f, + returnDelayMinDays = 1, + returnDelayMaxDays = 60, + traderBrandChance = 0f, + defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysColonist, + antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryBuyAnyway, + slaveSellFactor = 1f, + slaveBuyFactor = 0.3f, + }; + BlaxSlavesSettings loaded = LoadFile(xml); + List diff = Diff(expected, loaded, AllNames()); + T.Check(diff.Count == 0, "out-of-range values not clamped on load (Clamp no longer runs in PostLoadInit?): " + string.Join("; ", diff)); + } + + // ---- Clamp and reset -------------------------------------------------------------- + + [BlaxTest("settings: Clamp bounds out-of-range values and keeps valid ones")] + public static void ClampBounds() + { + var low = new BlaxSlavesSettings + { + returnChance = -0.5f, + returnDelayMinDays = -3, + returnDelayMaxDays = -3, + traderBrandChance = -0.1f, + defaultPurchaseMode = -1, + antiSlaveryTraders = -1, + slaveSellFactor = 0f, + slaveBuyFactor = 0.29f, + }; + low.Clamp(); + var lowExpected = new BlaxSlavesSettings + { + returnChance = 0f, + returnDelayMinDays = 1, + returnDelayMaxDays = 1, + traderBrandChance = 0f, + defaultPurchaseMode = BlaxSlavesSettings.PurchaseVanilla, + antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryBuyAnyway, + slaveSellFactor = 0.3f, + slaveBuyFactor = 0.3f, + }; + List diff = Diff(lowExpected, low, AllNames()); + T.Check(diff.Count == 0, "too-low values: " + string.Join("; ", diff)); + + var high = new BlaxSlavesSettings + { + returnChance = 1.5f, + returnDelayMinDays = 31, + returnDelayMaxDays = 61, + traderBrandChance = 2f, + defaultPurchaseMode = 3, + antiSlaveryTraders = 2, + slaveSellFactor = 1.01f, + slaveBuyFactor = 7f, + }; + high.Clamp(); + var highExpected = new BlaxSlavesSettings + { + returnChance = 1f, + returnDelayMinDays = 30, + returnDelayMaxDays = 60, + traderBrandChance = 1f, + defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysColonist, + antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryRefuse, + slaveSellFactor = 1f, + slaveBuyFactor = 1f, + }; + diff = Diff(highExpected, high, AllNames()); + T.Check(diff.Count == 0, "too-high values: " + string.Join("; ", diff)); + + var crossed = new BlaxSlavesSettings { returnDelayMinDays = 12, returnDelayMaxDays = 5 }; + crossed.Clamp(); + T.Equal(12, crossed.returnDelayMinDays, "earliest return after Clamp with latest < earliest"); + T.Equal(12, crossed.returnDelayMaxDays, "latest return after Clamp with latest < earliest (raised to the earliest)"); + + BlaxSlavesSettings valid = Varied(); + BlaxSlavesSettings copy = Copy(valid); + valid.Clamp(); + diff = Diff(copy, valid, AllNames()); + T.Check(diff.Count == 0, "Clamp changed valid values: " + string.Join("; ", diff)); + + var defaults = new BlaxSlavesSettings(); + defaults.Clamp(); + diff = Diff(new BlaxSlavesSettings(), defaults, AllNames()); + T.Check(diff.Count == 0, "Clamp changed the defaults: " + string.Join("; ", diff)); + } + + [BlaxTest("settings: ResetTrade and ResetGeneral each restore only their own tab")] + public static void ResetPerTab() + { + var listed = new HashSet(GeneralFields.Concat(TradeFields)); + var unlisted = AllNames().Where(n => !listed.Contains(n)).ToList(); + var unknown = listed.Where(n => typeof(BlaxSlavesSettings).GetField(n) == null).ToList(); + var onBothTabs = GeneralFields.Intersect(TradeFields).ToList(); + 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)); + + BlaxSlavesSettings defaults = new BlaxSlavesSettings(); + BlaxSlavesSettings varied = Varied(); + + BlaxSlavesSettings trade = Copy(varied); + trade.ResetTrade(); + List notReset = Diff(defaults, trade, TradeFields); + List wronglyReset = Diff(varied, trade, GeneralFields); + 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)); + + BlaxSlavesSettings general = Copy(varied); + general.ResetGeneral(); + notReset = Diff(defaults, general, GeneralFields); + wronglyReset = Diff(varied, general, TradeFields); + 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)); + + BlaxSlavesSettings both = Copy(varied); + both.ResetTrade(); + both.ResetGeneral(); + List left = Diff(defaults, both, AllNames()); + T.Check(left.Count == 0, "both reset buttons together leave fields changed: " + string.Join("; ", left)); + } + + [BlaxTest("settings: every setting a tab draws is one its own reset button restores")] + public static void ResetOwnsDrawnFields() + { + // The tabs need OnGUI, so the fields each one draws are read from its IL. Together with ResetPerTab + // this pins "Reset this tab" to exactly the controls the player sees on that tab. + var problems = new List(); + foreach (var (draw, reset, owned) in new[] { ("DoTrade", "ResetTrade", TradeFields), ("DoGeneral", "ResetGeneral", GeneralFields) }) + { + MethodInfo method = AccessTools.DeclaredMethod(typeof(BlaxSlavesMod), draw); + T.NotNull(method, "BlaxSlavesMod." + draw + " (renamed?)"); + List drawn = SettingsFieldsUsedBy(method); + T.Info(draw + " uses " + string.Join(", ", drawn)); + problems.AddRange(drawn.Where(n => !owned.Contains(n)).Select(n => $"{draw} draws {n}, but {reset} doesn't restore it")); + } + T.Check(problems.Count == 0, string.Join("; ", problems)); + } + + [BlaxTest("settings: the window's listing stays one column, so the scroll height counts every row after a tab switch")] + public static void SettingsListingOneColumn() + { + // Without maxOneColumn, a row past last frame's viewHeight wraps into a second column outside the + // scroll group and CurHeight counts only that column, so a tall tab drawn right after a short one + // loses its last rows (the Reset button) for good. + MethodInfo window = AccessTools.DeclaredMethod(typeof(BlaxSlavesMod), nameof(BlaxSlavesMod.DoSettingsWindowContents)); + T.NotNull(window, "BlaxSlavesMod.DoSettingsWindowContents"); + List> body = PatchProcessor.ReadMethodBody(window).ToList(); + T.Check(body.Count > 0, "could not read the IL of DoSettingsWindowContents"); + bool setsOneColumn = Enumerable.Range(1, body.Count - 1) + .Any(i => body[i].Key == OpCodes.Stfld && IsMaxOneColumn(body[i].Value) && body[i - 1].Key == OpCodes.Ldc_I4_1); + T.Check(setsOneColumn, "DoSettingsWindowContents doesn't set maxOneColumn = true on its listing"); + + foreach (Type type in new[] { typeof(Listing), typeof(Listing_Standard) }) + { + MethodInfo begin = AccessTools.DeclaredMethod(type, nameof(Listing.Begin), new[] { typeof(UnityEngine.Rect) }); + if (begin == null) + continue; + bool resets = PatchProcessor.ReadMethodBody(begin).Any(op => op.Key == OpCodes.Stfld && IsMaxOneColumn(op.Value)); + T.Check(!resets, type.Name + ".Begin now resets maxOneColumn, so setting it before Begin has no effect"); + } + + // The layout the fix relies on: rows past the rect's height stay in the first column and CurHeight + // grows with them. The wrapping listing shows the test really crosses the rect's height. + const float rectHeight = 100f, rowHeight = 30f; + const int rows = 10; + var oneColumn = new LayoutOnlyListing { maxOneColumn = true }; + var wrapping = new LayoutOnlyListing(); + var oneColumnX = new List(); + var wrappingX = new List(); + oneColumn.Begin(new UnityEngine.Rect(0f, 0f, 400f, rectHeight)); + wrapping.Begin(new UnityEngine.Rect(0f, 0f, 400f, rectHeight)); + for (int i = 0; i < rows; i++) + { + oneColumnX.Add(oneColumn.GetRect(rowHeight).x); + wrappingX.Add(wrapping.GetRect(rowHeight).x); + } + T.Check(wrappingX.Any(x => x > 0f), "a listing without maxOneColumn didn't wrap past its rect's height, so this check proves nothing (did Listing change?)"); + T.Check(oneColumnX.All(x => x == 0f), "a maxOneColumn listing still wrapped rows into a second column: x = " + string.Join(", ", oneColumnX)); + T.Equal(rows * rowHeight, oneColumn.CurHeight, "CurHeight of a maxOneColumn listing after " + rows + " rows of " + rowHeight); + } + + // ---- Compat ----------------------------------------------------------------------- + + [BlaxTest("compat: replaced-mod table has unique packageIds that resolve without exceptions")] + public static void ReplacedTable() + { + T.Check(Compat.Replaced != null && Compat.Replaced.Count > 0, "Compat.Replaced is empty"); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var problems = new List(); + foreach (Compat.ReplacedMod m in Compat.Replaced) + { + if (m.packageId.NullOrEmpty() || m.packageId.Trim() != m.packageId || m.packageId.Contains(" ")) + problems.Add("bad packageId '" + m.packageId + "'"); + else if (!seen.Add(m.packageId)) + problems.Add("duplicate packageId " + m.packageId); + if (m.name.NullOrEmpty()) + problems.Add(m.packageId + ": no name"); + if (m.note.NullOrEmpty() || !m.note.CanTranslate()) + problems.Add(m.packageId + ": note key '" + m.note + "' missing from Keyed"); + try + { + bool active = Compat.IsActive(m.packageId); + string note = m.note.NullOrEmpty() ? "" : (string)m.note.Translate(); + if (active) + T.Info("active: " + m.name + " (" + m.packageId + "): " + note); + } + catch (Exception e) + { + problems.Add(m.packageId + ": resolving threw " + e.GetType().Name + ": " + e.Message); + } + } + T.Check(problems.Count == 0, string.Join("; ", problems)); + + foreach (string id in new[] { Compat.TradeAsSlaveOrColonist, Compat.EverybodyBuysSlaves, Compat.SyrMoreSlaves }) + T.Check(seen.Contains(id), "Compat.Replaced misses " + id); + + // Where a replaced mod is installed from the Workshop, its About.xml must carry the id we look for. + int checkedMods = 0; + foreach (ModMetaData mod in ModLister.AllInstalledMods) + { + if (mod?.RootDir == null || !mod.OnSteamWorkshop || !ReplacedWorkshopIds.TryGetValue(mod.FolderName, out string id)) + continue; + checkedMods++; + T.Check(string.Equals(mod.PackageIdPlayerFacing, id, StringComparison.OrdinalIgnoreCase), + $"Workshop item {mod.FolderName} ({mod.Name}) has packageId {mod.PackageIdPlayerFacing}, Compat looks for {id}"); + } + T.Info(checkedMods + " replaced mod(s) installed from the Workshop, packageIds checked against their About.xml"); + } + + [BlaxTest("compat: IsActive finds Blax Slaves and the base game, not a made-up id")] + public static void IsActiveWorks() + { + T.Check(Compat.IsActive("blax.slaves"), "Compat.IsActive(\"blax.slaves\") is false while Blax Slaves runs"); + T.Check(Compat.IsActive("Blax.Slaves"), "Compat.IsActive is case-sensitive (packageIds aren't)"); + T.Check(Compat.IsActive("ludeon.rimworld"), "Compat.IsActive(\"ludeon.rimworld\") is false"); + T.Check(!Compat.IsActive("blax.slaves.no.such.mod"), "Compat.IsActive is true for a made-up packageId"); + } + + // ---- siblings --------------------------------------------------------------------- + + [BlaxTest("siblings: Describe returns text, calls without the sibling mods are safe no-ops")] + public static void SiblingsNoOps() + { + bool castes = Compat.IsActive(Siblings.CastesId); + bool zones = Compat.IsActive(Siblings.ZonesId); + string described = Siblings.Describe(); + T.Info($"castes active={castes} bound={Siblings.CastesBound} v{Siblings.CastesVersion}, zones active={zones} bound={Siblings.ZonesBound} v{Siblings.ZonesVersion}: \"{described}\""); + T.Check(!described.NullOrEmpty(), "Siblings.Describe() returned nothing"); + if (!castes) + T.Check(!Siblings.CastesBound && Siblings.CastesVersion == 0, "Blax Castes isn't active but its API counts as bound"); + if (!zones) + T.Check(!Siblings.ZonesBound && Siblings.ZonesVersion == 0, "Blax Zones isn't active but its API counts as bound"); + if (!castes && !zones) + T.Equal((string)"BlaxSlaves_CompatNoSiblings".Translate(), described, "Describe() without siblings"); + + Pawn slave = Fixtures.ColonySlave(); + // Null arguments are no-ops whether or not the siblings are bound. + Siblings.CastesNotifyJoined(null, Siblings.ReasonRunawayReturned); + Siblings.CastesHintJoinReason(null, null); + Siblings.CastesNotifyJoinedNextTick(null, Siblings.ReasonRunawayReturned); + T.Check(!Siblings.ZonesTryFindDropSpot(null, slave, out IntVec3 nullMapCell) && nullMapCell == IntVec3.Invalid, + "ZonesTryFindDropSpot with no map found a cell"); + T.Check(!Siblings.ZonesTryFindDropSpot(Fixtures.Map, null, out IntVec3 nullThingCell) && nullThingCell == IntVec3.Invalid, + "ZonesTryFindDropSpot with no thing found a cell"); + + if (Siblings.CastesBound) + T.Info("Blax Castes is bound; skipped the unbound Castes calls so the test pawn doesn't reach it"); + else + { + Siblings.CastesNotifyJoined(slave, Siblings.ReasonRunawayReturned); + Siblings.CastesHintJoinReason(slave, Siblings.ReasonRunawayReturned); + int queuedBefore = NotifyQueueCount(); + Siblings.CastesNotifyJoinedNextTick(slave, Siblings.ReasonRunawayReturned); + T.Equal(queuedBefore, NotifyQueueCount(), "NotifyJoined queue length after queueing without Blax Castes"); + Siblings.Tick(); + } + + if (Siblings.ZonesBound) + T.Info("Blax Zones is bound; skipped the unbound drop spot check"); + else + { + bool found = Siblings.ZonesTryFindDropSpot(Fixtures.Map, slave, out IntVec3 cell); + T.Check(!found && cell == IntVec3.Invalid, $"ZonesTryFindDropSpot without Blax Zones returned {found} with cell {cell}"); + } + } + + // ---- helpers ---------------------------------------------------------------------- + + private static FieldInfo[] Fields => typeof(BlaxSlavesSettings).GetFields(BindingFlags.Public | BindingFlags.Instance); + + private static IEnumerable AllNames() => Fields.Select(f => f.Name); + + /// The BlaxSlavesSettings instance fields a method reads, writes or passes by ref, from its IL. + private static List SettingsFieldsUsedBy(MethodInfo method) + { + List> body = PatchProcessor.ReadMethodBody(method).ToList(); + T.Check(body.Count > 0, "could not read the IL of " + method.Name); + return body.Select(op => op.Value).OfType() + .Where(f => f.DeclaringType == typeof(BlaxSlavesSettings) && !f.IsStatic && !f.IsLiteral) + .Select(f => f.Name).Distinct().OrderBy(n => n).ToList(); + } + + private static bool IsMaxOneColumn(object operand) => + operand is FieldInfo f && f.DeclaringType == typeof(Listing) && f.Name == nameof(Listing.maxOneColumn); + + /// Lays out rows like Listing_Standard but skips Widgets.BeginGroup and EndGroup, which need OnGUI. + private sealed class LayoutOnlyListing : Listing_Standard + { + public override void Begin(UnityEngine.Rect rect) + { + listingRect = rect; + curX = 0f; + curY = 0f; + } + + public override void End() { } + } + + /// Every field moved off its default to a value Clamp keeps. + private static BlaxSlavesSettings Varied() + { + var defaults = new BlaxSlavesSettings(); + var s = new BlaxSlavesSettings(); + foreach (FieldInfo f in Fields) + { + switch (f.GetValue(defaults)) + { + case bool b: + f.SetValue(s, !b); + break; + case int i: + f.SetValue(s, i + 1); + break; + case float x: + f.SetValue(s, x >= 0.5f ? x - 0.15f : x + 0.15f); + break; + } + } + s.Clamp(); + return s; + } + + private static BlaxSlavesSettings Copy(BlaxSlavesSettings from) + { + var s = new BlaxSlavesSettings(); + foreach (FieldInfo f in Fields) + f.SetValue(s, f.GetValue(from)); + return s; + } + + 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); + + private static List Diff(BlaxSlavesSettings expected, BlaxSlavesSettings actual, IEnumerable names) + { + var result = new List(); + foreach (string name in names) + { + FieldInfo f = typeof(BlaxSlavesSettings).GetField(name, BindingFlags.Public | BindingFlags.Instance); + if (f == null) + { + result.Add(name + ": no such field"); + continue; + } + object e = f.GetValue(expected), a = f.GetValue(actual); + if (!Same(e, a)) + result.Add($"{name}: expected {e}, got {a}"); + } + return result; + } + + /// Where vanilla's Read/WriteModSettings put the test mod's file (LoadedModManager.GetSettingsFilename). + private static string SettingsPath() => + Path.Combine(GenFilePaths.ConfigFolderPath, GenText.SanitizeFilename($"Mod_{TestModId}_{Handle}.xml")); + + private static BlaxSlavesSettings LoadFile(string xml) + { + string path = SettingsPath(); + try + { + File.WriteAllText(path, xml); + BlaxSlavesSettings loaded = LoadedModManager.ReadModSettings(TestModId, Handle); + StopScribe(); + T.NotNull(loaded, "ReadModSettings result"); + return loaded; + } + finally + { + StopScribe(); + Delete(path); + } + } + + /// A Scribe left mid-load or mid-save would break the runner's save and reload after phase 1. + private static void StopScribe() + { + if (Scribe.mode == LoadSaveMode.Inactive) + return; + T.Info("Scribe was left in mode " + Scribe.mode + "; forced stop"); + Scribe.ForceStop(); + } + + private static void Delete(string path) + { + try + { + if (File.Exists(path)) + File.Delete(path); + } + catch (Exception e) + { + T.Info("could not delete " + path + ": " + e.Message); + } + } + + private static int NotifyQueueCount() => + (AccessTools.Field(typeof(Siblings), "notifyQueue")?.GetValue(null) as ICollection)?.Count ?? 0; + } +} diff --git a/Tests/BlaxSlavesTests/Source/SlavePriceTests.cs b/Tests/BlaxSlavesTests/Source/SlavePriceTests.cs new file mode 100644 index 0000000..2bfe01e --- /dev/null +++ b/Tests/BlaxSlavesTests/Source/SlavePriceTests.cs @@ -0,0 +1,563 @@ +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 +{ + /// + /// Slave price sliders: Patch_SlavePrices on the private Tradeable.InitPriceDataIfNeeded. Every test opens a + /// real TradeSession with a slave ship (Orbital_PirateMerchant, stock from TradeShip.GenerateThings) and a + /// colonist negotiator, prices a colony slave and a stock pawn through Tradeable.GetPriceFor, and compares + /// with vanilla's own formula (the public TradeUtility.GetPricePlayerBuy/Sell fed with the tradeable's stored + /// price types and gains). + /// + public static class SlavePriceTests + { + private const string HarmonyId = "blax.slaves"; + private const string ShipDefName = "Orbital_PirateMerchant"; + private const float Vanilla = 0.6f; + private const float CapShare = 0.9f; + + private static readonly MethodInfo InitPriceData = AccessTools.Method(typeof(Tradeable), "InitPriceDataIfNeeded"); + + // ---- patch ----------------------------------------------------------------------- + + [BlaxTest("slave prices: prefix and postfix sit on Tradeable.InitPriceDataIfNeeded")] + public static void PatchApplied() + { + T.NotNull(InitPriceData, "Tradeable.InitPriceDataIfNeeded"); + Patches info = Harmony.GetPatchInfo(InitPriceData); + T.NotNull(info, "Harmony patch info on InitPriceDataIfNeeded"); + T.Check(info.Prefixes.Any(p => p.owner == HarmonyId && p.PatchMethod.DeclaringType == typeof(Patch_SlavePrices)), + "no Patch_SlavePrices prefix; owners: " + string.Join(", ", info.Prefixes.Select(p => p.owner))); + T.Check(info.Postfixes.Any(p => p.owner == HarmonyId && p.PatchMethod.DeclaringType == typeof(Patch_SlavePrices)), + "no Patch_SlavePrices postfix; owners: " + string.Join(", ", info.Postfixes.Select(p => p.owner))); + } + + // ---- prices ---------------------------------------------------------------------- + + [BlaxTest("slave prices: at 60%/60% captive and slave prices equal vanilla exactly")] + public static void VanillaAtDefaults() + { + Fixtures.Settings.slaveSellFactor = Vanilla; + Fixtures.Settings.slaveBuyFactor = Vanilla; + WithTrade(4801, 20, c => + { + foreach (Tradeable t in new[] { c.captiveT, c.stockT }) + { + Pawn p = (Pawn)t.AnyThing; + float buy = Buy(t), sell = Sell(t); + float joinAs = p.guest.joinStatus == JoinStatus.JoinAsSlave ? Vanilla : 1f; + T.Check(Near(F(t, "priceFactorBuy_JoinAs"), joinAs, 0.0001f), $"{Who(p)} buy factor {F(t, "priceFactorBuy_JoinAs")}, vanilla sets {joinAs}"); + T.Check(Near(F(t, "priceFactorSell_HumanPawn"), Vanilla, 0.0001f), $"{Who(p)} sell factor {F(t, "priceFactorSell_HumanPawn")}, vanilla sets {Vanilla}"); + float vBuy = FormulaBuy(t, joinAs); + float vSell = Math.Min(FormulaSell(t, Vanilla), vBuy); + T.Check(Near(buy, vBuy, 0.001f), $"{Who(p)} buy price {buy}, vanilla {vBuy}"); + T.Check(Near(sell, vSell, 0.001f), $"{Who(p)} sell price {sell}, vanilla {vSell}"); + } + float cap = LoopCap(c.captiveT, Vanilla); + T.Info($"negotiator gain {F(c.captiveT, "priceGain_PlayerNegotiator"):0.###}: vanilla captive sell {Sell(c.captiveT)}, " + + $"0.9 x best slave buy {cap:0.#} (cap {(Sell(c.captiveT) > cap ? "would bind" : "would not bind")}, not applied at defaults)"); + }); + } + + [BlaxTest("slave prices: sell factor 80% pays the recomputed price and stays below the buy price")] + public static void SellFactorRaisesCaptivePrice() + { + Fixtures.Settings.slaveSellFactor = 0.8f; + Fixtures.Settings.slaveBuyFactor = Vanilla; + WithTrade(4802, 0, c => + { + Tradeable t = c.captiveT; + float buy = Buy(t), sell = Sell(t); + T.Check(Near(F(t, "priceFactorSell_HumanPawn"), 0.8f, 0.0001f), "sell factor field " + F(t, "priceFactorSell_HumanPawn") + ", expected 0.8"); + T.Check(sell <= buy, $"sell price {sell} above buy price {buy}"); + + float vanillaSell = Math.Min(FormulaSell(t, Vanilla), buy); + float recomputed = FormulaSell(t, 0.8f); + float cap = ExpectedCap(t, Vanilla); + T.Info($"captive {Who(c.captive)}: vanilla sell {vanillaSell}, at 80% {recomputed}, own buy {buy}, cap {cap:0.#}, paid {sell}"); + T.Check(sell >= vanillaSell - 0.001f, $"sell price {sell} at 80% is below vanilla's {vanillaSell}"); + if (recomputed <= buy && recomputed <= cap) + { + T.Check(Math.Abs(sell - recomputed) <= 1f, $"sell price {sell}, GetPricePlayerSell at 0.8 gives {recomputed}"); + T.Check(sell > vanillaSell, $"sell price {sell} at 80% is not above vanilla's {vanillaSell}"); + } + else + { + T.Info("clamped by the buy price or the cap"); + T.Check(sell <= Math.Min(buy, cap) + 0.001f, $"sell price {sell} above min(buy {buy}, cap {cap})"); + } + }); + } + + [BlaxTest("slave prices: buy factor 50% makes a JoinAsSlave stock pawn cost the recomputed price")] + public static void BuyFactorLowersSlavePrice() + { + Fixtures.Settings.slaveSellFactor = Vanilla; + Fixtures.Settings.slaveBuyFactor = 0.5f; + WithTrade(4803, 10, c => + { + Tradeable t = c.stockT; + float buy = Buy(t); + T.Check(Near(F(t, "priceFactorBuy_JoinAs"), 0.5f, 0.0001f), "buy factor field " + F(t, "priceFactorBuy_JoinAs") + ", expected 0.5"); + float expected = FormulaBuy(t, 0.5f); + float vanilla = FormulaBuy(t, Vanilla); + T.Check(Near(buy, expected, 0.001f), $"buy price {buy}, GetPricePlayerBuy at 0.5 gives {expected}"); + T.Check(buy < vanilla, $"buy price {buy} at 50% is not below vanilla's {vanilla}"); + T.Info($"stock slave {Who(c.stock)}: vanilla {vanilla}, at 50% {buy} (ratio {buy / vanilla:0.###}, expected ~{0.5f / Vanilla:0.###})"); + + if (c.colonistStockT == null) + { + T.Info("no second humanlike stock pawn; colonist-price check skipped"); + return; + } + if (Compat.IsActive(Compat.TradeAsSlaveOrColonist)) + { + T.Info("Trade as Slave or Colonist is active and prices stock pawns by its own purchase mode; colonist-price check skipped"); + return; + } + float colonistBuy = Buy(c.colonistStockT); + T.Check(Near(F(c.colonistStockT, "priceFactorBuy_JoinAs"), 1f, 0.0001f), + "JoinAsColonist stock pawn got buy factor " + F(c.colonistStockT, "priceFactorBuy_JoinAs")); + T.Check(Near(colonistBuy, FormulaBuy(c.colonistStockT, 1f), 0.001f), + $"JoinAsColonist stock pawn costs {colonistBuy}, vanilla colonist price {FormulaBuy(c.colonistStockT, 1f)}"); + }); + } + + [BlaxTest("slave prices: a second InitPriceDataIfNeeded, cached or after invalidation, changes nothing")] + public static void SecondComputeIsIdempotent() + { + Fixtures.Settings.slaveSellFactor = 0.8f; + Fixtures.Settings.slaveBuyFactor = 0.5f; + WithTrade(4804, 10, c => + { + foreach (Tradeable t in new[] { c.captiveT, c.stockT }) + { + string who = Who((Pawn)t.AnyThing); + float buy = Buy(t), sell = Sell(t); + float joinAs = F(t, "priceFactorBuy_JoinAs"), human = F(t, "priceFactorSell_HumanPawn"); + + InitPriceData.Invoke(t, null); + Same(t, who + " after a cached call", buy, sell, joinAs, human); + + // What buy mode does after a click: invalidate both prices, then ask again. + Invalidate(t); + InitPriceData.Invoke(t, null); + Same(t, who + " after invalidate + InitPriceDataIfNeeded", buy, sell, joinAs, human); + + Invalidate(t); + Same(t, who + " after invalidate + GetPriceFor", buy, sell, joinAs, human); + } + }); + } + + [BlaxTest("slave prices: at sell 100%/buy 50% a Social 20 negotiator's captive price is capped at 0.9 x the best negotiator's slave price")] + public static void CapBoundsSellPrice() + { + // Buy below vanilla, so the vanilla floor stays off and the loop cap alone binds. + Fixtures.Settings.slaveSellFactor = 1f; + Fixtures.Settings.slaveBuyFactor = 0.5f; + WithTrade(4805, 20, c => + { + Tradeable t = c.captiveT; + float buy = Buy(t), sell = Sell(t); + float gain = F(t, "priceGain_PlayerNegotiator"); + float uncapped = Math.Min(FormulaSell(t, 1f), buy); + float bestSlaveBuy = BestSlaveBuy(t, 0.5f); + float ownSlaveBuy = FormulaBuy(t, 0.5f); + float cap = ExpectedCap(t, 0.5f); + T.Info($"captive {Who(c.captive)}: gain {gain:0.###} (best {MaxGain:0.###}), uncapped sell {uncapped}, slave buy {ownSlaveBuy} " + + $"(best negotiator {bestSlaveBuy}), cap {cap:0.#}, paid {sell}"); + T.Check(uncapped > cap, $"setup: the cap does not bind (gain {gain:0.###}, trader buy price type " + + $"{F(t, "priceFactorBuy_TraderPriceType")}); uncapped {uncapped} <= cap {cap:0.#}"); + T.Check(sell <= cap + 0.001f, $"sell price {sell} above 0.9 x best slave buy price {bestSlaveBuy} = {cap:0.#}"); + T.Check(sell >= cap - 1f, $"sell price {sell} far below the cap {cap:0.#}: something else lowered it"); + T.Check(sell < bestSlaveBuy, $"sell price {sell} not below what the best negotiator pays for the slave, {bestSlaveBuy}"); + T.Check(sell < ownSlaveBuy, $"sell price {sell} not below this negotiator's slave buy price {ownSlaveBuy}"); + }); + } + + [BlaxTest("slave prices: buying with a Social 20 negotiator and selling with a Social 0 one loses silver")] + public static void SwitchingNegotiatorsDoesNotPay() + { + // The review's case: buy 30%, sell vanilla. With the cap tied to the current negotiator, the Social 0 + // sale (vanilla's 36% of MV) beat the Social 20 purchase (1.4 x 0.3 x 0.7 = 29.4% of MV). + Fixtures.Settings.slaveSellFactor = Vanilla; + Fixtures.Settings.slaveBuyFactor = 0.3f; + WithTrade(4808, 20, c => + { + // Read the gain only after a price lookup: the field is filled by InitPriceDataIfNeeded. + float buyHigh = Buy(c.stockT); + float stockSellHigh = Sell(c.stockT), captiveSellHigh = Sell(c.captiveT); + float gainHigh = F(c.stockT, "priceGain_PlayerNegotiator"); + + // A new comms-console session with another negotiator builds new tradeables and prices. + c.Reopen(0); + float stockSellLow = Sell(c.stockT), captiveSellLow = Sell(c.captiveT); + float gainLow = F(c.stockT, "priceGain_PlayerNegotiator"); + + T.Info($"stock slave {Who(c.stock)}: bought at gain {gainHigh:0.###} for {buyHigh}; sells for {stockSellHigh} at that gain, " + + $"{stockSellLow} at gain {gainLow:0.###}. Captive {Who(c.captive)} sells for {captiveSellHigh} / {captiveSellLow}"); + T.Check(gainHigh > gainLow, $"setup: Social 20 gain {gainHigh:0.###} not above Social 0 gain {gainLow:0.###}"); + T.Check(stockSellLow < buyHigh, $"loop: bought for {buyHigh} with gain {gainHigh:0.###}, sells for {stockSellLow} with gain {gainLow:0.###}"); + T.Check(stockSellHigh < buyHigh, $"loop: bought for {buyHigh}, the same negotiator sells for {stockSellHigh}"); + T.Check(stockSellHigh >= stockSellLow, $"stock slave: the better negotiator gets {stockSellHigh}, the worse one {stockSellLow}"); + T.Check(captiveSellHigh >= captiveSellLow, $"captive: the better negotiator gets {captiveSellHigh}, the worse one {captiveSellLow}"); + }); + } + + [BlaxTest("slave prices: sell 65%/buy 60% never pays a Social 20 negotiator less than vanilla's 60% price")] + public static void SellSliderNeverBelowVanilla() + { + // Social 20 sells at vanilla for 0.36 x 1.3 = 46.8% of MV, above the loop cap (0.9 x 1.4 x 0.6 x 0.605 + // = 45.7%), so without the vanilla floor one notch up on the sell slider would lower the price. + Fixtures.Settings.slaveSellFactor = 0.65f; + Fixtures.Settings.slaveBuyFactor = Vanilla; + WithTrade(4809, 20, c => + { + foreach (Tradeable t in new[] { c.captiveT, c.stockT }) + { + Pawn p = (Pawn)t.AnyThing; + float buy = Buy(t), sell = Sell(t); + float joinAs = p.guest.joinStatus == JoinStatus.JoinAsSlave ? Vanilla : 1f; + float vanillaSell = Math.Min(FormulaSell(t, Vanilla), FormulaBuy(t, joinAs)); + float slider = FormulaSell(t, 0.65f); + float loopCap = LoopCap(t, Vanilla); + float expected = Math.Min(Math.Min(slider, buy), ExpectedCap(t, Vanilla)); + T.Info($"{Who(p)}: gain {F(t, "priceGain_PlayerNegotiator"):0.###}, vanilla sell {vanillaSell}, at 65% {slider}, " + + $"loop cap {loopCap:0.#} ({(loopCap < vanillaSell ? "below vanilla, floor binds" : "floor idle")}), paid {sell}"); + T.Check(sell >= vanillaSell - 0.001f, $"{Who(p)} sell price {sell} at 65% is below vanilla's {vanillaSell}"); + T.Check(sell <= slider + 0.001f, $"{Who(p)} sell price {sell} above the 65% price {slider}"); + T.Check(Math.Abs(sell - expected) <= 1f, $"{Who(p)} sell price {sell}, expected {expected}"); + } + }); + } + + [BlaxTest("slave prices: animals and items keep vanilla prices with both sliders off vanilla")] + public static void NonHumanlikeUntouched() + { + Fixtures.Settings.slaveSellFactor = 0.8f; + Fixtures.Settings.slaveBuyFactor = 0.5f; + WithTrade(4806, 20, c => + { + var checkedOnes = new List(); + Pawn animal = ColonyAnimal(); + if (animal != null) + { + Tradeable t = ColonyTradeable(animal); + CheckUntouched(t, "animal " + Who(animal)); + float cap = LoopCap(t, 0.5f); + T.Info($"animal {Who(animal)}: sell {Sell(t)}, a wrongly applied cap would give {cap:0.#}"); + checkedOnes.Add("animal"); + } + else T.Info("no animal PawnKindDef found; animal check skipped"); + + Tradeable item = TradeSession.deal.AllTradeables.FirstOrDefault(x => + x.FirstThingTrader != null && !(x.FirstThingTrader is Pawn) && !x.IsCurrency); + if (item != null) + { + CheckUntouched(item, "item " + item.ThingDef?.defName); + checkedOnes.Add("item " + item.ThingDef?.defName); + } + else T.Info("slave ship stock has no item; item check skipped"); + + T.Check(checkedOnes.Count > 0, "neither an animal nor an item to check"); + T.Info("checked: " + string.Join(", ", checkedOnes)); + }); + } + + [BlaxTest("slave prices: the trade tooltips show the slider factors")] + public static void TooltipShowsFactors() + { + Fixtures.Settings.slaveSellFactor = 0.8f; + Fixtures.Settings.slaveBuyFactor = 0.5f; + WithTrade(4807, 10, c => + { + if (TradeSession.TradeCurrency != TradeCurrency.Silver) + T.Skip("slave ship trades in " + TradeSession.TradeCurrency + ", the tooltip lists factors only for silver"); + string slave = "Slave".Translate(); + string slaveCap = "Slave".Translate().CapitalizeFirst(); + + string sellTip = c.captiveT.GetPriceTooltip(TradeAction.PlayerSells); + string sellLine = "x " + 0.8f.ToString("F2") + " (" + slave + ")"; + T.Check(sellTip.Contains(sellLine), $"sell tooltip lacks '{sellLine}': {sellTip}"); + + string buyTip = c.stockT.GetPriceTooltip(TradeAction.PlayerBuys); + string buyLine = slaveCap + ": x" + 0.5f.ToStringPercent(); + T.Check(buyTip.Contains(buyLine), $"buy tooltip lacks '{buyLine}': {buyTip}"); + }); + } + + // ---- setup ----------------------------------------------------------------------- + + private sealed class TradeCtx + { + public TradeShip ship; + public Pawn negotiator; + public Pawn captive; + public Tradeable captiveT; + public Pawn stock; // humanlike stock pawn set to JoinAsSlave + public Tradeable stockT; + public Pawn colonistStock; // a second humanlike stock pawn set to JoinAsColonist, may be null + public Tradeable colonistStockT; + + /// + /// Closes the session and opens a new one with the same ship and a new negotiator at the given Social + /// level, as reopening the comms console does: a new TradeDeal with new tradeables, so prices are + /// computed again with that negotiator's gain. + /// + public void Reopen(int socialLevel) + { + TradeSession.Close(); + negotiator = Negotiator(socialLevel); + TradeSession.SetupWith(ship, negotiator, giftMode: false); + Bind(); + } + + /// Looks up the tradeables in the current deal and invalidates their prices. + public void Bind() + { + captiveT = ColonyTradeable(captive); + stockT = StockTradeable(stock); + colonistStockT = colonistStock == null ? null : StockTradeable(colonistStock); + foreach (Tradeable t in new[] { captiveT, stockT, colonistStockT }) + if (t != null) Invalidate(t); + } + } + + /// + /// A slave ship with fresh stock, a colony slave 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. + /// + private static void WithTrade(int seed, int socialLevel, Action body) + { + if (!ModsConfig.IdeologyActive) + T.Skip("Ideology inactive: vanilla has no slave price factors"); + TraderKindDef def = DefDatabase.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"); + + HashSet worldBefore = new HashSet(Find.WorldPawns.AllPawnsAliveOrDead); + TradeShip ship = null; + try + { + Rand.PushState(seed); + try + { + ship = new TradeShip(def); + Fixtures.Map.passingShipManager.AddShip(ship); + ship.GenerateThings(); + } + finally + { + Rand.PopState(); + } + + List stockPawns = Goods(ship).OfType().Where(p => p.RaceProps.Humanlike && p.guest != null).ToList(); + T.Check(stockPawns.Count > 0, ShipDefName + " stock (seed " + seed + ") has no humanlike pawn"); + c.ship = ship; + c.stock = stockPawns[0]; + c.stock.guest.joinStatus = JoinStatus.JoinAsSlave; + c.colonistStock = stockPawns.Count > 1 ? stockPawns[1] : null; + if (c.colonistStock != null) + c.colonistStock.guest.joinStatus = JoinStatus.JoinAsColonist; + + Pawn oldNegotiator = TradeSession.playerNegotiator; + TradeDeal oldDeal = TradeSession.deal; + bool oldGiftMode = TradeSession.giftMode; + TradeSession.SetupWith(ship, c.negotiator, giftMode: false); + try + { + c.Bind(); + body(c); + } + finally + { + TradeSession.Close(); + // Close only clears the trader; drop the deal and negotiator that point at discarded pawns. + TradeSession.playerNegotiator = oldNegotiator; + TradeSession.deal = oldDeal; + TradeSession.giftMode = oldGiftMode; + } + } + finally + { + RemoveShip(ship, worldBefore); + } + } + + /// A spawned colonist who can talk trade, with Social set to the given level. + private static Pawn Negotiator(int socialLevel) + { + for (int i = 0; i < 10; i++) + { + Pawn p = Fixtures.Colonist(); + SkillRecord social = p.skills?.GetSkill(SkillDefOf.Social); + if (social == null || social.TotallyDisabled) + continue; + social.Level = socialLevel; + // A trait, gene or missing capacity can zero the trade bonus regardless of skill; such a + // negotiator would make the gain comparisons meaningless, so pick another. + if (socialLevel >= 10 && p.GetStatValue(StatDefOf.TradePriceImprovement) < 0.1f) + continue; + return p; + } + T.Skip("setup: 10 generated colonists could not do Social"); + return null; + } + + /// A spawned adult animal of the player's faction, or null if no animal kind exists. + private static Pawn ColonyAnimal() + { + PawnKindDef kind = DefDatabase.GetNamedSilentFail("Muffalo") + ?? DefDatabase.AllDefsListForReading.FirstOrDefault(k => k.RaceProps != null && k.RaceProps.Animal && !k.RaceProps.Dryad); + if (kind == null) + return null; + return Fixtures.Spawn(Fixtures.Generate(kind, Faction.OfPlayer)); + } + + /// + /// The deal's tradeable for a colony pawn, or one built the way TradeDeal.AddToTradeables builds it when + /// the pawn isn't in the deal (vanilla only lists secure prisoners and slaves, and pawns made after setup). + /// + private static Tradeable ColonyTradeable(Pawn p) + { + Tradeable t = TradeSession.deal.AllTradeables.FirstOrDefault(x => x.thingsColony.Contains(p)); + if (t != null) + return t; + t = new Tradeable_Pawn(); + t.AddThing(p, Transactor.Colony); + return t; + } + + private static Tradeable StockTradeable(Pawn p) + { + Tradeable t = TradeSession.deal.AllTradeables.FirstOrDefault(x => x.thingsTrader.Contains(p)); + T.NotNull(t, "trade deal tradeable for stock pawn " + Who(p)); + return t; + } + + // ---- price helpers --------------------------------------------------------------- + + private static float Buy(Tradeable t) => t.GetPriceFor(TradeAction.PlayerBuys); + + private static float Sell(Tradeable t) => t.GetPriceFor(TradeAction.PlayerSells); + + private static float F(Tradeable t, string field) => (float)AccessTools.Field(typeof(Tradeable), field).GetValue(t); + + /// What buy mode does after a click: both cached prices to -1, so the next lookup recomputes. + private static void Invalidate(Tradeable t) + { + AccessTools.Field(typeof(Tradeable), "pricePlayerBuy").SetValue(t, -1f); + AccessTools.Field(typeof(Tradeable), "pricePlayerSell").SetValue(t, -1f); + } + + /// Vanilla's buy price with the given join factor and the tradeable's stored price type and gains. + private static float FormulaBuy(Tradeable t, float joinAs) => + TradeUtility.GetPricePlayerBuy(t.AnyThing, F(t, "priceFactorBuy_TraderPriceType"), joinAs, + F(t, "priceGain_PlayerNegotiator"), F(t, "priceGain_Settlement")); + + /// Vanilla's sell price with the given human factor and the tradeable's stored price type and gains. + private static float FormulaSell(Tradeable t, float human) => + TradeUtility.GetPricePlayerSell(t.AnyThing, F(t, "priceFactorSell_TraderPriceType"), human, + F(t, "priceGain_PlayerNegotiator"), F(t, "priceGain_Settlement"), F(t, "priceGain_DrugBonus"), + F(t, "priceGain_AnimalProduceBonus"), TradeSession.TradeCurrency); + + /// The best trade gain a negotiator can reach: TradePriceImprovement's maxValue (0.395 in Core). + private static float MaxGain => StatDefOf.TradePriceImprovement.maxValue; + + /// + /// What the best possible negotiator would pay this trader for the pawn as a slave at the given buy factor: + /// the trader's buy price type at most Normal, its settlement gain, the negotiator gain at MaxGain. + /// + private static float BestSlaveBuy(Tradeable t, float slaveBuyFactor) => + TradeUtility.GetPricePlayerBuy(t.AnyThing, Math.Min(F(t, "priceFactorBuy_TraderPriceType"), 1f), slaveBuyFactor, + MaxGain, F(t, "priceGain_Settlement")); + + /// The spec's loop cap: 0.9 x BestSlaveBuy, whole silver (rounded down) above 99.5. + private static float LoopCap(Tradeable t, float slaveBuyFactor) + { + float cap = CapShare * BestSlaveBuy(t, slaveBuyFactor); + return cap > 99.5f ? (float)Math.Floor(cap) : cap; + } + + /// The cap the patch applies: LoopCap, raised to vanilla's own 60% sale while the buy factor is vanilla or above. + private static float ExpectedCap(Tradeable t, float slaveBuyFactor) + { + float cap = LoopCap(t, slaveBuyFactor); + return slaveBuyFactor >= Vanilla - 0.001f ? Math.Max(cap, FormulaSell(t, Vanilla)) : cap; + } + + private static void Same(Tradeable t, string when, float buy, float sell, float joinAs, float human) + { + T.Check(Buy(t) == buy, $"{when}: buy price {Buy(t)}, was {buy}"); + T.Check(Sell(t) == sell, $"{when}: sell price {Sell(t)}, was {sell}"); + T.Check(F(t, "priceFactorBuy_JoinAs") == joinAs, $"{when}: buy factor {F(t, "priceFactorBuy_JoinAs")}, was {joinAs}"); + T.Check(F(t, "priceFactorSell_HumanPawn") == human, $"{when}: sell factor {F(t, "priceFactorSell_HumanPawn")}, was {human}"); + } + + /// Factor fields at vanilla's 1 and both prices exactly vanilla's (no slider, no cap). + private static void CheckUntouched(Tradeable t, string what) + { + float buy = Buy(t), sell = Sell(t); + T.Check(F(t, "priceFactorBuy_JoinAs") == 1f, $"{what}: buy factor {F(t, "priceFactorBuy_JoinAs")}, vanilla 1"); + T.Check(F(t, "priceFactorSell_HumanPawn") == 1f, $"{what}: sell factor {F(t, "priceFactorSell_HumanPawn")}, vanilla 1"); + float vBuy = FormulaBuy(t, 1f); + float vSell = Math.Min(FormulaSell(t, 1f), vBuy); + T.Check(Near(buy, vBuy, 0.001f), $"{what}: buy price {buy}, vanilla {vBuy}"); + T.Check(Near(sell, vSell, 0.001f), $"{what}: sell price {sell}, vanilla {vSell}"); + } + + private static bool Near(float a, float b, float tolerance) => Math.Abs(a - b) <= tolerance; + + private static string Who(Pawn p) => p == null ? "null" : p.LabelShort + " [" + p.ThingID + "]"; + + // ---- stock cleanup (as TradersTests: fresh pawns discarded, redressed world pawns returned) ---- + + private static List Goods(TradeShip ship) => ship.GetDirectlyHeldThings().ToList(); + + private static void RemoveShip(TradeShip ship, HashSet formerWorldPawns) + { + if (ship == null) return; + List goods = Goods(ship); + ship.passingShipManager?.RemoveShip(ship); + foreach (Thing t in goods.Where(x => x != null)) + { + 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); + } + } + } + } +} diff --git a/Tests/BlaxSlavesTests/Source/TimeAsSlaveTests.cs b/Tests/BlaxSlavesTests/Source/TimeAsSlaveTests.cs new file mode 100644 index 0000000..ed59e55 --- /dev/null +++ b/Tests/BlaxSlavesTests/Source/TimeAsSlaveTests.cs @@ -0,0 +1,325 @@ +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using BlaxSlaves; +using HarmonyLib; +using RimWorld; +using RimWorld.Planet; +using Verse; + +namespace BlaxSlavesTests +{ + /// + /// Time as a slave: the counter in GameComponent_TimeAsSlave (no RecordDef, because records are saved by + /// def index and an added def shifts other mods' records), the Records tab row drawn by + /// Patch_RecordsCardTimeAsSlave (postfix on the private RecordsCardUtility.DrawTimeRecords), the slave + /// tab line drawn by Patch_SlaveTabLines (postfix on the private ITab_Pawn_Visitor.DoSlavePriceListing) + /// and the SlaveTabLines registry later releases add their lines to. Both tabs need OnGUI, so the tests + /// check the patches and the strings the rows show (SlaveTabLines.LabelsFor, TimeAsSlave.RecordValue). + /// + public static class TimeAsSlaveTests + { + private const string OldRecordName = "BlaxSlaves_TimeAsColonySlave"; + private const int TickSpan = 2500; // one in-game hour + private const int Interval = TimeAsSlave.CountInterval; + private const string HarmonyId = "blax.slaves"; + + private static GameComponent_TimeAsSlave Counter => GameComponent_TimeAsSlave.Instance; + + // ---- no def, component and patches ------------------------------------------------ + + [BlaxTest("time as slave: Blax Slaves adds no RecordDef; the counter is a GameComponent")] + public static void NoRecordDef() + { + T.Check(DefDatabase.GetNamedSilentFail(OldRecordName) == null, + "RecordDef " + OldRecordName + " is loaded again; any RecordDef from this mod shifts later mods' records in existing saves"); + ModContentPack ours = LoadedModManager.GetMod()?.Content; + T.NotNull(ours, "Blax Slaves' ModContentPack"); + List added = DefDatabase.AllDefsListForReading + .Where(d => d.modContentPack == ours || (d.defName != null && d.defName.StartsWith("BlaxSlaves_"))) + .Select(d => d.defName).ToList(); + T.Check(added.Count == 0, "RecordDefs from Blax Slaves: " + string.Join(", ", added)); + + T.NotNull(Counter, "GameComponent_TimeAsSlave in Current.Game"); + T.Check(Current.Game.components.Count(c => c is GameComponent_TimeAsSlave) == 1, "GameComponent_TimeAsSlave is not in the game exactly once"); + T.Equal(0, TimeAsSlave.Ticks(null), "TimeAsSlave.Ticks(null)"); + foreach (string key in new[] { "BlaxSlaves_TimeAsSlaveRecord", "BlaxSlaves_TimeAsSlaveRecordDesc" }) + T.Check(key.CanTranslate(), "Keyed string " + key + " missing"); + } + + [BlaxTest("time as slave: postfixes sit on DoSlavePriceListing and RecordsCardUtility.DrawTimeRecords")] + public static void PatchesApplied() + { + MethodInfo tab = AccessTools.Method(typeof(ITab_Pawn_Visitor), "DoSlavePriceListing"); + T.NotNull(tab, "ITab_Pawn_Visitor.DoSlavePriceListing (renamed in this game version?)"); + T.Check(HasOurPostfix(tab, typeof(Patch_SlaveTabLines)), + "no blax.slaves postfix from Patch_SlaveTabLines on DoSlavePriceListing (patch failed at startup?)"); + T.Check(SlaveTabLines.All.Any(l => l.id == TimeAsSlave.LineId), "the time-as-slave line is not registered in SlaveTabLines"); + + MethodInfo records = AccessTools.Method(typeof(RecordsCardUtility), "DrawTimeRecords"); + T.NotNull(records, "RecordsCardUtility.DrawTimeRecords (renamed in this game version?)"); + T.Equal(typeof(float), records.ReturnType, "DrawTimeRecords return type (the postfix adds its row height to it)"); + T.Check(HasOurPostfix(records, typeof(Patch_RecordsCardTimeAsSlave)), + "no blax.slaves postfix from Patch_RecordsCardTimeAsSlave on DrawTimeRecords (patch failed at startup?)"); + } + + [BlaxTest("time as slave: the Records tab row shows the counter as vanilla formats time records")] + public static void RecordsTabRow() + { + Pawn slave = Fixtures.ColonySlave(); + Fixtures.Tick(Interval * 2); + string label = TimeAsSlave.RecordLabel; + string value = TimeAsSlave.RecordValue(slave); + T.Info($"row: '{label}' = '{value}'"); + T.Check(!label.NullOrEmpty() && !label.Contains("BlaxSlaves_"), "Records tab label shows a raw key: " + label); + T.Check(!TimeAsSlave.RecordTooltip.Contains("BlaxSlaves_"), "Records tab tooltip shows a raw key: " + TimeAsSlave.RecordTooltip); + T.Check(TimeAsSlave.Ticks(slave) > 0, "counter still 0 after two counting passes"); + T.Equal(TimeAsSlave.Ticks(slave).ToStringTicksToPeriod(), value, "Records tab value"); + } + + // ---- counting --------------------------------------------------------------------- + + [BlaxTest("time as slave: a colony slave's counter grows, a free colonist's and a prisoner's stay 0")] + public static void CounterGrows() + { + Pawn slave = Fixtures.Keep(Fixtures.ColonySlave()); + Pawn colonist = Fixtures.Colonist(); + Pawn prisoner = Prisoner(); + int slaveBefore = TimeAsSlave.Ticks(slave); + + Fixtures.Tick(TickSpan); + + int slaveAfter = TimeAsSlave.Ticks(slave); + int grown = slaveAfter - slaveBefore; + T.Info($"after {TickSpan} ticks: slave {slaveBefore}->{slaveAfter}, colonist {TimeAsSlave.Ticks(colonist)}, prisoner {TimeAsSlave.Ticks(prisoner)}"); + T.Check(slave.IsSlaveOfColony, "the slave stopped being a colony slave while ticking"); + // One pass every Interval ticks adds Interval; where the span starts can shift one pass. + T.Check(grown >= TickSpan - Interval && grown <= TickSpan + Interval, + $"counter grew by {grown} over {TickSpan} ticks, expected about {TickSpan} ({Interval} per {Interval} ticks)"); + T.Equal(slaveAfter, Counter.TicksOf(slave), "TimeAsSlave.Ticks vs GameComponent_TimeAsSlave.TicksOf"); + T.Equal(0, TimeAsSlave.Ticks(colonist), "counter of a free colonist"); + T.Equal(0, TimeAsSlave.Ticks(prisoner), "counter of a prisoner of the colony"); + T.Check(!Counter.TrackedPawns.Contains(colonist) && !Counter.TrackedPawns.Contains(prisoner), + "the counter tracks a free colonist or a prisoner"); + + T.Carry["timeAsSlave.pawn"] = slave.ThingID; + T.Carry["timeAsSlave.ticks"] = slaveAfter.ToString(); + } + + [BlaxTest("time as slave: a freed slave keeps the time counted so far and stops counting")] + public static void FreedSlaveKeepsTime() + { + Pawn slave = Fixtures.ColonySlave(); + Fixtures.Tick(Interval * 2); + int counted = TimeAsSlave.Ticks(slave); + T.Check(counted > 0, "counter still 0 after two counting passes"); + + slave.guest.SetGuestStatus(null); + T.Check(!slave.IsSlaveOfColony, "SetGuestStatus(null) did not free the slave"); + Fixtures.Tick(Interval * 2); + T.Equal(counted, TimeAsSlave.Ticks(slave), "counter of the freed slave after two more passes"); + } + + [BlaxTest("time as slave: a colony slave in a caravan keeps counting")] + public static void CountsInCaravan() + { + Pawn slave = Fixtures.ColonySlave(); + Pawn colonist = Fixtures.Colonist(); + Caravan caravan = null; + try + { + caravan = CaravanMaker.MakeCaravan(new List { colonist, slave }, Faction.OfPlayer, Fixtures.Map.Tile, addToWorldPawnsIfNotAlready: true); + T.Check(!slave.Spawned && slave.GetCaravan() == caravan, "the slave did not join the caravan"); + T.Check(slave.IsSlaveOfColony, "the slave stopped being a colony slave in the caravan"); + int before = TimeAsSlave.Ticks(slave); + Fixtures.Tick(Interval * 2); + int after = TimeAsSlave.Ticks(slave); + T.Info($"caravan slave: {before}->{after} over {Interval * 2} ticks"); + T.Check(after - before >= Interval, $"counter grew by {after - before} in a caravan over {Interval * 2} ticks, expected at least {Interval}"); + } + finally + { + if (caravan != null && !caravan.Destroyed) + { + caravan.RemoveAllPawns(); + caravan.Destroy(); + } + } + } + + [BlaxTest("time as slave: Purge drops destroyed pawns and keeps living and dead ones")] + public static void PurgeDropsDestroyed() + { + Pawn kept = Fixtures.ColonySlave(); + Pawn dead = Fixtures.ColonySlave(); + Pawn gone = Fixtures.ColonySlave(); + Pawn goneUnpurged = Fixtures.ColonySlave(); + Fixtures.Tick(Interval * 2); + foreach (Pawn p in new[] { kept, dead, gone, goneUnpurged }) + T.Check(Counter.TrackedPawns.Contains(p), p.LabelShort + " not tracked after two counting passes"); + + dead.Kill(null); + int deadTicks = TimeAsSlave.Ticks(dead); + gone.Destroy(DestroyMode.Vanish); + T.Check(gone.Destroyed, "Destroy(Vanish) left the pawn undestroyed"); + Counter.Purge(); + T.Check(!Counter.TrackedPawns.Contains(gone), "Purge kept a destroyed pawn"); + T.Check(Counter.TrackedPawns.Contains(kept), "Purge dropped a living colony slave"); + T.Check(dead.Dead, "Kill left the slave alive"); + // Whether a killed pawn reads as Destroyed depends on how the game finalizes the kill; + // either way the rule is the same: Purge keeps it while it isn't destroyed, drops it once it is. + if (dead.Destroyed) + { + T.Info("the killed slave reads as Destroyed after Kill, so Purge must drop it"); + T.Check(!Counter.TrackedPawns.Contains(dead), "Purge kept a killed slave that reads as Destroyed"); + } + else + { + T.Check(Counter.TrackedPawns.Contains(dead) && TimeAsSlave.Ticks(dead) == deadTicks, "Purge dropped a dead slave whose corpse still exists"); + } + T.Check(Counter.TrackedPawns.All(p => p != null && !p.Destroyed), "a null or destroyed pawn is still tracked after Purge"); + + // Destroyed after the purge: the save between the phases must drop it (checked after the reload). + goneUnpurged.Destroy(DestroyMode.Vanish); + T.Carry["timeAsSlave.destroyed"] = goneUnpurged.ThingID; + } + + // ---- slave tab line --------------------------------------------------------------- + + [BlaxTest("time as slave: slave tab line shows for colony slaves only and follows the setting")] + public static void TabLine() + { + T.Check("BlaxSlaves_TimeAsSlaveLine".CanTranslate(), "Keyed string BlaxSlaves_TimeAsSlaveLine missing"); + T.Check("BlaxSlaves_TimeAsSlaveLineTip".CanTranslate(), "Keyed string BlaxSlaves_TimeAsSlaveLineTip missing"); + + Pawn slave = Fixtures.ColonySlave(); + Fixtures.Tick(Interval * 2); + string expected = TimeAsSlave.Label(slave); + T.Info("line: " + expected); + T.Check(expected.Contains(TimeAsSlave.Ticks(slave).ToStringTicksToPeriod()), "line '" + expected + "' doesn't contain the counter's period"); + T.Check(!expected.Contains("BlaxSlaves_"), "line shows a raw translation key: " + expected); + + Fixtures.Settings.showTimeInSlaveTab = true; + List shown = SlaveTabLines.LabelsFor(slave); + T.Check(shown.Contains(expected), "colony slave: line missing, tab would show [" + string.Join(" | ", shown) + "]"); + + Fixtures.Settings.showTimeInSlaveTab = false; + T.Check(!SlaveTabLines.LabelsFor(slave).Contains(expected), "line still shown with showTimeInSlaveTab off"); + int hiddenBefore = TimeAsSlave.Ticks(slave); + Fixtures.Tick(Interval * 2); + T.Check(TimeAsSlave.Ticks(slave) > hiddenBefore, + $"counter stopped with showTimeInSlaveTab off ({hiddenBefore}->{TimeAsSlave.Ticks(slave)}); the setting should only hide the line"); + Fixtures.Settings.showTimeInSlaveTab = true; + + Pawn prisoner = Prisoner(); + T.Check(!SlaveTabLines.LabelsFor(prisoner).Contains(TimeAsSlave.Label(prisoner)), "time-as-slave line shown in a prisoner's tab"); + T.Check(SlaveTabLines.LabelsFor(Fixtures.Colonist()).Count == 0, "slave tab lines for a free colonist"); + T.Check(SlaveTabLines.LabelsFor(null).Count == 0, "slave tab lines for a null pawn"); + } + + [BlaxTest("time as slave: tab lines can be added once, replaced by id and removed")] + public static void TabLineRegistry() + { + const string id = "blax.slaves.test.line"; + Fixtures.Settings.showTimeInSlaveTab = true; + int before = SlaveTabLines.All.Count; + try + { + SlaveTabLines.Add(new SlaveTabLine(id, p => "first " + p.LabelShort, prisonersToo: true)); + SlaveTabLines.Add(new SlaveTabLine(id, p => "second " + p.LabelShort, prisonersToo: true)); + T.Equal(before + 1, SlaveTabLines.All.Count, "line count after adding the same id twice"); + + Pawn prisoner = Prisoner(); + List forPrisoner = SlaveTabLines.LabelsFor(prisoner); + T.Check(forPrisoner.Contains("second " + prisoner.LabelShort) && !forPrisoner.Any(l => l.StartsWith("first ")), + "prisonersToo line: expected the replacement in the prisoner tab, got [" + string.Join(" | ", forPrisoner) + "]"); + + Pawn slave = Fixtures.ColonySlave(); + List forSlave = SlaveTabLines.LabelsFor(slave); + int ours = forSlave.IndexOf(TimeAsSlave.Label(slave)); + int added = forSlave.IndexOf("second " + slave.LabelShort); + T.Check(ours >= 0 && added > ours, "slave tab order: expected time as slave first, then the added line, got [" + string.Join(" | ", forSlave) + "]"); + + SlaveTabLines.Add(new SlaveTabLine(id + ".hidden", p => "hidden", visible: p => false)); + T.Check(!SlaveTabLines.LabelsFor(slave).Contains("hidden"), "line with visible=false shown"); + } + finally + { + SlaveTabLines.Remove(id); + SlaveTabLines.Remove(id + ".hidden"); + } + T.Equal(before, SlaveTabLines.All.Count, "line count after removing the test lines"); + } + + [BlaxTest("time as slave: the tab line reads the tab's own pawn (ITab.SelPawn binding)")] + public static void TabReadsItsPawn() + { + Pawn slave = Fixtures.ColonySlave(); + var tab = new FixedPawnTab { pawn = slave }; + T.Check(Patch_SlaveTabLines.PawnOf(tab) == slave, + "Patch_SlaveTabLines.PawnOf ignored the tab's SelPawn override (protected ITab.SelPawn not bound, fell back to the selection)"); + } + + // ---- reload ----------------------------------------------------------------------- + + [BlaxTest("time as slave (reload): the counter survives save and load", phase: 2)] + public static void CounterSurvivesReload() + { + T.Carry.TryGetValue("timeAsSlave.pawn", out string id); + T.Carry.TryGetValue("timeAsSlave.ticks", out string carried); + bool parsed = int.TryParse(carried, out int before); + 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"); + Pawn pawn = Fixtures.FindPawnById(id); + T.NotNull(pawn, $"slave {id} after reload (destroyed, or made to leave by a later phase-1 test?)"); + int after = TimeAsSlave.Ticks(pawn); + T.Info($"{pawn.LabelShort}: {before} ticks before the save, {after} after the reload, slave of colony={pawn.IsSlaveOfColony}"); + // Later phase-1 tests keep ticking, so the value may only have grown. + T.Check(after >= before && after > 0, $"counter after reload is {after}, below the {before} it had before the save"); + } + + [BlaxTest("time as slave (reload): no null or destroyed pawn comes back from the save", phase: 2)] + public static void ReloadHasNoStalePawns() + { + T.NotNull(Counter, "GameComponent_TimeAsSlave after reload"); + T.Check(Counter.TrackedPawns.All(p => p != null), "a null pawn is tracked after the reload"); + // Earlier phase-2 tests clean up slaves they killed, so destroyed pawns can be tracked here + // until the next purge (every save). Purge must clear them. + int destroyed = Counter.TrackedPawns.Count(p => p.Destroyed); + Counter.Purge(); + T.Check(Counter.TrackedPawns.All(p => p != null && !p.Destroyed), "Purge left a destroyed pawn tracked after the reload"); + 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.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"); + } + + // ---- helpers ---------------------------------------------------------------------- + + private static bool HasOurPostfix(MethodInfo target, System.Type patchClass) + { + Patches info = Harmony.GetPatchInfo(target); + return info != null && info.Postfixes.Any(p => p.owner == HarmonyId && p.PatchMethod.DeclaringType == patchClass); + } + + private static Pawn Prisoner() + { + Faction from = Fixtures.HostileFaction() ?? Fixtures.FriendlyFaction(); + Pawn p = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, from)); + p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner); + T.Check(p.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony"); + return p; + } + + /// A visitor tab whose SelPawn is fixed, so PawnOf must use the virtual getter, not the selection. + private class FixedPawnTab : ITab_Pawn_Visitor + { + public Pawn pawn; + + protected override Pawn SelPawn => pawn; + } + } +} diff --git a/Tests/BlaxSlavesTests/Source/TraderBuyersTests.cs b/Tests/BlaxSlavesTests/Source/TraderBuyersTests.cs new file mode 100644 index 0000000..796fdd7 --- /dev/null +++ b/Tests/BlaxSlavesTests/Source/TraderBuyersTests.cs @@ -0,0 +1,792 @@ +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 +{ + /// + /// 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. + /// + public class StockGenerator_BlaxTestPawnBroker : StockGenerator + { + public override IEnumerable GenerateThings(PlanetTile forTile, Faction faction = null) => Enumerable.Empty(); + + public override bool HandlesThingDef(ThingDef thingDef) => thingDef == ThingDefOf.Human; + } + + /// + /// "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. + /// + public static class TraderBuyersTests + { + /// Vanilla and Royalty kinds with no humanlike generator, even after Patches/BlaxSlaves_Traders.xml. + 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(); + var gained = new List(); + int checkedKinds = 0; + foreach (TraderKindDef def in DefDatabase.AllDefsListForReading) + { + List 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.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> 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(); + foreach (var kv in on) + { + List 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 now = kv.Key.stockGenerators; + List theirsBefore = kv.Value.Where(g => !(g is StockGenerator_BlaxBuySlaves)).ToList(); + List 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 visitors = TraderBuyers.VisitorKinds(); + T.Check(visitors.Count > 0, "no FactionDef lists visitorTraderKinds"); + List bare = DefDatabase.AllDefsListForReading + .Where(d => d.stockGenerators != null && !TraderBuyers.IsExcluded(d) && !TraderBuyers.OthersBuyHumans(d)).ToList(); + List bareVisitors = bare.Where(visitors.Contains).ToList(); + List 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(); + 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.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()), "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.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 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 visitors = TraderBuyers.VisitorKinds(); + List clean = DefDatabase.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) + T.Skip("Ideology inactive: the gate only acts with Ideology"); + 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) + T.Skip("Ideology inactive: TradeUI never calls DrawCaptiveTradeInfo, 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); + 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 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) + T.Skip("Ideology inactive: the gate only acts with Ideology"); + 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"); + }); + } + + // ---- 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(); + 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)AccessTools.Field(typeof(TraderBuyers), "originalRespect")?.GetValue(null); + T.NotNull(startup, "TraderBuyers.originalRespect"); + List 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.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 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.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 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(); + HashSet 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 visitors = TraderBuyers.VisitorKinds(); + var problems = new List(); + foreach (TraderKindDef def in DefDatabase.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 -------------------------------------------------- + + /// Changes settings, raises SettingsChanged, runs the body, then restores and re-applies. + private static void Change(Action set, Action body) + { + Dictionary snapshot = Fixtures.SnapshotSettings(); + try + { + Set(set); + body(); + } + finally + { + Fixtures.RestoreSettings(snapshot); + TraderBuyers.Apply(); + } + } + + private static void Set(Action set) + { + set(Fixtures.Settings); + RaiseSettingsChanged(); + } + + /// + /// 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. + /// + private static void RaiseSettingsChanged() + { + FieldInfo field = AccessTools.Field(typeof(BlaxSlavesMod), nameof(BlaxSlavesMod.SettingsChanged)); + T.NotNull(field, "backing field of BlaxSlavesMod.SettingsChanged"); + List 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.GetNamedSilentFail(defName); + T.NotNull(def, "TraderKindDef " + defName); + return def; + } + + private static List Ours(TraderKindDef def) => + def?.stockGenerators?.OfType().ToList() ?? new List(); + + private static List SlaveGenerators(TraderKindDef def) => + def?.stockGenerators?.OfType().ToList() ?? new List(); + + private static List<(TraderKindDef def, StockGenerator_Slaves gen)> AllSlaveGenerators() => + DefDatabase.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> Snapshot() => + DefDatabase.AllDefsListForReading.Where(d => d.stockGenerators != null) + .ToDictionary(d => d, d => d.stockGenerators.ToList()); + + private static bool SameRefs(List a, List b) => + a.Count == b.Count && a.Zip(b, (x, y) => ReferenceEquals(x, y)).All(same => same); + + private static string Describe(List 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()); + + /// A trader kind that exists only for the test, never in the DefDatabase. + private static TraderKindDef FakeKind(StockGenerator gen) => + new TraderKindDef { defName = "BlaxTestKind", stockGenerators = new List { 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 ----------------------------------------------------- + + /// A trader with a chosen faction and kind, nothing else. Never spawned, never traded with. + 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 Goods => Enumerable.Empty(); + 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 ColonyThingsWillingToBuy(Pawn playerNegotiator) => Enumerable.Empty(); + public void GiveSoldThingToTrader(Thing toGive, int countToGive, Pawn playerNegotiator) { } + public void GiveSoldThingToPlayer(Thing toGive, int countToGive, Pawn playerNegotiator) { } + } + + /// + /// 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. + /// + 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 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); + } + + /// Tradeable_Pawn.TraderWillTrade for a colony pawn, read inside a trade session with this trader. + private static bool WillTrade(ITrader trader, Pawn pawn, bool gift = false) => + InSession(trader, pawn, gift, row => row.TraderWillTrade); + + /// Whether the trade window's reason patch explains this colony pawn's row, inside a trade session with this trader. + private static bool Explains(ITrader trader, Pawn pawn, bool gift = false) => + InSession(trader, pawn, gift, row => Patch_TraderRefusesCaptiveReason.Explains(row, trader, out _)); + + /// Reads a trade row for a colony pawn with TradeSession.trader and giftMode set, then puts both back. + private static TR InSession(ITrader trader, Pawn pawn, bool gift, Func 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; + } + } + + /// + /// 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. + /// + 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.GetNamedSilentFail("Slavery_Honorable") + ?? DefDatabase.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; + } + + /// Runs the body with the faction following only this ideoligion, then puts its own back. + private static void WithIdeos(Faction faction, Ideo ideo, Action body) + { + Ideo oldPrimary = faction.ideos.PrimaryIdeo; + List minor = faction.ideos.IdeosMinorListForReading; + List oldMinor = minor.ToList(); + try + { + faction.ideos.SetPrimary(ideo); + minor.Clear(); + body(); + } + finally + { + faction.ideos.SetPrimary(oldPrimary); + minor.Clear(); + minor.AddRange(oldMinor); + } + } + + // ---- helpers: generated stock ---------------------------------------------------- + + /// Only the generator's first item, so a round costs one pawn at most. True if it is a humanlike pawn. + private static bool FirstSlave(StockGenerator_Slaves gen, Faction faction, int seed, List 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(); + } + } + + /// + /// World pawns before generation. StockGenerator_Slaves asks for forceGenerateNewPawn: false, so + /// PawnGenerator may redress one of them instead of making a new pawn. + /// + private static HashSet WorldSnapshot() => new HashSet(Find.WorldPawns.AllPawnsAliveOrDead); + + /// Fresh pawns are discarded, redressed world pawns go back to the world, as TradersTests does. + private static void DiscardAll(IEnumerable things, HashSet 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); + } + } + } + } +} diff --git a/Tests/BlaxSlavesTests/Source/TradersTests.cs b/Tests/BlaxSlavesTests/Source/TradersTests.cs index 3fae841..f3bf6ae 100644 --- a/Tests/BlaxSlavesTests/Source/TradersTests.cs +++ b/Tests/BlaxSlavesTests/Source/TradersTests.cs @@ -155,7 +155,12 @@ namespace BlaxSlavesTests TraderKindDef empire = DefDatabase.GetNamedSilentFail("Base_Empire_Standard"); if (empire != null && !SlaveGenerators(empire).Any(g => g.slaveKindDef != null && g.slaveKindDef.defName == "Slave_Empire")) - problems.Add("Base_Empire_Standard lost its Slave_Empire slaveKindDef (the patch should only replace countRange)"); + { + 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)"); + } T.Info("settlement trader kinds with slaves: " + string.Join(", ", withSlaves.Select(d => d.defName))); T.Check(problems.Count == 0, string.Join("; ", problems)); @@ -168,9 +173,16 @@ namespace BlaxSlavesTests { var problems = new List(); var seen = new List(); + 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"); + } foreach (var kv in SlaverSlaveCount) { TraderKindDef def = TraderDef(kv.Key); + IntRange expected = new IntRange(kv.Value.min, kv.Value.max + syrExtra); for (int seed = 1; seed <= 3; seed++) { TradeShip ship = null; @@ -191,8 +203,8 @@ namespace BlaxSlavesTests } int slaves = stock.OfType().Count(p => p.RaceProps.Humanlike); seen.Add($"{def.defName}#{seed}={slaves} ({how})"); - if (slaves < kv.Value.min || slaves > kv.Value.max) - problems.Add($"{def.defName} seed {seed}: {slaves} slaves via {how}, expected {Show(kv.Value)}"); + if (slaves < expected.min || slaves > expected.max) + problems.Add($"{def.defName} seed {seed}: {slaves} slaves via {how}, expected {Show(expected)}"); } finally { @@ -477,13 +489,18 @@ namespace BlaxSlavesTests T.Info("Royalty's Slave_Empire or Base_Empire_Standard missing, custom slave kind not checked"); return; } - T.Check(SlaveGenerators(empireBase).Any(g => g.slaveKindDef == empireSlave), "Base_Empire_Standard has no Slave_Empire slave generator"); + 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"); - 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"); + 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"); + } TraderKindDef generic = TraderDef("Caravan_Outlander_BulkGoods"); Pawn stray = Fixtures.Generate(empireSlave, trading); @@ -611,6 +628,42 @@ namespace BlaxSlavesTests private static string Show(IntRange r) => r.min + "~" + r.max; + /// + /// 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). + /// + 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; + } + private static string Who(Pawn p) => p.LabelShort + " [" + p.ThingID + "]"; private static bool ApprovesSlavery(Faction f) => diff --git a/Tests/run-tests.ps1 b/Tests/run-tests.ps1 index c5fd6ed..02403b6 100644 --- a/Tests/run-tests.ps1 +++ b/Tests/run-tests.ps1 @@ -56,7 +56,8 @@ foreach ($dlc in 'Royalty', 'Ideology', 'Biotech', 'Anomaly', 'Odyssey') { } if ($Compat) { foreach ($id in 'unlimitedhugs.hugslib', 'orion.hospitality', 'smuffle.harvestorganspostmortem', - 'mersid.wce2updated.core', 'mlie.syrmoreslaves', 'bblkepling.everybodybuysslaves') { + 'mersid.wce2updated.core', 'mlie.syrmoreslaves', 'bblkepling.everybodybuysslaves', + 'rhajiit.tradepurchasemode') { Add-WithDependencies $id $mods } } diff --git a/docs/roadmap.md b/docs/roadmap.md index 95d1718..ea4a70b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -39,12 +39,12 @@ The hard requirement: buy-mode replaces Trade as Slave or Colonist, which is in #### Buy as slave or colonist -- **Players get:** In the trade window, the "Joins as slave / Joins as colonist" label on each pawn a trader sells becomes a button. Click it to switch, and the price updates at once (a slave costs 60% of the colonist price, as in vanilla). Unwaveringly loyal pawns from orbital and settlement stock can only be bought as slaves, and the tooltip says why. -- **How:** A prefix on TransferableUIUtility.DrawCaptiveTradeInfo takes over only the trader-stock branch; TradeUI calls it only while Ideology is active. Colony captives keep vanilla's ransom and slave icon. The button fills vanilla's 140 px rect and its tooltip lists both prices. A click flips guest.joinStatus between JoinAsSlave and JoinAsColonist (colonist only if guest.Recruitable), sets Tradeable's private pricePlayerBuy and pricePlayerSell to -1 through FieldRefAccess so InitPriceDataIfNeeded recomputes, then calls TradeSession.deal.UpdateCurrencyCount(). ResolveTrade stays unpatched: vanilla Pawn.PreTraded(PlayerBuys) reads joinStatus. The default purchase mode is a new first step in the existing Patch_TraderSlaveBrand postfix on ThingWithComps.PostGeneratedForTrader. It must run before that postfix's early returns (children, non-Slave-kind stock, already branded pawns), or those pawns keep vanilla's 25/75 roll. Stands down and logs when Rhajiit.tradepurchasemode is active. Hidden without Ideology. -- **Settings:** buyModeEnabled (on). defaultPurchaseMode: vanilla roll (default), always slave, always colonist; recruitable pawns only. +- **Players get:** In the trade window, the "Joins as slave / Joins as colonist" label on each pawn a trader sells becomes a button. Click it to switch, and the price updates at once (a slave costs 60% of the colonist price, as in vanilla). Unwaveringly loyal pawns keep the terms vanilla rolled for them (usually slave), so the button is greyed out for them and the tooltip says why. +- **How:** A prefix on TransferableUIUtility.DrawCaptiveTradeInfo takes over only the trader-stock branch; TradeUI calls it only while Ideology is active. Colony captives keep vanilla's ransom and slave icon. The button is 140 px (vanilla's label width), growing to 170 px into the empty colony column for long translations, which are cut with "..." beyond that; its tooltip lists both prices. A click flips guest.joinStatus between JoinAsSlave and JoinAsColonist, refused both ways for an unrecruitable pawn (vanilla can roll such a pawn as a colonist, and a one-way flip would lose that offer for good), sets Tradeable's private pricePlayerBuy and pricePlayerSell to -1 through FieldRefAccess so InitPriceDataIfNeeded recomputes, then calls TradeSession.deal.UpdateCurrencyCount(). ResolveTrade stays unpatched: vanilla Pawn.PreTraded(PlayerBuys) reads joinStatus. The default purchase mode is a new first step in the existing Patch_TraderSlaveBrand postfix on ThingWithComps.PostGeneratedForTrader. It must run before that postfix's early returns (children, non-Slave-kind stock, already branded pawns), or those pawns keep vanilla's 25/75 roll. Stands down and logs when Rhajiit.tradepurchasemode is active. Hidden without Ideology. +- **Settings:** buyModeEnabled (on). defaultPurchaseMode: vanilla roll (default), always slave, always colonist; always colonist: recruitable pawns only (caravan chattel once the caravan's LordJob_TradeWithColony makes it recruitable). - **Replaces:** Trade as Slave or Colonist 3838162426 (111 subs, in your mod list). - **Effort:** M. -- **Tests:** Generate Orbital_PirateMerchant stock through a real TradeShip and TradeSession.SetupWith (existing TradersTests pattern). Toggle flips joinStatus, and the colonist to slave price ratio is 1/0.6 within 1%. With unwavering prisoners on, an orbital stock pawn with Recruitable false refuses the toggle. A caravan pawn stays recruitable (vanilla's LordJob_TradeWithColony clause), so the toggle works there. ResolveTrade as colonist gives !IsSlave, player faction and FreedFromSlavery; as slave it gives IsSlaveOfColony. "Always slave" makes every recruitable stock pawn JoinAsSlave, children and already branded pawns included, and the brand roll still runs. Phase 2: a toggled pawn keeps its joinStatus. +- **Tests:** Generate Orbital_PirateMerchant stock through a real TradeShip and TradeSession.SetupWith (existing TradersTests pattern). Toggle flips joinStatus, and the colonist to slave price ratio is 1/0.6 within 1%. With unwavering prisoners on, an orbital stock pawn with Recruitable false refuses the toggle in both directions. A caravan pawn stays recruitable (vanilla's LordJob_TradeWithColony clause), so the toggle works there. ResolveTrade as colonist gives !IsSlave, player faction and FreedFromSlavery; as slave it gives IsSlaveOfColony. "Always slave" makes every stock pawn JoinAsSlave, unrecruitable ones, children and already branded pawns included, and the brand roll still runs. "Always colonist" makes unrecruitable caravan chattel JoinAsColonist once the caravan's trade lord is made, while orbital stock stays JoinAsSlave. Phase 2: a toggled pawn keeps its joinStatus. - **Risks:** Rimdeed also patches DrawCaptiveTradeInfo; we take only the stock branch. A choice made and then cancelled stays on the stock pawn (saved, harmless). A trader-branded slave bought as colonist keeps the old brand; SlaveHarm already ignores brands on free colonists. #### Every trader buys slaves @@ -69,18 +69,18 @@ The hard requirement: buy-mode replaces Trade as Slave or Colonist, which is in #### Slave price sliders -- **Players get:** Two sliders set what slaves cost (vanilla 60% of the colonist price) and what captives fetch (vanilla 60%). The trade tooltip shows the factor in use. A hard cap means no buy-low, sell-high loop between traders. -- **How:** One Patch_SlavePrices on the private Tradeable.InitPriceDataIfNeeded. A prefix stores in __state whether pricePlayerBuy <= 0, so the postfix only acts after a real compute, not after the cached early return. The postfix, for humanlike pawns with Ideology, sets priceFactorBuy_JoinAs (when it is 0.6) to slaveBuyFactor and priceFactorSell_HumanPawn to slaveSellFactor, then recomputes both prices with the public TradeUtility.GetPricePlayerBuy and GetPricePlayerSell, passing the stored priceFactor and priceGain fields read through FieldRefAccess. It does not scale the stored prices, because vanilla stores them already clamped and rounded. Then it re-clamps sell <= buy and applies the hard cap: a humanlike captive's sell price is at most 0.9 x TradeUtility.GetPricePlayerBuy for the same pawn as a slave, with slaveBuyFactor and the same negotiator and settlement gains. Vanilla's GetPriceTooltip reads the factor fields, so the tooltip updates with no extra patch. Numbers: vanilla sale is market value x 0.6 x 0.6 = 36%, so an average adult (MV 1,750) fetches 630. Appraisal, abolitionist buyers and indenture pricing extend this one postfix. +- **Players get:** Two sliders set what slaves cost (vanilla 60% of the colonist price) and what captives fetch (vanilla 60%). The trade tooltip shows the factor in use. A hard cap means no buy-low, sell-high loop, between traders or by switching negotiators. +- **How:** One Patch_SlavePrices on the private Tradeable.InitPriceDataIfNeeded. A prefix stores in __state whether pricePlayerBuy <= 0, so the postfix only acts after a real compute, not after the cached early return. The postfix, for humanlike pawns with Ideology, sets priceFactorBuy_JoinAs (when it is 0.6) to slaveBuyFactor and priceFactorSell_HumanPawn to slaveSellFactor, then recomputes both prices with the public TradeUtility.GetPricePlayerBuy and GetPricePlayerSell, passing the stored priceFactor and priceGain fields read through FieldRefAccess. It does not scale the stored prices, because vanilla stores them already clamped and rounded. Then it re-clamps sell <= buy and applies the hard cap: a humanlike captive's sell price is at most 0.9 x TradeUtility.GetPricePlayerBuy for the same pawn as a slave, with slaveBuyFactor, the trader's buy price type counted at most Normal, its settlement gain, and the best negotiator gain any pawn can reach (TradePriceImprovement's maxValue, 0.395) instead of the current negotiator's. So the cap doesn't fall as Social rises, and buying with a skilled negotiator and selling with a poor one can't loop (the cheapest Normal purchase is 1.4 x buy factor x 0.585, the cap at most 0.9 x 1.4 x buy factor x 0.605). While slaveBuyFactor is at vanilla or above, the cap never goes below vanilla's own 60% sale price for the current negotiator, so raising only the sell slider never pays less than vanilla. That floor pays at most vanilla's sale against purchase prices at or above vanilla's, so it adds no loop vanilla lacks; below a 60% buy factor it is off, or the loop returns. Vanilla's GetPriceTooltip reads the factor fields, so the tooltip updates with no extra patch. Numbers: vanilla sale is market value x 0.6 x 0.6 = 36%, so an average adult (MV 1,750) fetches 630. Appraisal, abolitionist buyers and indenture pricing extend this one postfix. - **Settings:** slaveSellFactor 60% (30 to 100), slaveBuyFactor 60% (30 to 100). - **Replaces:** Profitable Slave Trade 3492615816 (378 subs, its +30% part). - **Effort:** S. -- **Tests:** At sell factor 0.8 the price equals GetPricePlayerSell with factor 0.8 (within 1) and never exceeds the buy price. A second InitPriceDataIfNeeded call leaves both prices unchanged. At 0.6/0.6 both prices equal vanilla exactly. A JoinAsSlave stock pawn at buy factor 0.5 costs the recomputed price. At sell factor 100% with a Social 20 negotiator the sell price stays below 0.9 x the slave buy price. The tooltip shows the new percentage. +- **Tests:** At sell factor 0.8 the price equals GetPricePlayerSell with factor 0.8 (within 1) and never exceeds the buy price. A second InitPriceDataIfNeeded call leaves both prices unchanged. At 0.6/0.6 both prices equal vanilla exactly. A JoinAsSlave stock pawn at buy factor 0.5 costs the recomputed price. At sell 100%/buy 50% with a Social 20 negotiator the sell price equals 0.9 x the best negotiator's slave buy price. At sell 60%/buy 30%, a stock slave bought with a Social 20 negotiator sells for less with a Social 0 one in a new session, and the Social 20 seller never gets less than the Social 0 one. At sell 65%/buy 60% a Social 20 seller gets at least vanilla's 60% price. The tooltip shows the new percentage. - **Risks:** A higher sell factor makes raider farming pay, so the default is vanilla and the cap bounds loops. #### Time as a slave - **Players get:** The Records tab shows how long each pawn has been your slave, and the slave tab shows "Enslaved for 23 days (tracked since install)". -- **How:** New RecordDef BlaxSlaves_TimeAsColonySlave (type Time) with a RecordWorker whose ShouldMeasureTimeNow returns pawn.IsSlaveOfColony. Vanilla's records tracker adds the time every 80 ticks with no patch; vanilla's own colonist-time record excludes slaves. A postfix on the private ITab_Pawn_Visitor.DoSlavePriceListing puts the line next to "Slave price" (the method also runs in the prisoner tab, so check IsSlave). The tab sizes itself, so the line can't be cut off. This postfix becomes the one place for later lines: appraised value, persuasion, loyalty, term. +- **How:** No RecordDef: vanilla saves records by def index (DefMap), so an added RecordDef shifts every later mod's record values when the mod is added to or removed from a save. Instead GameComponent_TimeAsSlave keeps pawn -> ticks and adds 250 ticks every 250 ticks to each colony slave from PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_SlavesOfColony (maps, caravans, transporters), purging destroyed pawns on save and load. A postfix on the private RecordsCardUtility.DrawTimeRecords draws the row in the Records tab. A postfix on the private ITab_Pawn_Visitor.DoSlavePriceListing puts the line next to "Slave price" (the method also runs in the prisoner tab, so check IsSlave). The tab sizes itself, so the line can't be cut off. This postfix becomes the one place for later lines: appraised value, persuasion, loyalty, term. - **Settings:** showTimeInSlaveTab (on). The record always counts. - **Replaces:** Time As a Slave 3310058867 (35,004 subs, no 1.7). - **Effort:** S. @@ -90,7 +90,7 @@ The hard requirement: buy-mode replaces Trade as Slave or Colonist, which is in #### Settings tabs, Compat tab and sibling hooks - **Players get:** The settings window gets tabs (Trade, Rebellion, Medicine, Freedom, General, Compat), each with a reset button; a tab appears once its release ships. The Compat tab lists active mods this version replaces, so you know what to unsubscribe, and which Blax siblings it found. -- **How:** DoSettingsWindowContents draws TabDrawer.DrawTabs plus a scroll view per tab. Existing settings move to General with unchanged Scribe keys, so saved settings carry over. Compat.IsActive moves out of SlaveHarm.cs into a shared Compat.cs helper built on ModLister.GetActiveModWithIdentifier(id, ignorePostfix: true). ModsConfig.IsActive misses a mod installed both locally and from Steam, so nothing uses it. The Compat table is a static list of packageIds (Rhajiit.tradepurchasemode, bblkepling.EverybodyBuysSlaves, Mlie.SYRMoreSlaves, then the ones later releases add); check each against its Workshop About.xml. Sibling hooks bind BlaxCastes.CastesApi and BlaxZones.ZonesApi by reflection at startup (see "Works with the other Blax mods"). First user: RunawayDelivery.TryDeliver calls CastesApi.NotifyJoined(pawn, "blax.slaves.runawayReturned") one tick after a returned runaway is delivered. About.xml gains loadAfter entries for blax.castes and blax.zones. +- **How:** DoSettingsWindowContents draws TabDrawer.DrawTabs plus a scroll view per tab. Existing settings move to General with unchanged Scribe keys, so saved settings carry over; the trader-brand slider sits on Trade, and each tab's reset covers exactly the settings it draws. Compat.IsActive moves out of SlaveHarm.cs into a shared Compat.cs helper built on ModLister.GetActiveModWithIdentifier(id, ignorePostfix: true). ModsConfig.IsActive misses a mod installed both locally and from Steam, so nothing uses it. The Compat table is a static list of packageIds (Rhajiit.tradepurchasemode, bblkepling.EverybodyBuysSlaves, Mlie.SYRMoreSlaves, then the ones later releases add); check each against its Workshop About.xml. Sibling hooks bind BlaxCastes.CastesApi and BlaxZones.ZonesApi by reflection at startup (see "Works with the other Blax mods"). First user: RunawayDelivery.TryDeliver calls CastesApi.NotifyJoined(pawn, "blax.slaves.runawayReturned") one tick after a returned runaway is delivered. About.xml gains loadAfter entries for blax.castes and blax.zones. - **Settings:** none of its own. - **Replaces:** none. - **Effort:** 2 x S (1 day).