feat: Blax Slaves for RimWorld 1.7

Slavery as an everyday part of the rim:
- slavers show up twice as often and carry more slaves; every caravan
  and orbital trader may have one or two for sale
- branding surgery for colony slaves; the brand remembers its owner,
  slows suppression loss, and some trader slaves arrive branded
- a branded runaway is returned by a non-hostile faction after a few
  days; hostile factions keep them
- harming slaves costs free colonists no mood, except pacifists and
  family

XML patches plus a Harmony mod built for 1.7's .NET 10 runtime.
This commit is contained in:
Fabian @ Blax Software 2026-11-27 19:53:36 +01:00
commit d331075649
13 changed files with 1438 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
Source/**/bin/
Source/**/obj/
.vs/
*.user

Binary file not shown.

Binary file not shown.

31
About/About.xml Normal file
View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<ModMetaData>
<name>Blax Slaves</name>
<author>Blax Gaming</author>
<packageId>blax.slaves</packageId>
<supportedVersions>
<li>1.7</li>
</supportedVersions>
<modDependencies>
<li>
<packageId>brrainz.harmony</packageId>
<displayName>Harmony</displayName>
<steamWorkshopUrl>steam://url/CommunityFilePage/2009463077</steamWorkshopUrl>
<downloadUrl>https://github.com/pardeike/HarmonyRimWorld/releases/latest</downloadUrl>
</li>
</modDependencies>
<loadAfter>
<li>brrainz.harmony</li>
<li>Mlie.SYRMoreSlaves</li>
</loadAfter>
<description>Slavery as an everyday part of the rim. Needs Ideology for slaves.
- Slavers (caravans and orbital slave ships) show up far more often and bring more slaves.
- Every caravan and orbital trader may have a slave or two for sale, and settlements keep more.
- Brand your slaves: a burn mark that shows who owns them. Branded slaves' suppression falls slower.
- Branded runaways come back: a non-hostile faction that finds one returns them after a few days. Hostile factions keep them.
- Some slaves you buy already carry a previous owner's brand. Rebrand them with your own mark.
- Harming slaves (execution, organ harvesting, selling, banishing, butchering) doesn't upset your colonists, except pacifists: Kind pawns and those incapable of violence still mind. Family still grieves.
Everything is adjustable in the mod settings.</description>
</ModMetaData>

79
Defs/BlaxSlaves_Brand.xml Normal file
View File

@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<Defs>
<HediffDef>
<defName>BlaxSlaves_SlaveBrand</defName>
<label>slave brand</label>
<description>A mark burned into the skin that shows who this person belongs to. A branded runaway is easy to recognize, so branded slaves give up on resisting sooner, and settlements that find one know where to bring them back.</description>
<hediffClass>HediffWithComps</hediffClass>
<defaultLabelColor>(0.85, 0.5, 0.3)</defaultLabelColor>
<isBad>false</isBad>
<initialSeverity>1</initialSeverity>
<allowMothballIfLowPriorityWorldPawn>true</allowMothballIfLowPriorityWorldPawn>
<tags>
<li>BlaxSlaves_Brand</li>
</tags>
<comps>
<li Class="BlaxSlaves.HediffCompProperties_BrandOwner" />
</comps>
<stages>
<li>
<statFactors MayRequire="Ludeon.RimWorld.Ideology">
<SlaveSuppressionFallRate MayRequire="Ludeon.RimWorld.Ideology">0.85</SlaveSuppressionFallRate>
</statFactors>
</li>
</stages>
</HediffDef>
<RecipeDef Name="BlaxSlaves_BrandBase" ParentName="SurgeryFlesh" Abstract="True">
<workAmount>600</workAmount>
<hideBodyPartNames>true</hideBodyPartNames>
<targetsBodyPart>false</targetsBodyPart>
<anesthetize>false</anesthetize>
<surgeryIgnoreEnvironment>true</surgeryIgnoreEnvironment>
<surgeryOutcomeEffect IsNull="True" />
<developmentalStageFilter>Adult</developmentalStageFilter>
<skillRequirements>
<Medicine>2</Medicine>
</skillRequirements>
<recipeUsers>
<li>Human</li>
</recipeUsers>
</RecipeDef>
<RecipeDef ParentName="BlaxSlaves_BrandBase">
<defName>BlaxSlaves_BrandSlave</defName>
<label>brand</label>
<description>Burn the colony's mark into a slave's skin. Branded slaves' suppression falls slower, and a non-hostile faction that finds a branded runaway brings them back.</description>
<workerClass>BlaxSlaves.Recipe_BrandSlave</workerClass>
<jobString>branding TargetA.</jobString>
<addsHediff>BlaxSlaves_SlaveBrand</addsHediff>
<incompatibleWithHediffTags>
<li>BlaxSlaves_Brand</li>
</incompatibleWithHediffTags>
</RecipeDef>
<RecipeDef ParentName="BlaxSlaves_BrandBase">
<defName>BlaxSlaves_RebrandSlave</defName>
<label>rebrand</label>
<description>Burn the colony's mark over a previous owner's brand.</description>
<workerClass>BlaxSlaves.Recipe_RebrandSlave</workerClass>
<jobString>rebranding TargetA.</jobString>
</RecipeDef>
<ThoughtDef>
<defName>BlaxSlaves_Branded</defName>
<workerClass>BlaxSlaves.ThoughtWorker_Branded</workerClass>
<hediff>BlaxSlaves_SlaveBrand</hediff>
<validWhileDespawned>true</validWhileDespawned>
<developmentalStageFilter>Child, Adult</developmentalStageFilter>
<stages>
<li>
<label>branded</label>
<description>Someone burned their mark into my skin. Everyone can see who owns me.</description>
<baseMoodEffect>-3</baseMoodEffect>
</li>
</stages>
</ThoughtDef>
</Defs>

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<!-- Brand -->
<BlaxSlaves_BrandOwnerTip>Owner: {0}</BlaxSlaves_BrandOwnerTip>
<BlaxSlaves_BrandedMessage>{DOCTOR_labelShort} branded {PAWN_labelShort}.</BlaxSlaves_BrandedMessage>
<BlaxSlaves_RebrandedMessage>{DOCTOR_labelShort} burned our mark over {PAWN_labelShort}'s old brand.</BlaxSlaves_RebrandedMessage>
<!-- Runaways -->
<BlaxSlaves_RunawaySearchMessage>{PAWN_nameDef} escaped, but {PAWN_possessive} brand marks {PAWN_objective} as ours. {FACTION_name} may bring {PAWN_objective} back.</BlaxSlaves_RunawaySearchMessage>
<BlaxSlaves_RunawayGoneMessage>{PAWN_nameDef} escaped. Nobody will bring {PAWN_objective} back.</BlaxSlaves_RunawayGoneMessage>
<BlaxSlaves_RunawayKeptLabel>Runaway kept: {PAWN_labelShort}</BlaxSlaves_RunawayKeptLabel>
<BlaxSlaves_RunawayKeptText>{PAWN_nameDef} ran to {FACTION_name}. They are hostile to us and will keep {PAWN_objective}, brand or not.</BlaxSlaves_RunawayKeptText>
<BlaxSlaves_RunawayReturnedLabel>Runaway returned: {PAWN_labelShort}</BlaxSlaves_RunawayReturnedLabel>
<BlaxSlaves_RunawayReturnedText>{FACTION_name} found {PAWN_nameDef}, recognized our brand and brought {PAWN_objective} back.\n\n{PAWN_pronoun} is our slave again.</BlaxSlaves_RunawayReturnedText>
<!-- Settings -->
<BlaxSlaves_SettingReturn>Return branded runaways</BlaxSlaves_SettingReturn>
<BlaxSlaves_SettingReturnTip>When a slave with our brand escapes, a non-hostile faction may bring them back. Hostile factions keep them.</BlaxSlaves_SettingReturnTip>
<BlaxSlaves_SettingReturnChance>Chance a runaway is returned: {0}</BlaxSlaves_SettingReturnChance>
<BlaxSlaves_SettingReturnDelayMin>Earliest return: {0} {0_multiple ? days : day}</BlaxSlaves_SettingReturnDelayMin>
<BlaxSlaves_SettingReturnDelayMax>Latest return: {0} {0_multiple ? days : day}</BlaxSlaves_SettingReturnDelayMax>
<BlaxSlaves_SettingMood>Harming slaves doesn't upset colonists</BlaxSlaves_SettingMood>
<BlaxSlaves_SettingMoodTip>Executing, harvesting, selling, banishing or butchering slaves gives free colonists no negative thoughts. Pacifists (Kind, or incapable of violence) still mind.</BlaxSlaves_SettingMoodTip>
<BlaxSlaves_SettingGrief>Family still grieves</BlaxSlaves_SettingGrief>
<BlaxSlaves_SettingGriefTip>Colonists related to the slave (family, lovers) keep their thoughts.</BlaxSlaves_SettingGriefTip>
<BlaxSlaves_SettingTraderBrand>Trader slaves with a previous owner's brand: {0}</BlaxSlaves_SettingTraderBrand>
</LanguageData>

