rimworld-blax-slaves/Tests/BlaxSlavesTests/Source/BrandTests.cs

623 lines
35 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using BlaxSlaves;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxSlavesTests
{
/// <summary>
/// Branding and rebranding surgeries, the brand hediff, its owner comp, the Branded mood and
/// the suppression factor, plus persistence of the owner over save and reload.
/// Surgeries run the way a doctor's bill finishes: a Bill_Medical queued through
/// HealthCardUtility.CreateSurgeryBill, then Bill_Medical.Notify_IterationCompleted (what
/// Toils_Recipe.FinishRecipeAndStartStoringProduct calls), which checks CompletableEver and calls
/// the recipe worker's ApplyOnPawn with the doctor and an empty ingredient list.
/// </summary>
public static class BrandTests
{
private const string GoneOwnerName = "Blax Vanished Masters";
// ---- availability ----------------------------------------------------------------
[BlaxTest("brand: surgery offered for colony slaves only, and only once")]
public static void BrandAvailability()
{
RecipeDef recipe = BrandRecipe;
T.Check(recipe.AvailableNow, "BlaxSlaves_BrandSlave.AvailableNow is false (research/meme prerequisite?), so the operations tab never lists it");
var worker = recipe.Worker as Recipe_BrandSlave;
T.NotNull(worker, "BlaxSlaves_BrandSlave worker as Recipe_BrandSlave (got " + recipe.Worker?.GetType().Name + ")");
Pawn slave = Fixtures.ColonySlave();
T.Check(slave.IsSlaveOfColony, "fixture slave is not a slave of the colony");
T.Check(Offered(recipe, slave), "brand surgery not offered for an unbranded colony slave");
T.Check(worker.CompletableEver(slave), "Recipe_BrandSlave.CompletableEver is false for an unbranded colony slave");
Pawn colonist = Fixtures.Colonist();
T.Check(!Offered(recipe, colonist), "brand surgery offered for a free colonist");
T.Check(!worker.CompletableEver(colonist), "Recipe_BrandSlave.CompletableEver is true for a free colonist");
Pawn prisoner = Prisoner();
T.Check(prisoner.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony");
T.Check(!Offered(recipe, prisoner), "brand surgery offered for a prisoner");
T.Check(!worker.CompletableEver(prisoner), "Recipe_BrandSlave.CompletableEver is true for a prisoner");
Pawn ours = Fixtures.ColonySlave();
BrandUtility.Brand(ours, Faction.OfPlayer);
T.Check(!Offered(recipe, ours), "brand surgery offered again for a slave that already carries our brand");
Pawn foreign = Fixtures.ColonySlave();
Faction other = OtherFaction(foreign.SlaveFaction);
if (other != null)
{
BrandUtility.Brand(foreign, other);
T.Check(!Offered(recipe, foreign), "brand surgery offered for a slave branded by " + other.Name + " (that's the rebrand's job)");
}
else T.Info("no second non-player faction; skipped the foreign-brand case");
T.Check(!recipe.CompatibleWithHediff(BlaxDefOf.BlaxSlaves_SlaveBrand),
"BlaxSlaves_BrandSlave is compatible with the brand hediff: incompatibleWithHediffTags no longer matches the BlaxSlaves_Brand tag");
QueueBill(slave, recipe);
T.Check(!Offered(recipe, slave), "brand surgery offered a second time while a brand bill is already queued");
}
[BlaxTest("brand: stale brand bill can't complete on a slave branded meanwhile")]
public static void StaleBrandBillOnBrandedSlave()
{
Pawn doctor = Fixtures.Colonist();
Pawn slave = Fixtures.ColonySlave();
Faction other = OtherFaction(slave.SlaveFaction);
if (other == null) T.Skip("no second non-player faction to brand the slave with");
Bill_Medical bill = QueueBill(slave, BrandRecipe);
BrandUtility.Brand(slave, other);
Hediff brand = BrandHediff(slave);
T.NotNull(brand, "brand hediff after BrandUtility.Brand");
float severityBefore = brand.Severity;
bool completable = ((Recipe_BrandSlave)BrandRecipe.Worker).CompletableEver(slave);
bool billCompletable = bill.CompletableEver;
FinishBill(bill, doctor, 51002);
HediffComp_BrandOwner comp = BrandUtility.BrandOf(slave);
int count = BrandCount(slave);
float severityAfter = BrandHediff(slave)?.Severity ?? -1f;
bool untouched = comp != null && comp.owner == other && count == 1 && Math.Abs(severityAfter - severityBefore) < 0.001f;
T.Check(!completable && !billCompletable && untouched,
$"slave already branded by {other.Name}: Recipe_BrandSlave.CompletableEver={completable}, Bill_Medical.CompletableEver={billCompletable} (expected both false). " +
$"Finishing the stale brand bill left owner={comp?.OwnerName ?? "no brand"}, brand hediffs={count}, brand severity {severityBefore}->{severityAfter}; " +
"expected the brand untouched (taking over someone else's brand is the rebrand surgery)");
}
[BlaxTest("rebrand: offered only for another owner's brand, and only once")]
public static void RebrandAvailability()
{
RecipeDef recipe = RebrandRecipe;
T.Check(recipe.AvailableNow, "BlaxSlaves_RebrandSlave.AvailableNow is false, so the operations tab never lists it");
var worker = recipe.Worker as Recipe_RebrandSlave;
T.NotNull(worker, "BlaxSlaves_RebrandSlave worker as Recipe_RebrandSlave (got " + recipe.Worker?.GetType().Name + ")");
Pawn foreign = Fixtures.ColonySlave();
Faction other = OtherFaction(foreign.SlaveFaction);
if (other == null) T.Skip("no second non-player faction to brand the slave with");
BrandUtility.Brand(foreign, other);
T.Check(Offered(recipe, foreign), "rebrand not offered for a colony slave branded by " + other.Name);
T.Check(worker.CompletableEver(foreign), "Recipe_RebrandSlave.CompletableEver is false for a colony slave branded by " + other.Name);
Pawn ours = Fixtures.ColonySlave();
BrandUtility.Brand(ours, Faction.OfPlayer);
T.Check(!Offered(recipe, ours), "rebrand offered for a slave that already carries our brand");
T.Check(!worker.CompletableEver(ours), "Recipe_RebrandSlave.CompletableEver is true for a slave with our brand");
Pawn plain = Fixtures.ColonySlave();
T.Check(!Offered(recipe, plain), "rebrand offered for an unbranded slave");
T.Check(!worker.CompletableEver(plain), "Recipe_RebrandSlave.CompletableEver is true for an unbranded slave");
Pawn freeBranded = Fixtures.Colonist();
BrandUtility.Brand(freeBranded, other);
T.Check(!Offered(recipe, freeBranded), "rebrand offered for a free colonist carrying " + other.Name + "'s brand");
T.Check(!worker.CompletableEver(freeBranded), "Recipe_RebrandSlave.CompletableEver is true for a free colonist");
// Owner faction gone: after a reload the reference is null and only the name is cached.
Pawn orphan = Fixtures.ColonySlave();
BrandUtility.Brand(orphan, other);
BrandUtility.BrandOf(orphan).owner = null;
T.Check(Offered(recipe, orphan), "rebrand not offered for a slave whose brand owner faction is gone (owner null)");
T.Check(worker.CompletableEver(orphan), "Recipe_RebrandSlave.CompletableEver is false for a slave whose brand owner faction is gone (owner null)");
QueueBill(foreign, recipe);
T.Check(!Offered(recipe, foreign), "rebrand offered a second time while a rebrand bill is already queued");
}
// ---- performing the surgeries ----------------------------------------------------
[BlaxTest("brand: surgery marks a colony slave as ours with a clean fresh burn")]
public static void BrandSurgeryOutcome()
{
RecipeDef recipe = BrandRecipe;
T.Check(recipe.surgeryOutcomeEffect == null,
"BlaxSlaves_BrandSlave.surgeryOutcomeEffect is " + recipe.surgeryOutcomeEffect +
"; Recipe_Surgery.CheckSurgeryFail only skips the failure roll when it is null, so branding can fail");
Pawn doctor = Fixtures.Colonist();
Pawn slave = Fixtures.ColonySlave();
ClearInjuries(slave);
T.Check(!BrandUtility.IsBranded(slave), "fresh fixture slave is already branded");
PerformSurgery(slave, recipe, doctor, 51001);
Hediff brand = BrandHediff(slave);
T.NotNull(brand, "hediff BlaxSlaves_SlaveBrand after the brand bill finished");
T.Equal(1, BrandCount(slave), "brand hediffs on the slave");
HediffComp_BrandOwner comp = brand.TryGetComp<HediffComp_BrandOwner>();
T.NotNull(comp, "HediffComp_BrandOwner on the brand");
T.Check(comp.owner == Faction.OfPlayer, "brand owner after the surgery: expected the player faction, got " + (comp.owner?.Name ?? "null"));
T.Equal(Faction.OfPlayer.Name, comp.ownerName, "cached owner name after the surgery");
T.Check(BrandUtility.IsBrandedByPlayer(slave), "BrandUtility.IsBrandedByPlayer is false right after our surgery");
T.Check(slave.IsSlaveOfColony, "slave lost slave status during the surgery");
CheckFreshBurn(slave, "after branding");
}
[BlaxTest("rebrand: finishing the bill makes another owner's brand ours")]
public static void RebrandSurgeryOutcome()
{
RecipeDef recipe = RebrandRecipe;
T.Check(recipe.surgeryOutcomeEffect == null, "BlaxSlaves_RebrandSlave.surgeryOutcomeEffect is " + recipe.surgeryOutcomeEffect + " (should be cleared like the brand's)");
Pawn doctor = Fixtures.Colonist();
Pawn slave = Fixtures.ColonySlave();
Faction other = OtherFaction(slave.SlaveFaction);
if (other == null) T.Skip("no second non-player faction to brand the slave with");
ClearInjuries(slave);
BrandUtility.Brand(slave, other);
T.Check(BrandUtility.BrandOf(slave)?.owner == other, "setup: brand owner is not " + other.Name);
PerformSurgery(slave, recipe, doctor, 51003);
HediffComp_BrandOwner comp = BrandUtility.BrandOf(slave);
T.NotNull(comp, "brand owner comp after the rebrand");
T.Check(comp.owner == Faction.OfPlayer, $"brand owner after the rebrand: expected the player faction, got {comp.owner?.Name ?? "null"} (was {other.Name})");
T.Equal(Faction.OfPlayer.Name, comp.ownerName, "cached owner name after the rebrand");
T.Equal(1, BrandCount(slave), "brand hediffs after the rebrand (it should reuse the existing brand)");
CheckFreshBurn(slave, "after rebranding");
T.Check(!Offered(recipe, slave), "rebrand still offered once the brand is ours");
}
// ---- mood and suppression --------------------------------------------------------
[BlaxTest("brand: Branded mood while a slave, gone once emancipated")]
public static void BrandedThoughtFollowsSlaveStatus()
{
ThoughtDef thought = BrandedThought;
T.Check(thought.Worker is ThoughtWorker_Branded, "BlaxSlaves_Branded worker is " + thought.Worker?.GetType().Name + ", not ThoughtWorker_Branded");
Pawn doctor = Fixtures.Colonist();
// An enslaved colonist: their home faction is ours, so vanilla emancipation frees them on
// the spot instead of sending them off the map while still a slave.
Pawn slave = Fixtures.Colonist();
slave.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
T.Check(slave.IsSlaveOfColony, "setup: enslaved colonist is not a slave of the colony");
T.Check(!thought.Worker.CurrentState(slave).Active, "unbranded slave already has the Branded thought");
PerformSurgery(slave, BrandRecipe, doctor, 51004);
T.Check(BrandUtility.IsBranded(slave), "slave not branded after the brand bill finished");
T.Check(thought.Worker.CurrentState(slave).Active, "BlaxSlaves_Branded inactive for a branded slave");
T.Check(HasMoodThought(slave, thought), "BlaxSlaves_Branded worker is active but the thought is not among the slave's mood thoughts");
GenGuest.EmancipateSlave(doctor, slave);
if (slave.IsSlave)
T.Skip("vanilla GenGuest.EmancipateSlave left the pawn a slave (home faction " + slave.HomeFaction?.Name + "); can't check the freed state");
T.Check(BrandUtility.IsBranded(slave), "the brand disappeared on emancipation; the scar should stay");
// Control: a plain ThoughtWorker_Hediff for the same def must still fire for the freed pawn.
// Otherwise the thought is off for another reason (CanGetThought, missing hediff) and the
// check below would pass without the slave gate doing anything.
var plain = new ThoughtWorker_Hediff { def = thought };
if (!plain.CurrentState(slave).Active)
T.Skip("control: a plain ThoughtWorker_Hediff for BlaxSlaves_Branded is inactive for the freed, still branded pawn; can't attribute the freed state to ThoughtWorker_Branded");
T.Check(!thought.Worker.CurrentState(slave).Active, "BlaxSlaves_Branded still active after the slave was emancipated");
T.Check(!HasMoodThought(slave, thought), "BlaxSlaves_Branded still among the mood thoughts after emancipation");
}
[BlaxTest("brand: slave suppression falls slower with the brand")]
public static void BrandSlowsSuppressionFall()
{
if (!ModsConfig.IdeologyActive) T.Skip("Ideology inactive: no suppression");
StatDef stat = StatDefOf.SlaveSuppressionFallRate;
T.NotNull(stat, "StatDefOf.SlaveSuppressionFallRate");
Pawn doctor = Fixtures.Colonist();
Pawn slave = Fixtures.ColonySlave();
ClearInjuries(slave);
// Worn gear's SlaveSuppressionOffset is subtracted by a stat part and the stat clamps at 0
// (a collar plus a head cover would zero it), so measure without random generated apparel.
slave.apparel?.DestroyAll();
Need_Suppression need = slave.needs?.TryGetNeed<Need_Suppression>();
T.NotNull(need, "suppression need of the colony slave");
// The real path: Pawn_NeedsTracker calls Need_Suppression.NeedInterval every 150 ticks,
// which lowers CurLevel by 0.0025 x SlaveSuppressionFallRate. Measured at a fixed 50%.
float dropBefore = SuppressionDrop(need);
PerformSurgery(slave, BrandRecipe, doctor, 51005);
Hediff brand = BrandHediff(slave);
T.NotNull(brand, "brand hediff after the brand bill finished");
float dropBranded = SuppressionDrop(need);
need.CurLevelPercentage = 0.5f;
float statBranded = slave.GetStatValue(stat);
// Take the brand alone off again (the fresh burn stays), so the brand is the only difference.
slave.health.RemoveHediff(brand);
float dropRemoved = SuppressionDrop(need);
need.CurLevelPercentage = 0.5f;
float statRemoved = slave.GetStatValue(stat);
T.Info($"suppression drop per NeedInterval at 50%: unbranded {dropBefore:F6}, branded {dropBranded:F6}, brand removed {dropRemoved:F6}; " +
$"SlaveSuppressionFallRate branded {statBranded}, brand removed {statRemoved}");
if (dropRemoved <= 0f)
T.Skip($"suppression did not fall in Need_Suppression.NeedInterval without the brand (drop {dropRemoved}; need frozen or fall rate 0); nothing for the brand to slow");
T.Check(dropBranded < dropRemoved - 1e-6f,
$"suppression fell by {dropBranded:F6} per NeedInterval with the brand and by {dropRemoved:F6} without it " +
$"(SlaveSuppressionFallRate {statBranded} vs {statRemoved}); expected the brand stage's x0.85 to slow it. " +
"StatWorker_SuppressionFallRate overrides GetValueUnfinalized without applying hediff statFactors");
}
/// <summary>Suppression lost in one vanilla Need_Suppression.NeedInterval call, starting from 50%.</summary>
private static float SuppressionDrop(Need_Suppression need)
{
need.CurLevelPercentage = 0.5f;
float before = need.CurLevel;
need.NeedInterval();
float drop = before - need.CurLevel;
need.CurLevelPercentage = 0.5f;
return drop;
}
// ---- owner name ------------------------------------------------------------------
[BlaxTest("brand: owner name in label and tooltip, cached name once the faction is gone")]
public static void BrandOwnerNameShown()
{
Pawn doctor = Fixtures.Colonist();
Pawn ours = Fixtures.ColonySlave();
PerformSurgery(ours, BrandRecipe, doctor, 51006);
CheckNameShown(ours, Faction.OfPlayer.Name, "our brand");
Pawn foreign = Fixtures.ColonySlave();
Faction other = OtherFaction(foreign.SlaveFaction);
if (other != null)
{
BrandUtility.Brand(foreign, other);
CheckNameShown(foreign, other.Name, other.Name + "'s brand");
}
else T.Info("no second non-player faction; skipped the foreign-brand case");
// A faction that is not in the world any more. After a reload CompExposeData leaves the
// reference null and only the cached name; the phase-2 test covers that real save.
Pawn orphan = Fixtures.ColonySlave();
BrandUtility.Brand(orphan, GoneFaction(GoneOwnerName));
HediffComp_BrandOwner comp = BrandUtility.BrandOf(orphan);
T.NotNull(comp, "brand owner comp of the orphan slave");
T.Equal(GoneOwnerName, comp.ownerName, "cached owner name right after branding");
comp.owner = null;
T.Equal(GoneOwnerName, comp.OwnerName, "OwnerName with the owner faction gone");
CheckNameShown(orphan, GoneOwnerName, "brand whose owner faction is gone");
}
// ---- persistence -----------------------------------------------------------------
[BlaxTest("brand: set up branded slaves for reload")]
public static void SetupForReload()
{
Pawn doctor = Fixtures.Colonist();
Pawn ours = Fixtures.Keep(Fixtures.ColonySlave());
ClearInjuries(ours);
PerformSurgery(ours, BrandRecipe, doctor, 51007);
T.Check(BrandUtility.IsBrandedByPlayer(ours), "setup: our slave is not branded by the player");
Calm(ours);
T.Carry["brand.ours"] = ours.ThingID;
T.Carry["brand.ours.name"] = Faction.OfPlayer.Name;
Pawn orphan = Fixtures.Keep(Fixtures.ColonySlave());
Faction gone = GoneFaction(GoneOwnerName);
BrandUtility.Brand(orphan, gone);
T.Check(BrandUtility.BrandOf(orphan)?.owner == gone, "setup: orphan brand owner is not the gone faction");
Calm(orphan);
T.Carry["brand.gone"] = orphan.ThingID;
T.Carry["brand.gone.name"] = GoneOwnerName;
T.Carry["brand.gone.faction"] = gone.GetUniqueLoadID();
Faction origin = Fixtures.FriendlyFaction();
Faction other = OtherFaction(origin);
if (other == null) T.Skip("no second non-player faction; the foreign-brand reload case is not set up");
Pawn foreign = Fixtures.Keep(Fixtures.ColonySlave(origin));
BrandUtility.Brand(foreign, other);
T.Check(BrandUtility.BrandOf(foreign)?.owner == other, "setup: foreign brand owner is not " + other.Name);
Calm(foreign);
T.Carry["brand.foreign"] = foreign.ThingID;
T.Carry["brand.foreign.faction"] = other.GetUniqueLoadID();
T.Carry["brand.foreign.name"] = other.Name;
}
[BlaxTest("brand (reload): our brand and owner survive save and load", phase: 2)]
public static void ReloadKeepsOurBrand()
{
Pawn pawn = CarriedPawn("brand.ours");
string name = T.Carry["brand.ours.name"];
HediffComp_BrandOwner comp = ReloadedBrand(pawn);
T.Check(comp.owner == Faction.OfPlayer, "brand owner after reload: expected the player faction, got " + (comp.owner?.Name ?? "null"));
T.Equal(name, comp.ownerName, "cached owner name after reload");
T.Check(BrandUtility.IsBrandedByPlayer(pawn), "BrandUtility.IsBrandedByPlayer is false after reload");
CheckNameShown(pawn, Faction.OfPlayer.Name, "our brand after reload");
if (pawn.IsSlave)
T.Check(BrandedThought.Worker.CurrentState(pawn).Active, "BlaxSlaves_Branded inactive for the branded slave after reload");
else
T.Info("pawn is no longer a slave after reload (a later phase-1 test may have freed it); skipped the mood check");
// The brand burn had its infecter removed. After a reload vanilla recreates the comp from
// the def; with nothing saved it must load as "will not infect".
BodyPartRecord core = pawn.RaceProps.body.corePart;
var burns = pawn.health.hediffSet.hediffs.OfType<Hediff_Injury>()
.Where(h => h.def == DamageDefOf.Burn.hediff && h.Part == core && !h.IsPermanent()).ToList();
if (burns.Count == 0) T.Info("brand burn already healed before the reload; skipped the infection check");
foreach (Hediff_Injury burn in burns)
{
HediffComp_Infecter infecter = burn.TryGetComp<HediffComp_Infecter>();
if (infecter == null) continue;
int ticks = Traverse.Create(infecter).Field("ticksUntilInfect").GetValue<int>();
T.Check(ticks <= 0, $"reloaded brand burn (severity {burn.Severity:F1}) has an infection timer of {ticks} ticks; it should never get infected");
}
}
[BlaxTest("brand (reload): another faction's brand and owner survive save and load", phase: 2)]
public static void ReloadKeepsForeignBrand()
{
Pawn pawn = CarriedPawn("brand.foreign");
string factionId = T.Carry["brand.foreign.faction"];
string name = T.Carry["brand.foreign.name"];
HediffComp_BrandOwner comp = ReloadedBrand(pawn);
T.NotNull(comp.owner, "brand owner after reload (expected " + name + ", " + factionId + ")");
T.Equal(factionId, comp.owner.GetUniqueLoadID(), "brand owner faction id after reload");
T.Check(Find.FactionManager.AllFactionsListForReading.Contains(comp.owner), "reloaded brand owner " + comp.owner.Name + " is not a faction of the loaded world");
T.Equal(name, comp.owner.Name, "brand owner name after reload");
T.Equal(name, comp.ownerName, "cached owner name after reload");
T.Check(!BrandUtility.IsBrandedByPlayer(pawn), "a slave branded by " + name + " counts as branded by the player after reload");
CheckNameShown(pawn, name, name + "'s brand after reload");
}
[BlaxTest("brand (reload): cached owner name kept when the owner faction is gone", phase: 2)]
public static void ReloadKeepsGoneOwnerName()
{
Pawn pawn = CarriedPawn("brand.gone");
string name = T.Carry["brand.gone.name"];
HediffComp_BrandOwner comp = ReloadedBrand(pawn);
T.Check(comp.owner == null,
$"brand owner after reload: expected null (the faction was never in the world), got {comp.owner?.Name} ({comp.owner?.GetUniqueLoadID()})");
T.Equal(name, comp.ownerName, "cached owner name after reload");
T.Equal(name, comp.OwnerName, "OwnerName after reload");
CheckNameShown(pawn, name, "brand with a gone owner after reload");
// owner == null alone doesn't prove the save guard: without it the reference is still
// written, and loading fails to resolve it to null too, just with a warning. Vanilla
// warns "Could not resolve reference to object with loadID Faction_N" on load (always)
// and "Object with load ID Faction_N is referenced ... but is not deep-saved" on save (dev mode).
if (!T.Carry.TryGetValue("brand.gone.faction", out string goneId))
{
T.Info("gone faction load ID not carried; skipped the save-guard log check");
return;
}
List<LogMessage> log = Log.Messages.ToList();
bool covered = log.Any(m => m.text != null && m.text.Contains("[BlaxTest] STAGE save+reload"));
if (!covered)
{
T.Info("the log no longer holds the save+reload stage (rolled over or logging stopped); skipped the save-guard log check");
return;
}
var idPattern = new Regex(@"\b" + Regex.Escape(goneId) + @"\b");
var hits = log.Where(m => m.text != null && idPattern.IsMatch(m.text)).Select(m => m.type + ": " + m.text).ToList();
T.Check(hits.Count == 0,
$"saving or loading logged a reference to the gone owner faction {goneId}; HediffComp_BrandOwner.CompExposeData should drop an owner " +
"that is not in the FactionManager before Scribe_References saves it: " + string.Join(" | ", hits.Take(2)));
}
// ---- helpers ---------------------------------------------------------------------
private static RecipeDef BrandRecipe => DefDatabase<RecipeDef>.GetNamed("BlaxSlaves_BrandSlave");
private static RecipeDef RebrandRecipe => DefDatabase<RecipeDef>.GetNamed("BlaxSlaves_RebrandSlave");
private static ThoughtDef BrandedThought => DefDatabase<ThoughtDef>.GetNamed("BlaxSlaves_Branded");
/// <summary>
/// What the operations tab asks before listing a recipe (HealthCardUtility.DrawMedOperationsTab
/// walks pawn.def.AllRecipes and lists a non-part recipe when Worker.AvailableReport accepts).
/// </summary>
private static bool Offered(RecipeDef recipe, Pawn pawn)
{
if (!pawn.def.AllRecipes.Contains(recipe))
T.Fail($"{recipe.defName} is not in {pawn.def.defName}.AllRecipes (recipeUsers), so the operations tab never lists it for {pawn.LabelShort}");
bool available = recipe.AvailableOnNow(pawn);
bool report = recipe.Worker.AvailableReport(pawn).Accepted;
if (available != report)
T.Fail($"{recipe.defName}: AvailableOnNow={available} but AvailableReport={report} for {pawn.LabelShort}");
return available;
}
private static Bill_Medical QueueBill(Pawn patient, RecipeDef recipe)
{
Bill_Medical bill = HealthCardUtility.CreateSurgeryBill(patient, recipe, null, null, sendMessages: false);
T.Check(patient.BillStack.Bills.Contains(bill), recipe.defName + " bill not in the patient's bill stack after queuing");
return bill;
}
private static void FinishBill(Bill_Medical bill, Pawn doctor, int seed)
{
Rand.PushState(seed);
try
{
bill.Notify_IterationCompleted(doctor, new List<Thing>());
}
finally
{
Rand.PopState();
}
}
/// <summary>
/// Queue the bill and finish it as the doctor would; fails when the bill is not completable.
/// Failure is made impossible here even if the def gained a surgery outcome (the outcome
/// tests assert that separately), so the other checks still say something.
/// </summary>
private static void PerformSurgery(Pawn patient, RecipeDef recipe, Pawn doctor, int seed)
{
Bill_Medical bill = QueueBill(patient, recipe);
T.Check(bill.CompletableEver, $"{recipe.defName} bill on {patient.LabelShort} is not completable (Bill_Medical.CompletableEver false)");
SurgeryOutcomeEffectDef outcome = recipe.surgeryOutcomeEffect;
if (outcome != null)
{
T.Info($"{recipe.defName} has surgeryOutcomeEffect {outcome.defName}; cleared for this surgery so it can't fail");
recipe.surgeryOutcomeEffect = null;
}
try
{
FinishBill(bill, doctor, seed);
}
finally
{
recipe.surgeryOutcomeEffect = outcome;
}
T.Check(!patient.BillStack.Bills.Contains(bill), recipe.defName + " bill still queued after it finished");
}
private static Hediff BrandHediff(Pawn pawn) =>
pawn.health.hediffSet.GetFirstHediffOfDef(BlaxDefOf.BlaxSlaves_SlaveBrand);
private static int BrandCount(Pawn pawn) =>
pawn.health.hediffSet.hediffs.Count(h => h.def == BlaxDefOf.BlaxSlaves_SlaveBrand);
/// <summary>Removes old injuries so a new brand burn can't merge into one (burns have canMerge).</summary>
private static void ClearInjuries(Pawn pawn)
{
foreach (Hediff h in pawn.health.hediffSet.hediffs.Where(h => h is Hediff_Injury).ToList())
pawn.health.RemoveHediff(h);
}
private static void CheckFreshBurn(Pawn pawn, string when)
{
HediffDef burnDef = DamageDefOf.Burn.hediff;
BodyPartRecord core = pawn.RaceProps.body.corePart;
List<Hediff_Injury> burns = pawn.health.hediffSet.hediffs.OfType<Hediff_Injury>()
.Where(h => h.def == burnDef && h.Part == core).ToList();
T.Check(burns.Count == 1, $"{when}: expected one burn on the {core.Label}, found {burns.Count}");
Hediff_Injury burn = burns[0];
T.Check(Math.Abs(burn.Severity - BrandUtility.FreshBurnSeverity) < 0.01f,
$"{when}: burn severity {burn.Severity}, expected {BrandUtility.FreshBurnSeverity}");
T.Check(!burn.IsPermanent(), when + ": the brand burn is already a permanent scar, expected a fresh injury");
T.Check(burn.ageTicks < 60, $"{when}: burn is {burn.ageTicks} ticks old, expected a fresh one");
T.Check(burn.TryGetComp<HediffComp_Infecter>() == null, when + ": the brand burn has an infection comp (HediffComp_Infecter); it should never get infected");
bool defInfects = burnDef.comps != null && burnDef.comps.Any(c => c.compClass != null && typeof(HediffComp_Infecter).IsAssignableFrom(c.compClass));
if (!defInfects) T.Info("the vanilla burn def has no infecter comp, so the no-infection check proves little");
}
private static void CheckNameShown(Pawn pawn, string name, string what)
{
Hediff brand = BrandHediff(pawn);
T.NotNull(brand, what + ": brand hediff");
T.Check(!name.NullOrEmpty(), what + ": expected owner name is empty");
string label = brand.Label;
T.Check(label != null && label.Contains(name), $"{what}: label \"{label}\" does not name the owner \"{name}\"");
// The tooltip starts with LabelCap, which already holds the name in brackets, so a plain
// Contains(name) would pass without the comp's tooltip line. Look for that line itself.
T.Check("BlaxSlaves_BrandOwnerTip".CanTranslate(), "language key BlaxSlaves_BrandOwnerTip is missing");
string ownerLine = "BlaxSlaves_BrandOwnerTip".Translate(name);
string tip = brand.GetTooltip(pawn, false);
T.Check(tip != null && tip.Contains(ownerLine), $"{what}: tooltip lacks the owner line \"{ownerLine}\": {tip}");
}
private static bool HasMoodThought(Pawn pawn, ThoughtDef def)
{
var thoughts = new List<Thought>();
pawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty();
pawn.needs.mood.thoughts.GetAllMoodThoughts(thoughts);
return thoughts.Any(t => t.def == def);
}
private static Pawn Prisoner()
{
Faction from = Fixtures.HostileFaction() ?? Fixtures.FriendlyFaction();
Pawn p = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, from));
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner);
return p;
}
/// <summary>A visible humanlike faction other than the player and the given ones, hostile first.</summary>
private static Faction OtherFaction(params Faction[] exclude) =>
Find.FactionManager.AllFactionsVisible
.Where(f => !f.IsPlayer && !f.defeated && !f.temporary && f.def.humanlikeFaction && !exclude.Contains(f))
.OrderByDescending(f => f.HostileTo(Faction.OfPlayer))
.ThenBy(f => f.loadID)
.FirstOrDefault();
/// <summary>
/// A faction object that is not part of the world, like a removed temporary faction:
/// never added to the FactionManager, so saving must drop the reference.
/// </summary>
private static Faction GoneFaction(string name)
{
Faction template = Fixtures.FriendlyFaction() ?? OtherFaction();
T.NotNull(template, "a faction def to model the gone faction on");
Faction gone;
Rand.PushState(51099);
try
{
gone = new Faction
{
def = template.def,
loadID = Find.UniqueIDsManager.GetNextFactionID(),
temporary = true,
};
}
finally
{
Rand.PopState();
}
gone.Name = name;
return gone;
}
/// <summary>Full suppression so a kept slave is unlikely to rebel during later phase-1 tests.</summary>
private static void Calm(Pawn slave)
{
Need_Suppression need = slave.needs?.TryGetNeed<Need_Suppression>();
if (need != null) need.CurLevelPercentage = 1f;
}
private static Pawn CarriedPawn(string key)
{
if (!T.Carry.TryGetValue(key, out string id))
T.Skip("phase-1 setup did not carry '" + key + "' (setup failed or skipped)");
Pawn pawn = Fixtures.FindPawnById(id);
T.NotNull(pawn, $"pawn {id} ({key}) after reload (destroyed, or made to leave by a later phase-1 test?)");
T.Info($"{key}: {pawn.LabelShort}, spawned={pawn.Spawned}, slave of colony={pawn.IsSlaveOfColony}");
return pawn;
}
private static HediffComp_BrandOwner ReloadedBrand(Pawn pawn)
{
Hediff brand = BrandHediff(pawn);
T.NotNull(brand, "brand hediff on " + pawn.LabelShort + " after reload");
T.Equal(1, BrandCount(pawn), "brand hediffs on " + pawn.LabelShort + " after reload");
HediffComp_BrandOwner comp = brand.TryGetComp<HediffComp_BrandOwner>();
T.NotNull(comp, "HediffComp_BrandOwner on the reloaded brand");
return comp;
}
}
}