diff --git a/README.md b/README.md index 4ba5a1c..23849fc 100644 --- a/README.md +++ b/README.md @@ -36,13 +36,13 @@ No extra dependency is required. Keep your existing BeaverBuddies Stability Fork - 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. -The currently selected building still uses its normal game outline. Clearing pins restores normal selection behavior; deselecting that building then hides its normal outline. Pins reset on map exit, loading, and multiplayer resynchronization. They are not saved. Deleting a pinned building removes its pin. +The currently selected building still uses its normal game outline. Clearing pins restores normal selection behavior; deselecting that building then hides its normal outline. Pins are remembered for each settlement on your own computer, in `PersistentWorkAreas\Pins.txt` next to your Timberborn `Saves` folder (on Windows, `Documents\Timberborn\PersistentWorkAreas\Pins.txt`), and come back when you load any save of that settlement, as the latest pins you set there. A different settlement starts with none. They are never written into the save, so co-op players each keep their own. A co-op guest's game names the settlement after the host's save, which changes with every resynchronization, so a guest's pins usually do not come back. The file keeps the 100 settlements you loaded or changed most recently. To forget every pin, delete that file. Deleting a pinned building removes its pin. The mod supports navigation-based working areas. It does not pin district road coloring, every kind of effect-radius overlay, or building-placement ghosts. UI text is currently English. The panel, button and key-binding text is all in `version-1.1/Localizations/enUS_PersistentWorkAreas.csv` (in the repository, under `packaging/PersistentWorkAreas/`), so a translation is one more file in that folder with the same keys, named for the game's language code (for example `deDE_PersistentWorkAreas.csv`). Keep `{0}` in the clear-button text: it becomes the pin count. ## Compatibility and validation -Designed for compatibility with the **BeaverBuddies Stability Fork**. The mod does not patch game methods, change simulation or building data, send multiplayer events, or modify saves. It uses the same navigation queries as the game's selected-building visualizer and a separate instance of its outline renderer. +Designed for compatibility with the **BeaverBuddies Stability Fork**. The mod does not patch game methods, change simulation or building data, send multiplayer events, or modify saves; the pins live in their own small local file. It uses the same navigation queries as the game's selected-building visualizer and a separate instance of its outline renderer. The release build passes 38 automated lifecycle/API checks. The mod has been tested in game on Timberborn 1.1.2.4, both single-player and in a two-player BeaverBuddies Stability Fork session with the mod installed on both computers. See `VALIDATION.md` for what was checked and how. diff --git a/VALIDATION.md b/VALIDATION.md index 39ff593..09adea3 100644 --- a/VALIDATION.md +++ b/VALIDATION.md @@ -12,7 +12,7 @@ - 38 checks passed: reference-identity pins, duplicate pin/unpin, independent pins, replacement/deletion behavior, global clear, new-map isolation, native renderer constructors/methods/cleanup fields, delegate binding to internal renderer methods, lifecycle/navigation/event interfaces, no simulation persistence interfaces, no Harmony/BeaverBuddies dependencies, package/key-binding consistency, manifest/assembly version agreement, and presence of the Builder's Hut marker component used to exclude it from pinning. - Compared the display path with the installed game's `BuildingRangeDrawer`, `BoundsNavRangeDrawer`, and navigation query calls. The mod uses those same range queries and its own outline-renderer instance. - Reviewed the BeaverBuddies Stability Fork's `IO/BuildCompatibility.cs`: its handshake identifies Timberborn and the BeaverBuddies/TimberNet binaries. This mod changes none of them. -- The display service only implements frame-update, input, load, and navigation-notification interfaces. Pin state is per game-scoped service instance. There are no Harmony patches, replay events, simulation ticks, random calls, or save writes. +- The display service only implements frame-update, input, load, and navigation-notification interfaces. Pin state is per game-scoped service instance. Each settlement's pins are also kept, by entity id, in a local text file next to the `Saves` folder (`Documents\Timberborn\PersistentWorkAreas\Pins.txt` on Windows). It is read once after the map loads, and rewritten from the frame update after the pins change, and once after a load that finds the settlement below the top of the file, to keep it among the 100 most recent. A failed write is retried every 10 seconds and again on leaving the map, which never erases the file. A file this version cannot read is kept as `Pins.txt.bak` before it is replaced. There are no Harmony patches, replay events, simulation ticks, random calls, or save writes. - Renderer geometry refreshes on pin, selection, construction-mode, height-visibility and navigation changes, with navigation refreshes capped at five per second. Empty pin sets do no range queries or drawing. All pins share a combined mesh. Clearing releases the renderer's owned meshes and cloned materials. ## Not established by the automated checks @@ -28,9 +28,11 @@ Re-run this for each release and after each Timberborn update. 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 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. +6. Delete a pinned building. Its outline and pin count should disappear. Load a different settlement: it should start with no pins. 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. +9. Pin two buildings, save, exit to the main menu and load that save: both outlines should come back and the button should read **Clear pinned areas (2)**. Unpin one, save, exit and load again: only the other should come back. Load an older save of the same settlement: the remembered buildings that exist in it should be pinned, with no error in the log. In co-op, pin different buildings on each computer and perform a resync: the host's pins should come back and the guest's should be empty. +10. While still in the map, pin a building: within a second its settlement's line in `Documents\Timberborn\PersistentWorkAreas\Pins.txt` should list one more id. Press **Clear pinned areas**: the line should disappear. Pin a building that is already in your latest save, exit to the desktop without saving, relaunch and load that save: the pin should come back. Load an older save that lacks one of the pinned buildings, then load the newest save again: every pin should come back. `Pins.txt.tmp` should never be left behind. ## References diff --git a/source/PinSet.cs b/source/PinSet.cs index 9ddc4f3..0ecbaa5 100644 --- a/source/PinSet.cs +++ b/source/PinSet.cs @@ -15,16 +15,21 @@ private sealed class IdentityComparer : IEqualityComparer private readonly HashSet _items = new HashSet(Identity); public int Count => _items.Count; public IEnumerable Items => _items; + // Set by every pin, unpin or clear that changes the set, so the pin file is written only after a change. + public bool Changed { get; set; } public bool Contains(T item) => item != null && _items.Contains(item); public bool Set(T item, bool pinned) { if (item == null) return false; - return pinned ? _items.Add(item) : _items.Remove(item); + bool changed = pinned ? _items.Add(item) : _items.Remove(item); + Changed |= changed; + return changed; } public bool Clear() { if (_items.Count == 0) return false; _items.Clear(); + Changed = true; return true; } } diff --git a/source/PinStore.cs b/source/PinStore.cs new file mode 100644 index 0000000..84e7762 --- /dev/null +++ b/source/PinStore.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace PersistentWorkAreas +{ + // Each settlement's pins, remembered in a local text file and never in the save, so co-op players keep their own + // and a resync or join never carries them. A building is identified by its entity id, which the save keeps, so a pin + // finds the same building after a load. Unity-free so the checks can run it. + internal static class PinStore + { + // A later format should keep this header and add only fields that this version skips (anything that is not an + // entity id), so that going back to an older build still reads it. This version does not read a file with any + // other header, and PinFile keeps a copy of such a file before replacing it. + public const string Header = "Persistent Work Areas pins v1"; + // Only the most recently loaded or changed settlements are kept. A co-op guest's settlement is named after the + // host's map, which changes on every join or resync, so the file would otherwise grow with every session. + public const int MaxSettlements = 100; + + // The entity ids remembered for a settlement. A missing, corrupt or unrecognized file remembers none. + public static List Read(string text, string settlement) + { + foreach (var entry in Parse(text)) + if (entry.Settlement == settlement) return entry.Pins; + return new List(); + } + + // The file text with the settlement's pins replaced and listed first. A settlement without pins is removed. + public static string Write(string text, string settlement, IEnumerable pins) + { + if (string.IsNullOrEmpty(settlement)) throw new ArgumentException("A settlement name is required.", nameof(settlement)); + var entries = Parse(text); + entries.RemoveAll(entry => entry.Settlement == settlement); + var ids = pins.Where(id => id != Guid.Empty).Select(id => id.ToString("D")).Distinct() + .OrderBy(id => id, StringComparer.Ordinal).ToList(); + var output = new StringBuilder(Header).Append('\n'); + if (ids.Count > 0) output.Append(Escape(settlement)).Append('\t').Append(string.Join("\t", ids)).Append('\n'); + foreach (var entry in entries.Take(ids.Count > 0 ? MaxSettlements - 1 : MaxSettlements)) + { + output.Append(Escape(entry.Settlement)); + foreach (var id in entry.Pins) output.Append('\t').Append(id.ToString("D")); + output.Append('\n'); + } + return output.ToString(); + } + + // The file text with the settlement's entry moved first and its pins unchanged, so that loading a settlement keeps + // it among the most recent. Null when there is nothing to move: it has no entry, or its entry is already first. + public static string Touch(string text, string settlement) + { + var entries = Parse(text); + int index = entries.FindIndex(entry => entry.Settlement == settlement); + return index > 0 ? Write(text, settlement, entries[index].Pins) : null; + } + + // Whether this version can read the file: there is none yet, or it starts with this version's header. + public static bool Recognizes(string text) => string.IsNullOrEmpty(text) || text.Split('\n')[0].TrimEnd('\r') == Header; + + // The buildings to pin again: every remembered id that still names a building which can be pinned, once each. + public static List Restore(IEnumerable ids, Func resolve, Func supports) where T : class + { + var restored = new List(); + var seen = new HashSet(PinSet.Identity); + foreach (var id in ids) + { + var pin = resolve(id); + if (pin != null && supports(pin) && seen.Add(pin)) restored.Add(pin); + } + return restored; + } + + // One line per settlement: its escaped name, then its pinned entity ids, separated by tabs. + // Damaged lines and ids are skipped; the first line for a name wins. + private static List<(string Settlement, List Pins)> Parse(string text) + { + var entries = new List<(string Settlement, List Pins)>(); + if (string.IsNullOrEmpty(text)) return entries; + var lines = text.Split('\n'); + if (!Recognizes(text)) return entries; + for (int i = 1; i < lines.Length; i++) + { + var fields = lines[i].TrimEnd('\r').Split('\t'); + if (!Unescape(fields[0], out var settlement) || settlement.Length == 0 || entries.Any(entry => entry.Settlement == settlement)) continue; + var pins = new List(); + for (int j = 1; j < fields.Length; j++) + if (Guid.TryParseExact(fields[j], "D", out var id) && id != Guid.Empty && !pins.Contains(id)) pins.Add(id); + if (pins.Count > 0) entries.Add((settlement, pins)); + } + return entries; + } + + private static string Escape(string name) => + name.Replace("\\", "\\\\").Replace("\t", "\\t").Replace("\n", "\\n").Replace("\r", "\\r"); + + private static bool Unescape(string field, out string name) + { + name = null; + var result = new StringBuilder(field.Length); + for (int i = 0; i < field.Length; i++) + { + char c = field[i]; + if (c != '\\') { result.Append(c); continue; } + if (++i == field.Length) return false; + switch (field[i]) + { + case '\\': result.Append('\\'); break; + case 't': result.Append('\t'); break; + case 'n': result.Append('\n'); break; + case 'r': result.Append('\r'); break; + default: return false; + } + } + name = result.ToString(); + return true; + } + } + + // The pin file on disk. Every call reads or rewrites the whole file, which stays small. + internal sealed class PinFile + { + public PinFile(string filePath) { FilePath = filePath; } + public string FilePath { get; } + + public List Load(string settlement) => PinStore.Read(ReadText(), settlement); + + public void Save(string settlement, IEnumerable pins) + { + var existing = ReadText(); + Replace(existing, PinStore.Write(existing, settlement, pins)); + } + + // Moves the settlement's entry first, so that loading the settlement counts as using it. Writes nothing when + // there is nothing to move. + public void Touch(string settlement) + { + var existing = ReadText(); + var text = PinStore.Touch(existing, settlement); + if (text != null) Replace(existing, text); + } + + private string ReadText() => File.Exists(FilePath) ? File.ReadAllText(FilePath) : null; + + private void Replace(string existing, string text) + { + var folder = Path.GetDirectoryName(FilePath); + if (!string.IsNullOrEmpty(folder)) Directory.CreateDirectory(folder); + // A file this version cannot read, such as one from a newer version, is kept beside it instead of being lost. + if (!PinStore.Recognizes(existing)) File.Copy(FilePath, FilePath + ".bak", true); + // Written beside the file and swapped in, so an interrupted write never leaves half a file. + var temporary = FilePath + ".tmp"; + File.WriteAllText(temporary, text); + if (File.Exists(FilePath)) File.Replace(temporary, FilePath, null); + else File.Move(temporary, FilePath); + } + } +} diff --git a/source/WorkAreaService.cs b/source/WorkAreaService.cs index 6b56858..f2a1333 100644 --- a/source/WorkAreaService.cs +++ b/source/WorkAreaService.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.IO; +using System.Linq; using Timberborn.BaseComponentSystem; using Timberborn.BlockSystem; using Timberborn.BlueprintSystem; @@ -17,8 +19,10 @@ using Timberborn.Navigation; using Timberborn.Planting; using Timberborn.PlantingUI; +using Timberborn.PlatformUtilities; using Timberborn.SceneLoading; using Timberborn.SelectionSystem; +using Timberborn.SettlementNameSystem; using Timberborn.SingletonSystem; using Timberborn.ToolSystem; using Timberborn.UILayoutSystem; @@ -46,6 +50,8 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto private readonly MapSize _mapSize; private readonly ISpecService _specs; private readonly EntityComponentRegistry _registry; + private readonly EntityRegistry _entities; + private readonly SettlementReferenceService _settlements; private readonly EventBus _events; private readonly LoadingScreen _loading; private readonly UILayout _layout; @@ -59,6 +65,12 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto // The resource group of the plant whose planting tool is open, or null. private string _planting; private bool _plantersChanged; + private PinFile _pinFile; + // Set at load, so the first update marks this settlement as recently used in the pin file. + private bool _touchPinFile; + // After a failed write the next attempt waits, and only the first failure is logged. + private float _nextSave; + private bool _saveWarned; public event Action Changed; public int Count => _pins.Count; public bool Available => _active && !_rendererFailed; @@ -66,11 +78,12 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto public WorkAreaService(INavigationRangeService navigation, NavigationDistance distance, ConstructionModeService construction, IBlockService blocks, PreviewBlockService previews, ILevelVisibilityService visibility, MapSize mapSize, ISpecService specs, EntityComponentRegistry registry, EventBus events, LoadingScreen loading, - UILayout layout, InputService input, ILoc loc) + UILayout layout, InputService input, ILoc loc, EntityRegistry entities, SettlementReferenceService settlements) { _navigation = navigation; _construction = construction; _blocks = blocks; _previews = previews; _visibility = visibility; _mapSize = mapSize; _specs = specs; _registry = registry; _events = events; _loading = loading; _layout = layout; _input = input; _loc = loc; + _entities = entities; _settlements = settlements; // BuildingTerrainRange's own margin for deciding whether a navigation change can alter a range. _reach = distance.ResourceBuildings + 2f; _planner = new PinRefreshPlanner( @@ -89,6 +102,8 @@ public void PostLoad() _clearButton.tooltip = _loc.T(LocKeys.ClearAllTooltip); _clearButton.style.marginTop = 6; _layout.AddTopRight(_clearButton, 1000); + _pinFile = new PinFile(Path.Combine(UserDataFolder.Folder, "PersistentWorkAreas", "Pins.txt")); + RestorePins(Supports); Notify(); } @@ -134,17 +149,21 @@ public bool ProcessInput() return true; } - public void UpdateSingleton() + public void UpdateSingleton() => UpdateAt(Time.unscaledTime); + + // The frame update, given the clock, so the checks can run it outside the game. + private void UpdateAt(float now) { if (!Available) return; try { + if (now >= _nextSave && !SavePins()) _nextSave = now + 10f; if (_plantersChanged) ShowPlanters(); if (_planner.Count == 0) return; - if (_planner.Pending && Time.unscaledTime >= _nextRefresh) + if (_planner.Pending && now >= _nextRefresh) { RefreshCells(); - _nextRefresh = Time.unscaledTime + .2f; + _nextRefresh = now + .2f; } if (_planner.Cells.Count > 0) _outline?.Draw(); } @@ -276,6 +295,52 @@ private void Plant(string group) _plantersChanged = true; } + // Pins come back from the pin file, never from the save, so each co-op player gets back only their own. + // PostLoad passes Supports; the checks pass their own test, because Supports needs live game objects. + private void RestorePins(Func supports) + { + var settlement = _settlements.SettlementReference?.SettlementName; + if (settlement == null) return; + try + { + foreach (var pin in PinStore.Restore(_pinFile.Load(settlement), _entities.GetEntity, supports)) + if (_pins.Set(pin, true)) _planner.Add(pin); + _touchPinFile = true; + } + catch (Exception error) + { + Debug.LogWarning("[PersistentWorkAreas] Pinned areas not restored from " + _pinFile.FilePath + ": " + error.Message); + } + // Restoring is not a change: the file keeps remembered buildings this save lacks, for when a newer save loads. + _pins.Changed = false; + } + + // Writes the pins after they change, or marks the loaded settlement as recently used. A new game's settlement + // has no name until the player gives one, so its pins wait until then. Leaving the map, loading or a renderer + // failure forgets pins in memory only. False when the write failed; the change stays pending for a retry. + private bool SavePins() + { + if ((!_pins.Changed && !_touchPinFile) || _pinFile == null) return true; + var settlement = _settlements.SettlementReference?.SettlementName; + if (settlement == null) return true; + try + { + if (_pins.Changed) _pinFile.Save(settlement, _pins.Items.Select(pin => pin.EntityId)); + else _pinFile.Touch(settlement); + _pins.Changed = false; + _touchPinFile = false; + return true; + } + catch (Exception error) + { + // Moving the settlement's entry first is only a courtesy, so it is not retried. + _touchPinFile = false; + if (!_saveWarned) Debug.LogWarning("[PersistentWorkAreas] Pinned areas not saved to " + _pinFile.FilePath + ": " + error.Message); + _saveWarned = true; + return false; + } + } + private void Notify() { if (_clearButton != null) @@ -303,12 +368,14 @@ 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. + // Saves a pending pin change, then forgets the pins and the planting tool's buildings, and releases the renderer. private void Reset() { + SavePins(); _planting = null; _plantersChanged = false; _pins.Clear(); + _pins.Changed = false; ReleaseOutline(); Notify(); } diff --git a/tests/Checks.csproj b/tests/Checks.csproj index 835233a..1cdd42a 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 271bb21..79179aa 100644 --- a/tests/Program.cs +++ b/tests/Program.cs @@ -31,6 +31,15 @@ void Check(bool ok, string name) pins.Set(forester, true); Check(pins.Set(forester, false) && pins.Count == 0, "Deleting last pinned building empties collection"); Check(new PinSet().Count == 0, "New map begins without pins"); +var tracked = new PinSet(); +Check(!tracked.Changed && tracked.Set(farm, true) && tracked.Changed, "Pinning marks the pins for saving"); +tracked.Changed = false; +Check(!tracked.Set(farm, true) && !tracked.Set(forester, false) && !tracked.Set(null, true) && !tracked.Changed, "A pin or unpin that changes nothing needs no save"); +Check(tracked.Set(farm, false) && tracked.Changed, "Unpinning marks the pins for saving"); +tracked.Set(farm, true); tracked.Changed = false; +Check(tracked.Clear() && tracked.Changed, "Clearing marks the pins for saving"); +tracked.Changed = false; +Check(!tracked.Clear() && !tracked.Changed, "Clearing no pins needs no save"); // Refresh planning, against a fake navigation world that counts range queries and outline rebuilds. var around = CellBox.Around(10.5f, 20.5f, 3f, 22f); @@ -148,10 +157,101 @@ void QueryFakeRange(FakePin pin, (int X, int Y, int Z, bool Preview) key, HashSe "Closing the tool keeps the ranges that are pinned and drops the rest"); planner.Clear(); +// Pins are remembered per settlement in a local file, by the entity id the save keeps for each building, never in the save. +var idA = new Guid("18c0e8f4-5b0e-4d7a-9a52-0c7c1d3b9e01"); +var idB = new Guid("6d2f9a31-0e47-4b8c-8f1d-5a9e7c3b2d44"); +var idC = new Guid("c4a7e2d9-3f61-4e0b-b8a5-9d2c6f1e7a53"); +var remembered = PinStore.Write(null, "Beaverton", new[] { idB, idA, idB, Guid.Empty }); +Check(PinStore.Read(remembered, "Beaverton").SequenceEqual(new[] { idA, idB }) && remembered.Split(idB.ToString("D")).Length == 2 && !remembered.Contains(Guid.Empty.ToString("D")), + "Pins round-trip through the pin file as entity ids, written once each"); +Check(PinStore.Read(remembered, "Otter Bay").Count == 0 && PinStore.Read(remembered, "beaverton").Count == 0 && PinStore.Read(remembered, "Beaverton ").Count == 0, + "A different settlement shows none: the settlement name must match exactly"); +remembered = PinStore.Write(remembered, "Otter Bay", new[] { idC }); +Check(PinStore.Read(remembered, "Beaverton").SequenceEqual(new[] { idA, idB }) && PinStore.Read(remembered, "Otter Bay").SequenceEqual(new[] { idC }), + "Saving one settlement's pins keeps every other settlement's"); +var forgotten = PinStore.Write(remembered, "Beaverton", Array.Empty()); +Check(PinStore.Read(forgotten, "Beaverton").Count == 0 && !forgotten.Contains("Beaverton") && PinStore.Read(forgotten, "Otter Bay").SequenceEqual(new[] { idC }), + "Clearing a settlement's pins removes its entry and keeps the others"); +Check(PinStore.Read(null, "Beaverton").Count == 0 && PinStore.Read("", "Beaverton").Count == 0, "A missing or empty pin file remembers no pins"); +Check(PinStore.Read("PK\u0003\u0004\uFFFD\u0000 not a pin file\n" + remembered, "Beaverton").Count == 0 && + PinStore.Read(remembered.Replace(PinStore.Header, PinStore.Header + "0"), "Beaverton").Count == 0, + "A corrupt pin file, or one in another format, remembers no pins"); +var damaged = remembered.Replace(idA.ToString("D"), "18c0e8f4-5b0e") + "Bad\\qname\t" + idC + "\n\t" + idC + "\nhalf a li"; +Check(PinStore.Read(damaged, "Beaverton").SequenceEqual(new[] { idB }) && PinStore.Read(damaged, "Otter Bay").SequenceEqual(new[] { idC }) && + PinStore.Read(damaged, "Badqname").Count == 0 && PinStore.Read(damaged, "Bad\\qname").Count == 0 && PinStore.Read(damaged, "").Count == 0, + "Damaged entries in the pin file are skipped and the rest survive"); +Check(PinStore.Write("garbage\n\u0000", "Beaverton", new[] { idA }) == PinStore.Write(null, "Beaverton", new[] { idA }), "Saving over a corrupt pin file replaces it"); +var names = new[] { "Tab\tTown", "Two\nLines\r", "Back\\slash\\t", "Back\\slash\t", "\u00DCbersee \u6CB3\u72F8", " spaced ", "Online Games" }; +string awkward = null; +for (int i = 0; i < names.Length; i++) awkward = PinStore.Write(awkward, names[i], new[] { i % 2 == 0 ? idA : idB }); +Check(names.Select((name, i) => PinStore.Read(awkward, name).SequenceEqual(new[] { i % 2 == 0 ? idA : idB })).All(x => x) && + PinStore.Read(awkward, "Tab").Count == 0 && PinStore.Read(awkward, "Two").Count == 0 && awkward.Split('\n').Length == names.Length + 2, + "Settlement names with tabs, line breaks, backslashes and other scripts keep their own pins, one line each"); +string crowded = null; +for (int i = 0; i <= PinStore.MaxSettlements; i++) crowded = PinStore.Write(crowded, "Settlement " + i, new[] { idA }); +Check(PinStore.Read(crowded, "Settlement 0").Count == 0 && PinStore.Read(crowded, "Settlement 1").Count == 1 && + PinStore.Read(crowded, "Settlement " + PinStore.MaxSettlements).Count == 1, "The pin file keeps only the most recently changed settlements"); +crowded = PinStore.Write(PinStore.Write(crowded, "Settlement 1", new[] { idB }), "Settlement new", new[] { idA }); +Check(PinStore.Read(crowded, "Settlement 1").SequenceEqual(new[] { idB }) && PinStore.Read(crowded, "Settlement 2").Count == 0, + "Changing a settlement's pins makes it the most recent"); +var touched = PinStore.Touch(PinStore.Write(PinStore.Write(null, "Beaverton", new[] { idA, idB }), "Otter Bay", new[] { idC }), "Beaverton"); +Check(touched != null && touched.Split('\n')[1].StartsWith("Beaverton\t") && PinStore.Read(touched, "Beaverton").SequenceEqual(new[] { idA, idB }) && + PinStore.Read(touched, "Otter Bay").SequenceEqual(new[] { idC }), "Loading a settlement moves its entry first and keeps its pins and every other settlement's"); +Check(PinStore.Touch(touched, "Beaverton") == null && PinStore.Touch(touched, "Nowhere") == null && PinStore.Touch(null, "Beaverton") == null && + PinStore.Touch("garbage\nBeaverton\t" + idA, "Beaverton") == null, "Loading a settlement that is already first, has no entry or has no readable file rewrites nothing"); +crowded = PinStore.Write(PinStore.Touch(crowded, "Settlement 3")!, "Settlement newer", new[] { idA }); +Check(PinStore.Read(crowded, "Settlement 3").SequenceEqual(new[] { idA }) && PinStore.Read(crowded, "Settlement 4").Count == 0, + "A settlement loaded recently is kept over one changed longer ago"); +var doubled = PinStore.Header + "\nBeaverton\t" + idA + "\t" + idA + "\t" + Guid.Empty + "\t" + idB + "\nBeaverton\t" + idC + "\n"; +Check(PinStore.Read(doubled, "Beaverton").SequenceEqual(new[] { idA, idB }), "A hand-edited pin file that lists a settlement twice uses its first line, each building once"); +var built = new[] { new SavedBuilding(idA), new SavedBuilding(idB), new SavedBuilding(idC) }; +remembered = PinStore.Write(null, "Beaverton", built.Take(2).Select(x => x.Id)); +var reloaded = new[] { new SavedBuilding(idA), new SavedBuilding(idB), new SavedBuilding(idC) }; +SavedBuilding Resolve(Guid id) => reloaded.FirstOrDefault(x => x.Id == id); +Check(PinStore.Restore(PinStore.Read(remembered, "Beaverton"), Resolve, _ => true).SequenceEqual(reloaded.Take(2), PinSet.Identity), + "After a load, pins find the reloaded buildings by entity id, not the objects that were pinned"); +Check(PinStore.Restore(new[] { idA, Guid.NewGuid(), idA }, Resolve, _ => true).SequenceEqual(new[] { reloaded[0] }, PinSet.Identity), + "Ids of buildings the loaded save no longer has are dropped, and each building is pinned once"); +Check(PinStore.Restore(new[] { idA, idB }, Resolve, x => !ReferenceEquals(x, reloaded[0])).SequenceEqual(new[] { reloaded[1] }, PinSet.Identity), + "A remembered building that can no longer be pinned stays unpinned"); +var pinFolder = Path.Combine(Path.GetTempPath(), "pwa-checks-" + Guid.NewGuid().ToString("N")); +try +{ + var pinFile = new PinFile(Path.Combine(pinFolder, "PersistentWorkAreas", "Pins.txt")); + Check(pinFile.Load("Beaverton").Count == 0 && !Directory.Exists(pinFolder), "Before any pin is saved there is no pin file, and loading needs none"); + pinFile.Save("Beaverton", new[] { idB, idA }); + pinFile.Save("Otter Bay", new[] { idC }); + Check(new PinFile(pinFile.FilePath).Load("Beaverton").SequenceEqual(new[] { idA, idB }) && new PinFile(pinFile.FilePath).Load("Otter Bay").SequenceEqual(new[] { idC }), + "Pins round-trip through the file on disk, whose folder is created on the first save"); + var pinFiles = Path.GetDirectoryName(pinFile.FilePath)!; + string[] FileNames() => Directory.GetFiles(pinFiles).Select(x => Path.GetFileName(x)!).OrderBy(x => x, StringComparer.Ordinal).ToArray(); + var beforeTouch = File.ReadAllText(pinFile.FilePath); + pinFile.Touch("Nowhere"); + bool untouched = File.ReadAllText(pinFile.FilePath) == beforeTouch; + pinFile.Touch("Beaverton"); + Check(untouched && File.ReadAllLines(pinFile.FilePath)[1].StartsWith("Beaverton\t") && pinFile.Load("Beaverton").SequenceEqual(new[] { idA, idB }) && + pinFile.Load("Otter Bay").SequenceEqual(new[] { idC }) && FileNames().SequenceEqual(new[] { "Pins.txt" }), + "Loading a settlement moves its entry first on disk, with no copy or temporary file left behind"); + var corrupt = new byte[] { 0x50, 0x4B, 0x03, 0x04, 0x00, 0xFF, 0xFE, 0x0A, 0x09, 0xC3 }; + File.WriteAllBytes(pinFile.FilePath, corrupt); + Check(pinFile.Load("Beaverton").Count == 0, "A corrupt pin file on disk is ignored"); + pinFile.Save("Beaverton", new[] { idA }); + Check(pinFile.Load("Beaverton").SequenceEqual(new[] { idA }) && FileNames().SequenceEqual(new[] { "Pins.txt", "Pins.txt.bak" }) && + File.ReadAllBytes(pinFile.FilePath + ".bak").SequenceEqual(corrupt), "Saving replaces an unreadable pin file, keeps a copy of it and leaves no temporary file behind"); + var newer = PinStore.Header.Replace("v1", "v2") + "\nBeaverton\t" + idB + "\n"; + File.WriteAllText(pinFile.FilePath, newer); + pinFile.Save("Beaverton", new[] { idA }); + Check(pinFile.Load("Beaverton").SequenceEqual(new[] { idA }) && File.ReadAllText(pinFile.FilePath + ".bak") == newer, + "A pin file from a newer version is kept as a copy before this version replaces it"); +} +finally +{ + if (Directory.Exists(pinFolder)) Directory.Delete(pinFolder, true); +} // 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 = 56; // A full run fails if this stops matching the checks below. +const int GameChecks = 65; // A full run fails if this stops matching the checks below. int gameFreeChecks = checks; if (args.Length == 0) { @@ -312,6 +412,92 @@ object Planting(string group) 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"); +// Remembered pins, on the same instance: its pin file in a temporary folder, and the settlement as the game's own service names it. +// SavePins is what the frame update starts with; UpdateSingleton itself only reads Time.unscaledTime (which runs only in the game) +// and passes it to UpdateAt, which the last check here invokes. +var settlementReference = GameType("Timberborn.GameSaveRepositorySystem", "Timberborn.GameSaveRepositorySystem.SettlementReference"); +var settlements = RuntimeHelpers.GetUninitializedObject(GameType("Timberborn.SettlementNameSystem", "Timberborn.SettlementNameSystem.SettlementReferenceService")); +Set(live, "_settlements", settlements); +var liveFolder = Path.Combine(Path.GetTempPath(), "pwa-checks-" + Guid.NewGuid().ToString("N")); +var livePinPath = Path.Combine(liveFolder, "Pins.txt"); +var pinFileType = mod.GetType("PersistentWorkAreas.PinFile", true)!; +Set(live, "_pinFile", Activator.CreateInstance(pinFileType, livePinPath)!); +void PinEntity(Guid id) +{ + var entity = RuntimeHelpers.GetUninitializedObject(entityComponent); + Set(entity, "k__BackingField", id); + livePins.GetType().GetMethod("Set")!.Invoke(livePins, new object[] { entity, true }); +} +bool PinsChanged() => (bool)livePins.GetType().GetProperty("Changed")!.GetValue(livePins)!; +List Remembered(string settlement) => File.Exists(livePinPath) ? PinStore.Read(File.ReadAllText(livePinPath), settlement) : new List(); +void SavePins() => service.GetMethod("SavePins", fields)!.Invoke(live, null); +try +{ + PinEntity(idB); PinEntity(idA); + SavePins(); + Check(!File.Exists(livePinPath) && PinsChanged(), "A new game's pins wait until the player names the settlement"); + Set(settlements, "k__BackingField", Activator.CreateInstance(settlementReference, "Beaverton", "Saves")!); + SavePins(); + Check(Remembered("Beaverton").SequenceEqual(new[] { idA, idB }) && !PinsChanged(), "A pin change is saved under the game's settlement name at the next update"); + File.WriteAllText(livePinPath, PinStore.Write(File.ReadAllText(livePinPath), "Otter Bay", new[] { idC })); + service.GetMethod("ClearAll")!.Invoke(live, null); + Check(PinsChanged() && Remembered("Beaverton").Count == 2, "Clear pinned areas leaves the file to the next update"); + SavePins(); + Check(Remembered("Beaverton").Count == 0 && Remembered("Otter Bay").SequenceEqual(new[] { idC }), "Clear pinned areas forgets this settlement's pins and keeps other settlements'"); + PinEntity(idC); + service.GetMethod("Reset", fields)!.Invoke(live, null); + SavePins(); + Check(Remembered("Beaverton").SequenceEqual(new[] { idC }) && (int)service.GetProperty("Count")!.GetValue(live)! == 0 && !PinsChanged(), + "Leaving the map saves a pending pin change, then forgets the pins in memory only"); + + // Loading: the settlement's remembered ids go through the game's own EntityRegistry. idD is a building only a newer save has. + // PostLoad passes Supports, which needs live game objects, so this passes a test that turns down building A. + var idD = new Guid("f3b1c8e2-7a4d-4c59-9e06-2b8d5f1a6c37"); + File.WriteAllText(livePinPath, PinStore.Write(PinStore.Write(null, "Beaverton", new[] { idA, idB, idD }), "Otter Bay", new[] { idC })); + var entityRegistry = Activator.CreateInstance(GameType("Timberborn.EntitySystem", "Timberborn.EntitySystem.EntityRegistry"))!; + object Loaded(Guid id) + { + var entity = RuntimeHelpers.GetUninitializedObject(entityComponent); + Set(entity, "k__BackingField", id); + Get(entityRegistry, "_entities")[id] = entity; + return entity; + } + var loadedA = Loaded(idA); var loadedB = Loaded(idB); Loaded(idC); + Set(live, "_entities", entityRegistry); + var beforeLoad = File.ReadAllText(livePinPath); + Func pinnable = x => !ReferenceEquals(x, loadedA); + service.GetMethod("RestorePins", fields)!.Invoke(live, new object[] { pinnable }); + Check((int)service.GetProperty("Count")!.GetValue(live)! == 1 && (bool)livePins.GetType().GetMethod("Contains")!.Invoke(livePins, new[] { loadedB })! && + liveEntries.Count == 1 && liveEntries.Contains(loadedB) && !PinsChanged() && File.ReadAllText(livePinPath) == beforeLoad, + "Loading pins this settlement's remembered buildings that can be pinned, draws them, and writes nothing yet"); + SavePins(); + Check(File.ReadAllLines(livePinPath)[1].StartsWith("Beaverton\t") && Remembered("Beaverton").SequenceEqual(new[] { idA, idB, idD }) && + Remembered("Otter Bay").SequenceEqual(new[] { idC }), + "The first update after loading moves the settlement first in the pin file and keeps the buildings this save lacks"); + + // The frame update, given the clock: it saves before anything else, and waits 10 seconds after a failed write. + // The failure warning goes to Unity's log, which runs only in the game, so it is marked as already given. + service.GetMethod("ClearAll")!.Invoke(live, null); + Set(live, "_active", true); + Set(live, "_saveWarned", true); + var goodPinFile = Get(live, "_pinFile"); + Set(live, "_pinFile", Activator.CreateInstance(pinFileType, Path.Combine(livePinPath, "Pins.txt"))!); + void UpdateAt(float now) => service.GetMethod("UpdateAt", fields)!.Invoke(live, new object[] { now }); + UpdateAt(100f); + bool retryLater = PinsChanged() && Get(live, "_nextSave") == 110f; + Set(live, "_pinFile", goodPinFile); + UpdateAt(109f); + bool waited = Remembered("Beaverton").Count == 3; + UpdateAt(110f); + Check(retryLater && waited && Remembered("Beaverton").Count == 0 && Remembered("Otter Bay").SequenceEqual(new[] { idC }) && !PinsChanged() && liveEntries.Count == 0, + "The frame update saves a pin change with nothing left to draw, and retries a failed write 10 seconds later"); + Set(live, "_active", false); +} +finally +{ + if (Directory.Exists(liveFolder)) Directory.Delete(liveFolder, true); +} + // 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)>(); @@ -347,6 +533,10 @@ string[] ShownFor(string plant) => planters.Where(p => PlantingRanges.Shows(plan Check(interfaces.Contains("Timberborn.SingletonSystem.IUpdatableSingleton"), "Display refresh lifecycle"); Check(interfaces.Contains("Timberborn.Navigation.ISingletonInstantNavMeshListener") && interfaces.Contains("Timberborn.Navigation.ISingletonPreviewNavMeshListener"), "Live and construction preview invalidation"); Check(!interfaces.Any(x => x.Contains("Saveable") || x.Contains("Tickable") || x.Contains("PersistentEntity")), "No simulation tick or persistence interfaces"); +Check(mod.GetTypes().All(t => !t.GetInterfaces().Any(x => x.Namespace?.StartsWith("Timberborn") == true && + (x.Name.Contains("Sav") || x.Name.Contains("Persist") || x.Name.Contains("Tick")))) && + !mod.GetReferencedAssemblies().Any(x => x.Name is "Timberborn.Persistence" or "Timberborn.WorldPersistence" or "Timberborn.SaveSystem" or "Timberborn.GameSaveRuntimeSystem"), + "Pins stay out of the save: no mod type saves, persists or ticks, and the mod never references the game's save writers"); Check(!mod.GetReferencedAssemblies().Any(x => x.Name.Contains("BeaverBuddies") || x.Name.Contains("TimberNet") || x.Name.Contains("Harmony")), "No multiplayer or Harmony assembly dependencies"); Check(mod.GetTypes().All(t => !t.GetCustomAttributesData().Any(a => a.AttributeType.Name.StartsWith("HarmonyPatch"))), "No method patches"); var fragment = mod.GetType("PersistentWorkAreas.WorkAreaFragment", true)!; @@ -384,9 +574,16 @@ string[] ShownFor(string plant) => planters.Where(p => PlantingRanges.Shows(plan var reflected = new[] { drawer, calculator, bounds, layer }; var reflectedNames = reflected.Select(x => x.FullName!).Concat(reflected.SelectMany(x => x.GetMembers( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly)).Select(x => x.Name)).ToHashSet(); +// The pin file's header, folder and file names, its escapes and GUID format, PinStore's argument check, and the +// ": " that joins a log warning to its error. None of it is shown in the game's UI. +var pinFileText = new HashSet { + (string)mod.GetType("PersistentWorkAreas.PinStore", true)!.GetField("Header")!.GetRawConstantValue()!, + "PersistentWorkAreas", "Pins.txt", ".tmp", ".bak", "D", "\t", "\n", "\r", "\\", "\\\\", "\\t", "\\n", "\\r", + "A settlement name is required.", "settlement", ": " }; bool IsCode(string x) => x.StartsWith("PersistentWorkAreas.") ? x == clearKey || enUS.ContainsKey(x) : x.StartsWith("[PersistentWorkAreas] ") || x.StartsWith(" loaded. ") // log text; Mod.cs splits its line around the version - || System.Text.RegularExpressions.Regex.IsMatch(x, "^PersistentWorkAreas[A-Z][A-Za-z]*$") || reflectedNames.Contains(x); + || System.Text.RegularExpressions.Regex.IsMatch(x, "^PersistentWorkAreas[A-Z][A-Za-z]*$") || reflectedNames.Contains(x) + || pinFileText.Contains(x); var hardCoded = literals.Keys.Where(x => !IsCode(x)).ToArray(); Check(hardCoded.Length == 0, "No hard-coded English UI text in the mod DLL" + string.Concat(hardCoded.Select(x => "\n \"" + x + "\""))); var locKeys = mod.GetType("PersistentWorkAreas.LocKeys")?.GetFields(BindingFlags.Public | BindingFlags.Static) @@ -476,6 +673,15 @@ sealed class EqualBuilding public override int GetHashCode() => 1; } +// A building as a save knows it: only its entity id survives a load. Equal-valued so that restoring must go by id. +sealed class SavedBuilding +{ + public readonly Guid Id; + public SavedBuilding(Guid id) { Id = id; } + public override bool Equals(object obj) => obj is SavedBuilding; + public override int GetHashCode() => 1; +} + // Radius stands in for the navigation state: changing it changes the range the next query returns. sealed class FakePin {