using System; using System.Collections.Generic; using System.Linq; using BlaxDefaults; using HarmonyLib; using RimWorld; using Verse; namespace BlaxDefaultsTests { /// /// Work package "hooks". The tests of design.md: New stockpiles start from your default; New storage buildings start from your default. /// Methods: [BlaxTest(": ", phase: N)] public static void X(). Skip DLC-only checks with /// Fixtures.NeedDlc(DlcSupport.Biotech) ("skipped: needs Biotech"). /// public static class HooksTests { private const string KeptZoneKey = "hooks.keptZone"; private const string KeptZoneSettingsKey = "hooks.keptZoneSettings"; // ---- stockpiles ------------------------------------------------------------------ [BlaxTest("stockpiles: a new stockpile starts from the Stockpile default")] public static void NewStockpile() { SaveMealsOnlyStockpile(); CellRect area = Fixtures.EmptyArea(3, 3); List zones = Designate(GameDesignator(), area.Cells); T.Equal(1, zones.Count, "new zones"); T.Equal(9, zones[0].CellCount, "cells of the new zone"); CheckMealsOnly(zones[0].settings, "the new stockpile"); } [BlaxTest("stockpiles: two disjoint blocks in one drag give two zones, both with the default")] public static void TwoBlocks() { SaveMealsOnlyStockpile(); CellRect area = Fixtures.EmptyArea(7, 3); // Columns 0-2 and 4-6; column 3 stays free, so the blocks don't touch. IEnumerable cells = area.Cells.Where(c => c.x - area.minX != 3); List zones = Designate(GameDesignator(), cells); T.Equal(2, zones.Count, "new zones"); foreach (Zone_Stockpile z in zones) { T.Equal(9, z.CellCount, "cells of " + z.label); CheckMealsOnly(z.settings, z.label); } } [BlaxTest("stockpiles: a dumping drag without a dumping default stays vanilla")] public static void DumpingWithoutDefault() { SaveMealsOnlyStockpile(); ForgetInMemory(DefaultsKeys.Dumping); CellRect area = Fixtures.EmptyArea(3, 3); List zones = Designate(GameDesignator(), area.Cells); T.Equal(1, zones.Count, "new zones"); StorageSettings s = zones[0].settings; T.Equal(StoragePriority.Normal, s.Priority, "dumping stockpile priority"); T.Check(s.filter.Allows(ThingDefOf.ChunkSlagSteel), "the dumping stockpile refuses slag chunks"); T.Check(s.filter.Allows(ThingDefOf.Human.race.corpseDef), "the dumping stockpile refuses human corpses"); T.Check(!s.filter.Allows(ThingDefOf.MealSimple), "the dumping stockpile took the Stockpile default (allows MealSimple)"); CheckGameDefault(Fixtures.DumpingKind, s, "the dumping stockpile"); } [BlaxTest("stockpiles: an Expand drag next to a zone grows it without touching its filter")] public static void ExpandKeepsFilter() { ForgetInMemory(DefaultsKeys.Stockpile); CellRect area = Fixtures.EmptyArea(6, 3); List left = area.Cells.Where(c => c.x - area.minX < 3).ToList(); List right = area.Cells.Where(c => c.x - area.minX >= 3).ToList(); List made = Designate(GameDesignator(), left); T.Equal(1, made.Count, "zones made by the first drag"); Zone_Stockpile zone = made[0]; zone.settings.Priority = StoragePriority.Low; zone.settings.filter.SetAllow(ThingDefOf.Steel, false); string before = Fixtures.StockpileKind.Capture(zone.settings).ContentFingerprint(); SaveMealsOnlyStockpile(); List grown = Designate(new Designator_ZoneAddStockpile_Expand(), right, select: zone); T.Equal(0, grown.Count, "zones made by the Expand drag"); T.Equal(18, zone.CellCount, "cells of the grown zone"); T.Equal(StoragePriority.Low, zone.settings.Priority, "priority of the grown zone"); T.Check(zone.settings.filter.Allows(ThingDefOf.WoodLog) && !zone.settings.filter.Allows(ThingDefOf.Steel), "the grown zone's filter changed (WoodLog " + zone.settings.filter.Allows(ThingDefOf.WoodLog) + ", Steel " + zone.settings.filter.Allows(ThingDefOf.Steel) + ")"); T.Check(Fixtures.StockpileKind.Capture(zone.settings).ContentFingerprint() == before, "the grown zone's settings changed"); } [BlaxTest("stockpiles: an Expand drag away from any zone makes a stockpile with the Stockpile default")] public static void ExpandAloneMakesStockpile() { SaveMealsOnlyStockpile(); CellRect area = Fixtures.EmptyArea(3, 3); List zones = Designate(new Designator_ZoneAddStockpile_Expand(), area.Cells); T.Equal(1, zones.Count, "new zones"); CheckMealsOnly(zones[0].settings, "the stockpile an Expand drag made"); } [BlaxTest("stockpiles: with stockpile defaults or the master switch off, a new stockpile stays vanilla")] public static void StockpilesOff() { SaveMealsOnlyStockpile(); Fixtures.Settings.stockpileDefaults = false; List zones = Designate(GameDesignator(), Fixtures.EmptyArea(3, 3).Cells); T.Equal(1, zones.Count, "new zones with stockpile defaults off"); CheckGameDefault(Fixtures.StockpileKind, zones[0].settings, "a stockpile made with stockpile defaults off"); Fixtures.Settings.stockpileDefaults = true; Fixtures.Settings.enabled = false; zones = Designate(GameDesignator(), Fixtures.EmptyArea(3, 3).Cells); T.Equal(1, zones.Count, "new zones with the master switch off"); CheckGameDefault(Fixtures.StockpileKind, zones[0].settings, "a stockpile made with the master switch off"); } [BlaxTest("stockpiles: a kept stockpile for the phase-2 check")] public static void KeepStockpile() { SaveMealsOnlyStockpile(); List zones = Designate(GameDesignator(), Fixtures.EmptyArea(3, 3).Cells); T.Equal(1, zones.Count, "new zones"); Zone_Stockpile zone = Fixtures.KeepZone(zones[0]); CheckMealsOnly(zone.settings, "the kept stockpile"); T.Carry[KeptZoneKey] = zone.ID.ToString(); T.Carry[KeptZoneSettingsKey] = Fixtures.StockpileKind.Capture(zone.settings).ContentFingerprint(); } [BlaxTest("stockpiles: the kept stockpile's settings persist after save and reload", phase: 2)] public static void KeptStockpilePersists() { T.Carry.TryGetValue(KeptZoneKey, out string idText); T.Check(int.TryParse(idText, out int id), "phase 1 kept no stockpile"); var zone = Fixtures.FindZoneById(id) as Zone_Stockpile; T.NotNull(zone, "the kept stockpile " + id); CheckMealsOnly(zone.settings, "the kept stockpile after reload"); T.Check(Fixtures.StockpileKind.Capture(zone.settings).ContentFingerprint() == T.Carry[KeptZoneSettingsKey], "the kept stockpile's settings changed over save and reload"); } // ---- storage buildings ----------------------------------------------------------- [BlaxTest("buildings: a shelf blueprint starts from the Shelf default")] public static void ShelfBlueprint() { SaveSteelOnlyShelf(); CellRect area = Fixtures.EmptyArea(3, 3); Blueprint_Storage bp = PlaceBlueprint(ThingDefOf.Shelf, ThingDefOf.WoodLog, area.CenterCell); CheckSteelOnly(bp.settings, "the shelf blueprint"); } [BlaxTest("buildings: changes made on the blueprint win over the default when the shelf is built")] public static void BlueprintChangesWin() { SaveSteelOnlyShelf(); CellRect area = Fixtures.EmptyArea(3, 3); Thing shelf = Build(ThingDefOf.Shelf, ThingDefOf.WoodLog, area.CenterCell, bp => bp.settings.filter.SetAllow(ThingDefOf.WoodLog, true)); StorageSettings s = SettingsOf(shelf); T.Equal(StoragePriority.Normal, s.Priority, "built shelf priority"); T.Check(s.filter.Allows(ThingDefOf.Steel), "the built shelf refuses Steel"); T.Check(s.filter.Allows(ThingDefOf.WoodLog), "the built shelf refuses WoodLog allowed on its blueprint"); T.Check(!s.filter.Allows(ThingDefOf.Silver), "the built shelf allows Silver"); } [BlaxTest("buildings: a shelf spawned without a blueprint keeps the game's default")] public static void SpawnedShelfKeepsGameDefault() { SaveSteelOnlyShelf(); CellRect area = Fixtures.EmptyArea(3, 3); Thing shelf = ThingMaker.MakeThing(ThingDefOf.Shelf, ThingDefOf.WoodLog); shelf.SetFactionDirect(Faction.OfPlayer); Fixtures.Track(GenSpawn.Spawn(shelf, area.CenterCell, Fixtures.Map, Rot4.North)); StorageSettings s = SettingsOf(shelf); T.Equal(StoragePriority.Preferred, s.Priority, "spawned shelf priority"); CheckGameDefault(Fixtures.Kind("Shelf"), s, "the spawned shelf"); } [BlaxTest("buildings: auto-rebuild of a shelf keeps the destroyed shelf's settings")] public static void RebuiltShelfKeepsSettings() { SaveSteelOnlyShelf(); CellRect area = Fixtures.EmptyArea(5, 5); Thing shelf = Build(ThingDefOf.Shelf, ThingDefOf.WoodLog, area.CenterCell); StorageSettings s = SettingsOf(shelf); s.filter.SetDisallowAll(); s.filter.SetAllow(ThingDefOf.Silver, true); StorageSettings rebuilt = DestroyWithAutoRebuild(shelf, area); T.Check(rebuilt.filter.Allows(ThingDefOf.Silver), "the rebuild blueprint refuses Silver"); T.Check(!rebuilt.filter.Allows(ThingDefOf.Steel), "the rebuild blueprint allows Steel (the default replaced the old settings)"); T.Check(!rebuilt.filter.Allows(ThingDefOf.WoodLog), "the rebuild blueprint allows WoodLog"); } [BlaxTest("buildings: auto-rebuild of a bookcase starts from the Bookcase default")] public static void RebuiltBookcaseTakesDefault() { ThingDef bookcase = Fixtures.Thing("Bookcase"); StorageKind kind = Fixtures.Kind("Bookcase"); Fixtures.Save(Fixtures.Template(kind, StoragePriority.Normal, ThingDefOf.Novel)); CellRect area = Fixtures.EmptyArea(5, 5); Thing built = Build(bookcase, StuffFor(bookcase), area.CenterCell); StorageSettings s = SettingsOf(built); T.Check(s.filter.Allows(ThingDefOf.Novel) && !s.filter.Allows(ThingDefOf.TextBook), "the built bookcase did not take the default"); s.filter.SetDisallowAll(); s.filter.SetAllow(ThingDefOf.TextBook, true); StorageSettings rebuilt = DestroyWithAutoRebuild(built, area); T.Equal(StoragePriority.Normal, rebuilt.Priority, "rebuild blueprint priority"); T.Check(rebuilt.filter.Allows(ThingDefOf.Novel), "the rebuild blueprint refuses novels"); T.Check(!rebuilt.filter.Allows(ThingDefOf.TextBook), "the rebuild blueprint allows textbooks"); } [BlaxTest("buildings: a template naming Steel never makes a hopper accept Steel")] public static void HopperNeverTakesSteel() { StorageKind kind = Fixtures.Kind("Hopper"); T.Check(!kind.ParentFilter.Allows(ThingDefOf.Steel), "the hopper's parent filter allows Steel"); StorageTemplate t = Fixtures.Template(kind, StoragePriority.Low); t.allowed.Add(ThingDefOf.Steel.defName); t.unlisted = UnlistedRule.Allow; Fixtures.Save(t); CellRect area = Fixtures.EmptyArea(3, 3); Thing hopper = Build(ThingDefOf.Hopper, StuffFor(ThingDefOf.Hopper), area.CenterCell, bp => { T.Equal(StoragePriority.Low, bp.settings.Priority, "hopper blueprint priority (the default was not applied)"); T.Check(!bp.settings.filter.Allows(ThingDefOf.Steel), "the hopper blueprint's filter allows Steel"); T.Check(!bp.settings.AllowedToAccept(ThingDefOf.Steel), "the hopper blueprint accepts Steel"); }); StorageSettings s = SettingsOf(hopper); T.Check(!s.filter.Allows(ThingDefOf.Steel), "the built hopper's filter allows Steel"); T.Check(!s.AllowedToAccept(ThingDefOf.Steel), "the built hopper accepts Steel"); } [BlaxTest("buildings: with storage defaults or the master switch off, a shelf blueprint stays vanilla")] public static void StorageOff() { SaveSteelOnlyShelf(); StorageKind kind = Fixtures.Kind("Shelf"); Fixtures.Settings.storageDefaults = false; Blueprint_Storage bp = PlaceBlueprint(ThingDefOf.Shelf, ThingDefOf.WoodLog, Fixtures.EmptyArea(3, 3).CenterCell); CheckGameDefault(kind, bp.settings, "a shelf blueprint placed with storage defaults off"); Fixtures.Settings.storageDefaults = true; Fixtures.Settings.enabled = false; bp = PlaceBlueprint(ThingDefOf.Shelf, ThingDefOf.WoodLog, Fixtures.EmptyArea(3, 3).CenterCell); CheckGameDefault(kind, bp.settings, "a shelf blueprint placed with the master switch off"); } // ---- -Compat --------------------------------------------------------------------- [BlaxTest("compat: a Weapon Racks rack built through a frame takes its default")] public static void WeaponRackTakesDefault() { if (!Compat.IsActive(Compat.WeaponRacks)) T.Skip("Weapon Racks is not active"); ThingDef rack = Fixtures.Thing("WeaponRacks_1Rack"); T.Check(StorageKinds.IsCovered(rack), "WeaponRacks_1Rack is not covered"); StorageKind kind = StorageKinds.ForDef(rack); ThingDef weapon = DefDatabase.GetNamedSilentFail("Gun_Revolver"); if (weapon == null || !kind.ParentFilter.Allows(weapon)) weapon = StorageKinds.StorableDefs(kind.ParentFilter).FirstOrDefault(d => d.IsWeapon); T.NotNull(weapon, "a weapon the rack takes"); StorageTemplate t = Fixtures.Save(Fixtures.Template(kind, StoragePriority.Low, weapon)); Thing built = Build(rack, StuffFor(rack), Fixtures.EmptyArea(3, 3).CenterCell); StorageSettings s = SettingsOf(built); T.Info("rack class " + built.GetType().FullName + ", template weapon " + weapon.defName); T.Equal(StoragePriority.Low, s.Priority, "built rack priority"); T.Check(s.filter.Allows(weapon), "the built rack refuses " + weapon.defName); T.Check(kind.Capture(s).SameSettingsAs(t), "the built rack's settings differ from the default"); } [BlaxTest("compat: Replace Stuff's stuff replacement of a shelf keeps the shelf's settings")] public static void ReplaceStuffKeepsSettings() { if (!Compat.IsActive(Compat.ReplaceStuff)) T.Skip("Replace Stuff is not active"); var place = AccessTools.Method("Replace_Stuff.GenReplace:PlaceReplaceFrame"); T.NotNull(place, "Replace_Stuff.GenReplace.PlaceReplaceFrame"); SaveSteelOnlyShelf(); CellRect area = Fixtures.EmptyArea(5, 5); Thing shelf = Build(ThingDefOf.Shelf, ThingDefOf.WoodLog, area.CenterCell); StorageSettings s = SettingsOf(shelf); s.filter.SetDisallowAll(); s.filter.SetAllow(ThingDefOf.Silver, true); s.Priority = StoragePriority.Low; var frame = place.Invoke(null, new object[] { shelf, ThingDefOf.Steel }) as Frame; T.NotNull(frame, "the replace frame"); Fixtures.Track(frame); frame.CompleteConstruction(Fixtures.Worker()); T.Check(shelf.Spawned, "the shelf is gone after the stuff replacement"); T.Equal(ThingDefOf.Steel, shelf.Stuff, "shelf stuff after the replacement"); StorageSettings after = SettingsOf(shelf); T.Equal(StoragePriority.Low, after.Priority, "shelf priority after the replacement"); T.Check(after.filter.Allows(ThingDefOf.Silver), "the replaced shelf refuses Silver"); T.Check(!after.filter.Allows(ThingDefOf.Steel), "the replaced shelf allows Steel (the default was applied)"); } // ---- helpers --------------------------------------------------------------------- /// "Stockpile: Important, simple meals only", saved. private static void SaveMealsOnlyStockpile() => Fixtures.Save(Fixtures.Template(Fixtures.StockpileKind, StoragePriority.Important, ThingDefOf.MealSimple)); /// "Shelf: Normal, Steel only", saved. private static void SaveSteelOnlyShelf() => Fixtures.Save(Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Normal, ThingDefOf.Steel)); private static void CheckMealsOnly(StorageSettings s, string what) { T.Equal(StoragePriority.Important, s.Priority, what + " priority"); T.Check(s.filter.Allows(ThingDefOf.MealSimple), what + " refuses MealSimple"); T.Check(!s.filter.Allows(ThingDefOf.Steel), what + " allows Steel"); } private static void CheckSteelOnly(StorageSettings s, string what) { T.Equal(StoragePriority.Normal, s.Priority, what + " priority"); T.Check(s.filter.Allows(ThingDefOf.Steel), what + " refuses Steel"); T.Check(!s.filter.Allows(ThingDefOf.WoodLog), what + " allows WoodLog"); } private static void CheckGameDefault(StorageKind kind, StorageSettings s, string what) { StorageTemplate expected = kind.Capture(kind.GameDefault()); StorageTemplate actual = kind.Capture(s); T.Equal(expected.priority, actual.priority, what + " priority"); T.Check(actual.SameSettingsAs(expected), what + " differs from the game's default"); } /// Removes an entry from the library in memory only; the runner restores it after the test. private static void ForgetInMemory(string key) => DefaultsLibrary.RestoreForTests(DefaultsLibrary.Snapshot().Where(e => e.key != key).ToList()); /// Runs the designator over the cells as one drag and returns the stockpiles it made (tracked). private static List Designate(Designator_ZoneAddStockpile designator, IEnumerable cells, Zone select = null) { Map map = Fixtures.Map; Find.Selector.ClearSelection(); if (select != null) Find.Selector.Select(select, playSound: false, forceDesignatorDeselect: false); var before = new HashSet(map.zoneManager.AllZones); try { designator.DesignateMultiCell(cells.ToList()); } finally { Find.Selector.ClearSelection(); } var made = map.zoneManager.AllZones.Where(z => !before.Contains(z)).ToList(); foreach (Zone z in made) Fixtures.TrackZone(z); T.Check(made.All(z => z is Zone_Stockpile), "the designator made a zone that is not a stockpile"); return made.Cast().ToList(); } /// The instance the game made for its architect menu, else a new one (the game makes them the same way). private static TD GameDesignator() where TD : Designator, new() => DefDatabase.AllDefsListForReading .SelectMany(c => c.AllResolvedDesignators ?? new List()) .FirstOrDefault(d => d.GetType() == typeof(TD)) as TD ?? new TD(); private static ThingDef StuffFor(ThingDef def) => def.MadeFromStuff ? GenStuff.DefaultStuffFor(def) : null; internal static StorageSettings SettingsOf(Thing t) { StorageSettings s = t is IStorageGroupMember member ? member.ThingStoreSettings : (t as IStoreSettingsParent)?.GetStoreSettings(); T.NotNull(s, "storage settings of " + t); return s; } private static Blueprint_Storage PlaceBlueprint(ThingDef def, ThingDef stuff, IntVec3 at) { Blueprint_Build placed = GenConstruct.PlaceBlueprintForBuild(def, at, Fixtures.Map, Rot4.North, Faction.OfPlayer, stuff); Fixtures.Track(placed); var bp = placed as Blueprint_Storage; T.NotNull(bp, "a Blueprint_Storage for " + def.defName + " (got " + placed?.GetType().Name + ")"); return bp; } /// /// Places a blueprint, lets the test change it, turns it into a frame and completes the frame with a /// colonist, as a construction job does. Returns the building (tracked). /// internal static Thing Build(ThingDef def, ThingDef stuff, IntVec3 at, Action onBlueprint = null) { Map map = Fixtures.Map; Blueprint_Storage bp = PlaceBlueprint(def, stuff, at); onBlueprint?.Invoke(bp); Pawn worker = Fixtures.Worker(); T.Check(bp.TryReplaceWithSolidThing(worker, out Thing made, out bool _), "the " + def.defName + " blueprint did not turn into a frame"); var frame = made as Frame; T.NotNull(frame, "the " + def.defName + " frame"); Fixtures.Track(frame); frame.CompleteConstruction(worker); Thing built = at.GetThingList(map).FirstOrDefault(t => t.def == def); T.NotNull(built, "the built " + def.defName); return Fixtures.Track(built); } /// /// Destroys a player building with auto-rebuild on and its cell in the home area, as a raid would, and /// returns a copy of the rebuild blueprint's settings. Restores auto-rebuild and the home area, then /// cancels the blueprint as a player would, so Replace Stuff (in -Compat runs) forgets the destroyed /// building and doesn't revive it into a later test's building on the same cell. /// private static StorageSettings DestroyWithAutoRebuild(Thing building, CellRect area) { Map map = Fixtures.Map; T.Check(building.def.IsResearchFinished, building.def.defName + " needs research the test colony lacks, so auto-rebuild can't place it"); IntVec3 at = building.Position; bool autoRebuild = Find.PlaySettings.autoRebuild; Area_Home home = map.areaManager.Home; var homeBefore = area.Cells.ToDictionary(c => c, c => home[c]); try { Find.PlaySettings.autoRebuild = true; foreach (IntVec3 c in area.Cells) home[c] = true; building.Destroy(DestroyMode.KillFinalize); } finally { Find.PlaySettings.autoRebuild = autoRebuild; foreach (var kv in homeBefore) home[kv.Key] = kv.Value; } Blueprint_Storage bp = at.GetThingList(map).OfType().FirstOrDefault(); T.NotNull(bp, "the rebuild blueprint of " + building.def.defName); Fixtures.Track(bp); var copy = new StorageSettings(); copy.CopyFrom(bp.settings); bp.Destroy(DestroyMode.Cancel); return copy; } } }