Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
7 changes: 4 additions & 3 deletions VALIDATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
50 changes: 46 additions & 4 deletions source/PinRefreshPlanner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TPin, TKey, TCell> where TPin : class
{
// Returns false when the pin can no longer be shown. The key holds everything the query depends on
Expand All @@ -42,6 +43,8 @@ internal sealed class PinRefreshPlanner<TPin, TKey, TCell> where TPin : class

private sealed class Entry
{
public bool Pinned;
public bool Shown;
public bool Described;
public TKey Key;
public bool Stale = true;
Expand All @@ -59,6 +62,7 @@ private sealed class Entry
private HashSet<TCell> _cells = new HashSet<TCell>();
private HashSet<TCell> _next = new HashSet<TCell>();
private HashSet<TCell> _queried = new HashSet<TCell>();
private readonly List<TPin> _hidden = new List<TPin>();
private TPin _selected;
private bool _pending;
private bool _union;
Expand All @@ -69,26 +73,58 @@ public PinRefreshPlanner(DescribePin describe, QueryRange query, Func<TCell, Cel
_describe = describe; _query = query; _cellBox = cellBox;
}

// Buildings drawn: pinned, shown by the planting tool, or both.
public int Count => _entries.Count;
public bool Pending => _pending;
// The combined range of every pin except the selected one, which the game outlines itself.
public IReadOnlyCollection<TCell> Cells => _cells;

public bool Add(TPin pin)
{
if (pin == null || _entries.ContainsKey(pin)) return false;
_entries.Add(pin, new Entry());
if (pin == null) return false;
if (_entries.TryGetValue(pin, out var entry))
{
// Already drawn for the planting tool, so its cached range stays in use.
if (entry.Pinned) return false;
entry.Pinned = true;
return true;
}
_entries.Add(pin, new Entry { Pinned = true });
_pending = true;
return true;
}

public bool Remove(TPin pin)
{
if (pin == null || !_entries.Remove(pin)) return false;
_pending = _union = true;
if (pin == null || !_entries.TryGetValue(pin, out var entry) || !entry.Pinned) return false;
entry.Pinned = false;
if (!entry.Shown) Drop(pin);
return true;
}

// The buildings the planting tool shows, replacing the previous set. A building leaving the set keeps its
// range only while it is pinned; one joining it reuses a pin's cached range, so switching between crops
// of the same planters costs nothing.
public void Show(IEnumerable<TPin> 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();
Expand Down Expand Up @@ -181,6 +217,12 @@ public bool Refresh(List<TPin> 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<TBounds>(CellBox box, TBounds bounds, Func<CellBox, TBounds, bool> intersects) =>
!box.IsEmpty && (box.IsUnbounded || intersects(box, bounds));
}
Expand Down
13 changes: 13 additions & 0 deletions source/PlantingRanges.cs
Original file line number Diff line number Diff line change
@@ -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);
}
}
86 changes: 75 additions & 11 deletions source/WorkAreaService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -32,6 +36,7 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto
private readonly PinSet<EntityComponent> _pins = new PinSet<EntityComponent>();
private readonly PinRefreshPlanner<EntityComponent, (Vector3? Center, bool Preview, bool Terrain), Vector3Int> _planner;
private readonly List<EntityComponent> _removed = new List<EntityComponent>();
private readonly List<EntityComponent> _planters = new List<EntityComponent>();
private readonly float _reach;
private readonly INavigationRangeService _navigation;
private readonly ConstructionModeService _construction;
Expand All @@ -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;
Expand All @@ -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<EntityComponent, (Vector3? Center, bool Preview, bool Terrain), Vector3Int>(
Expand Down Expand Up @@ -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();
}

Expand All @@ -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();
Expand All @@ -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<Workplace>())
{
var planter = workplace.GetComponent<PlanterBuildingSpec>();
if (planter != null && PlantingRanges.Shows(_planting, planter.PlantableResourceGroup) && Supports(workplace))
_planters.Add(workplace.GetComponent<EntityComponent>());
}
_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)
Expand Down Expand Up @@ -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<PlanterBuildingSpec>() != null) _plantersChanged = true;
var pin = e.Entity.GetComponent<EntityComponent>();
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<PlanterBuildingSpec>() != 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()
{
Expand Down Expand Up @@ -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()
{
Expand All @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion tests/Checks.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><TargetFramework>net8.0</TargetFramework><OutputType>Exe</OutputType><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><Compile Include="../source/PinSet.cs" Link="PinSet.cs" /><Compile Include="../source/PinRefreshPlanner.cs" Link="PinRefreshPlanner.cs" /></ItemGroup>
<ItemGroup><Compile Include="../source/PinSet.cs" Link="PinSet.cs" /><Compile Include="../source/PinRefreshPlanner.cs" Link="PinRefreshPlanner.cs" /><Compile Include="../source/PlantingRanges.cs" Link="PlantingRanges.cs" /></ItemGroup>
</Project>
Loading
Loading