View File

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="utf-8"?>
<Patch>
<!-- Slavers: the outlander "slaver" caravan, the tribal "slaver" caravan and the orbital "slave ship".
Vanilla weighs them 1 against 3 other trader kinds and drops them to zero once the colony is large. -->
<Operation Class="PatchOperationReplace">
<success>Always</success>
<xpath>Defs/TraderKindDef[defName="Caravan_Outlander_PirateMerchant" or defName="Caravan_Neolithic_Slaver" or defName="Orbital_PirateMerchant"]/commonality</xpath>
<value>
<commonality>2</commonality>
</value>
</Operation>
<Operation Class="PatchOperationAdd">
<success>Always</success>
<xpath>Defs/TraderKindDef[(defName="Caravan_Outlander_PirateMerchant" or defName="Caravan_Neolithic_Slaver" or defName="Orbital_PirateMerchant") and not(commonality)]</xpath>
<value>
<commonality>2</commonality>
</value>
</Operation>
<!-- Vanilla: (0.2, 0) (1, 1) (2, 3), so a big colony never sees slavers. Keep at least half weight. -->
<Operation Class="PatchOperationReplace">
<success>Always</success>
<xpath>Defs/TraderKindDef[defName="Caravan_Outlander_PirateMerchant" or defName="Caravan_Neolithic_Slaver" or defName="Orbital_PirateMerchant"]/commonalityMultFromPopulationIntent</xpath>
<value>
<commonalityMultFromPopulationIntent>
<points>
<li>(0, 0.5)</li>
<li>(1, 1)</li>
<li>(2, 2)</li>
</points>
</commonalityMultFromPopulationIntent>
</value>
</Operation>
<!-- Slaver stock: vanilla 2~4 each. -->
<Operation Class="PatchOperationReplace">
<xpath>Defs/TraderKindDef[defName="Caravan_Outlander_PirateMerchant"]/stockGenerators/li[@Class="StockGenerator_Slaves"]/countRange</xpath>
<value>
<countRange>5~9</countRange>
</value>
</Operation>
<Operation Class="PatchOperationReplace">
<xpath>Defs/TraderKindDef[defName="Caravan_Neolithic_Slaver"]/stockGenerators/li[@Class="StockGenerator_Slaves"]/countRange</xpath>
<value>
<countRange>4~7</countRange>
</value>
</Operation>
<Operation Class="PatchOperationReplace">
<xpath>Defs/TraderKindDef[defName="Orbital_PirateMerchant"]/stockGenerators/li[@Class="StockGenerator_Slaves"]/countRange</xpath>
<value>
<countRange>6~10</countRange>
</value>
</Operation>
<!-- Every other caravan and orbital trader: about half of them carry 1~2 slaves. -->
<Operation Class="PatchOperationAdd">
<success>Always</success>
<xpath>Defs/TraderKindDef[(starts-with(defName, "Caravan_") or starts-with(defName, "Orbital_")) and not(stockGenerators/li[@Class="StockGenerator_Slaves"])]/stockGenerators</xpath>
<value>
<li Class="StockGenerator_Slaves">
<countRange>-1~2</countRange>
</li>
</value>
</Operation>
<!-- Settlements: vanilla -1~2. -->
<Operation Class="PatchOperationReplace">
<success>Always</success>
<xpath>Defs/TraderKindDef[starts-with(defName, "Base_")]/stockGenerators/li[@Class="StockGenerator_Slaves"]/countRange</xpath>
<value>
<countRange>1~4</countRange>
</value>
</Operation>
</Patch>

43
README.md Normal file
View File

@ -0,0 +1,43 @@
# Blax Slaves
RimWorld mod (1.7) that makes slavery an everyday part of the rim. First mod under the Blax Gaming label. Needs Harmony; slaves need Ideology.
## Features
- **Slavers are common.** The three vanilla slavers (outlander "slaver" caravan, tribal "slaver" caravan, orbital "slave ship") get commonality 2 instead of 1, and big colonies keep seeing them at half weight instead of zero. They carry more: outlander 5~9, tribal 4~7, slave ship 6~10 (vanilla 2~4). Every other caravan and orbital trader has a ~50% chance of 1~2 slaves, settlements stock 1~4. `Patches/BlaxSlaves_Traders.xml`
- **Branding.** "Brand" surgery for colony slaves (adults, Medicine 2, never fails). The brand remembers its owner (shown as "slave brand (Owner)"), slows suppression loss by 15%, gives the slave a -3 "branded" mood and a fresh torso burn. "Rebrand" burns your mark over another owner's. `Defs/BlaxSlaves_Brand.xml`, `Source/BlaxSlaves/Brand.cs`
- **Trader slaves come branded.** 35% of adult slaves in trader stock carry the trader faction's brand (orbital ships: a random faction).
- **Runaways come back.** A slave with your brand who escapes (slave rebellion, or a caravan whose last free member dies) is tracked. If the faction they end up with is hostile, they keep them. Otherwise, after 3~10 days (80% chance) a non-hostile faction returns them as your slave, walking in (tribal/medieval) or by drop pod. `Source/BlaxSlaves/Runaways.cs`
- **Harming slaves doesn't upset colonists.** Executing, harvesting, selling (trade or gift pod), banishing, butchering, blinding, gibbeting a slave gives free colonists no negative thoughts. Deaths only count when the colony caused them: a slave killed by raiders, animals or disease is mourned normally. Branded pawns count too unless they became free colonists. Pacifists (Kind, or incapable of violence) still mind, family still grieves, and the banish dialog shows the reduced cost. `Source/BlaxSlaves/SlaveHarm.cs`
- Mod settings for all the numbers and toggles.
Compat: War Crimes Expanded 2 torture and Harvest Organs Post Mortem autopsies count as slave harm when their mods are active. Hospitality visitor groups never take a runaway who is due to be returned. No Sympathy For Prisoners already removes slavery and execution precept thoughts for everyone, pacifists included. Load after [SYR] More Slaves, or every trader gets its extra 3~5 slaves on top of ours.
Not covered: eating slave meat, slave-leather apparel, slaves lost when a map closes or kidnapped by raiders (vanilla ransom handles those).
## Development
The repo is the mod folder. Link it into the game with a directory junction, run from the repo root (adjust the RimWorld path):
```powershell
New-Item -ItemType Junction -Path "E:\SteamLibrary\steamapps\common\RimWorld\Mods\BlaxSlaves" -Target (Get-Location).Path
```
Build (needs the .NET 10 SDK; output goes to `1.7/Assemblies/BlaxSlaves.dll`):
```powershell
dotnet build Source\BlaxSlaves\BlaxSlaves.csproj -c Release
```
`RimWorldDir` and `HarmonyDir` in the csproj point at the Steam install and the Harmony mod; override them with `-p:RimWorldDir=...` elsewhere.
RimWorld 1.7 no longer runs on Unity/Mono. It runs on .NET 10 (CoreCLR) with Ludeon's own engine ("Waylith"):
- `Assembly-CSharp.dll` and `UnityStubs.dll` (Rect, Color...) sit in the install root, and target `net10.0`.
- Harmony for 1.7 is the Harmony mod's `1.7/Assemblies/0Harmony.dll` (3.0-rc.7, Workshop 2009463077). Reference it, don't ship it. Parameterless `PatchAll()` is obsolete in Harmony 3.
- In game, the Harmony mod swaps in a Waylith method-body backend (`HarmonyMod.RuntimeIL.dll`). Check `Player.log` for `[Blax Slaves] N patches applied` and Harmony's `runtime-body provider` line.
- Patches are applied from a `[StaticConstructorOnStartup]` class, one class at a time, so one broken target can't disable the rest.
Quick test map: `RimWorld.exe -quicktest`. Dev mode: spawn a slaver caravan, enslave a prisoner, brand them, then trigger a slave rebellion from the debug actions.
A decompiled copy of the 1.7 game code for reference lives outside the repo in `..\rimworld-src-1.7` (never commit or publish it).

