using System; using System.Collections.Generic; using System.Reflection; using HarmonyLib; using RimWorld; using UnityEngine; using Verse; 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() { base.ExposeData(); Scribe_Values.Look(ref returnRunaways, "returnRunaways", true); Scribe_Values.Look(ref returnChance, "returnChance", 0.8f); Scribe_Values.Look(ref returnDelayMinDays, "returnDelayMinDays", 3); Scribe_Values.Look(ref returnDelayMaxDays, "returnDelayMaxDays", 10); 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); } // The settings each tab draws and its "Reset this tab" button restores (SettingsTests pins both to the tabs). public static readonly string[] GeneralFields = { nameof(returnRunaways), nameof(returnChance), nameof(returnDelayMinDays), nameof(returnDelayMaxDays), nameof(suppressSlaveHarmMood), nameof(keepRelationGrief), nameof(showTimeInSlaveTab), }; public static readonly string[] TradeFields = { nameof(traderBrandChance), nameof(buyModeEnabled), nameof(defaultPurchaseMode), nameof(allTradersBuySlaves), nameof(visitorsBuySlaves), nameof(antiSlaveryTraders), nameof(slaveStockIgnoresColonySize), nameof(slaveSellFactor), nameof(slaveBuyFactor), }; public void ResetGeneral() => Reset(GeneralFields); public void ResetTrade() => Reset(TradeFields); /// /// Puts these settings back to their defaults, except the ones that need a missing DLC: the window draws /// those greyed out and never changes them, so they keep their values for when the DLC is back. /// private void Reset(string[] fields) { var defaults = new BlaxSlavesSettings(); foreach (string name in fields) { if (BlaxSlavesMod.MissingDlc(name) != null) continue; FieldInfo field = typeof(BlaxSlavesSettings).GetField(name); field.SetValue(this, field.GetValue(defaults)); } } } public class BlaxSlavesMod : Mod { 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(); } 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.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(); } // ---- DLC-dependent settings --------------------------------------------------------------- public const string Ideology = "Ideology"; /// /// Settings that only do something with a DLC: field name to the DLC it needs. Without that DLC the /// settings window draws them greyed out with a "needs ..." note and leaves their values alone. Every /// field missing here works with any DLC combination. /// public static readonly Dictionary NeedsDlc = new Dictionary { // Trade tab: buying as slave or colonist, refusing captives over the ideoligion, trader brands and // the slave price factors all need slaves (vanilla prices captives at 100% without Ideology). { nameof(BlaxSlavesSettings.buyModeEnabled), Ideology }, { nameof(BlaxSlavesSettings.defaultPurchaseMode), Ideology }, { nameof(BlaxSlavesSettings.antiSlaveryTraders), Ideology }, { nameof(BlaxSlavesSettings.traderBrandChance), Ideology }, { nameof(BlaxSlavesSettings.slaveSellFactor), Ideology }, { nameof(BlaxSlavesSettings.slaveBuyFactor), Ideology }, // General tab: runaways, the slave harm mood gate and time as a slave. { nameof(BlaxSlavesSettings.returnRunaways), Ideology }, { nameof(BlaxSlavesSettings.returnChance), Ideology }, { nameof(BlaxSlavesSettings.returnDelayMinDays), Ideology }, { nameof(BlaxSlavesSettings.returnDelayMaxDays), Ideology }, { nameof(BlaxSlavesSettings.suppressSlaveHarmMood), Ideology }, { nameof(BlaxSlavesSettings.keepRelationGrief), Ideology }, { nameof(BlaxSlavesSettings.showTimeInSlaveTab), Ideology }, }; /// Whether a DLC (by the names NeedsDlc uses) is active. Unknown names count as active. public static bool DlcActive(string dlc) { switch (dlc) { case "Royalty": return ModsConfig.RoyaltyActive; case Ideology: return ModsConfig.IdeologyActive; case "Biotech": return ModsConfig.BiotechActive; case "Anomaly": return ModsConfig.AnomalyActive; case "Odyssey": return ModsConfig.OdysseyActive; default: return true; } } /// The DLC a setting needs and that is not active, or null when the setting works now. public static string MissingDlc(string field) => field != null && NeedsDlc.TryGetValue(field, out string dlc) && !DlcActive(dlc) ? dlc : null; /// The DLC every one of these settings is missing (the first one's), or null when any of them works now. public static string MissingDlcForAll(IEnumerable fields) { string missing = null; foreach (string field in fields) { string dlc = MissingDlc(field); if (dlc == null) return null; missing ??= dlc; } return missing; } /// "Label (needs Ideology)". public static string WithDlcNote(string label, string dlc) => "BlaxSlaves_NeedsDlc".Translate(label, dlc); // With the DLC active these draw exactly what Listing_Standard draws. Without it: the same row greyed // out, with the note, taking no input. Fields go in by ref, so the tab methods still read every field // directly (SettingsTests reads their IL to pin each tab's reset button to what it draws). private static void Checkbox(Listing_Standard l, string label, ref bool value, string field, string tooltip) { string dlc = MissingDlc(field); if (dlc == null) { l.CheckboxLabeled(label, ref value, tooltip); return; } label = WithDlcNote(label, dlc); Rect rect = l.GetRect(Text.CalcHeight(label, l.ColumnWidth)); if (!tooltip.NullOrEmpty()) TooltipHandler.TipRegion(rect, tooltip); Color old = GUI.color; GUI.color = ColoredText.SubtleGrayColor; bool shown = value; Widgets.CheckboxLabeled(rect, label, ref shown, disabled: true); GUI.color = old; l.Gap(l.verticalSpacing); } /// A radio group's heading; gets the note when the group's setting needs a missing DLC. private static void Heading(Listing_Standard l, string label, string field) { string dlc = MissingDlc(field); if (dlc == null) { l.Label(label); return; } Grey(l, WithDlcNote(label, dlc), null); } /// True when the player picked this option; never while its setting needs a missing DLC. private static bool Radio(Listing_Standard l, string label, bool active, string field) { if (MissingDlc(field) == null) return l.RadioButton(label, active, 12f); // RadioButtonLabeled still reports clicks when disabled, so they are dropped here. l.RadioButton(label, active, 12f, null, null, disabled: true); return false; } /// /// A slider row under its label. Without the DLC only the label shows, greyed out with the note and the /// current value, and the value comes back unchanged. /// private static float Slider(Listing_Standard l, string label, float value, float min, float max, string field, string tooltip = null) { string dlc = MissingDlc(field); if (dlc != null) { Grey(l, WithDlcNote(label, dlc), tooltip); return value; } if (tooltip == null) l.Label(label); else l.Label(label, tooltip: tooltip); return l.Slider(value, min, max); } /// /// "Reset this tab". The reset itself skips settings that need a missing DLC; when every setting on the /// tab needs one, the button is greyed out with the note and takes no click. /// private static bool ResetButton(Listing_Standard l, string[] fields) { string label = "BlaxSlaves_ResetTab".Translate(); string dlc = MissingDlcForAll(fields); if (dlc == null) return l.ButtonText(label); Rect rect = l.GetRect(30f); Color old = GUI.color; GUI.color = ColoredText.SubtleGrayColor; Widgets.ButtonText(rect, WithDlcNote(label, dlc), active: false); GUI.color = old; l.Gap(l.verticalSpacing); return false; } private static void Grey(Listing_Standard l, string text, string tooltip) { Color old = GUI.color; GUI.color = ColoredText.SubtleGrayColor; if (tooltip == null) l.Label(text); else l.Label(text, tooltip: tooltip); GUI.color = old; } private static void DoTrade(Listing_Standard l) { BlaxSlavesSettings s = Settings; if (!ModsConfig.IdeologyActive) { l.Label("BlaxSlaves_SettingNeedsIdeology".Translate()); l.GapLine(); } Checkbox(l, "BlaxSlaves_SettingBuyMode".Translate(), ref s.buyModeEnabled, nameof(BlaxSlavesSettings.buyModeEnabled), "BlaxSlaves_SettingBuyModeTip".Translate()); if (Compat.IsActive(Compat.TradeAsSlaveOrColonist)) l.Label("BlaxSlaves_SettingBuyModeStandsDown".Translate()); Heading(l, "BlaxSlaves_SettingPurchaseMode".Translate(), nameof(BlaxSlavesSettings.defaultPurchaseMode)); if (Radio(l, "BlaxSlaves_SettingPurchaseVanilla".Translate(), s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseVanilla, nameof(BlaxSlavesSettings.defaultPurchaseMode))) s.defaultPurchaseMode = BlaxSlavesSettings.PurchaseVanilla; if (Radio(l, "BlaxSlaves_SettingPurchaseSlave".Translate(), s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseAlwaysSlave, nameof(BlaxSlavesSettings.defaultPurchaseMode))) s.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysSlave; if (Radio(l, "BlaxSlaves_SettingPurchaseColonist".Translate(), s.defaultPurchaseMode == BlaxSlavesSettings.PurchaseAlwaysColonist, nameof(BlaxSlavesSettings.defaultPurchaseMode))) s.defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysColonist; l.GapLine(); TraderBuyers.SettingNotes buyerNotes = TraderBuyers.Notes; // cached, DoTrade runs every frame Checkbox(l, "BlaxSlaves_SettingAllTradersBuy".Translate(), ref s.allTradersBuySlaves, nameof(BlaxSlavesSettings.allTradersBuySlaves), "BlaxSlaves_SettingAllTradersBuyTip".Translate()); if (buyerNotes.everybodyBuysTraders) l.Label("BlaxSlaves_SettingAllTradersBuyEverybodyBuys".Translate()); Checkbox(l, "BlaxSlaves_SettingVisitorsBuy".Translate(), ref s.visitorsBuySlaves, nameof(BlaxSlavesSettings.visitorsBuySlaves), "BlaxSlaves_SettingVisitorsBuyTip".Translate()); if (buyerNotes.everybodyBuysVisitors) l.Label("BlaxSlaves_SettingVisitorsBuyEverybodyBuys".Translate()); if (buyerNotes.hospitality) l.Label("BlaxSlaves_SettingVisitorsBuyHospitality".Translate()); Heading(l, "BlaxSlaves_SettingAntiSlavery".Translate(), nameof(BlaxSlavesSettings.antiSlaveryTraders)); if (Radio(l, "BlaxSlaves_SettingAntiSlaveryBuy".Translate(), s.antiSlaveryTraders == BlaxSlavesSettings.AntiSlaveryBuyAnyway, nameof(BlaxSlavesSettings.antiSlaveryTraders))) s.antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryBuyAnyway; if (Radio(l, "BlaxSlaves_SettingAntiSlaveryRefuse".Translate(), s.antiSlaveryTraders == BlaxSlavesSettings.AntiSlaveryRefuse, nameof(BlaxSlavesSettings.antiSlaveryTraders))) s.antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryRefuse; l.GapLine(); Checkbox(l, "BlaxSlaves_SettingStockAnySize".Translate(), ref s.slaveStockIgnoresColonySize, nameof(BlaxSlavesSettings.slaveStockIgnoresColonySize), "BlaxSlaves_SettingStockAnySizeTip".Translate()); s.traderBrandChance = Slider(l, "BlaxSlaves_SettingTraderBrand".Translate(s.traderBrandChance.ToStringPercent()), s.traderBrandChance, 0f, 1f, nameof(BlaxSlavesSettings.traderBrandChance)); l.GapLine(); s.slaveSellFactor = Mathf.Round(Slider(l, "BlaxSlaves_SettingSellFactor".Translate(s.slaveSellFactor.ToStringPercent()), s.slaveSellFactor, 0.3f, 1f, nameof(BlaxSlavesSettings.slaveSellFactor), "BlaxSlaves_SettingSellFactorTip".Translate()) * 20f) / 20f; s.slaveBuyFactor = Mathf.Round(Slider(l, "BlaxSlaves_SettingBuyFactor".Translate(s.slaveBuyFactor.ToStringPercent()), s.slaveBuyFactor, 0.3f, 1f, nameof(BlaxSlavesSettings.slaveBuyFactor), "BlaxSlaves_SettingBuyFactorTip".Translate()) * 20f) / 20f; l.Gap(); if (ResetButton(l, BlaxSlavesSettings.TradeFields)) s.ResetTrade(); } private static void DoGeneral(Listing_Standard l) { BlaxSlavesSettings s = Settings; if (!ModsConfig.IdeologyActive) { l.Label("BlaxSlaves_SettingGeneralNeedsIdeology".Translate()); l.GapLine(); } Checkbox(l, "BlaxSlaves_SettingReturn".Translate(), ref s.returnRunaways, nameof(BlaxSlavesSettings.returnRunaways), "BlaxSlaves_SettingReturnTip".Translate()); s.returnChance = Slider(l, "BlaxSlaves_SettingReturnChance".Translate(s.returnChance.ToStringPercent()), s.returnChance, 0f, 1f, nameof(BlaxSlavesSettings.returnChance)); s.returnDelayMinDays = Mathf.RoundToInt(Slider(l, "BlaxSlaves_SettingReturnDelayMin".Translate(s.returnDelayMinDays), s.returnDelayMinDays, 1f, 30f, nameof(BlaxSlavesSettings.returnDelayMinDays))); s.returnDelayMaxDays = Mathf.RoundToInt(Slider(l, "BlaxSlaves_SettingReturnDelayMax".Translate(s.returnDelayMaxDays), s.returnDelayMaxDays, 1f, 60f, nameof(BlaxSlavesSettings.returnDelayMaxDays))); if (s.returnDelayMaxDays < s.returnDelayMinDays) s.returnDelayMaxDays = s.returnDelayMinDays; l.GapLine(); Checkbox(l, "BlaxSlaves_SettingMood".Translate(), ref s.suppressSlaveHarmMood, nameof(BlaxSlavesSettings.suppressSlaveHarmMood), "BlaxSlaves_SettingMoodTip".Translate()); Checkbox(l, "BlaxSlaves_SettingGrief".Translate(), ref s.keepRelationGrief, nameof(BlaxSlavesSettings.keepRelationGrief), "BlaxSlaves_SettingGriefTip".Translate()); l.GapLine(); Checkbox(l, "BlaxSlaves_SettingTimeAsSlave".Translate(), ref s.showTimeInSlaveTab, nameof(BlaxSlavesSettings.showTimeInSlaveTab), "BlaxSlaves_SettingTimeAsSlaveTip".Translate()); l.Gap(); if (ResetButton(l, BlaxSlavesSettings.GeneralFields)) 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()); } } /// /// Applies the Harmony patches after every Mod class exists (so the Harmony mod has set up /// its 1.7 backend), one class at a time so a single broken target can't take the rest down. /// [StaticConstructorOnStartup] public static class BlaxSlavesStartup { public static readonly Harmony Harmony = new Harmony("blax.slaves"); static BlaxSlavesStartup() { int ok = 0, failed = 0; foreach (Type type in typeof(BlaxSlavesStartup).Assembly.GetTypes()) { if (!type.IsDefined(typeof(HarmonyPatch), false)) continue; try { Harmony.CreateClassProcessor(type).Patch(); ok++; } catch (Exception e) { failed++; Log.Error("[Blax Slaves] Patch " + type.Name + " failed: " + e); } } ok += Compat.Apply(Harmony); Log.Message("[Blax Slaves] " + ok + " patches applied" + (failed > 0 ? ", " + failed + " failed" : "")); Siblings.Init(); } } [DefOf] public static class BlaxDefOf { public static HediffDef BlaxSlaves_SlaveBrand; static BlaxDefOf() { DefOfHelper.EnsureInitializedInCtor(typeof(BlaxDefOf)); } } }