diff --git a/README.md b/README.md index c46da01..4ba5a1c 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,9 @@ No extra dependency is required. Keep your existing BeaverBuddies Stability Fork - Select a farm, forester, lumberjack flag, gatherer, or another building with a terrain/road-spill working range. - Check **Keep working area visible**. - Deselect it and use your planting/building tools. The outline remains. +- Pick a crop or tree in the planting tools and the working areas of the buildings that plant it appear on their own: every farmhouse for crops (aquatic farmhouses for aquatic crops) and every forester for trees and bushes, including ones still under construction. They disappear when you leave the planting tool; your pins stay. - Pin additional buildings as needed. Overlapping pinned areas merge into a combined outline. -- Click **Clear pinned areas (N)** at the top right to remove every pin, without finding or selecting any building. +- Click **Clear pinned areas (N)** at the top right to remove every pin, without finding or selecting any building. Areas the planting tool shows stay until you leave that tool. - For a keyboard shortcut, assign **Clear all pinned working areas** under **Persistent Work Areas** in the game's key-binding settings. It starts unbound to avoid taking an existing shortcut. - To remove just one pin, select its building and uncheck the checkbox. diff --git a/VALIDATION.md b/VALIDATION.md index c6e166d..39ff593 100644 --- a/VALIDATION.md +++ b/VALIDATION.md @@ -23,13 +23,14 @@ These are compiled API and logic checks, not Unity rendering tests or a co-op se Re-run this for each release and after each Timberborn update. -1. With the BeaverBuddies Stability Fork enabled, load a colony, select a farm and enable its checkbox. Deselect and paint crops: the working-area outline should remain. -2. Pin a forester and paint trees. Pin a second nearby building; verify overlapping areas merge and separate areas both remain visible. +1. With the BeaverBuddies Stability Fork enabled, load a colony, select a farm and enable its checkbox. Deselect, paint crops and leave the planting tool: the working-area outline should remain. +2. Pin a forester, paint trees and leave the planting tool: the forester's outline should remain. Pin a second nearby building; verify overlapping areas merge and separate areas both remain visible. 3. Select an unrelated building, then clear all from the top-right button. No pinned outlines should remain after deselecting. Reselect formerly pinned buildings and verify their checkboxes are off. -4. Assign the clear command in key bindings and verify it clears while a planting tool is active. Do not assign a shortcut already used by a tool. +4. Assign the clear command in key bindings and verify it clears the pins while a planting tool is active; the buildings that tool shows stay until you leave it. Do not assign a shortcut already used by a tool. 5. Modify a path or terrain, switch visible levels and construction mode, and verify the outline updates. Pause the simulation and repeat selection/clear. 6. Delete a pinned building. Its outline and pin count should disappear. Exit/load another map or perform a co-op resync: pins should be empty. 7. Join with two BeaverBuddies Stability Fork clients. Pin different buildings on each computer and clear on only one. Only that player's pins should change; normal building/planting actions should remain synchronized. +8. With a few farmhouses (one still under construction) and foresters placed and none pinned, pick a crop in the Fields tools: every farmhouse's outline should appear and no forester's. Pick a tree or bush: only the foresters'. As Folktails, pick an aquatic crop: only the aquatic farmhouses'. Pin one forester and leave the planting tool: only that forester's outline should remain. ## References diff --git a/source/PinRefreshPlanner.cs b/source/PinRefreshPlanner.cs index 00dbf3b..ab2c924 100644 --- a/source/PinRefreshPlanner.cs +++ b/source/PinRefreshPlanner.cs @@ -33,6 +33,7 @@ public bool Intersects(CellBox other) => !IsEmpty && !other.IsEmpty && // Decides which pinned ranges need a fresh navigation query and when the combined outline must be rebuilt. // Each pin caches its cells, so a navigation change re-queries only the pins it can reach, and a // selection change rebuilds the outline from the cache. Unity-free so the checks can count the work. + // A building is drawn while the player pins it, the planting tool shows it, or both; either way it has one cache. internal sealed class PinRefreshPlanner where TPin : class { // Returns false when the pin can no longer be shown. The key holds everything the query depends on @@ -42,6 +43,8 @@ internal sealed class PinRefreshPlanner where TPin : class private sealed class Entry { + public bool Pinned; + public bool Shown; public bool Described; public TKey Key; public bool Stale = true; @@ -59,6 +62,7 @@ private sealed class Entry private HashSet _cells = new HashSet(); private HashSet _next = new HashSet(); private HashSet _queried = new HashSet(); + private readonly List _hidden = new List(); private TPin _selected; private bool _pending; private bool _union; @@ -69,6 +73,7 @@ public PinRefreshPlanner(DescribePin describe, QueryRange query, Func _entries.Count; public bool Pending => _pending; // The combined range of every pin except the selected one, which the game outlines itself. @@ -76,19 +81,50 @@ public PinRefreshPlanner(DescribePin describe, QueryRange query, Func pins) + { + foreach (var entry in _entries.Values) entry.Shown = false; + foreach (var pin in pins) + { + if (pin == null) continue; + if (!_entries.TryGetValue(pin, out var entry)) + { + _entries.Add(pin, entry = new Entry()); + _pending = true; + } + entry.Shown = true; + } + _hidden.Clear(); + foreach (var pair in _entries) + if (!pair.Value.Pinned && !pair.Value.Shown) _hidden.Add(pair.Key); + foreach (var pin in _hidden) Drop(pin); + _hidden.Clear(); + } + public void Clear() { _entries.Clear(); @@ -181,6 +217,12 @@ public bool Refresh(List dropped) private bool Has(TPin pin) => pin != null && _entries.ContainsKey(pin); + private void Drop(TPin pin) + { + _entries.Remove(pin); + _pending = _union = true; + } + private static bool Hits(CellBox box, TBounds bounds, Func intersects) => !box.IsEmpty && (box.IsUnbounded || intersects(box, bounds)); } diff --git a/source/PlantingRanges.cs b/source/PlantingRanges.cs new file mode 100644 index 0000000..80aa082 --- /dev/null +++ b/source/PlantingRanges.cs @@ -0,0 +1,13 @@ +using System; + +namespace PersistentWorkAreas +{ + // Which buildings' working areas the planting tool shows. Unity-free so the checks can run it on the game's blueprints. + internal static class PlantingRanges + { + // The game pairs a plantable with the planter buildings of its resource group (PlanterBuilding.GetAllowedPlantables): + // crops with farmhouses, aquatic crops with aquatic farmhouses, trees and bushes with foresters. + public static bool Shows(string plantableGroup, string planterGroup) => + !string.IsNullOrEmpty(plantableGroup) && string.Equals(plantableGroup, planterGroup, StringComparison.Ordinal); + } +} diff --git a/source/WorkAreaService.cs b/source/WorkAreaService.cs index a1659b0..6b56858 100644 --- a/source/WorkAreaService.cs +++ b/source/WorkAreaService.cs @@ -15,10 +15,14 @@ using Timberborn.Localization; using Timberborn.MapStateSystem; using Timberborn.Navigation; +using Timberborn.Planting; +using Timberborn.PlantingUI; using Timberborn.SceneLoading; using Timberborn.SelectionSystem; using Timberborn.SingletonSystem; +using Timberborn.ToolSystem; using Timberborn.UILayoutSystem; +using Timberborn.WorkSystem; using UnityEngine; using UnityEngine.UIElements; @@ -32,6 +36,7 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto private readonly PinSet _pins = new PinSet(); private readonly PinRefreshPlanner _planner; private readonly List _removed = new List(); + private readonly List _planters = new List(); private readonly float _reach; private readonly INavigationRangeService _navigation; private readonly ConstructionModeService _construction; @@ -40,6 +45,7 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto private readonly ILevelVisibilityService _visibility; private readonly MapSize _mapSize; private readonly ISpecService _specs; + private readonly EntityComponentRegistry _registry; private readonly EventBus _events; private readonly LoadingScreen _loading; private readonly UILayout _layout; @@ -50,18 +56,21 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto private bool _active; private float _nextRefresh; private bool _rendererFailed; + // The resource group of the plant whose planting tool is open, or null. + private string _planting; + private bool _plantersChanged; public event Action Changed; public int Count => _pins.Count; public bool Available => _active && !_rendererFailed; public WorkAreaService(INavigationRangeService navigation, NavigationDistance distance, ConstructionModeService construction, IBlockService blocks, PreviewBlockService previews, ILevelVisibilityService visibility, - MapSize mapSize, ISpecService specs, EventBus events, LoadingScreen loading, + MapSize mapSize, ISpecService specs, EntityComponentRegistry registry, EventBus events, LoadingScreen loading, UILayout layout, InputService input, ILoc loc) { _navigation = navigation; _construction = construction; _blocks = blocks; _previews = previews; _visibility = visibility; _mapSize = mapSize; _specs = specs; - _events = events; _loading = loading; _layout = layout; _input = input; _loc = loc; + _registry = registry; _events = events; _loading = loading; _layout = layout; _input = input; _loc = loc; // BuildingTerrainRange's own margin for deciding whether a navigation change can alter a range. _reach = distance.ResourceBuildings + 2f; _planner = new PinRefreshPlanner( @@ -103,15 +112,18 @@ public void SetPinned(BaseComponent entity, bool value) { if (value) _planner.Add(pin); else _planner.Remove(pin); _nextRefresh = 0; - if (_pins.Count == 0) ReleaseOutline(); + if (_planner.Count == 0) ReleaseOutline(); Notify(); } } + // Clears the player's pins. An open planting tool keeps showing its buildings. public void ClearAll() { + foreach (var pin in _pins.Items) _planner.Remove(pin); _pins.Clear(); - ReleaseOutline(); + _nextRefresh = 0; + if (_planner.Count == 0) ReleaseOutline(); Notify(); } @@ -124,9 +136,11 @@ public bool ProcessInput() public void UpdateSingleton() { - if (!Available || Count == 0) return; + if (!Available) return; try { + if (_plantersChanged) ShowPlanters(); + if (_planner.Count == 0) return; if (_planner.Pending && Time.unscaledTime >= _nextRefresh) { RefreshCells(); @@ -139,23 +153,42 @@ public void UpdateSingleton() // Fail only this cosmetic feature if a later game update changes an internal API. _rendererFailed = true; Debug.LogError("[PersistentWorkAreas] Outline disabled for this map: " + error); - ClearAll(); + Reset(); } } + // The planting tool shows the working areas of the buildings that plant its crop or tree, finished or not. + private void ShowPlanters() + { + _plantersChanged = false; + _planters.Clear(); + if (_planting != null) + foreach (var workplace in _registry.GetAll()) + { + var planter = workplace.GetComponent(); + if (planter != null && PlantingRanges.Shows(_planting, planter.PlantableResourceGroup) && Supports(workplace)) + _planters.Add(workplace.GetComponent()); + } + _planner.Show(_planters); + _planters.Clear(); + _nextRefresh = 0; + if (_planner.Count == 0) ReleaseOutline(); + } + private void RefreshCells() { _removed.Clear(); bool redraw = _planner.Refresh(_removed); - foreach (var entity in _removed) _pins.Set(entity, false); - if (_removed.Count > 0) Notify(); + bool unpinned = false; + foreach (var entity in _removed) unpinned |= _pins.Set(entity, false); + if (unpinned) Notify(); var cells = _planner.Cells; if ((redraw || _outline == null) && cells.Count > 0) { if (_outline == null) _outline = new NativeOutline(_blocks, _previews, _visibility, _mapSize, _specs); _outline.Update(cells); } - if (Count == 0) ReleaseOutline(); + if (_planner.Count == 0) ReleaseOutline(); } private bool Describe(EntityComponent entity, out (Vector3? Center, bool Preview, bool Terrain) key, out CellBox reach) @@ -211,15 +244,37 @@ [OnEvent] public void OnUnselected(SelectableObjectUnselectedEvent e) } [OnEvent] public void OnDeleted(EntityDeletedEvent e) { + // The game has already taken a deleted building out of the entity registry, so the next scan drops it. + if (_planting != null && e.Entity.GetComponent() != null) _plantersChanged = true; var pin = e.Entity.GetComponent(); if (_pins.Set(pin, false)) { _planner.Remove(pin); _nextRefresh = 0; - if (Count == 0) ReleaseOutline(); + if (_planner.Count == 0) ReleaseOutline(); Notify(); } } + // A planter loaded, or placed by another co-op player, while the planting tool is open. + [OnEvent] public void OnInitialized(EntityInitializedEvent e) + { + if (_planting != null && e.Entity.GetComponent() != null) _plantersChanged = true; + } + // ToolService.SwitchTool exits the old tool and enters the new one in the same call, so the buildings are found + // on the next update: switching between crops of the same planters keeps their cached ranges. + [OnEvent] public void OnToolEntered(ToolEnteredEvent e) + { + if (e.Tool is PlantingTool tool) Plant(tool.PlantableSpec?.ResourceGroup); + } + [OnEvent] public void OnToolExited(ToolExitedEvent e) + { + if (e.Tool is PlantingTool) Plant(null); + } + private void Plant(string group) + { + _planting = group; + _plantersChanged = true; + } private void Notify() { @@ -248,6 +303,15 @@ private void ReleaseOutline() catch (Exception error) { Debug.LogError("[PersistentWorkAreas] Renderer cleanup failed: " + error); } _planner.Clear(); } + // Forgets the pins and the planting tool's buildings, and releases the renderer. + private void Reset() + { + _planting = null; + _plantersChanged = false; + _pins.Clear(); + ReleaseOutline(); + Notify(); + } private void OnLoading(object sender, EventArgs e) => Dispose(); public void Dispose() { @@ -256,7 +320,7 @@ public void Dispose() _loading.LoadingScreenEnabled -= OnLoading; _input.RemoveInputProcessor(this); _events.Unregister(this); - ClearAll(); + Reset(); _planner.Select(null); _clearButton?.RemoveFromHierarchy(); _clearButton = null; diff --git a/tests/Checks.csproj b/tests/Checks.csproj index b82c3f7..835233a 100644 --- a/tests/Checks.csproj +++ b/tests/Checks.csproj @@ -1,4 +1,4 @@ net8.0Exeenable - + diff --git a/tests/Program.cs b/tests/Program.cs index 1100867..271bb21 100644 --- a/tests/Program.cs +++ b/tests/Program.cs @@ -1,3 +1,4 @@ +using System.IO.Compression; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; @@ -107,10 +108,50 @@ void QueryFakeRange(FakePin pin, (int X, int Y, int Z, bool Preview) key, HashSe Check(twins.Add(new EqualBuilding()) && twins.Add(new EqualBuilding()) && twins.Count == 2, "Refresh planning keeps equal-valued buildings apart"); planner.Clear(); NavigationChange(CellBox.Point(0, 0, 5)); Check(planner.Count == 0 && planner.Cells.Count == 0 && !planner.Pending, "Clearing forgets every pin and cached range"); +// The planting tool shows the ranges of the buildings that plant the selected crop or tree, alongside the pins. +Check(PlantingRanges.Shows("Farmhouse", "Farmhouse") && PlantingRanges.Shows("Forester", "Forester") && PlantingRanges.Shows("AquaticFarmhouse", "AquaticFarmhouse"), + "The planting tool shows the planter buildings of the plant's resource group"); +Check(!PlantingRanges.Shows("Farmhouse", "Forester") && !PlantingRanges.Shows("Forester", "Farmhouse") && !PlantingRanges.Shows("AquaticFarmhouse", "Farmhouse"), + "Crops never show foresters, trees never show farmhouses, and aquatic crops show only aquatic farmhouses"); +Check(!PlantingRanges.Shows("Farmhouse", null) && !PlantingRanges.Shows(null, null) && !PlantingRanges.Shows("", ""), + "Buildings that plant nothing, and plants without a group, show nothing"); +Check(!PlantingRanges.Shows("farmhouse", "Farmhouse"), "Groups match exactly, as the game compares them"); +var farmA = new FakePin(0, 0, 5); var farmB = new FakePin(100, 0, 5); var grove = new FakePin(0, 100, 5); var kept = new FakePin(200, 0, 5); +planner.Add(kept); Pass(); +planner.Show(new[] { farmA, farmB }); +Check(Pass() == (2, 1) && planner.Cells.Count == 3 * 13 && planner.Cells.Contains((100, 0, 5)) && planner.Cells.Contains((200, 0, 5)), + "Opening the planting tool for a crop: 1 query per farmhouse and 1 rebuild, drawn with the pins"); +planner.Show(new[] { farmB, farmA }); +Check(!planner.Pending && Pass() == (0, 0), "Switching to another crop for the same farmhouses reuses their ranges: 0 queries and 0 rebuilds"); +NavigationChange(CellBox.Point(15, 0, 5)); +Check(Pass() == (1, 0), "A navigation change near one shown farmhouse re-queries only that farmhouse"); +planner.Select(farmB); +Check(Pass() == (0, 1) && !planner.Cells.Contains((100, 0, 5)), "A shown building that is selected is left to the game's own outline"); +planner.Select(null); Pass(); +planner.InvalidateAll(); +Check(Pass() == (3, 1), "Construction-mode toggle re-queries pins and shown buildings alike"); +planner.Show(new[] { grove }); +Check(Pass() == (1, 1) && planner.Count == 2 && planner.Cells.Contains((0, 100, 5)) && !planner.Cells.Contains((0, 0, 5)), + "Switching to a tree: the forester is queried and the farmhouses are dropped with their ranges"); +planner.Show(Array.Empty()); +Check(Pass() == (0, 1) && planner.Count == 1 && planner.Cells.Count == 13 && planner.Cells.Contains((200, 0, 5)), + "Closing the planting tool: 0 queries and 1 rebuild back to the pinned outline"); +planner.Show(new FakePin[] { null }); +Check(!planner.Pending && Pass() == (0, 0) && planner.Count == 1, "Closing it again does no work"); +planner.Show(new[] { kept, farmA }); +Check(Pass() == (1, 1), "A pinned building the tool also shows keeps its cached range: only the other farmhouse is queried"); +Check(planner.Remove(kept) && !planner.Remove(kept) && Pass() == (0, 0) && planner.Cells.Contains((200, 0, 5)), + "Unpinning a building the tool shows keeps its range drawn while the tool is open"); +Check(planner.Add(farmA) && !planner.Add(farmA) && Pass() == (0, 0), "Pinning a building the tool shows reuses its range"); +planner.Show(Array.Empty()); +Check(Pass() == (0, 1) && planner.Count == 1 && planner.Cells.Contains((0, 0, 5)) && !planner.Cells.Contains((200, 0, 5)), + "Closing the tool keeps the ranges that are pinned and drops the rest"); +planner.Clear(); + // The checks above use only the mod's game-free sources, so CI runs them without arguments on a machine without // Timberborn. The rest need the installed game, the built mod DLL and its package folder. Add checks that need no game // files above this block, or CI never runs them: the count guard at the end cannot tell where a check was placed. -const int GameChecks = 42; // A full run fails if this stops matching the checks below. +const int GameChecks = 56; // A full run fails if this stops matching the checks below. int gameFreeChecks = checks; if (args.Length == 0) { @@ -218,6 +259,89 @@ object Update(int x, int y, int z) => navMeshUpdate.Invoke(navMeshUpdate.GetPara Set(livePlanner, "_selected", livePin); Check(Handle("OnUnselected", null) == (true, false, false, true) && Get(livePlanner, "_selected") == null, "Deselecting a pinned building rebuilds the pinned outline from the cache"); + +// Planting tool events, with the game's own tool types. The handlers only record the plant's group; the next update finds the buildings. +var plantableSpec = GameType("Timberborn.Planting", "Timberborn.Planting.PlantableSpec"); +var plantingTool = GameType("Timberborn.PlantingUI", "Timberborn.PlantingUI.PlantingTool"); +object Planting(string group) +{ + var spec = RuntimeHelpers.GetUninitializedObject(plantableSpec); + Set(spec, "k__BackingField", group); + var tool = RuntimeHelpers.GetUninitializedObject(plantingTool); + Set(tool, "k__BackingField", spec); + return tool; +} +var cancelPlanting = RuntimeHelpers.GetUninitializedObject(GameType("Timberborn.PlantingUI", "Timberborn.PlantingUI.CancelPlantingTool")); +var toolEntered = GameType("Timberborn.ToolSystem", "Timberborn.ToolSystem.ToolEnteredEvent"); +var toolExited = GameType("Timberborn.ToolSystem", "Timberborn.ToolSystem.ToolExitedEvent"); +// What a tool switch leaves behind: the plant group shown, and whether the next update scans for its buildings. +// ToolService.SwitchTool posts the old tool's exit and then the new tool's entry within one call. +(string Group, bool Scan) Switch(object from, object to) +{ + Set(live, "_plantersChanged", false); + if (from != null) service.GetMethod("OnToolExited")!.Invoke(live, new[] { Activator.CreateInstance(toolExited, from) }); + service.GetMethod("OnToolEntered")!.Invoke(live, new[] { Activator.CreateInstance(toolEntered, to, false) }); + return (Get(live, "_planting"), Get(live, "_plantersChanged")); +} +var crops = Planting("Farmhouse"); var trees = Planting("Forester"); +Check(Switch(null, crops) == ("Farmhouse", true), "Opening a crop's planting tool shows the farmhouses from the next update"); +Check(Switch(crops, trees) == ("Forester", true), "Switching from a crop to a tree shows the foresters instead"); +Check(Switch(trees, cancelPlanting) == (null, true), "Leaving the planting tools, even for the cancel-planting tool beside them, hides the planters"); +Check(Switch(null, cancelPlanting) == (null, false), "Other tools show no planter ranges and cause no scan"); +Check(GameType("Timberborn.WorkSystem", "Timberborn.WorkSystem.Workplace").GetInterfaces().Any(x => x.FullName == "Timberborn.EntitySystem.IRegisteredComponent"), + "Workplaces are registered components, so the entity registry lists every planter building"); + +// The service's Clear and scan with the planting tool's buildings, on the same instance: one building only the tool shows, one only pinned. +var entityComponent = GameType("Timberborn.EntitySystem", "Timberborn.EntitySystem.EntityComponent"); +var shownOnly = RuntimeHelpers.GetUninitializedObject(entityComponent); +var pinnedOnly = RuntimeHelpers.GetUninitializedObject(entityComponent); +var liveEntries = Get(livePlanner, "_entries"); +var livePins = Get(live, "_pins"); +livePlanner.GetType().GetMethod("Clear")!.Invoke(livePlanner, null); +var shownSet = Array.CreateInstance(entityComponent, 1); +shownSet.SetValue(shownOnly, 0); +livePlanner.GetType().GetMethod("Show")!.Invoke(livePlanner, new object[] { shownSet }); +livePlanner.GetType().GetMethod("Add")!.Invoke(livePlanner, new[] { pinnedOnly }); +livePins.GetType().GetMethod("Set")!.Invoke(livePins, new object[] { pinnedOnly, true }); +service.GetMethod("ClearAll")!.Invoke(live, null); +Check(liveEntries.Count == 1 && liveEntries.Contains(shownOnly) && (int)service.GetProperty("Count")!.GetValue(live)! == 0, + "Clear pinned areas removes the pins and keeps drawing the planting tool's buildings"); +// UpdateSingleton reads Time.unscaledTime, which only runs in the game, so the scan it starts with is invoked directly. +Set(live, "_planting", null!); +Set(live, "_plantersChanged", true); +service.GetMethod("ShowPlanters", fields)!.Invoke(live, null); +Check(liveEntries.Count == 0 && !Get(live, "_plantersChanged"), "Leaving the planting tool with no pins drops its buildings at the next update"); + +// The planting tool's rule on the game's own blueprints: crops show farmhouses, trees and bushes show foresters. +var plantables = new List<(string Name, string Group, bool Crop, bool Tree)>(); +var planters = new List<(string Name, string Group, bool FarmHouse, bool Forester, bool Outlined)>(); +using (var blueprints = ZipFile.OpenRead(Path.Combine(game, "Timberborn_Data", "StreamingAssets", "Modding", "Blueprints.zip"))) + foreach (var entry in blueprints.Entries.Where(x => x.FullName.EndsWith(".blueprint.json", StringComparison.OrdinalIgnoreCase))) + { + using var stream = entry.Open(); + using var blueprint = JsonDocument.Parse(stream, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }); + var root = blueprint.RootElement; + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("TemplateSpec", out var template)) continue; + var name = template.GetProperty("TemplateName").GetString()!; + bool Has(string spec) => root.TryGetProperty(spec, out _); + if (root.TryGetProperty("PlantableSpec", out var plantable)) + plantables.Add((name, plantable.GetProperty("ResourceGroup").GetString()!, Has("CropSpec"), Has("TreeComponentSpec") || Has("BushSpec"))); + if (root.TryGetProperty("PlanterBuildingSpec", out var planter)) + planters.Add((name, planter.GetProperty("PlantableResourceGroup").GetString()!, Has("FarmHouseSpec"), Has("ForesterSpec"), + Has("WorkplaceSpec") && Has("BuildingAccessibleSpec"))); + } +string[] ShownFor(string plant) => planters.Where(p => PlantingRanges.Shows(plantables.Single(x => x.Name == plant).Group, p.Group)) + .Select(p => p.Name).OrderBy(x => x, StringComparer.Ordinal).ToArray(); +Check(planters.Count >= 4 && planters.All(p => p.Outlined), + "Every planter building is a workplace with an access point, so the planting tool finds and outlines it"); +Check(plantables.Count >= 20 && plantables.All(x => x.Crop != x.Tree && ShownFor(x.Name).Length > 0), "Every plantable in the game shows at least one planter building"); +Check(plantables.All(x => ShownFor(x.Name).All(n => x.Crop ? planters.Single(p => p.Name == n).FarmHouse : planters.Single(p => p.Name == n).Forester)), + "Crops show only farmhouses; trees and bushes show only foresters"); +Check(ShownFor("Carrot").SequenceEqual(new[] { "EfficientFarmHouse.Folktails", "FarmHouse.IronTeeth" }) && + ShownFor("Cattail").SequenceEqual(new[] { "AquaticFarmhouse.Folktails" }) && + ShownFor("Pine").SequenceEqual(new[] { "Forester.Folktails", "Forester.IronTeeth" }) && + ShownFor("BlueberryBush").SequenceEqual(new[] { "Forester.Folktails", "Forester.IronTeeth" }), + "Carrots show both factions' farmhouses, cattails only the aquatic farmhouse, pines and blueberries only foresters"); var interfaces = service.GetInterfaces().Select(x => x.FullName).ToArray(); Check(interfaces.Contains("Timberborn.SingletonSystem.IPostLoadableSingleton"), "Game post-load lifecycle"); Check(interfaces.Contains("Timberborn.SingletonSystem.IUpdatableSingleton"), "Display refresh lifecycle"); @@ -227,7 +351,7 @@ object Update(int x, int y, int z) => navMeshUpdate.Invoke(navMeshUpdate.GetPara Check(mod.GetTypes().All(t => !t.GetCustomAttributesData().Any(a => a.AttributeType.Name.StartsWith("HarmonyPatch"))), "No method patches"); var fragment = mod.GetType("PersistentWorkAreas.WorkAreaFragment", true)!; Check(fragment.GetInterfaces().Any(x => x.FullName == "Timberborn.EntityPanelSystem.IEntityPanelFragment"), "Building checkbox fragment contract"); -foreach (var method in new[] { "OnVisibleLevel", "OnConstruction", "OnSelected", "OnUnselected", "OnDeleted" }) +foreach (var method in new[] { "OnVisibleLevel", "OnConstruction", "OnSelected", "OnUnselected", "OnDeleted", "OnInitialized", "OnToolEntered", "OnToolExited" }) Check(service.GetMethod(method)!.GetCustomAttributesData().Any(x => x.AttributeType.Name == "OnEventAttribute"), method + " event subscription"); var packaging = Path.GetFullPath(args[2]);