View File

@ -0,0 +1,43 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- RimWorld 1.7 runs on .NET 10 (CoreCLR). Build: dotnet build -c Release -->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<AssemblyName>BlaxSlaves</AssemblyName>
<RootNamespace>BlaxSlaves</RootNamespace>
<LangVersion>latest</LangVersion>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<OutputPath>..\..\1.7\Assemblies\</OutputPath>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
<GenerateDependencyFile>false</GenerateDependencyFile>
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
<DebugType>portable</DebugType>
<Deterministic>true</Deterministic>
<!-- Keep local paths out of the shipped DLL/PDB. -->
<PathMap>$(MSBuildProjectDirectory)=Source/BlaxSlaves</PathMap>
</PropertyGroup>
<!-- Override on the command line if the game or the Harmony mod live elsewhere. -->
<PropertyGroup>
<RimWorldDir Condition="'$(RimWorldDir)' == ''">E:\SteamLibrary\steamapps\common\RimWorld</RimWorldDir>
<HarmonyDir Condition="'$(HarmonyDir)' == ''">E:\SteamLibrary\steamapps\workshop\content\294100\2009463077\1.7\Assemblies</HarmonyDir>
</PropertyGroup>
<ItemGroup>
<Reference Include="Assembly-CSharp">
<HintPath>$(RimWorldDir)\Assembly-CSharp.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="UnityStubs">
<HintPath>$(RimWorldDir)\UnityStubs.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="0Harmony">
<HintPath>$(HarmonyDir)\0Harmony.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
</Project>

View File

@ -0,0 +1,112 @@
using System;
using HarmonyLib;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxSlaves
{
public class BlaxSlavesSettings : ModSettings
{
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 float traderBrandChance = 0.35f;
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);
}
}
public class BlaxSlavesMod : Mod
{
public static BlaxSlavesSettings Settings;
public BlaxSlavesMod(ModContentPack content) : base(content)
{
Settings = GetSettings<BlaxSlavesSettings>();
}
public override string SettingsCategory() => "Blax Slaves";
public override void DoSettingsWindowContents(Rect inRect)
{
var l = new Listing_Standard();
l.Begin(inRect);
l.CheckboxLabeled("BlaxSlaves_SettingReturn".Translate(), ref Settings.returnRunaways, "BlaxSlaves_SettingReturnTip".Translate());
l.Label("BlaxSlaves_SettingReturnChance".Translate(Settings.returnChance.ToStringPercent()));
Settings.returnChance = l.Slider(Settings.returnChance, 0f, 1f);
l.Label("BlaxSlaves_SettingReturnDelayMin".Translate(Settings.returnDelayMinDays));
Settings.returnDelayMinDays = Mathf.RoundToInt(l.Slider(Settings.returnDelayMinDays, 1f, 30f));
l.Label("BlaxSlaves_SettingReturnDelayMax".Translate(Settings.returnDelayMaxDays));
Settings.returnDelayMaxDays = Mathf.RoundToInt(l.Slider(Settings.returnDelayMaxDays, 1f, 60f));
if (Settings.returnDelayMaxDays < Settings.returnDelayMinDays)
Settings.returnDelayMaxDays = Settings.returnDelayMinDays;
l.GapLine();
l.CheckboxLabeled("BlaxSlaves_SettingMood".Translate(), ref Settings.suppressSlaveHarmMood, "BlaxSlaves_SettingMoodTip".Translate());
l.CheckboxLabeled("BlaxSlaves_SettingGrief".Translate(), ref Settings.keepRelationGrief, "BlaxSlaves_SettingGriefTip".Translate());
l.GapLine();
l.Label("BlaxSlaves_SettingTraderBrand".Translate(Settings.traderBrandChance.ToStringPercent()));
Settings.traderBrandChance = l.Slider(Settings.traderBrandChance, 0f, 1f);
l.End();
}
}
/// <summary>
/// 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.
/// </summary>
[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" : ""));
}
}
[DefOf]
public static class BlaxDefOf
{
public static HediffDef BlaxSlaves_SlaveBrand;
static BlaxDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(BlaxDefOf));
}
}
}

199
Source/BlaxSlaves/Brand.cs Normal file
View File

