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 docs/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ The allocation checks need no game files, so GitHub Actions also runs them on ev

Percentages use integer units totaling 10,000. Whole-item limits use largest-remainder rounding with ordinal good-ID ordering for ties. Incoming reservations guard against conflicting limit reductions; existing excess stock is preserved. Copy/paste transfers percentages atomically into a draft and rejects incompatible goods. Hauling mode and priority are not copied. In Supply mode a mixed building offers its allocated goods with the most unreserved stock first, ordinal good IDs breaking ties (`AllocationPlan.SupplyCandidates`). Goods without unreserved stock are skipped: the game's search for a building to take one scans the whole district and can only fail, so skipping them never changes which good is carried. Those searches did fill the building's cached road route map, which a few of the game's path queries use only when it is already filled, so co-op players still need the same MixedStorage build.

The game's Duplicate settings tool calls `SingleGoodAllower.DuplicateFrom`. A mixed source applies its allocation to the target through the same checks as Apply. They run before the base game's copy of the single good, so when they reject it that copy is skipped and logged, and the target keeps its allocation or single good whether or not it was mixed. The tool copies each of the building's other settings separately, such as the storage mode (`StockpilePriority`), so those still apply. A source set to store nothing, such as a building just placed, leaves a mixed target's allocation alone (the base game would clear the target's good), so copying the storage mode from a new building does not wipe a tuned allocation, which has no undo. Any other source gives the target that building's single good, as in the base game, so a mixed target first leaves mixed mode (`StorageState.Deactivate`). That is the only way back to the base game's rules. The storage panel stores a single good as a 100% allocation, so such a source is a building given a single good in the goods dropdown of the game's building list (`StockpileDropdownProvider`, which still works on a building without an allocation; `AllowPatch` and `DisallowPatch` ignore it on a mixed one), a warehouse or pile from before the mod, or a storage the mod does not manage, such as the map editor's reserve storage or another mod's storage. Leaving lowers limits too, so it gets Apply's incoming-delivery guard: the base game has room only for the kept good, and none for it while any other good is in stock. A delivery that would no longer fit refuses the copy the same way, before the base game's copy runs. The decision is `AllocationPlan.PlanCopy`, and what the patch then does (leave, run the base game's copy, apply, or log a refusal) is `AllocationPlan.Steps`; the allocation tests cover both. BeaverBuddies replays the tool on every player (`DuplicationEvent`), and the decision reads only simulation state (accepted goods, capacity, stock and reservations), so every player decides the same. Leaving mixed mode announces every formerly allocated good, because the game's `InventoryRegistry` caches which buildings have room for each good and only updates a good when it is announced. During those announcements the visuals are pointed at the representative good, so the pile keeps showing what it holds. Loading also mirrors the save: a building loaded without an allocation (for example by the map editor's undo) leaves mixed mode.
The game's Duplicate settings tool calls `SingleGoodAllower.DuplicateFrom`. A mixed source applies its allocation to the target through the same checks as Apply. They run before the base game's copy of the single good, so when they reject it that copy is skipped and logged, and the target keeps its allocation or single good whether or not it was mixed. The tool copies each of the building's other settings separately, such as the storage mode (`StockpilePriority`), so those still apply. A source set to store nothing, such as a building just placed, leaves a mixed target's allocation alone (the base game would clear the target's good), so copying the storage mode from a new building does not wipe a tuned allocation, which has no undo. Any other source gives the target that building's single good, as in the base game, so a mixed target first leaves mixed mode (`StorageState.Deactivate`). That is the only way back to the base game's rules. The storage panel stores a single good as a 100% allocation, so such a source is a building given a single good in the goods dropdown of the game's building list (`StockpileDropdownProvider`, which still works on a building without an allocation; `AllowPatch` and `DisallowPatch` ignore it on a mixed one), a warehouse or pile from before the mod, or a storage the mod does not manage, such as the map editor's reserve storage or another mod's storage. Leaving lowers limits too, so it gets Apply's incoming-delivery guard: the base game has room only for the kept good, and none for it while any other good is in stock. A delivery that would no longer fit refuses the copy the same way, before the base game's copy runs. The decision is `AllocationPlan.PlanCopy`, and what the patch then does (leave, run the base game's copy, apply, or log a refusal) is `AllocationPlan.Steps`; the allocation tests cover both. BeaverBuddies replays the tool on every player (`DuplicationEvent`), and the decision reads only simulation state (accepted goods, capacity, stock and reservations), so every player decides the same. Leaving mixed mode announces every formerly allocated good the building accepts, because the game's `InventoryRegistry` caches which buildings have room for each good and only updates a good when it is announced. A good the building does not accept is limited to 0 by the game whatever the allocation says, and a saved allocation can name a good the game no longer knows (after a goods mod is removed), which `InventoryRegistry` would throw on, so neither is announced. During those announcements the visuals are pointed at the representative good, so the pile keeps showing what it holds. Loading also mirrors the save: a mixed building reloaded without an allocation (the map editor's undo) leaves mixed mode the same way, and one reloaded with another allocation announces the goods of both. A building loaded from a save is never mixed before its own load, so a normal save load announces nothing. A redraw queued before a building left mixed mode finds no allocation and puts the native pile back instead of disabling the mixed visuals.

Every announcement goes through the game's private `SingleGoodAllower.InvokeDisallowedGoodsChangedEvent(string)`, looked up by signature when `ModStarter` starts. If a game update renames or changes it, `ModStarter` logs why and allocations are frozen instead of half-applied: Apply is refused with that reason, and so is every copy that would set or leave an allocation (from a mixed building, or onto one), while copies between single-good buildings work as in the base game. A mixed building stays mixed, and saved allocations keep limiting their buildings. The game still starts: `ModStarter` reads this through `AllocationProblem`, which also reports, rather than throws, a `StorageState` that cannot load at all. Frozen mode depends on the installed game, so every co-op player must run the same game version; BeaverBuddies only warns when they differ, and a player whose game lacks the method would refuse changes the others apply.

Expand Down Expand Up @@ -55,6 +55,7 @@ The mod reuses the installed game's styles and assets: `NineSliceVisualElement`
- Every Harmony patch in the built DLL checked against installed game assemblies (`visual-tests/PatchTargetTests.cs`), resolved the way Harmony does at startup: 22 targets in 20 patch classes, the 4 injected `___` fields and the 11 other named parameters, with their types. A renamed target would otherwise throw from `PatchAll` and stop the game from starting. The same test checks the 6 reflection handles the mod keeps in static fields, the 8 native visualizer members `MixedContentsRenderer` reads by name, that the mod reads the installed BeaverBuddies' `EventIO.IsNull` as "no connection", and that LateGamePerformance's two trusted patches keep their names and Harmony id, with no other patch on the methods its counting workers call, on its 15 saving helpers, or on anything one of the game's component `Save` methods calls directly (read from their IL).
- 201 whole-cell partition cases covering boundary ownership, complete topology, compact vertices, per-vertex attributes, and unknown-topology fallback.
- 400 random piles (plain and rotated/scaled transforms, random section boundaries) whose extracted sections are compared triangle by triangle with the original algorithm that transformed and kept every vertex, plus the whole-mesh fit used for bulk surfaces.
- Leaving mixed mode and reloading a building run against the game's own `SingleGoodAllower` and `Inventory`, created without Unity (`visual-tests/AnnouncementTests.cs`): the goods the mod announces are recorded, and must be exactly the allocated goods the building accepts, never one the game no longer knows, all announced as the mod's own change; a normal save load announces nothing.
- Ten native API signatures checked against installed game assemblies: nine for rendering, plus the goods announcement. The old ambiguous Initialize lookup is reproduced as a regression check, and `StorageState`'s IL must look the announcement up by its `(string)` signature. A copy of the built mod with the announcement's name changed must report why through `ModStarter.AllocationProblem`, refuse Apply and every copy that would set or leave an allocation, and keep a mixed building mixed. A copy with a game type `StorageState` keeps in a static field renamed must be reported there too, without throwing. `StartMod` and `DuplicatePatch` need Unity, so their IL is checked instead: `StartMod` asks `AllocationProblem` before patching and never touches `StorageState` itself, and `DuplicatePatch` checks for frozen allocations before anything else.
- Isolated loading processes with and without BeaverBuddies check eager main-type enumeration, bridge event discovery, delegate installation, repeated initialization, and obsolete-addon rejection. A stub BeaverBuddies with one member missing (`loading-tests/StubBeaverBuddies`) checks that an incompatible build is skipped without stopping startup, that the reason names exactly that member, that a failed bridge is not loaded twice, and that Apply without the bridge only counts as single-player when BeaverBuddies reports no connection. They also check that every prefix that can replace the game's method (every prefix returning `bool`, in every class Harmony's `PatchAll` would patch) carries `[HarmonyPriority(Priority.Last)]`, on the method or on its class.
- BeaverBuddies replays the Duplicate settings tool on every player. A loading check walks the IL of the patches that run inside that replay, and of every mod method they call, and fails if any of them reads the panel's message or pending state, the panel or renderer, submits a command, or reads a clock, input or random numbers (`loading-tests/ReplayChecks.cs`). Two control scans check that it finds such state where the mod does use it.
Expand Down
3 changes: 3 additions & 0 deletions source/MixedContentsRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@ private static KeyValuePair<string, int>[] SortedShares(StorageState state)
private void Render(StockpileVisualizers owner, StorageState state)
{
if (_busy || _failed) return;
// A redraw queued before the building left mixed mode, for example when a reload leaves it without an
// allocation, finds no shares; the native pile is back.
if (!state.Active) { Release(); return; }
if (_sharesRevision != state.Revision)
{
_shares = SortedShares(state);
Expand Down
48 changes: 30 additions & 18 deletions source/StorageState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,19 +130,27 @@ private void Publish()
}

// Returns the building to the base game's single-good rules; the caller then sets that good.
// Every formerly allocated good is announced because its limit changes, and the game caches
// which buildings have room for each good.
public void Deactivate()
{
// Without the announcement the building stays mixed (see UnavailableReason), and AllowPatch then keeps
// the base game's copy from switching its good.
if (!Active || UnavailableReason != null) return;
var previous = Shares;
SetShares(null);
// While these fire, the building still has its representative good; the visuals must follow
// that good (VisualizerPatch), not whichever formerly allocated good is announced last.
Announce(previous.Keys);
}

// Announces goods whose limit changed, because the game caches which buildings have room for each good.
// Only goods the building accepts: the game limits any other good to 0 whatever the allocation says
// (Inventory.LimitedAmount), and a saved allocation can name a good the game no longer knows, which
// would throw from InventoryRegistry. While these fire, the building still has its representative good;
// the visuals must follow that good (VisualizerPatch), not whichever good is announced last. Without the
// announcement method (see UnavailableReason) nothing is announced.
private void Announce(IEnumerable<string> goods)
{
if (NotifyGood == null) return;
InternalChange = true;
try { foreach (string good in previous.Keys) Notify(good); }
try { foreach (string good in goods) if (Inventory.Takes(good)) Notify(good); }
finally { InternalChange = false; }
}

Expand All @@ -156,21 +164,25 @@ public void Save(IEntitySaver saver)

public void Load(IEntityLoader loader)
{
// The state mirrors the save, also when the map editor's undo reloads an existing building.
if (!loader.TryGetComponent(SaveKey, out var component) || !component.Has(SharesKey))
{
if (Active) SetShares(null);
return;
}
string saved = component.Get(SharesKey);
try { SetShares(AllocationPlan.Deserialize(saved)); }
catch (FormatException ex)
// The state mirrors the save, also when the map editor's undo reloads an existing building. A building
// loaded for the first time is never mixed yet, so a mixed one is already in the world: its changed
// limits are announced as Apply and Deactivate do, which also sends its visuals back to the native pile
// when it leaves mixed mode (MixedAllocationVisualPatch).
var previous = Shares;
if (!loader.TryGetComponent(SaveKey, out var component) || !component.Has(SharesKey)) { if (Active) SetShares(null); }
else
{
// One unreadable building must not stop the whole save from loading. It keeps the
// single good the base game saved alongside it, and the warning says what was lost.
if (Active) SetShares(null);
Debug.LogWarning("[MixedStorage] Ignoring an unreadable saved allocation for " + Allower.Name + " (" + ex.Message + "): " + saved);
string saved = component.Get(SharesKey);
try { SetShares(AllocationPlan.Deserialize(saved)); }
catch (FormatException ex)
{
// One unreadable building must not stop the whole save from loading. It keeps the
// single good the base game saved alongside it, and the warning says what was lost.
if (Active) SetShares(null);
Debug.LogWarning("[MixedStorage] Ignoring an unreadable saved allocation for " + Allower.Name + " (" + ex.Message + "): " + saved);
}
}
if (previous != null) Announce(previous.Keys.Union(Shares?.Keys ?? Enumerable.Empty<string>(), StringComparer.Ordinal));
}

public void Duplicate(StorageState source)
Expand Down
Loading