rimworld-blax-defaults/Tests/BlaxDefaultsTests/Source/ForbidTests.cs

1264 lines
70 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using BlaxDefaults;
using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using UnityEngine;
using Verse;
using Verse.AI;
using Verse.AI.Group;
namespace BlaxDefaultsTests
{
/// <summary>
/// Work package "forbid". The tests of design.md, 1.1: Gear rules for your colony and for enemies; Wait until
/// the fight is over; Stripping forbids what doesn't match; Corpses outside the home area stay allowed.
/// No hostile pawn stands on the test map unless a test says so (Begin checks). Pawns are downed with an
/// anesthetic (HealthUtility.TryAnesthetize), which goes through Pawn_HealthTracker.MakeDowned without the
/// death roll, and killed with Pawn.Kill. Every test area is 9x9 with the pawn in its centre, and its cells are
/// set inside or outside the home area (restored after the test), so every drop lands on the side the test names.
/// </summary>
public static class ForbidTests
{
private const string KeptAllowedKey = "forbid.keptAllowed";
private const string KeptForbiddenKey = "forbid.keptForbidden";
private const string WaitingRifleKey = "forbid.waitingRifle";
private const string WaitingThreatKey = "forbid.waitingThreat";
private static Map Map => Fixtures.Map;
// ---- setup helpers ---------------------------------------------------------------
/// <summary>Clears the wait list before and after the test and checks the map has no active threat.</summary>
private static void Begin()
{
ForbidWaitList.Clear();
Fixtures.AfterTest(ForbidWaitList.Clear);
if (GenHostility.AnyHostileActiveThreatTo(Map, Faction.OfPlayer, out IAttackTarget threat))
T.Fail("setup: a hostile threat is on the test map: " + threat?.Thing);
}
/// <summary>A 9x9 area, inside or outside the home area.</summary>
private static CellRect Area(bool home)
{
CellRect r = Fixtures.EmptyArea(9, 9);
SetHome(r, home);
return r;
}
private static void SetHome(CellRect r, bool home)
{
Area_Home area = Map.areaManager.Home;
var old = r.Cells.Select(c => (c, area[c])).ToList();
foreach (IntVec3 c in r.Cells)
area[c] = home;
Fixtures.AfterTest(() =>
{
foreach (var (c, v) in old)
area[c] = v;
});
}
private static Pawn Generate(PawnKindDef kind, Faction faction)
{
var req = new PawnGenerationRequest(kind, faction, PawnGenerationContext.NonPlayer,
forceGenerateNewPawn: true, canGeneratePawnRelations: false,
colonistRelationChanceFactor: 0f, developmentalStages: DevelopmentalStage.Adult);
Pawn p = Fixtures.TrackPawn(PawnGenerator.GeneratePawn(req));
p.equipment?.DestroyAllEquipment();
p.inventory?.DestroyAll();
return p;
}
private static Pawn Spawn(Pawn p, IntVec3 at)
{
GenSpawn.Spawn(p, at, Map);
if (p.needs?.food != null) p.needs.food.CurLevel = p.needs.food.MaxLevel;
if (p.needs?.rest != null) p.needs.rest.CurLevel = 1f;
if (p.needs?.joy != null) p.needs.joy.CurLevel = 1f;
return p;
}
private static Pawn Colonist(IntVec3 at, bool canFight = false)
{
for (int i = 0; ; i++)
{
Pawn p = Generate(PawnKindDefOf.Colonist, Faction.OfPlayer);
if (!canFight || !p.WorkTagIsDisabled(WorkTags.Violent) || i >= 20)
{
if (canFight && p.WorkTagIsDisabled(WorkTags.Violent))
T.Fail("setup: 20 generated colonists were all incapable of violence");
return Spawn(p, at);
}
p.Destroy(DestroyMode.Vanish);
}
}
private static Faction Hostile()
{
Faction f = Fixtures.HostileFaction();
if (f == null)
T.Skip("setup: no hostile humanlike faction in this world");
return f;
}
private static Faction Friendly()
{
Faction f = Fixtures.FriendlyFaction();
if (f == null)
T.Skip("setup: no friendly humanlike faction in this world");
return f;
}
private static PawnKindDef MemberKind(Faction f) => f.def.basicMemberKind ?? PawnKindDefOf.Villager;
/// <summary>A spawned raider of a hostile faction, without weapon or inventory: an active threat until downed or killed.</summary>
private static Pawn Raider(IntVec3 at)
{
Faction f = Hostile();
return Spawn(Generate(MemberKind(f), f), at);
}
private static ThingWithComps Weapon(string defName, QualityCategory quality, float hitPoints)
{
ThingDef def = Fixtures.Thing(defName);
var t = (ThingWithComps)ThingMaker.MakeThing(def, def.MadeFromStuff ? GenStuff.DefaultStuffFor(def) : null);
t.TryGetComp<CompQuality>()?.SetQuality(quality, ArtGenerationContext.Outsider);
t.HitPoints = Mathf.RoundToInt(t.MaxHitPoints * hitPoints);
return Fixtures.Track(t);
}
private static Apparel Wear(Pawn p, string defName, QualityCategory quality, float hitPoints)
{
var a = (Apparel)Weapon(defName, quality, hitPoints);
p.apparel.Wear(a, dropReplacedApparel: false);
T.Check(p.apparel.WornApparel.Contains(a), "setup: " + p + " is not wearing " + a);
return a;
}
private static Thing Stack(string defName, int count)
{
Thing t = ThingMaker.MakeThing(Fixtures.Thing(defName));
t.stackCount = count;
return Fixtures.Track(t);
}
private static Thing Give(Pawn p, string defName, int count)
{
Thing t = Stack(defName, count);
T.Check(p.inventory.innerContainer.TryAdd(t), "setup: could not put " + defName + " into " + p + "'s inventory");
return t;
}
private static ThingWithComps Arm(Pawn p, string defName, QualityCategory quality, float hitPoints)
{
ThingWithComps w = Weapon(defName, quality, hitPoints);
p.equipment.AddEquipment(w);
return w;
}
private static void Down(Pawn p)
{
T.Check(HealthUtility.TryAnesthetize(p), "setup: " + p + " can't be anesthetized");
T.Check(p.Downed, "setup: " + p + " did not go down");
}
private static bool Forbidden(Thing t) => t.TryGetComp<CompForbiddable>()?.Forbidden ?? false;
private const string Hospitality = "Orion.Hospitality";
/// <summary>
/// Hospitality's MakeDowned transpiler calls DropAndForbidEverything without rememberPrimary (its
/// Source/Patches/Pawn_HealthTracker_MakeDowned_Patch.cs), so with it a downed pawn never remembers its
/// weapon, and its "disable friendly gear drops" option keeps a downed visitor's things on it. Skips the
/// rest of a test about the remembered weapon when that happened.
/// </summary>
private static void NeedRememberedWeapon(Pawn p, Thing weapon)
{
if (p.mindState.droppedWeapon == weapon)
return;
if (Compat.IsActive(Hospitality))
T.Skip("Hospitality drops a downed pawn's weapon without remembering it, so there is no remembered weapon to wait for");
T.Fail("the weapon is not the downed pawn's droppedWeapon");
}
private static void ColonyRule(bool anywhere = true)
{
ForbidRules.Colony.UseSuggested();
ForbidRules.Colony.Ticked = true;
ForbidRules.Colony.Anywhere = anywhere;
}
private static void EnemyRule(bool anywhere = true)
{
ForbidRules.Enemies.UseSuggested();
ForbidRules.Enemies.Ticked = true;
ForbidRules.Enemies.Anywhere = anywhere;
}
/// <summary>Saves a filter for the rule: every item but these defs, full ranges, unlisted allowed.</summary>
private static void FilterRefusing(ForbidRule rule, params string[] refused)
{
StorageKind kind = StorageKinds.ForForbid(rule);
StorageSettings s = kind.GameDefault();
foreach (string name in refused)
s.filter.SetAllow(Fixtures.Thing(name), false);
StorageTemplate t = kind.Capture(s);
t.unlisted = UnlistedRule.Allow;
Fixtures.Save(t);
}
/// <summary>A raider killed in the area's centre with the enemy rule's usual kit.</summary>
private sealed class RaiderKit
{
public Pawn Raider;
public ThingWithComps Good; // Normal at 80%: allowed by the suggested setup
public ThingWithComps Poor; // Poor at 80%
public ThingWithComps Damaged; // Normal at 40%
public Thing GoJuice;
public Thing Medicine;
}
private static RaiderKit KitRaider(IntVec3 at)
{
var k = new RaiderKit { Raider = Raider(at) };
k.Good = Arm(k.Raider, "Gun_AssaultRifle", QualityCategory.Normal, 0.8f);
k.Poor = Weapon("Gun_AssaultRifle", QualityCategory.Poor, 0.8f);
k.Damaged = Weapon("Gun_AssaultRifle", QualityCategory.Normal, 0.4f);
T.Check(k.Raider.inventory.innerContainer.TryAdd(k.Poor) && k.Raider.inventory.innerContainer.TryAdd(k.Damaged), "setup: rifles into the inventory");
k.GoJuice = Give(k.Raider, "GoJuice", 2);
k.Medicine = Give(k.Raider, "MedicineIndustrial", 3);
return k;
}
/// <summary>A spawned hostile pawn that stands on the map as an active threat until Down() takes it out.</summary>
private static Pawn Threat(CellRect area)
{
Pawn p = Raider(area.Corners.First());
T.Check(GenHostility.AnyHostileActiveThreatToPlayer(Map), "setup: the hostile test pawn is not an active threat");
return p;
}
// ---- the rules on the settings page ----------------------------------------------
[BlaxTest("forbid rules: everything ships off, and the parent filter has no corpses")]
public static void ShipsOff()
{
var fresh = new BlaxDefaultsSettings();
T.Check(fresh.forbidRules, "forbidRules is off in fresh settings");
T.Check(!fresh.colonyGearRule && !fresh.enemyGearRule && !fresh.colonyStripRule && !fresh.enemyStripRule, "a gear rule or strip switch is on in fresh settings");
T.Check(!fresh.animalCorpsesAllowed && !fresh.enemyCorpsesAllowed && !fresh.otherCorpsesAllowed, "a corpse switch is on in fresh settings");
T.Check(fresh.colonyGearAnywhere && fresh.enemyGearAnywhere, "\"Where\" does not default to anywhere");
ThingFilter parent = ForbidRules.ParentFilter;
T.Check(!parent.Allows(ThingDefOf.Human.race.corpseDef), "the forbid parent filter allows human corpses");
T.Check(parent.Allows(Fixtures.Thing("Gun_AssaultRifle")) && parent.Allows(ThingDefOf.MedicineIndustrial) && parent.Allows(ThingDefOf.Silver),
"the forbid parent filter refuses a rifle, medicine or silver");
T.Equal(DefaultsKeys.ForbidColony, ForbidRules.Colony.Key, "colony key");
T.Equal(DefaultsKeys.ForbidEnemies, ForbidRules.Enemies.Key, "enemy key");
}
private static readonly string[] Keys =
{
"BlaxDefaults_ForbidColonyRule", "BlaxDefaults_ForbidColonyRuleTip", "BlaxDefaults_ForbidCorpsesAnimal", "BlaxDefaults_ForbidCorpsesAnimalTip", "BlaxDefaults_ForbidCorpsesEnemy", "BlaxDefaults_ForbidCorpsesEnemyTip", "BlaxDefaults_ForbidCorpsesHeader", "BlaxDefaults_ForbidCorpsesOther", "BlaxDefaults_ForbidCorpsesOtherTip", "BlaxDefaults_ForbidEditTitle", "BlaxDefaults_ForbidEnemyRule", "BlaxDefaults_ForbidEnemyRuleTip", "BlaxDefaults_ForbidFilterMissing", "BlaxDefaults_ForbidForgetConfirm", "BlaxDefaults_ForbidNeutral", "BlaxDefaults_ForbidNoFilter", "BlaxDefaults_ForbidSection", "BlaxDefaults_ForbidStrip", "BlaxDefaults_ForbidStripNeedsFilter", "BlaxDefaults_ForbidStripTip", "BlaxDefaults_ForbidSuggestedColony", "BlaxDefaults_ForbidSuggestedEnemies", "BlaxDefaults_ForbidSummaryAll", "BlaxDefaults_ForbidSummaryHitPoints", "BlaxDefaults_ForbidSummaryNone", "BlaxDefaults_ForbidSummaryQualityMax", "BlaxDefaults_ForbidSummaryQualityMin", "BlaxDefaults_ForbidSummaryQualityOnly", "BlaxDefaults_ForbidSummaryQualityRange", "BlaxDefaults_ForbidSummaryRefuses", "BlaxDefaults_ForbidSummarySome", "BlaxDefaults_ForbidToggle", "BlaxDefaults_ForbidToggleTip", "BlaxDefaults_ForbidUnlistedTip", "BlaxDefaults_ForbidUseSuggested", "BlaxDefaults_ForbidUseSuggestedConfirm", "BlaxDefaults_ForbidUsedSuggested", "BlaxDefaults_ForbidWhere", "BlaxDefaults_ForbidWhereAnywhere", "BlaxDefaults_ForbidWhereHome", "BlaxDefaults_ForbidWhereTip", "BlaxDefaults_OverlapWhatForbid", "BlaxDefaults_OverlapWhatAllowEverything", "BlaxDefaults_OverlapWhatPinata", "BlaxDefaults_OverlapWhatDeadAnimals",
};
[BlaxTest("forbid rules: every string of the forbid rules section, its edit window and its overlap line is in Keyed")]
public static void Strings()
{
var missing = Keys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
}
[BlaxTest("forbid rules: ticking a rule without a filter saves its suggested setup and turns it on")]
public static void TickWithoutFilter()
{
DefaultsLibrary.Forget(DefaultsKeys.ForbidColony);
DefaultsLibrary.Forget(DefaultsKeys.ForbidEnemies);
ForbidRule enemies = ForbidRules.Enemies;
enemies.Anywhere = false;
T.Check(!enemies.HasFilter && !enemies.Active, "setup: the enemy rule has a filter or acts");
T.Check(enemies.SetTicked(true), "SetTicked(true) without a filter did not report the suggested setup");
T.Check(enemies.Ticked && enemies.HasFilter && enemies.Active, "the enemy rule is not on with a filter after ticking");
T.Check(enemies.Template.SameSettingsAs(enemies.Suggested()), "the saved enemy filter is not the suggested setup");
T.Check(enemies.StripTicked, "the suggested enemy setup did not turn stripping on");
T.Check(enemies.Anywhere, "the suggested setup did not set \"Where\" to anywhere");
T.Check(!enemies.SetTicked(true), "ticking a rule that has a filter reported the suggested setup again");
ForbidRule colony = ForbidRules.Colony;
T.Check(colony.SetTicked(true), "SetTicked(true) on the colony rule did not report the suggested setup");
T.Check(colony.Active && !colony.StripTicked, "the colony rule is off, or its stripping is on, after ticking");
T.Check(colony.Template.SameSettingsAs(colony.Suggested()), "the saved colony filter is not the suggested setup");
T.Check(!colony.SetTicked(false) && !colony.Ticked && colony.HasFilter, "unticking changed the filter or did not untick");
}
[BlaxTest("forbid rules: Forget on a saved enemy filter turns the rule and its strip switch off")]
public static void ForgetTurnsOff()
{
EnemyRule();
T.Check(Fixtures.Settings.enemyGearRule && Fixtures.Settings.enemyStripRule, "setup: rule or strip switch off");
ForbidRules.Enemies.Forget();
T.Check(!DefaultsLibrary.Has(DefaultsKeys.ForbidEnemies), "the enemy filter is still saved");
T.Check(!Fixtures.Settings.enemyGearRule, "enemyGearRule is still on after Forget");
T.Check(!Fixtures.Settings.enemyStripRule, "enemyStripRule is still on after Forget");
}
[BlaxTest("forbid rules: a rule ticked in mod settings with an empty library acts as off and logs nothing")]
public static void TickedWithoutFilter()
{
Begin();
DefaultsLibrary.Forget(DefaultsKeys.ForbidEnemies);
Fixtures.Settings.enemyGearRule = true;
Fixtures.Settings.enemyStripRule = true;
T.Check(!ForbidRules.Enemies.Active && !ForbidRules.Enemies.StripActive, "the enemy rule acts without a filter");
CellRect r = Area(home: false);
RaiderKit k = KitRaider(r.CenterCell);
k.Raider.Kill(null);
T.Check(Forbidden(k.Good) && Forbidden(k.Medicine), "a raider's drops were allowed by a rule without a filter");
T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3)));
}
[BlaxTest("forbid rules: with forbidRules or the master switch off, gear, corpses and stripping keep the game's flags")]
public static void SwitchesOff()
{
Begin();
EnemyRule();
Fixtures.Settings.enemyCorpsesAllowed = true;
T.Check(ForbidRules.Enemies.Active && ForbidRules.Enemies.StripActive, "setup: the enemy rule or its strip switch is off");
Fixtures.Settings.forbidRules = false;
T.Check(!BlaxDefaultsMod.ForbidOn, "ForbidOn with forbidRules off");
KillAndStrip("forbidRules off", acts: false);
// The master switch turns the forbid rules off too (BlaxDefaultsMod.ForbidOn, the PageEnabled tooltip).
Fixtures.Settings.forbidRules = true;
Fixtures.Settings.enabled = false;
T.Check(!BlaxDefaultsMod.ForbidOn, "ForbidOn with the master switch off");
KillAndStrip("the master switch off", acts: false);
Fixtures.Settings.enabled = true;
KillAndStrip("both on again", acts: true);
}
/// <summary>A raider with a Normal rifle at 80% and a Poor tuque, killed outside the home area, its corpse stripped.</summary>
private static void KillAndStrip(string when, bool acts)
{
CellRect r = Area(home: false);
Pawn raider = Raider(r.CenterCell);
raider.apparel.DestroyAll();
Apparel tuque = Wear(raider, "Apparel_Tuque", QualityCategory.Poor, 0.9f);
ThingWithComps rifle = Arm(raider, "Gun_AssaultRifle", QualityCategory.Normal, 0.8f);
Corpse corpse = KillKeepingHitPoints(raider, tuque);
T.Check(rifle.Spawned, "setup: the rifle is not on the ground with " + when);
T.Equal(!acts, Forbidden(rifle), "the Normal rifle at 80% forbidden with " + when);
T.Equal(!acts, Forbidden(corpse), "the raider's corpse forbidden with " + when);
corpse.Strip();
T.Check(tuque.Spawned, "setup: the tuque is not on the ground with " + when);
T.Equal(acts, Forbidden(tuque), "the stripped Poor tuque forbidden with " + when);
}
[BlaxTest("forbid rules: the row says what the suggested filters allow")]
public static void RowSummary()
{
T.Equal("all items, hit points 50 to 100%, Normal or better", ForbidRules.Summary(ForbidRules.Enemies.Suggested()), "enemy row");
T.Equal("all items", ForbidRules.Summary(ForbidRules.Colony.Suggested()), "colony row");
}
[BlaxTest("forbid rules: the edit window saves a forbid filter with no priority and unlisted Refuse or Allow")]
public static void EditWindow()
{
EnemyRule();
Dialog_EditStorageTemplate dialog = ForbidRulesSection.Editor(ForbidRules.Enemies);
T.Check(dialog.Kind.IsForbid, "the window's kind is not a forbid rule");
T.Equal(UnlistedRule.Allow, dialog.Unlisted, "unlisted rule of the suggested setup in the window");
T.Check(dialog.Scratch.filter.AllowedQualityLevels == new QualityRange(QualityCategory.Normal, QualityCategory.Legendary),
"the window's filter lost the quality range");
ThingDef rifle = Fixtures.Thing("Gun_AssaultRifle");
dialog.Scratch.filter.SetAllow(rifle, false);
StorageTemplate t = dialog.BuildTemplate();
T.Equal(DefaultsKeys.ForbidEnemies, t.key, "key of the saved filter");
T.Check(t.refused.Contains(rifle.defName), "the saved filter does not refuse the rifle");
T.Check(!t.allowed.Concat(t.refused).Any(n => DefDatabase<ThingDef>.GetNamedSilentFail(n)?.IsCorpse ?? false), "the saved filter names a corpse");
Fixtures.Save(t);
ThingWithComps gun = Weapon("Gun_AssaultRifle", QualityCategory.Legendary, 1f);
T.Check(!ForbidRules.Enemies.Allows(gun), "the rule still allows the rifle after the edit");
T.Check(ForbidRules.Enemies.Allows(Stack("MedicineIndustrial", 1)), "the rule refuses medicine after the edit");
}
// ---- gear rules: your colony -----------------------------------------------------
[BlaxTest("forbid gear: a downed colonist's meal and medicine are allowed, its rifle waits until it dies")]
public static void ColonistDowned()
{
Begin();
ColonyRule();
CellRect r = Area(home: false);
Pawn c = Colonist(r.CenterCell);
ThingWithComps rifle = Arm(c, "Gun_AssaultRifle", QualityCategory.Normal, 1f);
Thing meal = Give(c, "MealSurvivalPack", 1);
Thing herbal = Give(c, "MedicineHerbal", 2);
Down(c);
T.Check(meal.Spawned && herbal.Spawned && rifle.Spawned, "setup: the drops are not on the ground");
T.Check(!Forbidden(meal), "the survival meal is forbidden");
T.Check(!Forbidden(herbal), "the herbal medicine is forbidden");
if (c.mindState.droppedWeapon != rifle && Compat.IsActive(Hospitality))
{
// Nothing remembers the rifle, so the colonist never comes back for it: the rule decides at once.
T.Check(!Forbidden(rifle) && !ForbidWaitList.Contains(rifle), "with Hospitality the rifle nobody remembers is still forbidden or waiting");
T.Info("Hospitality: the downed colonist does not remember its rifle, so the rule allowed it at once");
return;
}
T.Check(Forbidden(rifle), "the rifle was allowed at once");
T.Check(c.mindState.droppedWeapon == rifle, "the rifle is not the colonist's droppedWeapon");
T.Check(ForbidWaitList.Contains(rifle), "the rifle does not wait");
for (int i = 0; i < 3; i++)
{
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(Forbidden(rifle), "the rifle was allowed while its colonist lies where it fell (check " + (i + 1) + ")");
}
c.Kill(null);
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(!Forbidden(rifle), "the rifle is still forbidden after its colonist died and a check passed");
T.Check(!ForbidWaitList.Contains(rifle), "the rifle is still on the wait list");
}
[BlaxTest("forbid gear: with the colony rule off, a downed colonist's rifle, meal and medicine stay forbidden")]
public static void ColonistDownedRuleOff()
{
Begin();
ForbidRules.Colony.UseSuggested();
ForbidRules.Colony.Ticked = false;
// The enemy rule keeps the downing scope open, so the colony rule's own checkbox is what leaves the drops alone.
EnemyRule();
T.Check(ForbidHooks.ShouldOpen, "setup: no scope opens");
CellRect r = Area(home: false);
Pawn c = Colonist(r.CenterCell);
ThingWithComps rifle = Arm(c, "Gun_AssaultRifle", QualityCategory.Normal, 1f);
Thing meal = Give(c, "MealSurvivalPack", 1);
Thing herbal = Give(c, "MedicineHerbal", 2);
Down(c);
T.Check(!ForbidWaitList.Contains(rifle), "the rifle waits with the colony rule off");
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(Forbidden(rifle) && Forbidden(meal) && Forbidden(herbal),
"with the rule off: rifle " + Forbidden(rifle) + ", meal " + Forbidden(meal) + ", medicine " + Forbidden(herbal) + " (all should be forbidden)");
}
[BlaxTest("forbid gear: colony rule only inside the home area: a colonist downed outside keeps its meal and medicine forbidden")]
public static void ColonistDownedOnlyInsideHome()
{
Begin();
ColonyRule(anywhere: false);
CellRect r = Area(home: false);
Pawn c = Colonist(r.CenterCell);
Thing meal = Give(c, "MealSurvivalPack", 1);
Thing herbal = Give(c, "MedicineHerbal", 2);
Down(c);
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(meal.Spawned && herbal.Spawned, "setup: the drops are not on the ground");
T.Check(Forbidden(meal) && Forbidden(herbal),
"outside the home area: meal " + Forbidden(meal) + ", medicine " + Forbidden(herbal) + " (both should be forbidden)");
}
[BlaxTest("forbid gear: a downed colonist carried off by a rescuer: its rifle is allowed after the next check")]
public static void ColonistRescued()
{
Begin();
ColonyRule();
CellRect r = Area(home: false);
Pawn c = Colonist(r.CenterCell);
ThingWithComps rifle = Arm(c, "Gun_AssaultRifle", QualityCategory.Normal, 1f);
Down(c);
NeedRememberedWeapon(c, rifle);
T.Check(Forbidden(rifle) && ForbidWaitList.Contains(rifle), "setup: the rifle is not forbidden and waiting");
Pawn rescuer = Colonist(r.CenterCell + IntVec3.North * 2);
rescuer.drafter.Drafted = true;
// The rescue job carries the pawn with Toils_Haul.StartCarryThing, which is Pawn_CarryTracker.TryStartCarry.
T.Check(rescuer.carryTracker.TryStartCarry(c, 1, reserve: false) > 0, "setup: the rescuer could not pick the colonist up");
T.Check(!c.Spawned && c.mindState.droppedWeapon == null, "the carried colonist still remembers its rifle");
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(!Forbidden(rifle), "the rifle is still forbidden after the rescue and a check");
if (rescuer.carryTracker.CarriedThing != null)
rescuer.carryTracker.TryDropCarriedThing(rescuer.Position, ThingPlaceMode.Near, out _);
}
[BlaxTest("forbid gear: a downed colonist healed where it fell equips its still forbidden rifle, which leaves the list")]
public static void ColonistHealed()
{
Begin();
ColonyRule();
CellRect r = Area(home: false);
Pawn c = Colonist(r.CenterCell, canFight: true);
ThingWithComps rifle = Arm(c, "Gun_AssaultRifle", QualityCategory.Normal, 1f);
Down(c);
NeedRememberedWeapon(c, rifle);
T.Check(Forbidden(rifle) && ForbidWaitList.Contains(rifle), "setup: the rifle is not forbidden and waiting");
Hediff anesthetic = c.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Anesthetic);
T.NotNull(anesthetic, "the anesthetic");
c.health.RemoveHediff(anesthetic);
T.Check(!c.Downed, "the colonist is still down after the anesthetic was removed");
int waited = 0;
while (c.equipment.Primary != rifle && waited < 3000)
{
Fixtures.Tick(60);
waited += 60;
}
T.Check(c.equipment.Primary == rifle, "the colonist did not pick its rifle up within 3000 ticks (job: " + c.CurJobDef?.defName + ")");
T.Info("equipped after " + waited + " ticks");
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(!ForbidWaitList.Contains(rifle), "the equipped rifle is still on the wait list");
T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3)));
}
[BlaxTest("forbid gear: a prisoner breaking out, downed with a knife: it waits, then follows the colony rule once carried")]
public static void PrisonerBreakingOut()
{
Begin();
ColonyRule();
CellRect r = Area(home: false);
Pawn p = Spawn(Generate(PawnKindDefOf.Slave, Hostile()), r.CenterCell);
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner);
T.Check(p.IsPrisonerOfColony, "setup: not a prisoner of the colony");
ThingWithComps knife = Arm(p, "MeleeWeapon_Knife", QualityCategory.Normal, 1f);
LordMaker.MakeNewLord(p.Faction, new LordJob_PrisonBreak(p.Position, p.Position, -1), Map, new[] { p });
T.Check(PrisonBreakUtility.IsPrisonBreaking(p), "setup: the prisoner is not breaking out");
T.Check(p.HostileTo(Faction.OfPlayer), "setup: the escaping prisoner is not hostile to the player");
T.Equal(ForbidGroup.Colony, ForbidRules.GroupOf(p), "group of the escaping prisoner");
Down(p);
NeedRememberedWeapon(p, knife);
T.Check(Forbidden(knife), "the knife was allowed at once");
Fixtures.Tick(ForbidWaitList.CheckInterval * 2);
T.Check(Forbidden(knife), "the knife was allowed while the prisoner lies where it fell");
Pawn carrier = Colonist(r.CenterCell + IntVec3.East * 2);
carrier.drafter.Drafted = true;
T.Check(carrier.carryTracker.TryStartCarry(p, 1, reserve: false) > 0, "setup: the colonist could not pick the prisoner up");
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(!Forbidden(knife), "the knife is still forbidden after the prisoner was carried off");
if (carrier.carryTracker.CarriedThing != null)
carrier.carryTracker.TryDropCarriedThing(carrier.Position, ThingPlaceMode.Near, out _);
}
// ---- gear rules: enemies ---------------------------------------------------------
[BlaxTest("forbid gear: a raider killed outside the home area, suggested setup: good rifle, drugs and medicine allowed, the rest forbidden")]
public static void RaiderKilled()
{
Begin();
EnemyRule();
CellRect r = Area(home: false);
RaiderKit k = KitRaider(r.CenterCell);
Pawn raider = k.Raider;
raider.Kill(null);
T.Check(!Forbidden(k.Good), "the Normal assault rifle at 80% is forbidden");
T.Check(Forbidden(k.Poor), "the Poor assault rifle at 80% is allowed");
T.Check(Forbidden(k.Damaged), "the Normal assault rifle at 40% is allowed");
T.Check(!Forbidden(k.GoJuice), "the go-juice is forbidden");
T.Check(!Forbidden(k.Medicine), "the medicine is forbidden");
T.NotNull(raider.Corpse, "the raider's corpse");
T.Check(Forbidden(raider.Corpse), "the corpse is allowed with the corpse switches off");
}
[BlaxTest("forbid gear: a raider downed, not killed: its weapon is allowed; captured afterwards, nothing else changes")]
public static void RaiderDowned()
{
Begin();
EnemyRule();
CellRect r = Area(home: false);
RaiderKit k = KitRaider(r.CenterCell);
Down(k.Raider);
T.Check(!Forbidden(k.Good), "the downed raider's Normal rifle at 80% is forbidden");
T.Check(Forbidden(k.Poor), "the downed raider's Poor rifle is allowed");
T.Check(!ForbidWaitList.Contains(k.Good), "an enemy's weapon waits like a remembered colony weapon");
Pawn captor = Colonist(r.CenterCell + IntVec3.West * 2);
k.Raider.guest.CapturedBy(Faction.OfPlayer, captor);
T.Check(k.Raider.IsPrisonerOfColony, "setup: the raider was not captured");
T.Check(!Forbidden(k.Good) && Forbidden(k.Poor), "capture changed the flags");
T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3)));
}
[BlaxTest("forbid gear: \"only inside the home area\": killed outside stays vanilla, killed inside the good rifle is allowed")]
public static void OnlyInsideHome()
{
Begin();
EnemyRule(anywhere: false);
CellRect outside = Area(home: false);
RaiderKit a = KitRaider(outside.CenterCell);
a.Raider.Kill(null);
T.Check(Forbidden(a.Good) && Forbidden(a.Medicine), "a raider killed outside the home area got its drops allowed");
CellRect inside = Area(home: true);
RaiderKit b = KitRaider(inside.CenterCell);
b.Raider.Kill(null);
T.Check(!Forbidden(b.Good), "the Normal rifle at 80% of a raider killed inside the home area is forbidden");
}
[BlaxTest("forbid gear: two raiders' medicine merging into one stack outside the home area is allowed; a stack the player forbade stays forbidden")]
public static void MergedStacks()
{
Begin();
EnemyRule();
CellRect r = Area(home: false);
ThingDef medicine = ThingDefOf.MedicineIndustrial;
for (int i = 0; i < 2; i++)
{
Pawn raider = Raider(r.CenterCell);
Give(raider, medicine.defName, 5);
raider.Kill(null);
}
List<Thing> stacks = r.Cells.SelectMany(c => c.GetThingList(Map)).Where(t => t.def == medicine).ToList();
T.Equal(1, stacks.Count, "medicine stacks in the area");
T.Equal(10, stacks[0].stackCount, "medicine in the merged stack");
T.Check(!Forbidden(stacks[0]), "the merged stack of 10 is forbidden");
CellRect r2 = Area(home: false);
// The corpse takes the centre cell, so the first cell the drop tries after it is the next one of the radial pattern.
IntVec3 spot = r2.CenterCell + GenRadial.RadialPattern[1];
Thing mine = GenSpawn.Spawn(Stack(medicine.defName, 10), spot, Map);
mine.SetForbidden(true, warnOnFail: false);
Pawn third = Raider(r2.CenterCell);
Give(third, medicine.defName, 5);
// The corpse fills the centre, and the player's stack is on the first cell a drop near it tries, so the raider's 5 merge into it.
third.Kill(null);
List<Thing> after = r2.Cells.SelectMany(c => c.GetThingList(Map)).Where(t => t.def == medicine).ToList();
T.Info("medicine stacks next to the player's: " + string.Join(", ", after.Select(t => t.stackCount + (Forbidden(t) ? " forbidden" : " allowed"))));
T.Check(!mine.Destroyed && mine.stackCount == 15, "the raider's medicine did not merge into the player's stack (" + mine.stackCount + ")");
T.Check(Forbidden(mine), "the stack the player forbade was allowed");
}
[BlaxTest("forbid gear: a raider carrying 200 silver killed inside the home area: allowed with the rule on, forbidden with it off")]
public static void CarriedSilver()
{
Begin();
EnemyRule();
// The colony rule keeps the death scope open in the "off" pass, so the enemy rule's own checkbox decides.
ColonyRule();
foreach (bool on in new[] { true, false })
{
ForbidRules.Enemies.Ticked = on;
T.Check(ForbidHooks.ShouldOpen, "setup: no scope opens with the enemy rule " + (on ? "on" : "off"));
CellRect r = Area(home: true);
Pawn raider = Raider(r.CenterCell);
Thing silver = Stack("Silver", 200);
T.Check(raider.carryTracker.TryStartCarry(silver), "setup: the raider could not carry the silver");
raider.Kill(null);
Thing dropped = r.Cells.SelectMany(c => c.GetThingList(Map)).FirstOrDefault(t => t.def == ThingDefOf.Silver);
T.NotNull(dropped, "the silver on the ground");
T.Equal(!on, Forbidden(dropped), "silver forbidden with the rule " + (on ? "on" : "off"));
}
}
[BlaxTest("forbid gear: a filter refusing medicine never forbids: a raider killed inside the home area leaves its medicine allowed")]
public static void RefusingNeverForbids()
{
Begin();
FilterRefusing(ForbidRules.Enemies, "MedicineIndustrial");
ForbidRules.Enemies.Ticked = true;
CellRect r = Area(home: true);
Pawn raider = Raider(r.CenterCell);
Thing medicine = Give(raider, "MedicineIndustrial", 4);
raider.Kill(null);
T.Check(medicine.Spawned, "setup: the medicine is not on the ground");
T.Check(!Forbidden(medicine), "the medicine was forbidden");
}
[BlaxTest("forbid gear: with both rules on, a downed trader guest's wares and a downed quest lodger's weapon stay forbidden")]
public static void NeutralsStayVanilla()
{
Begin();
ColonyRule();
EnemyRule();
CellRect r = Area(home: false);
Faction friendly = Friendly();
Pawn trader = Spawn(Generate(MemberKind(friendly), friendly), r.CenterCell);
Thing wares = Give(trader, "Silver", 50);
Thing cloth = Give(trader, "Cloth", 20);
T.Equal(ForbidGroup.None, ForbidRules.GroupOf(trader), "group of the trader");
Down(trader);
Fixtures.Tick(ForbidWaitList.CheckInterval);
// With Hospitality's "disable friendly gear drops" a downed visitor keeps its things; what does drop stays forbidden.
if (!Compat.IsActive(Hospitality))
T.Check(wares.Spawned && cloth.Spawned, "setup: the downed trader's wares are not on the ground");
else if (!wares.Spawned && !cloth.Spawned)
T.Info("the downed trader kept its wares (Hospitality keeps a friendly pawn's gear on it)");
T.Check((!wares.Spawned || Forbidden(wares)) && (!cloth.Spawned || Forbidden(cloth)), "the trader's dropped wares were allowed");
Pawn lodger = Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer), r.CenterCell + IntVec3.North * 3);
Quest quest = Quest.MakeRaw();
quest.hidden = true;
quest.acceptanceTick = Find.TickManager.TicksGame;
var part = new QuestPart_ExtraFaction { extraFaction = new ExtraFaction(friendly, ExtraFactionType.HomeFaction) };
part.affectedPawns.Add(lodger);
quest.AddPart(part);
Find.QuestManager.Add(quest);
try
{
T.Check(lodger.IsQuestLodger(), "setup: the pawn is not a quest lodger");
T.Equal(ForbidGroup.None, ForbidRules.GroupOf(lodger), "group of the quest lodger");
ThingWithComps weapon = Arm(lodger, "Gun_AssaultRifle", QualityCategory.Normal, 1f);
Down(lodger);
T.Check(Forbidden(weapon), "the lodger's weapon was allowed");
T.Check(!ForbidWaitList.Contains(weapon), "the lodger's weapon waits on the list");
}
finally
{
if (Find.QuestManager.QuestsListForReading.Contains(quest))
Find.QuestManager.Remove(quest);
}
}
[BlaxTest("forbid gear: a downed slave's meal outside the home area follows the colony rule (Ideology)")]
public static void SlaveDowned()
{
Fixtures.NeedDlc(DlcSupport.Ideology);
Begin();
ColonyRule();
CellRect r = Area(home: false);
Pawn slave = Spawn(Generate(PawnKindDefOf.Slave, Friendly()), r.CenterCell);
slave.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
T.Check(slave.IsSlaveOfColony, "setup: not a slave of the colony");
T.Equal(ForbidGroup.Colony, ForbidRules.GroupOf(slave), "group of the slave");
Thing meal = Give(slave, "MealSurvivalPack", 1);
Down(slave);
T.Check(meal.Spawned && !Forbidden(meal), "the slave's meal is forbidden or not on the ground");
}
[BlaxTest("forbid gear: a colony mech hauling forbidden steel goes down and the steel keeps its flag; a hostile Lancer's weapon is destroyed, not dropped (Biotech)")]
public static void Mechs()
{
Fixtures.NeedDlc(DlcSupport.Biotech);
Begin();
ColonyRule();
EnemyRule();
CellRect r = Area(home: false);
PawnKindDef lifterKind = DefDatabase<PawnKindDef>.GetNamedSilentFail("Mech_Lifter");
Fixtures.NeedDef(lifterKind, "PawnKindDef Mech_Lifter");
Pawn lifter = Spawn(Fixtures.TrackPawn(PawnGenerator.GeneratePawn(lifterKind, Faction.OfPlayer)), r.CenterCell);
T.Check(lifter.IsColonyMech, "setup: the lifter is not a colony mech");
// Forbidden before the haul: the colony's suggested filter allows every item, so a rule that allowed
// what the game never forbade in the downing would show here.
Thing steel = Stack("Steel", 30);
steel.SetForbidden(true, warnOnFail: false);
T.Check(lifter.carryTracker.TryStartCarry(steel), "setup: the lifter could not carry steel");
HealthUtility.DamageUntilDowned(lifter, allowBleedingWounds: false);
T.Check(lifter.Downed && !lifter.Dead, "setup: the lifter is not down (dead: " + lifter.Dead + ")");
Thing dropped = r.Cells.SelectMany(c => c.GetThingList(Map)).FirstOrDefault(t => t.def == ThingDefOf.Steel);
T.NotNull(dropped, "the steel on the ground");
T.Check(Forbidden(dropped), "the forbidden steel the colony mech carried was allowed");
CellRect r2 = Area(home: false);
T.NotNull(Faction.OfMechanoids, "setup: the mechanoid faction");
PawnKindDef lancerKind = Fixtures.NeedDef(DefDatabase<PawnKindDef>.GetNamedSilentFail("Mech_Lancer"), "PawnKindDef Mech_Lancer");
Pawn lancer = Spawn(Fixtures.TrackPawn(PawnGenerator.GeneratePawn(lancerKind, Faction.OfMechanoids)), r2.CenterCell);
T.Equal(ForbidGroup.Enemies, ForbidRules.GroupOf(lancer), "group of the hostile Lancer");
ThingWithComps weapon = lancer.equipment?.Primary;
T.NotNull(weapon, "setup: the Lancer's weapon");
lancer.Kill(null);
T.Check(weapon.Destroyed, "the Lancer's weapon was not destroyed");
T.Check(!r2.Cells.SelectMany(c => c.GetThingList(Map)).Any(t => t.def.IsWeapon), "a weapon lies next to the dead Lancer");
T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3)));
}
[BlaxTest("forbid gear: with Hospitality, a downed guest's weapon stays forbidden (-Compat)")]
public static void HospitalityGuest()
{
if (!Compat.IsActive("Orion.Hospitality"))
T.Skip("needs Hospitality (-Compat)");
Begin();
ColonyRule();
EnemyRule();
CellRect r = Area(home: false);
Faction friendly = Friendly();
Pawn guest = Spawn(Generate(MemberKind(friendly), friendly), r.CenterCell);
guest.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Guest);
ThingWithComps weapon = Arm(guest, "Gun_AssaultRifle", QualityCategory.Normal, 1f);
Down(guest);
Fixtures.Tick(ForbidWaitList.CheckInterval);
if (!weapon.Spawned)
T.Info("the downed guest kept its weapon (Hospitality's option to keep a friendly pawn's gear on it)");
T.Check(!weapon.Spawned || Forbidden(weapon), "the guest's dropped weapon was allowed");
T.Check(!ForbidWaitList.Contains(weapon), "the guest's weapon waits on the list");
}
[BlaxTest("forbid gear: with Pick Up And Haul, an allowed rifle is listed for hauling and gets a haul job (-Compat)")]
public static void PickUpAndHaul()
{
if (!Compat.IsActive("Mehni.PickUpAndHaul"))
T.Skip("needs Pick Up And Haul (-Compat)");
Begin();
EnemyRule();
CellRect r = Area(home: false);
RaiderKit k = KitRaider(r.CenterCell);
k.Raider.Kill(null);
T.Check(!Forbidden(k.Good), "setup: the good rifle is forbidden");
CellRect pile = Fixtures.EmptyArea(3, 3);
var zone = new Zone_Stockpile(StorageSettingsPreset.DefaultStockpile, Map.zoneManager);
Map.zoneManager.RegisterZone(zone);
Fixtures.TrackZone(zone);
foreach (IntVec3 c in pile.Cells)
zone.AddCell(c);
T.Check(zone.settings.AllowedToAccept(k.Good), "setup: the stockpile refuses the rifle");
T.Check(Map.listerHaulables.ThingsPotentiallyNeedingHauling().Contains(k.Good), "the allowed rifle is not listed for hauling");
Pawn hauler = Colonist(r.CenterCell + IntVec3.South * 3);
T.Check(HaulAIUtility.PawnCanAutomaticallyHaulFast(hauler, k.Good, forced: false), "a colonist can't haul the allowed rifle");
WorkGiverDef puah = DefDatabase<WorkGiverDef>.AllDefsListForReading.FirstOrDefault(w => w.giverClass?.FullName == "PickUpAndHaul.WorkGiver_HaulToInventory");
T.NotNull(puah, "Pick Up And Haul's work giver");
Job job = (puah.Worker as WorkGiver_Scanner)?.JobOnThing(hauler, k.Good, forced: false);
T.Check(job != null, "Pick Up And Haul gave no job for the allowed rifle");
T.Info("Pick Up And Haul job: " + job.def.defName);
}
[BlaxTest("forbid gear: kept drops for the phase-2 check, and a rifle still waiting at save time")]
public static void KeepForPhase2()
{
Begin();
EnemyRule();
CellRect r = Area(home: false);
RaiderKit k = KitRaider(r.CenterCell);
k.Raider.Kill(null);
T.Check(!Forbidden(k.Good) && Forbidden(k.Poor), "setup: flags after the kill");
Fixtures.Keep(k.Good);
Fixtures.Keep(k.Poor);
T.Carry[KeptAllowedKey] = k.Good.ThingID;
T.Carry[KeptForbiddenKey] = k.Poor.ThingID;
// Right before the save, after every other phase-1 test: a hostile pawn stands on the map and a raider
// killed then leaves its rifle on the wait list. Nothing here is tracked, so no cleanup removes it.
T.CarryAtSave(WaitingRifleKey, WaitingRifleAtSave);
}
private static string WaitingRifleAtSave()
{
BlaxDefaultsSettings s = BlaxDefaultsMod.Settings;
List<DefaultsEntry> library = DefaultsLibrary.Snapshot();
bool rule = s.enemyGearRule, strip = s.enemyStripRule, anywhere = s.enemyGearAnywhere;
try
{
ForbidRules.Enemies.UseSuggested();
ForbidRules.Enemies.Ticked = true;
Map map = Map;
Faction hostile = Fixtures.HostileFaction();
IntVec3 cell = map.AllCells
.Where(c => !c.CloseToEdge(map, 8) && c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) != null
&& !map.areaManager.Home[c] && c.GetThingList(map).Count == 0)
.OrderBy(c => (c - map.Center).LengthHorizontalSquared)
.First();
Pawn threat = PawnGenerator.GeneratePawn(new PawnGenerationRequest(MemberKind(hostile), hostile, forceGenerateNewPawn: true));
threat.equipment?.DestroyAllEquipment();
GenSpawn.Spawn(threat, cell, map);
Pawn raider = PawnGenerator.GeneratePawn(new PawnGenerationRequest(MemberKind(hostile), hostile, forceGenerateNewPawn: true));
raider.equipment?.DestroyAllEquipment();
raider.inventory?.DestroyAll();
var rifle = (ThingWithComps)ThingMaker.MakeThing(Fixtures.Thing("Gun_AssaultRifle"));
rifle.TryGetComp<CompQuality>()?.SetQuality(QualityCategory.Normal, ArtGenerationContext.Outsider);
raider.equipment.AddEquipment(rifle);
GenSpawn.Spawn(raider, cell, map);
raider.Kill(null);
T.Carry[WaitingThreatKey] = threat.ThingID;
return Forbidden(rifle) && ForbidWaitList.Contains(rifle) ? rifle.ThingID : "not waiting: forbidden " + Forbidden(rifle) + ", on the list " + ForbidWaitList.Contains(rifle);
}
finally
{
s.enemyGearRule = rule;
s.enemyStripRule = strip;
s.enemyGearAnywhere = anywhere;
DefaultsLibrary.RestoreForTests(library);
}
}
[BlaxTest("forbid gear: the flags persist; a rifle waiting at save time stays forbidden after the load and nothing logs", phase: 2)]
public static void Phase2()
{
Thing allowed = FindAnywhere(T.Carry.TryGetValue(KeptAllowedKey, out string a) ? a : null);
Thing forbidden = FindAnywhere(T.Carry.TryGetValue(KeptForbiddenKey, out string f) ? f : null);
T.NotNull(allowed, "the kept allowed rifle");
T.NotNull(forbidden, "the kept forbidden rifle");
T.Check(!Forbidden(allowed), "the allowed rifle is forbidden after the load");
T.Check(Forbidden(forbidden), "the forbidden rifle is allowed after the load");
T.Carry.TryGetValue(WaitingRifleKey, out string rifleId);
Thing rifle = FindAnywhere(rifleId);
T.NotNull(rifle, "the rifle waiting at save time (" + rifleId + ")");
Pawn threat = FindAnywhere(T.Carry.TryGetValue(WaitingThreatKey, out string th) ? th : null) as Pawn;
if (threat != null && threat.Spawned)
threat.Destroy(DestroyMode.Vanish);
EnemyRule();
T.Check(!GenHostility.AnyHostileActiveThreatToPlayer(Map), "a hostile threat is still on the map");
T.Equal(0, ForbidWaitList.Count, "wait list entries after the load");
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(Forbidden(rifle), "the rifle that waited at save time was allowed after the load");
T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3)));
if (rifle.Spawned)
rifle.Destroy(DestroyMode.Vanish);
}
private static Thing FindAnywhere(string thingId)
{
if (thingId == null)
return null;
Thing t = Fixtures.FindThingById(thingId);
if (t != null)
return t;
foreach (Map m in Find.Maps)
{
foreach (Pawn p in m.mapPawns.AllPawnsSpawned)
{
IEnumerable<Thing> held = (p.carryTracker?.innerContainer ?? Enumerable.Empty<Thing>())
.Concat(p.inventory?.innerContainer ?? Enumerable.Empty<Thing>())
.Concat(p.equipment?.AllEquipmentListForReading ?? Enumerable.Empty<Thing>());
foreach (Thing h in held)
if (h.ThingID == thingId) return h;
}
}
return null;
}
// ---- wait until the fight is over ------------------------------------------------
[BlaxTest("forbid wait: with a hostile pawn standing, a killed raider's rifle waits; once it is downed and 250 ticks pass, it is allowed")]
public static void WaitForThreat()
{
Begin();
EnemyRule();
CellRect r = Area(home: false);
Pawn threat = Threat(r);
RaiderKit k = KitRaider(r.CenterCell);
k.Raider.Kill(null);
T.Check(Forbidden(k.Good), "the rifle was allowed while a hostile pawn stands on the map");
T.Check(ForbidWaitList.Contains(k.Good), "the rifle does not wait");
Down(threat);
T.Check(!GenHostility.AnyHostileActiveThreatToPlayer(Map), "the downed hostile pawn is still an active threat");
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(!Forbidden(k.Good), "the rifle is still forbidden after the fight and a check");
T.Check(!Forbidden(k.Medicine), "the medicine is still forbidden after the fight and a check");
T.Check(Forbidden(k.Poor), "the Poor rifle was allowed after the fight");
T.Equal(0, ForbidWaitList.Count, "entries left on the wait list");
}
[BlaxTest("forbid wait: a waiting rifle the player allows and forbids again stays forbidden")]
public static void WaitPlayerChange()
{
Begin();
EnemyRule();
CellRect r = Area(home: false);
Pawn threat = Threat(r);
RaiderKit k = KitRaider(r.CenterCell);
k.Raider.Kill(null);
T.Check(ForbidWaitList.Contains(k.Good), "setup: the rifle does not wait");
k.Good.SetForbidden(false);
k.Good.SetForbidden(true);
T.Check(!ForbidWaitList.Contains(k.Good), "the rifle still waits after the player changed its flag");
Down(threat);
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(Forbidden(k.Good), "the rifle the player forbade again was allowed");
}
[BlaxTest("forbid wait: a waiting rifle a pawn picks up leaves the list without a log line")]
public static void WaitPickedUp()
{
Begin();
EnemyRule();
CellRect r = Area(home: false);
Threat(r);
RaiderKit k = KitRaider(r.CenterCell);
k.Raider.Kill(null);
T.Check(ForbidWaitList.Contains(k.Good), "setup: the rifle does not wait");
Pawn c = Colonist(r.CenterCell + IntVec3.South * 2);
c.drafter.Drafted = true;
T.Check(c.carryTracker.TryStartCarry(k.Good, 1, reserve: false) > 0, "setup: the colonist could not pick the rifle up");
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(!ForbidWaitList.Contains(k.Good), "the picked-up rifle is still on the wait list");
T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3)));
if (c.carryTracker.CarriedThing != null)
c.carryTracker.TryDropCarriedThing(c.Position, ThingPlaceMode.Near, out _);
}
[BlaxTest("forbid wait: a waiting rifle the filter no longer allows stays forbidden")]
public static void WaitFilterChanged()
{
Begin();
EnemyRule();
CellRect r = Area(home: false);
Pawn threat = Threat(r);
RaiderKit k = KitRaider(r.CenterCell);
k.Raider.Kill(null);
T.Check(ForbidWaitList.Contains(k.Good), "setup: the rifle does not wait");
FilterRefusing(ForbidRules.Enemies, "Gun_AssaultRifle");
Down(threat);
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(Forbidden(k.Good), "the rifle the filter now refuses was allowed");
T.Check(!Forbidden(k.Medicine), "the medicine the filter still allows is forbidden");
}
// ---- stripping ---------------------------------------------------------------------
private static Pawn DressedRaider(IntVec3 at, out Apparel duster, out Apparel tuque)
{
Pawn p = Raider(at);
p.apparel.DestroyAll();
duster = Wear(p, "Apparel_Duster", QualityCategory.Normal, 0.8f);
tuque = Wear(p, "Apparel_Tuque", QualityCategory.Poor, 0.9f);
return p;
}
/// <summary>Kills the pawn and puts its apparel's hit points back where the test set them.</summary>
private static Corpse KillKeepingHitPoints(Pawn p, params Apparel[] apparel)
{
int[] hp = apparel.Select(a => a.HitPoints).ToArray();
p.Kill(null);
for (int i = 0; i < apparel.Length; i++)
apparel[i].HitPoints = hp[i];
T.NotNull(p.Corpse, "the corpse of " + p);
return p.Corpse;
}
[BlaxTest("forbid strip: a raider corpse stripped with the enemy switch on: Normal duster at 80% allowed, Poor tuque forbidden; switch off: both allowed")]
public static void StripRaiderCorpse()
{
Begin();
EnemyRule();
foreach (bool on in new[] { true, false })
{
ForbidRules.Enemies.StripTicked = on;
CellRect r = Area(home: false);
Pawn p = DressedRaider(r.CenterCell, out Apparel duster, out Apparel tuque);
Corpse corpse = KillKeepingHitPoints(p, duster, tuque);
corpse.Strip();
T.Check(duster.Spawned && tuque.Spawned, "setup: the apparel is not on the ground");
T.Check(!Forbidden(duster), "the Normal duster at 80% is forbidden (switch " + (on ? "on" : "off") + ")");
T.Equal(on, Forbidden(tuque), "Poor tuque forbidden with the switch " + (on ? "on" : "off"));
}
}
[BlaxTest("forbid strip: the strip in butchering's ingredient step leaves both allowed with the switch on")]
public static void StripButchering()
{
Begin();
EnemyRule();
T.Check(ForbidRules.Enemies.StripActive, "setup: the enemy strip switch is off");
CellRect r = Area(home: false);
Pawn p = DressedRaider(r.CenterCell, out Apparel duster, out Apparel tuque);
Corpse corpse = KillKeepingHitPoints(p, duster, tuque);
RecipeDef butcher = Fixtures.NeedDef(DefDatabase<RecipeDef>.GetNamedSilentFail("ButcherCorpseFlesh"), "RecipeDef ButcherCorpseFlesh");
T.Check(butcher.autoStripCorpses, "setup: butchering does not strip corpses");
Pawn butcherPawn = Colonist(r.CenterCell + IntVec3.East * 2);
Job job = JobMaker.MakeJob(JobDefOf.DoBill, butcherPawn);
job.bill = new Bill_Production(butcher);
job.placedThings = new List<ThingCountClass> { new ThingCountClass(corpse, 1) };
// The private static ingredient step of the butcher's bill job (Verse.AI/Toils_Recipe.cs:301), as the
// finish toil calls it: it strips the corpse because the recipe has autoStripCorpses.
AccessTools.Method(typeof(Toils_Recipe), "CalculateIngredients").Invoke(null, new object[] { job, butcherPawn });
T.Check(duster.Spawned && tuque.Spawned, "the butchering step did not strip the corpse");
T.Check(!Forbidden(duster) && !Forbidden(tuque), "butchering forbade stripped apparel (duster " + Forbidden(duster) + ", tuque " + Forbidden(tuque) + ")");
T.Check(!ForbidHooks.Butchering, "the butchering flag is still set");
}
[BlaxTest("forbid strip: a colonist's corpse stripped with only the enemy switch on: both allowed; with only the colony switch on, the colony filter decides")]
public static void StripColonistCorpse()
{
Begin();
EnemyRule();
foreach (bool colonySwitch in new[] { false, true })
{
if (colonySwitch)
{
// The colony filter refuses the Normal duster and allows the Poor tuque, the opposite of the
// enemy filter, so the colony switch and the colony filter are both what decides.
FilterRefusing(ForbidRules.Colony, "Apparel_Duster");
ForbidRules.Colony.StripTicked = true;
ForbidRules.Enemies.StripTicked = false;
T.Check(ForbidRules.Colony.StripActive && !ForbidRules.Enemies.StripActive, "setup: strip switches");
}
string pass = colonySwitch ? "only the colony switch on" : "only the enemy switch on";
CellRect r = Area(home: false);
Pawn c = Colonist(r.CenterCell);
c.apparel.DestroyAll();
Apparel duster = Wear(c, "Apparel_Duster", QualityCategory.Normal, 0.8f);
Apparel tuque = Wear(c, "Apparel_Tuque", QualityCategory.Poor, 0.9f);
Corpse corpse = KillKeepingHitPoints(c, duster, tuque);
corpse.Strip();
T.Check(duster.Spawned && tuque.Spawned, "setup: the apparel is not on the ground (" + pass + ")");
T.Equal(colonySwitch, Forbidden(duster), "the colonist's Normal duster forbidden with " + pass);
T.Check(!Forbidden(tuque), "the colonist's Poor tuque was forbidden with " + pass);
}
}
[BlaxTest("forbid strip: a raider stripped while down: its Poor shirt isn't tainted and is forbidden, its Normal duster allowed")]
public static void StripDownedRaider()
{
Begin();
EnemyRule();
CellRect r = Area(home: false);
Pawn p = Raider(r.CenterCell);
p.apparel.DestroyAll();
Apparel shirt = Wear(p, "Apparel_BasicShirt", QualityCategory.Poor, 1f);
Apparel duster = Wear(p, "Apparel_Duster", QualityCategory.Normal, 1f);
Down(p);
T.Equal(ForbidGroup.Enemies, ForbidRules.GroupOf(p), "group of the downed raider");
p.Strip();
T.Check(shirt.Spawned && duster.Spawned, "setup: the apparel is not on the ground");
T.Check(!shirt.WornByCorpse, "the shirt stripped from a living raider is tainted");
T.Check(Forbidden(shirt), "the Poor shirt was allowed");
T.Check(!Forbidden(duster), "the Normal duster was forbidden");
}
[BlaxTest("forbid strip: a strip inside a caravan logs nothing")]
public static void StripInCaravan()
{
Begin();
FilterRefusing(ForbidRules.Colony, "Apparel_Tuque");
ForbidRules.Colony.StripTicked = true;
T.Check(ForbidRules.Colony.StripActive, "setup: the colony strip switch is off");
Pawn colonist = Generate(PawnKindDefOf.Colonist, Faction.OfPlayer);
Pawn prisoner = Generate(PawnKindDefOf.Slave, Hostile());
prisoner.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner);
prisoner.apparel.DestroyAll();
Apparel tuque = Wear(prisoner, "Apparel_Tuque", QualityCategory.Normal, 1f);
Caravan caravan = CaravanMaker.MakeCaravan(new[] { colonist, prisoner }, Faction.OfPlayer, Map.Tile, addToWorldPawnsIfNotAlready: true);
try
{
T.Check(prisoner.GetCaravan() == caravan, "setup: the prisoner is not in the caravan");
prisoner.Strip();
T.Check(!tuque.Spawned, "the tuque landed on a map");
T.Check(!prisoner.apparel.WornApparel.Contains(tuque), "the tuque was not stripped");
T.Check(T.ErrorsSoFar().Count == 0, "errors were logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3)));
}
finally
{
caravan.RemoveAllPawns();
if (!caravan.Destroyed)
caravan.Destroy();
foreach (Pawn p in new[] { colonist, prisoner })
{
if (!p.Destroyed && p.IsWorldPawn())
Find.WorldPawns.RemoveAndDiscardPawnViaGC(p);
}
}
}
// ---- corpses -----------------------------------------------------------------------
private static Pawn Animal(string kindName, IntVec3 at)
{
PawnKindDef kind = Fixtures.NeedDef(DefDatabase<PawnKindDef>.GetNamedSilentFail(kindName), "PawnKindDef " + kindName);
return Spawn(Fixtures.TrackPawn(PawnGenerator.GeneratePawn(kind, null)), at);
}
[BlaxTest("forbid corpses: a wild animal killed outside the home area: allowed with the animal switch, forbidden without; a hunter's kill is unchanged")]
public static void AnimalCorpses()
{
Begin();
foreach (bool on in new[] { true, false })
{
Fixtures.Settings.animalCorpsesAllowed = on;
CellRect r = Area(home: false);
Pawn muffalo = Animal("Muffalo", r.CenterCell);
muffalo.Kill(null);
T.NotNull(muffalo.Corpse, "the muffalo's corpse");
T.Equal(!on, Forbidden(muffalo.Corpse), "muffalo corpse forbidden with the animal switch " + (on ? "on" : "off"));
}
Fixtures.Settings.animalCorpsesAllowed = false;
CellRect h = Area(home: false);
Pawn prey = Animal("Muffalo", h.CenterCell);
Pawn hunter = Colonist(h.CenterCell + IntVec3.West * 3, canFight: true);
Arm(hunter, "Gun_AssaultRifle", QualityCategory.Normal, 1f);
Job hunt = JobMaker.MakeJob(JobDefOf.Hunt, prey);
// A hunt job without the Hunt designation, so the game's own "designated for hunting" exception doesn't apply.
hunt.ignoreDesignations = true;
hunter.jobs.StartJob(hunt, JobCondition.InterruptForced);
T.Check(hunter.jobs.curDriver is JobDriver_Hunt, "setup: the hunter is not hunting");
prey.Kill(new DamageInfo(DamageDefOf.Bullet, 10f, instigator: hunter));
T.NotNull(prey.Corpse, "the hunted muffalo's corpse");
T.Check(!Forbidden(prey.Corpse), "the corpse the hunter reserved was forbidden");
hunter.jobs.EndCurrentJob(JobCondition.InterruptForced);
}
[BlaxTest("forbid corpses: a raider killed outside the home area with the enemy switch on is allowed")]
public static void EnemyCorpse()
{
Begin();
Fixtures.Settings.enemyCorpsesAllowed = true;
CellRect r = Area(home: false);
Pawn raider = Raider(r.CenterCell);
raider.Kill(null);
T.NotNull(raider.Corpse, "the raider's corpse");
T.Check(!Forbidden(raider.Corpse), "the raider's corpse is forbidden with the enemy switch on");
}
[BlaxTest("forbid corpses: a manhunter husky killed outside the home area follows the animal switch, not the enemy switch")]
public static void ManhunterCorpse()
{
Begin();
foreach (bool animal in new[] { true, false })
{
Fixtures.Settings.animalCorpsesAllowed = animal;
Fixtures.Settings.enemyCorpsesAllowed = !animal;
CellRect r = Area(home: false);
Pawn husky = Animal("Husky", r.CenterCell);
T.Check(husky.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, forced: true), "setup: the husky did not turn manhunter");
T.Equal(ForbidGroup.Enemies, ForbidRules.GroupOf(husky), "group of the manhunter");
husky.Kill(null);
T.NotNull(husky.Corpse, "the husky's corpse");
T.Equal(!animal, Forbidden(husky.Corpse), "manhunter corpse forbidden with only the " + (animal ? "animal" : "enemy") + " switch on");
}
}
[BlaxTest("forbid corpses: the other switch allows a colonist's and a friendly visitor's corpse outside the home area; the animal and enemy switches don't")]
public static void OtherCorpses()
{
Begin();
Faction friendly = Friendly();
foreach (bool other in new[] { true, false })
{
Fixtures.Settings.otherCorpsesAllowed = other;
Fixtures.Settings.animalCorpsesAllowed = !other;
Fixtures.Settings.enemyCorpsesAllowed = !other;
string pass = other ? "only the other switch on" : "only the animal and enemy switches on";
CellRect r = Area(home: false);
Pawn colonist = Colonist(r.CenterCell);
Pawn visitor = Spawn(Generate(MemberKind(friendly), friendly), r.CenterCell + IntVec3.North * 3);
T.Equal(ForbidGroup.None, ForbidRules.GroupOf(visitor), "group of the visitor");
colonist.Kill(null);
visitor.Kill(null);
T.NotNull(colonist.Corpse, "the colonist's corpse");
T.NotNull(visitor.Corpse, "the visitor's corpse");
T.Equal(!other, Forbidden(colonist.Corpse), "the colonist's corpse forbidden with " + pass);
T.Equal(!other, Forbidden(visitor.Corpse), "the visitor's corpse forbidden with " + pass);
}
}
[BlaxTest("forbid corpses: a corpse inside the home area is never touched")]
public static void CorpseInsideHome()
{
Begin();
Fixtures.Settings.animalCorpsesAllowed = true;
Fixtures.Settings.enemyCorpsesAllowed = true;
Fixtures.Settings.otherCorpsesAllowed = true;
CellRect r = Area(home: true);
Pawn raider = Raider(r.CenterCell);
raider.Kill(null);
T.NotNull(raider.Corpse, "the raider's corpse");
T.Check(!Forbidden(raider.Corpse), "a corpse inside the home area is forbidden");
T.Check(!ForbidWaitList.Contains(raider.Corpse), "a corpse inside the home area waits");
}
[BlaxTest("forbid corpses: with a hostile pawn on the map, an enemy corpse waits and is allowed once the hostile pawn is downed")]
public static void CorpseWaits()
{
Begin();
Fixtures.Settings.enemyCorpsesAllowed = true;
CellRect r = Area(home: false);
Pawn threat = Threat(r);
Pawn raider = Raider(r.CenterCell);
raider.Kill(null);
Corpse corpse = raider.Corpse;
T.NotNull(corpse, "the raider's corpse");
T.Check(Forbidden(corpse) && ForbidWaitList.Contains(corpse), "the corpse was allowed during the fight, or does not wait");
Down(threat);
Fixtures.Tick(ForbidWaitList.CheckInterval);
T.Check(!Forbidden(corpse), "the corpse is still forbidden after the fight");
}
}
}