@ -0,0 +1,199 @@
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxSlaves
{
public class HediffCompProperties_BrandOwner : HediffCompProperties
{
public HediffCompProperties_BrandOwner()
{
compClass = typeof(HediffComp_BrandOwner);
}
}
/// <summary>Remembers whose mark the brand is. The name is cached in case the faction is removed.</summary>
public class HediffComp_BrandOwner : HediffComp
{
public Faction owner;
public string ownerName;
public string OwnerName => owner?.Name ?? ownerName;
public void SetOwner(Faction faction)
{
owner = faction;
ownerName = faction?.Name;
}
public override string CompLabelInBracketsExtra => OwnerName;
public override string CompTipStringExtra =>
OwnerName.NullOrEmpty() ? null : (string)"BlaxSlaves_BrandOwnerTip".Translate(OwnerName);
public override void CompExposeData()
{
base.CompExposeData();
if (Scribe.mode == LoadSaveMode.Saving && owner != null && !Find.FactionManager.AllFactionsListForReading.Contains(owner))
owner = null;
Scribe_References.Look(ref owner, "owner");
Scribe_Values.Look(ref ownerName, "ownerName");
}
public override void CopyFrom(HediffComp other)
{
base.CopyFrom(other);
if (other is HediffComp_BrandOwner o)
{
owner = o.owner;
ownerName = o.ownerName;
}
}
}
public static class BrandUtility
{
public const float FreshBurnSeverity = 10f;
public static bool IsBranded(Pawn pawn) =>
pawn?.health?.hediffSet != null && pawn.health.hediffSet.HasHediff(BlaxDefOf.BlaxSlaves_SlaveBrand);
public static HediffComp_BrandOwner BrandOf(Pawn pawn) =>
pawn?.health?.hediffSet?.GetFirstHediffOfDef(BlaxDefOf.BlaxSlaves_SlaveBrand)?.TryGetComp<HediffComp_BrandOwner>();
public static bool IsBrandedByPlayer(Pawn pawn)
{
HediffComp_BrandOwner brand = BrandOf(pawn);
return brand != null && brand.owner != null && brand.owner == Faction.OfPlayer;
}
public static void Brand(Pawn pawn, Faction owner)
{
if (IsBranded(pawn))
{
BrandOf(pawn)?.SetOwner(owner);
return;
}
Hediff brand = HediffMaker.MakeHediff(BlaxDefOf.BlaxSlaves_SlaveBrand, pawn);
brand.TryGetComp<HediffComp_BrandOwner>()?.SetOwner(owner);
pawn.health.AddHediff(brand);
}
/// <summary>A fresh burn on the core part (torso for humans): about a day of pain.</summary>
public static void AddFreshBurn(Pawn pawn, float severity = FreshBurnSeverity)
{
HediffDef burnDef = DamageDefOf.Burn?.hediff;
BodyPartRecord part = pawn.RaceProps?.body?.corePart;
if (burnDef == null || part == null || pawn.health.hediffSet.PartIsMissing(part))
return;
if (pawn.health.WouldDieAfterAddingHediff(burnDef, part, severity))
return;
Hediff burn = HediffMaker.MakeHediff(burnDef, pawn, part);
burn.Severity = severity;
// A deliberate mark, like scarification: no infection roll. After a reload the recreated
// comp starts inert (ticksUntilInfect defaults to "will not infect").
(burn as HediffWithComps)?.comps?.RemoveAll(c => c is HediffComp_Infecter);
pawn.health.AddHediff(burn, part);
}
}
/// <summary>"Branded" mood only while they're someone's slave; a freed pawn keeps the scar, not the shame.</summary>
public class ThoughtWorker_Branded : ThoughtWorker_Hediff
{
protected override ThoughtState CurrentStateInternal(Pawn p) =>
p.IsSlave ? base.CurrentStateInternal(p) : ThoughtState.Inactive;
}
/// <summary>Branding surgery: colony slaves only. Never fails, marks them as the player's.</summary>
public class Recipe_BrandSlave : Recipe_AddHediff
{
public override bool AvailableOnNow(Thing thing, BodyPartRecord part = null) =>
thing is Pawn pawn && pawn.IsSlaveOfColony && base.AvailableOnNow(thing, part);
public override bool CompletableEver(Pawn surgeryTarget) =>
base.CompletableEver(surgeryTarget) && surgeryTarget.IsSlaveOfColony;
protected override void OnSurgerySuccess(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
{
base.OnSurgerySuccess(pawn, part, billDoer, ingredients, bill);
BrandUtility.BrandOf(pawn)?.SetOwner(Faction.OfPlayer);
BrandUtility.AddFreshBurn(pawn);
if (billDoer != null)
Messages.Message("BlaxSlaves_BrandedMessage".Translate(billDoer.Named("DOCTOR"), pawn.Named("PAWN")), pawn, MessageTypeDefOf.NeutralEvent);
}
}
/// <summary>Burns the colony's mark over another owner's brand.</summary>
public class Recipe_RebrandSlave : Recipe_Surgery
{
public override bool AvailableOnNow(Thing thing, BodyPartRecord part = null)
{
if (!(thing is Pawn pawn) || !pawn.IsSlaveOfColony)
return false;
HediffComp_BrandOwner brand = BrandUtility.BrandOf(pawn);
return brand != null && brand.owner != Faction.OfPlayer
&& !pawn.BillStack.Bills.Any(b => b.recipe == recipe)
&& base.AvailableOnNow(thing, part);
}
public override bool CompletableEver(Pawn surgeryTarget) =>
base.CompletableEver(surgeryTarget) && surgeryTarget.IsSlaveOfColony
&& BrandUtility.BrandOf(surgeryTarget) is HediffComp_BrandOwner brand && brand.owner != Faction.OfPlayer;
public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
{
HediffComp_BrandOwner brand = BrandUtility.BrandOf(pawn);
if (brand == null || brand.owner == Faction.OfPlayer)
return;
brand.SetOwner(Faction.OfPlayer);
BrandUtility.AddFreshBurn(pawn);
if (billDoer != null)
Messages.Message("BlaxSlaves_RebrandedMessage".Translate(billDoer.Named("DOCTOR"), pawn.Named("PAWN")), pawn, MessageTypeDefOf.NeutralEvent);
}
}
/// <summary>Some slaves in trader stock already carry an owner's brand: the trader's faction, or another one.</summary>
[HarmonyPatch(typeof(ThingWithComps), nameof(ThingWithComps.PostGeneratedForTrader))]
public static class Patch_TraderSlaveBrand
{
public static void Postfix(ThingWithComps __instance, TraderKindDef trader, Faction forFaction)
{
if (!(__instance is Pawn pawn) || pawn.Dead || pawn.RaceProps == null || !pawn.RaceProps.Humanlike)
return;
if (pawn.ageTracker == null || !pawn.ageTracker.Adult || BrandUtility.IsBranded(pawn))
return;
if (!IsSlaveStock(pawn, trader))
return;
if (pawn.guest != null && pawn.guest.joinStatus == JoinStatus.JoinAsColonist)
return;
if (!Rand.Chance(BlaxSlavesMod.Settings.traderBrandChance))
return;
Faction owner = forFaction;
if (owner == null || owner.IsPlayer)
{
owner = Find.FactionManager.AllFactionsVisible
.Where(f => !f.IsPlayer && !f.temporary && f.def.humanlikeFaction && f != pawn.Faction)
.RandomElementWithFallback();
}
if (owner != null)
BrandUtility.Brand(pawn, owner);
}
/// <summary>
/// Only pawns a slave generator made: the Slave kind (vanilla, and More Slaves' own generator),
/// or a trader's custom slave kind (Royalty's Slave_Empire). Not hired pawns from mods like Rimdeed.
/// </summary>
private static bool IsSlaveStock(Pawn pawn, TraderKindDef trader)
{
if (trader != null && trader.defName == "RD_PawnTrader")
return false;
if (pawn.kindDef == PawnKindDefOf.Slave)
return true;
return trader?.stockGenerators != null
&& trader.stockGenerators.Any(g => g is StockGenerator_Slaves s && s.slaveKindDef != null && s.slaveKindDef == pawn.kindDef);
}
}
}

View File

@ -0,0 +1,375 @@
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using RimWorld.QuestGen;
using Verse;
namespace BlaxSlaves
{
public class RunawayRecord : IExposable
{
public Pawn pawn;
public Faction origin; // the slave's SlaveFaction before escaping
public Faction finder; // who brings them back
public SlaveInteractionModeDef mode;
public Map map;
public int dueTick;
public bool pinnedByUs;
public void ExposeData()
{
if (Scribe.mode == LoadSaveMode.Saving)
{
if (map != null && !Find.Maps.Contains(map))
map = null;
List<Faction> factions = Find.FactionManager.AllFactionsListForReading;
if (origin != null && !factions.Contains(origin))
origin = null;
if (finder != null && !factions.Contains(finder))
finder = null;
}
Scribe_References.Look(ref pawn, "pawn");
Scribe_References.Look(ref origin, "origin");
Scribe_References.Look(ref finder, "finder");
Scribe_Defs.Look(ref mode, "mode");
Scribe_References.Look(ref map, "map");
Scribe_Values.Look(ref dueTick, "dueTick");
Scribe_Values.Look(ref pinnedByUs, "pinnedByUs");
}
}
/// <summary>
/// Tracks branded slaves who escaped. A non-hostile faction brings them back after a few days.
/// A hostile faction keeps them.
/// </summary>
public class GameComponent_BlaxRunaways : GameComponent
{
private const int CheckInterval = 250;
private List<RunawayRecord> records = new List<RunawayRecord>();
private static readonly HashSet<Pawn> pending = new HashSet<Pawn>();
public static GameComponent_BlaxRunaways Instance => Current.Game?.GetComponent<GameComponent_BlaxRunaways>();
public static bool IsPending(Pawn pawn) => pawn != null && pending.Contains(pawn);
public GameComponent_BlaxRunaways(Game game)
{
pending.Clear();
}
public void Register(Pawn pawn, Faction origin, SlaveInteractionModeDef mode, Map map)
{
if (pawn == null || IsPending(pawn))
return;
BlaxSlavesSettings settings = BlaxSlavesMod.Settings;
Faction finder = pawn.Faction;
if (finder != null && finder.HostileTo(Faction.OfPlayer))
{
Find.LetterStack.ReceiveLetter(
"BlaxSlaves_RunawayKeptLabel".Translate(pawn.Named("PAWN")),
"BlaxSlaves_RunawayKeptText".Translate(pawn.Named("PAWN"), finder.Named("FACTION")),
LetterDefOf.NegativeEvent, null, finder);
return;
}
if (finder == null || finder.IsPlayer || finder.defeated || finder.Hidden)
finder = Find.FactionManager.RandomNonHostileFaction(allowHidden: false, allowDefeated: false, allowNonHumanlike: false);
if (!settings.returnRunaways || finder == null || !ModsConfig.IdeologyActive || !Rand.Chance(settings.returnChance))
{
Messages.Message("BlaxSlaves_RunawayGoneMessage".Translate(pawn.Named("PAWN")), MessageTypeDefOf.NegativeEvent);
return;
}
int minDays = settings.returnDelayMinDays;
int maxDays = settings.returnDelayMaxDays < minDays ? minDays : settings.returnDelayMaxDays;
var record = new RunawayRecord
{
pawn = pawn,
origin = origin,
finder = finder,
mode = mode,
map = map,
dueTick = Find.TickManager.TicksGame + Rand.RangeInclusive(minDays, maxDays) * GenDate.TicksPerDay,
pinnedByUs = Find.WorldPawns.ForcefullyKeptPawns.Add(pawn),
};
records.Add(record);
pending.Add(pawn);
Messages.Message("BlaxSlaves_RunawaySearchMessage".Translate(pawn.Named("PAWN"), finder.Named("FACTION")), MessageTypeDefOf.NeutralEvent);
}
public override void GameComponentTick()
{
if (records.Count == 0 || Find.TickManager.TicksGame % CheckInterval != 0)
return;
int now = Find.TickManager.TicksGame;
for (int i = records.Count - 1; i >= 0; i--)
{
RunawayRecord r = records[i];
if (r.pawn == null || r.pawn.Destroyed || r.pawn.Dead || r.pawn.Discarded)
{
Drop(i);
continue;
}
// Spawning elsewhere (a visit) drops the pin; restore it once they're back in the world.
if (r.pinnedByUs && r.pawn.IsWorldPawn())
Find.WorldPawns.ForcefullyKeptPawns.Add(r.pawn);
if (now < r.dueTick)
continue;
switch (RunawayDelivery.TryDeliver(r))
{
case DeliveryResult.Delivered:
pending.Remove(r.pawn);
records.RemoveAt(i);
break;
case DeliveryResult.Retry:
r.dueTick = now + GenDate.TicksPerDay / 2;
break;
default:
Drop(i);
break;
}
}
}
private void Drop(int index)
{
RunawayRecord r = records[index];
if (r.pawn != null)
{
pending.Remove(r.pawn);
if (r.pinnedByUs)
Find.WorldPawns.ForcefullyKeptPawns.Remove(r.pawn);
}
records.RemoveAt(index);
}
public override void ExposeData()
{
base.ExposeData();
Scribe_Collections.Look(ref records, "runaways", LookMode.Deep);
if (Scribe.mode == LoadSaveMode.PostLoadInit)
{
if (records == null)
records = new List<RunawayRecord>();
records.RemoveAll(r => r == null || r.pawn == null);
pending.Clear();
foreach (RunawayRecord r in records)
pending.Add(r.pawn);
}
}
}
public enum DeliveryResult
{
Delivered,
Retry,
Cancel,
}
public static class RunawayDelivery
{
public static DeliveryResult TryDeliver(RunawayRecord r)
{
Pawn pawn = r.pawn;
if (!pawn.IsWorldPawn())
{
// Out visiting with another mod's guest group, say: wait until they're back in the world.
// Recruited or captured by the player: nothing left to return.
if (pawn.SpawnedOrAnyParentSpawned && pawn.Faction != Faction.OfPlayer && !pawn.IsPrisoner)
return DeliveryResult.Retry;
return DeliveryResult.Cancel;
}
if (Find.WorldPawns.GetSituation(pawn) != WorldPawnSituation.Free || pawn.guest == null)
return DeliveryResult.Cancel;
Faction holder = pawn.Faction;
if (holder != null && holder.HostileTo(Faction.OfPlayer))
{
Find.LetterStack.ReceiveLetter(
"BlaxSlaves_RunawayKeptLabel".Translate(pawn.Named("PAWN")),
"BlaxSlaves_RunawayKeptText".Translate(pawn.Named("PAWN"), holder.Named("FACTION")),
LetterDefOf.NegativeEvent, null, holder);
return DeliveryResult.Cancel;
}
List<Faction> factions = Find.FactionManager.AllFactionsListForReading;
Faction deliverer = r.finder;
if (deliverer == null || !factions.Contains(deliverer) || deliverer.HostileTo(Faction.OfPlayer) || deliverer.defeated)
deliverer = holder != null && !holder.IsPlayer && !holder.Hidden ? holder : Find.FactionManager.RandomNonHostileFaction(allowNonHumanlike: false);
if (deliverer == null || !ModsConfig.IdeologyActive)
return DeliveryResult.Cancel;
Map map = r.map != null && Find.Maps.Contains(r.map) && r.map.IsPlayerHome ? r.map : Find.AnyPlayerHomeMap;
if (map == null)
return DeliveryResult.Retry;
// Put them back under their original faction first, so SlaveFaction (and HomeFaction) is
// exactly what it was before the escape, not whoever found them. Null (wild or hidden-faction
// origin) and the player (born in the colony) are restored as-is: they decide whether an
// emancipated slave stays.
Faction origin = r.origin != null && factions.Contains(r.origin) ? r.origin : null;
if (pawn.Faction != origin)
pawn.SetFaction(origin);
pawn.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
SlaveInteractionModeDef mode = r.mode;
if (mode == null || mode == SlaveInteractionModeDefOf.Execute || mode == SlaveInteractionModeDefOf.Emancipate || mode == SlaveInteractionModeDefOf.Imprison)
mode = SlaveInteractionModeDefOf.Suppress;
pawn.guest.slaveInteractionMode = mode;
pawn.apparel?.UnlockAll();
// Weapons come back separately, not in their hands (a relic they ran off with included).
var delivery = new List<Thing> { pawn };
if (pawn.equipment != null)
{
foreach (ThingWithComps eq in pawn.equipment.AllEquipmentListForReading.ToList())
{
pawn.equipment.Remove(eq);
delivery.Add(eq);
}
}
bool walkIn = deliverer.def.techLevel < TechLevel.Industrial && map.CanEverExit;
IntVec3 cell = IntVec3.Invalid;
if (walkIn
&& !CellFinder.TryFindRandomEdgeCellWith(c => c.Standable(map) && map.reachability.CanReachColony(c), map, CellFinder.EdgeRoadChance_Friendly, out cell)
&& !CellFinder.TryFindRandomEdgeCellWith(c => c.Standable(map), map, CellFinder.EdgeRoadChance_Friendly, out cell))
{
walkIn = false;
}
if (walkIn)
{
GenSpawn.Spawn(pawn, cell, map);
for (int i = 1; i < delivery.Count; i++)
GenPlace.TryPlaceThing(delivery[i], cell, map, ThingPlaceMode.Near);
}
else
{
DropPodUtility.DropThingsNear(DropCellFinder.TradeDropSpot(map), map, delivery, canRoofPunch: false, forbid: false, faction: deliverer);
}
Find.LetterStack.ReceiveLetter(
"BlaxSlaves_RunawayReturnedLabel".Translate(pawn.Named("PAWN")),
"BlaxSlaves_RunawayReturnedText".Translate(pawn.Named("PAWN"), deliverer.Named("FACTION")),
LetterDefOf.PositiveEvent, pawn, deliverer);
return DeliveryResult.Delivered;
}
}
/// <summary>Main escape path: a branded colony slave walks off the map (slave rebellion).</summary>
[HarmonyPatch(typeof(Pawn), nameof(Pawn.ExitMap))]
public static class Patch_RunawayExitMap
{
public class State
{
public Faction origin;
public SlaveInteractionModeDef mode;
public Map map;
}
public static void Prefix(Pawn __instance, out State __state)
{
__state = null;
Pawn pawn = __instance;
if (!pawn.IsSlaveOfColony || pawn.guest == null || pawn.guest.Released || pawn.teleporting || !pawn.Spawned)
return;
if (pawn.IsCaravanMember() || pawn.IsQuestLodger()
|| ThingOwnerUtility.AnyParentIs<ActiveTransporterInfo>(pawn)
|| ThingOwnerUtility.AnyParentIs<TravellingTransporters>(pawn))
return;
if (!BrandUtility.IsBrandedByPlayer(pawn))
return;
__state = new State { origin = pawn.SlaveFaction, mode = pawn.guest.slaveInteractionMode, map = pawn.Map };
}
public static void Postfix(Pawn __instance, State __state)
{
if (__state == null)
return;
Pawn pawn = __instance;
if (pawn.Dead || pawn.Destroyed || !pawn.IsWorldPawn() || pawn.IsCaravanMember())
return;
if (Find.WorldPawns.GetSituation(pawn) != WorldPawnSituation.Free)
return;
GameComponent_BlaxRunaways.Instance?.Register(pawn, __state.origin, __state.mode, __state.map);
}
}
/// <summary>
/// Second escape path: the last free member of a caravan dies and its slaves walk away.
/// Vanilla leaves them as player-faction world pawns, so give them a faction the way an escape would.
/// </summary>
[HarmonyPatch(typeof(Caravan), nameof(Caravan.Notify_MemberDied))]
public static class Patch_RunawayCaravanDisband
{
public static void Prefix(Caravan __instance, Pawn member, out List<Pawn> __state)
{
__state = null;
if (__instance.Faction != Faction.OfPlayer)
return;
List<Pawn> pawns = __instance.PawnsListForReading;
for (int i = 0; i < pawns.Count; i++)
{
if (pawns[i] != member && __instance.IsOwner(pawns[i]))
return;
}
for (int i = 0; i < pawns.Count; i++)
{
Pawn p = pawns[i];
if (p != member && p.IsSlaveOfColony && BrandUtility.IsBrandedByPlayer(p))
{
if (__state == null)
__state = new List<Pawn>();
__state.Add(p);
}
}
}
public static void Postfix(List<Pawn> __state)
{
if (__state == null)
return;
foreach (Pawn pawn in __state)
{
if (pawn.Dead || pawn.Destroyed || !pawn.IsWorldPawn() || pawn.IsCaravanMember())
continue;
Faction origin = pawn.SlaveFaction;
SlaveInteractionModeDef mode = pawn.guest?.slaveInteractionMode;
if (pawn.Faction == Faction.OfPlayer)
{
if (Find.FactionManager.TryGetRandomNonColonyHumanlikeFaction(out Faction faction, tryMedievalOrBetter: false))
pawn.SetFaction(faction);
else
pawn.SetFaction(null);
}
GameComponent_BlaxRunaways.Instance?.Register(pawn, origin, mode, null);
}
}
}
/// <summary>Keep vanilla from recycling a pending runaway into an unrelated raid, trader or slave stock.</summary>
[HarmonyPatch(typeof(PawnGenerator), "IsValidCandidateToRedress")]
public static class Patch_RunawayNoRedress
{
public static void Postfix(Pawn pawn, ref bool __result)
{
if (__result && GameComponent_BlaxRunaways.IsPending(pawn))
__result = false;
}
}
/// <summary>Keep quest generation from taking a pending runaway.</summary>
[HarmonyPatch(typeof(QuestNode_GetPawn), "IsGoodPawn")]
public static class Patch_RunawayNotForQuests
{
public static void Postfix(Pawn pawn, ref bool __result)
{
if (__result && GameComponent_BlaxRunaways.IsPending(pawn))
__result = false;
}
}
}

View File

@ -0,0 +1,446 @@
using System;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using Verse;
namespace BlaxSlaves
{
/// <summary>
/// "Owning slaves is normal": while the game hands out thoughts about something the colony did to a
/// slave, free colonists don't take the negative ones. Pacifists (Kind, or incapable of violence) still
/// do, and so does family when the relation-grief setting is on.
///
/// Thought givers rarely say who the victim was, so the patches below open a "frame" around the
/// places where the victim is still known, and one gate on TryGainMemory reads the innermost frame.
/// </summary>
public static class SlaveHarm
{
public sealed class Frame
{
public Pawn victim;
public bool protectedVictim;
public Frame previous;
}
[ThreadStatic]
private static Frame top;
public static Frame Top => top;
/// <summary>
/// Slaves, and branded pawns who aren't free members of the colony (runaways, prisoners, sold
/// slaves). A branded pawn who became a free colonist is mourned like anyone else.
/// </summary>
public static bool IsProtected(Pawn pawn) =>
pawn != null && pawn.RaceProps != null && pawn.RaceProps.Humanlike
&& (pawn.IsSlave || (pawn.Faction != Faction.OfPlayer && BrandUtility.IsBranded(pawn)));
public static Frame Push(Pawn victim, bool forceProtected = false)
{
var frame = new Frame
{
victim = victim,
protectedVictim = forceProtected || IsProtected(victim),
previous = top,
};
top = frame;
return frame;
}
public static void Pop(Frame frame)
{
if (frame != null)
top = frame.previous;
}
public static bool IsPacifist(Pawn pawn) =>
pawn.story?.traits?.HasTrait(TraitDefOf.Kind) == true || pawn.WorkTagIsDisabled(WorkTags.Violent);
public static bool ShouldSuppress(Pawn recipient, Thought thought, Pawn victim)
{
try
{
if (!BlaxSlavesMod.Settings.suppressSlaveHarmMood || recipient == null || recipient == victim)
return false;
if (recipient.Faction != Faction.OfPlayer || recipient.IsSlave || recipient.RaceProps == null || !recipient.RaceProps.Humanlike)
return false;
ThoughtStage stage = thought?.CurStage;
if (stage == null || (stage.baseMoodEffect >= 0f && stage.baseOpinionOffset >= 0f))
return false;
if (IsPacifist(recipient))
return false;
if (BlaxSlavesMod.Settings.keepRelationGrief && victim != null && recipient.GetMostImportantRelation(victim) != null)
return false;
return true;
}
catch (Exception e)
{
Log.ErrorOnce("[Blax Slaves] mood gate failed, letting the thought through: " + e, 0x6B1A5E);
return false;
}
}
/// <summary>
/// Deaths and losses only count when the colony caused them: banishment, executions and surgery
/// kills, or a killer from the player faction. Raiders, animals, disease and kidnapping don't.
/// </summary>
public static bool CausedByColony(DamageInfo? dinfo, PawnDiedOrDownedThoughtsKind kind)
{
switch (kind)
{
case PawnDiedOrDownedThoughtsKind.Banished:
case PawnDiedOrDownedThoughtsKind.BanishedToDie:
return true;
case PawnDiedOrDownedThoughtsKind.Died:
if (!dinfo.HasValue)
return false;
DamageInfo d = dinfo.Value;
if (d.Def != null && (d.Def.execution || d.Def == DamageDefOf.SurgicalCut))
return true;
return d.Instigator != null && d.Instigator.Faction == Faction.OfPlayer;
default:
return false;
}
}
}
// ---- the gate -------------------------------------------------------------------------------
[HarmonyPatch(typeof(MemoryThoughtHandler), nameof(MemoryThoughtHandler.TryGainMemory), new[] { typeof(Thought_Memory), typeof(Pawn) })]
[HarmonyPriority(Priority.Last)]
public static class Patch_SlaveHarmGate
{
public static bool Prefix(MemoryThoughtHandler __instance, Thought_Memory newThought)
{
SlaveHarm.Frame frame = SlaveHarm.Top;
if (frame == null || !frame.protectedVictim)
return true;
return !SlaveHarm.ShouldSuppress(__instance.pawn, newThought, frame.victim);
}
}
// ---- frames: places where the victim is known -----------------------------------------------
[HarmonyPatch(typeof(ThoughtUtility), nameof(ThoughtUtility.GiveThoughtsForPawnExecuted))]
public static class Frame_Executed
{
public static void Prefix(Pawn victim, out SlaveHarm.Frame __state) => __state = SlaveHarm.Push(victim);
public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state)
{
SlaveHarm.Pop(__state);
return __exception;
}
}
[HarmonyPatch(typeof(ThoughtUtility), nameof(ThoughtUtility.GiveThoughtsForPawnOrganHarvested))]
public static class Frame_OrganHarvested
{
public static void Prefix(Pawn victim, out SlaveHarm.Frame __state) => __state = SlaveHarm.Push(victim);
public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state)
{
SlaveHarm.Pop(__state);
return __exception;
}
}
/// <summary>Death, banishment and loss thoughts, protected only when the colony caused them.</summary>
[HarmonyPatch(typeof(PawnDiedOrDownedThoughtsUtility), nameof(PawnDiedOrDownedThoughtsUtility.TryGiveThoughts),
new[] { typeof(Pawn), typeof(DamageInfo?), typeof(PawnDiedOrDownedThoughtsKind) })]
public static class Frame_DiedOrDowned
{
public static void Prefix(Pawn victim, DamageInfo? dinfo, PawnDiedOrDownedThoughtsKind thoughtsKind, out SlaveHarm.Frame __state)
{
// Always push, so this victim's frame also shadows an outer frame about someone else.
__state = SlaveHarm.Push(victim);
if (__state.protectedVictim && !SlaveHarm.CausedByColony(dinfo, thoughtsKind))
__state.protectedVictim = false;
}
public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state)
{
SlaveHarm.Pop(__state);
return __exception;
}
}
/// <summary>Gene death events (BloodfeederDied) fire after the death thoughts, outside their frame.</summary>
[HarmonyPatch(typeof(Pawn_GeneTracker), nameof(Pawn_GeneTracker.Notify_PawnDied))]
public static class Frame_GenesDied
{
public static void Prefix(Pawn_GeneTracker __instance, DamageInfo? dinfo, out SlaveHarm.Frame __state)
{
__state = SlaveHarm.Push(__instance.pawn);
if (__state.protectedVictim && !SlaveHarm.CausedByColony(dinfo, PawnDiedOrDownedThoughtsKind.Died))
__state.protectedVictim = false;
}
public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state)
{
SlaveHarm.Pop(__state);
return __exception;
}
}
/// <summary>A failed surgery that kills the patient (other mods' postfixes give thoughts here).</summary>
[HarmonyPatch(typeof(Recipe_Surgery), "CheckSurgeryFail")]
public static class Frame_SurgeryFail
{
public static void Prefix(Pawn patient, out SlaveHarm.Frame __state) => __state = SlaveHarm.Push(patient);
public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state)
{
SlaveHarm.Pop(__state);
return __exception;
}
}
/// <summary>Selling a slave. Its slave status is cleared before the SoldSlave event fires, so decide up front.</summary>
[HarmonyPatch(typeof(Tradeable_Pawn), nameof(Tradeable_Pawn.ResolveTrade))]
public static class Frame_SoldSlave
{
public static void Prefix(Tradeable_Pawn __instance, out SlaveHarm.Frame __state)
{
__state = null;
if (__instance.ActionToDo != TradeAction.PlayerSells || __instance.thingsColony == null)
return;
foreach (Thing thing in __instance.thingsColony)
{
if (thing is Pawn pawn && SlaveHarm.IsProtected(pawn))
{
__state = SlaveHarm.Push(pawn, forceProtected: true);
return;
}
}
}
public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state)
{
SlaveHarm.Pop(__state);
return __exception;
}
}
/// <summary>
/// Gifting slaves by transport pod fires one SoldSlave event per pawn that isn't going home, in
/// container order. Queue those pawns so each event gets its own victim.
/// </summary>
[HarmonyPatch(typeof(TransportersArrivalAction_GiveGift), nameof(TransportersArrivalAction_GiveGift.Arrived))]
public static class Frame_GiftArrived
{
[ThreadStatic]
internal static Queue<Pawn> soldInGift;
public static void Prefix(List<ActiveTransporterInfo> transporters, Settlement ___settlement, out Queue<Pawn> __state)
{
__state = soldInGift;
var queue = new Queue<Pawn>();
Faction to = ___settlement?.Faction;
if (transporters != null)
{
foreach (ActiveTransporterInfo info in transporters)
{
if (info?.innerContainer == null)
continue;
foreach (Thing thing in info.innerContainer)
{
if (thing is Pawn pawn && pawn.RaceProps.Humanlike && pawn.HomeFaction != to)
queue.Enqueue(pawn);
}
}
}
soldInGift = queue;
}
public static Exception Finalizer(Exception __exception, Queue<Pawn> __state)
{
soldInGift = __state;
return __exception;
}
}
/// <summary>
/// History events that name the victim: butchering (VICTIM), seeing a corpse (SUBJECT),
/// blinding and scarification rituals (the target is the DOER), pod-gifted slaves (queued above).
/// Events that name nobody push nothing, so an outer frame (an execution) stays in charge.
/// </summary>
[HarmonyPatch(typeof(HistoryEventsManager), nameof(HistoryEventsManager.RecordEvent))]
public static class Frame_HistoryEvent
{
public static void Prefix(HistoryEvent historyEvent, out SlaveHarm.Frame __state)
{
__state = null;
try
{
if (historyEvent.def == null)
return;
if (historyEvent.def == HistoryEventDefOf.SoldSlave && Frame_GiftArrived.soldInGift != null && Frame_GiftArrived.soldInGift.Count > 0)
{
__state = SlaveHarm.Push(Frame_GiftArrived.soldInGift.Dequeue());
return;
}
Pawn victim = null;
if (historyEvent.args.TryGetArg(HistoryEventArgsNames.Victim, out Pawn named))
victim = named;
else if (historyEvent.args.TryGetArg(HistoryEventArgsNames.Subject, out Corpse corpse))
victim = corpse?.InnerPawn;
else if ((historyEvent.def == HistoryEventDefOf.GotBlinded || historyEvent.def == HistoryEventDefOf.GotScarified)
&& historyEvent.args.TryGetArg(HistoryEventArgsNames.Doer, out Pawn target))
victim = target;
if (victim != null && victim.RaceProps != null && victim.RaceProps.Humanlike)
__state = SlaveHarm.Push(victim);
}
catch (Exception e)
{
Log.ErrorOnce("[Blax Slaves] history event frame failed: " + e, 0x6B1A5F);
}
}
public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state)
{
SlaveHarm.Pop(__state);
return __exception;
}
}
/// <summary>A slave's corpse in a gibbet cage doesn't scare non-pacifist colonists.</summary>
[HarmonyPatch(typeof(Building_GibbetCage), nameof(Building_GibbetCage.GiveObservedThought))]
public static class Patch_GibbetCage
{
public static void Postfix(Building_GibbetCage __instance, Pawn observer, ref Thought_Memory __result)
{
if (__result == null)
return;
Pawn victim = __instance.Corpse?.InnerPawn;
if (victim != null && SlaveHarm.IsProtected(victim) && SlaveHarm.ShouldSuppress(observer, __result, victim))
__result = null;
}
}
// ---- banish / abandon confirmation dialogs ----------------------------------------------------
/// <summary>The previews build their thought lists through GetThoughts; mark when that happens for a preview.</summary>
[HarmonyPatch]
public static class Patch_ThoughtPreviewScope
{
[ThreadStatic]
internal static int depth;
public static IEnumerable<System.Reflection.MethodBase> TargetMethods()
{
foreach (System.Reflection.MethodInfo m in typeof(PawnDiedOrDownedThoughtsUtility).GetMethods())
{
if (m.Name == nameof(PawnDiedOrDownedThoughtsUtility.BuildMoodThoughtsListString))
yield return m;
}
}
public static void Prefix() => depth++;
public static Exception Finalizer(Exception __exception)
{
depth--;
return __exception;
}
}
/// <summary>Drop the thoughts the gate will suppress from the preview, so the dialog doesn't overstate the cost.</summary>
[HarmonyPatch(typeof(PawnDiedOrDownedThoughtsUtility), nameof(PawnDiedOrDownedThoughtsUtility.GetThoughts))]
public static class Patch_ThoughtPreview
{
public static void Postfix(Pawn victim, DamageInfo? dinfo, PawnDiedOrDownedThoughtsKind thoughtsKind,
List<IndividualThoughtToAdd> outIndividualThoughts, List<ThoughtToAddToAll> outAllColonistsThoughts)
{
if (Patch_ThoughtPreviewScope.depth <= 0 || !BlaxSlavesMod.Settings.suppressSlaveHarmMood)
return;
if (!SlaveHarm.IsProtected(victim) || !SlaveHarm.CausedByColony(dinfo, thoughtsKind))
return;
outIndividualThoughts?.RemoveAll(t => SlaveHarm.ShouldSuppress(t.addTo, t.thought, victim));
// No recipient to check here: drop negative all-colonist lines from the preview only.
outAllColonistsThoughts?.RemoveAll(t => t.thoughtDef?.stages != null && t.thoughtDef.stages.Count > 0 && t.thoughtDef.stages[0].baseMoodEffect < 0f);
}
}
// ---- other mods ------------------------------------------------------------------------------
public static class Compat
{
public static int Apply(Harmony harmony)
{
int applied = 0;
var finalizer = new HarmonyMethod(typeof(Compat), nameof(FrameFinalizer));
// War Crimes Expanded 2: torture recipes give precept thoughts with no victim attached.
var torture = AccessTools.Method("WarCrimesExpanded2.WCE2_ThoughtHelper:WCE2_GiveThoughtsForPawnTortured");
if (torture != null && TryPatch(harmony, torture, new HarmonyMethod(typeof(Compat), nameof(VictimPrefix)), null, finalizer, "War Crimes Expanded 2"))
applied++;
// Harvest Organs Post Mortem: autopsy thoughts come from a postfix on MakeRecipeProducts.
if (IsActive("Smuffle.HarvestOrgansPostMortem"))
{
var make = AccessTools.Method(typeof(GenRecipe), nameof(GenRecipe.MakeRecipeProducts));
if (make != null && TryPatch(harmony, make, new HarmonyMethod(typeof(Compat), nameof(CorpseIngredientPrefix)), null, finalizer, "Harvest Organs Post Mortem"))
applied++;
}
// Hospitality: visitor groups reuse world pawns of the visiting faction, pending runaways included.
if (IsActive("Orion.Hospitality"))
{
var validGuest = AccessTools.Method("Hospitality.Utilities.SpawnGroupUtility:ValidGuest");
if (validGuest != null && TryPatch(harmony, validGuest, null, new HarmonyMethod(typeof(Compat), nameof(NotPendingPostfix)), null, "Hospitality"))
applied++;
}
return applied;
}
private static bool IsActive(string packageId) => ModLister.GetActiveModWithIdentifier(packageId, ignorePostfix: true) != null;
private static bool TryPatch(Harmony harmony, System.Reflection.MethodBase target, HarmonyMethod prefix, HarmonyMethod postfix, HarmonyMethod finalizer, string label)
{
try
{
harmony.Patch(target, prefix: prefix, postfix: postfix, finalizer: finalizer);
return true;
}
catch (Exception e)
{
Log.Warning("[Blax Slaves] " + label + " compatibility patch failed: " + e.Message);
return false;
}
}
public static void VictimPrefix(Pawn victim, out SlaveHarm.Frame __state) => __state = SlaveHarm.Push(victim);
public static void CorpseIngredientPrefix(List<Thing> ingredients, out SlaveHarm.Frame __state)
{
__state = null;
if (ingredients == null)
return;
foreach (Thing thing in ingredients)
{
if (thing is Corpse corpse && SlaveHarm.IsProtected(corpse.InnerPawn))
{
__state = SlaveHarm.Push(corpse.InnerPawn, forceProtected: true);
return;
}
}
}
public static Exception FrameFinalizer(Exception __exception, SlaveHarm.Frame __state)
{
SlaveHarm.Pop(__state);
return __exception;
}
public static void NotPendingPostfix(Pawn pawn, ref bool __result)
{
if (__result && GameComponent_BlaxRunaways.IsPending(pawn))
__result = false;
}
}
}