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); } } } }