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