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