Idle facilities cost near nothing: the catalog owns a filler index, the bay counts its changes, a failed take waits for the hold to change; the overshoot carry is the stated rule

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-28 06:56:34 +01:00
commit 3254580a6d
5 changed files with 167 additions and 23 deletions

View file

@ -29,6 +29,10 @@ public class Facility : Behavior
// Why the facility advanced no further this step: derived by Advance every step, never stored on the unit.
public Stall Stall { get; private set; }
// The hold's Revision when an idle facility last failed to take a cycle's inputs. A failed take reads nothing but the hold, so
// until the hold changes a retry fails the same way and is skipped. Not persisted: a restored facility tries once on its first step.
private long _failedAt;
public Facility(FacilityData data, EquippedItem item) : base(data, item)
{
_runList = Production.RunList(ItemManager.ItemData, Item.EquippableItem.Data.Key);
@ -37,9 +41,12 @@ public class Facility : Behavior
public override bool Execute(float dt)
{
_hold ??= new EntityHold(Entity);
var idle = Item.EquippableItem.Run == null || Item.EquippableItem.Run.Progress <= 0;
if (idle && Stall == Stall.Inputs && _hold.Revision == _failedAt) return true;
var (run, stall) = Production.Advance(ItemManager.ItemData, _runList, Item.EquippableItem.Run, dt, _hold);
Item.EquippableItem.Run = run;
Stall = stall;
if (idle && stall == Stall.Inputs) _failedAt = _hold.Revision;
return true;
}
}

View file

@ -2425,6 +2425,10 @@ public class EquippedCargoBay : EquippedItem
public float ThermalMass { get; private set; }
public string Name { get; }
// Counts every change to what the bay holds (a stack stored, merged, split or removed, a unit stored or removed). Monotonic and
// not persisted: a holder that remembers the value it last read learns whether the contents changed since, without comparing them.
public long Revision { get; private set; }
public Shape UnoccupiedSpace
{
get
@ -2579,6 +2583,7 @@ public class EquippedCargoBay : EquippedItem
Occupancy[pos.x, pos.y] = item;
}
Cargo[item] = cargoCoord;
Revision++;
if(!ItemsOfType.ContainsKey(item.Data.Key))
ItemsOfType[item.Data.Key] = new List<ItemInstance>();
@ -2586,6 +2591,7 @@ public class EquippedCargoBay : EquippedItem
}
else if (Occupancy[cargoCoord.x, cargoCoord.y] is ICommodityStack held && stack.StacksWith(Occupancy[cargoCoord.x, cargoCoord.y]))
{
Revision++;
if (held.Quantity + stack.Quantity <= maxStack)
{
held.Quantity += stack.Quantity;
@ -2623,6 +2629,7 @@ public class EquippedCargoBay : EquippedItem
Occupancy[pos.x, pos.y] = item;
}
Cargo[item] = cargoCoord;
Revision++;
if(!ItemsOfType.ContainsKey(item.Data.Key))
ItemsOfType[item.Data.Key] = new List<ItemInstance>();
@ -2681,6 +2688,7 @@ public class EquippedCargoBay : EquippedItem
if (item is ICommodityStack stack && quantity < stack.Quantity)
{
var itemData = ItemManager.GetData(item);
Revision++;
stack.Quantity -= quantity;
Mass -= itemData.Mass * quantity;
ThermalMass -= itemData.Mass * itemData.SpecificHeat * quantity;
@ -2702,6 +2710,7 @@ public class EquippedCargoBay : EquippedItem
// The item, with everything it holds, leaves the bay: the one place a cell is freed.
private void RemoveWhole(ItemInstance item)
{
Revision++;
foreach(var v in Data.InteriorShape.Coordinates)
if (Occupancy[v.x, v.y] == item)
Occupancy[v.x, v.y] = null;

View file

@ -77,7 +77,8 @@ public static class Production
// starts the first recipe after the cursor, wrapping, whose units the hold grants, and takes them at once; a running one adds
// time; at Progress >= Cycle it stores the output and goes idle, the recipe staying as the cursor. A store the hold refuses
// holds the batch at Cycle (Room) and retries on the next call. Time left after a cycle ends runs the next one in the same call,
// so a long span runs several cycles; time that no cycle can use is dropped. A facility with nothing to start writes nothing.
// so a long span runs several cycles (the rule that makes one span equal as many steps as it covers); time that no cycle can start is
// dropped. A facility with nothing to start writes nothing.
public static (FacilityRun run, Stall stall) Advance(CultCache catalog, IReadOnlyList<RecipeData> runList, FacilityRun run,
double seconds, IProductionHold hold)
{
@ -131,6 +132,18 @@ public sealed class EntityHold : IProductionHold
public EntityHold(Entity entity) => _entity = entity;
// Changes whenever anything the bays hold changes (each bay counts its own changes); a bay seated or removed moves it too. A holder
// that remembers the value it last failed to take from learns whether a retry could differ.
public long Revision
{
get
{
long revision = _entity.CargoBays.Count;
for (var at = 0; at < _entity.CargoBays.Count; at++) revision += _entity.CargoBays[at].Revision;
return revision;
}
}
public int Held(CultRecordKey design) => _entity.CargoBays.Sum(bay => bay.Count(design));
public bool TryTake(IReadOnlyList<(CultRecordKey design, int units)> units)

View file

@ -140,13 +140,55 @@ public static class Recipes
public static bool IsConsumerGood(CultCache catalog, RecipeData recipe) =>
IsCommodity(catalog.Get(recipe.Output)) && IsRoleRecipe(catalog, recipe);
// The commodities whose recipes Fill the role, ordered by key so a choice never depends on store order.
public static CultRecordKey[] Fillers(CultCache catalog, string role) =>
catalog.GetAll<RecipeData>()
.Where(recipe => recipe.Fills != null && recipe.Fills.Contains(role) && IsCommodity(catalog.Get(recipe.Output)))
.Select(recipe => recipe.Output.Key)
.OrderBy(key => key.Value, StringComparer.Ordinal)
.ToArray();
// The commodities whose recipes Fill the role, ordered by key so a choice never depends on store order. Read from the catalog's
// filler index, which is built on the first read and rebuilt on the first read after a recipe or commodity changes.
public static CultRecordKey[] Fillers(CultCache catalog, string role) => FillerIndexes.GetValue(catalog, cache => new FillerIndex(cache)).Of(role);
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<CultCache, FillerIndex> FillerIndexes = new();
// Role to its fillers, derived from the recipes and owned by the catalog it was built from (one index per catalog, dropped with it).
// The catalog is read-only while a game runs, so a build serves every read; a write to a recipe or a commodity design (a test, an
// authoring batch) marks it stale, and the next read rebuilds it.
private sealed class FillerIndex
{
private readonly CultCache _catalog;
private readonly object _gate = new object();
private Dictionary<string, CultRecordKey[]> _byRole;
private volatile bool _stale = true;
public FillerIndex(CultCache catalog)
{
_catalog = catalog;
// The journal runs under the catalog's own gate and must wait for nothing, so it only raises the flag.
catalog.AddJournal(changes =>
{
foreach (var change in changes)
if (Matters(change.Document) || Matters(change.PreviousDocument)) _stale = true;
});
}
private static bool Matters(object document) => document is RecipeData || document is SimpleCommodityData || document is CompoundCommodityData;
public CultRecordKey[] Of(string role)
{
lock (_gate)
{
if (_stale)
{
_stale = false;
_byRole = Build();
}
return _byRole.TryGetValue(role, out var fillers) ? fillers : Array.Empty<CultRecordKey>();
}
}
private Dictionary<string, CultRecordKey[]> Build() =>
_catalog.GetAll<RecipeData>()
.Where(recipe => recipe.Fills != null && IsCommodity(_catalog.Get(recipe.Output)))
.SelectMany(recipe => recipe.Fills.Where(role => role != null).Distinct().Select(role => (role, recipe.Output.Key)))
.GroupBy(pair => pair.role)
.ToDictionary(group => group.Key, group => group.Select(pair => pair.Key).OrderBy(key => key.Value, StringComparer.Ordinal).ToArray());
}
// The recipes a facility design runs, ordered by recipe key so a choice never depends on store order. The one reader of which
// recipes a facility runs; RecipeData.Facility owns it and nothing is stored on the facility.

View file

@ -17,20 +17,17 @@ public sealed class FacilityProductionTests : IDisposable
private const double IronCycle = 600;
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-facilityproduction-" + Guid.NewGuid().ToString("N"));
private readonly CultCache _cache;
private readonly CultCache _scratch;
public FacilityProductionTests()
{
Directory.CreateDirectory(_root);
_cache = Open("catalog.cc");
_scratch = Open("scratch.cc");
Add(_cache);
}
public void Dispose()
{
_cache.Dispose();
_scratch.Dispose();
Directory.Delete(_root, true);
}
@ -62,18 +59,6 @@ public sealed class FacilityProductionTests : IDisposable
cache.Upsert(new CargoBayData { Name = "Pocket", Shape = new Shape(), InteriorShape = Solid(1, 1), Price = 5, Durability = 4 });
cache.Upsert(new SimpleCommodityData { Name = "Slag", Shape = new Shape(), Price = 1, MaxStack = 100 });
cache.Upsert(new ConsumableItemData { Name = "Facility Pill", Shape = new Shape(), Price = 1, Behaviors = { new FacilityData() } });
// The shipped facility gear carries GearData's unauthored thermal defaults (0 to 100, best at 50) while every station cell starts
// at 280, so a shipped facility is not Active (ThermalOnline) on a station that is not kept warm: a catalog fact this cut does
// not write. The fixture's station has no heater and cools toward 0, so its private copy of the catalog gives facility gear a
// band that holds every temperature a cell reaches, and the cycle rule is what these tests read.
foreach (var facility in cache.GetAll<GearData>().Where(StationKinds.IsRecipeFacility).ToArray())
{
facility.MinimumTemperature = -1000;
facility.MaximumTemperature = 1000;
facility.OptimalTemperature = 0;
facility.PlateauWidth = 1000;
cache.Upsert(facility);
}
}
private sealed class World
@ -345,4 +330,92 @@ public sealed class FacilityProductionTests : IDisposable
var error = Assert.Throws<InvalidOperationException>(() => new ConsumableItemEffect(pill, world.Station));
Assert.Contains("Facility Pill", error.Message);
}
// The shipped catalog as it boots, a shipped station hull with no heater, the shipped Refinery on its Facility row: an hour of sim
// time (the station's cells cool toward 0 meanwhile) turns 15 ore into 5 cycles of iron, one cycle fewer than the hour holds.
[Fact]
public void TheShippedRefineryRunsAnHourOnAHeaterlessShippedStation()
{
using var shipped = Open("shipped.cc");
var items = new ItemManager(1u, shipped, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { });
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
var station = new OrbitalEntity(items, zone, Mint(items, shipped, "Zenith"), default, new EntitySettings());
Assert.True(station.TryEquip(Mint(items, shipped, "Refinery")));
var bay = shipped.GetAll<CargoBayData>().Where(data => !(data is DockingBayData)).OrderByDescending(data => data.InteriorShape.Coordinates.Length).ThenBy(data => data.Name, StringComparer.Ordinal).First();
Assert.True(station.TryEquip(Mint(items, shipped, bay.Name)));
Assert.DoesNotContain(station.Equipment.Select(equipped => equipped.Data), data => data is GearData gear && gear.Behaviors.Any(behavior => behavior is HeatData));
zone.Admit(station, piloted: false);
var world = Wrap(items, zone, station);
// An ore only iron takes, so no other recipe competes for it in the round robin.
var others = shipped.GetAll<RecipeData>().SelectMany(recipe => Recipes.RoleInputsOf(shipped, recipe)).Select(role => role.Name).Where(role => role != "iron ore").Distinct();
var ore = Recipes.Fillers(shipped, "iron ore").Except(others.SelectMany(role => Recipes.Fillers(shipped, role))).First();
var maxStack = items.MaxStack(Goods(ore, 1));
for (var left = 15; left > 0; left -= maxStack) Assert.True(station.CargoBays[0].TryStore(Goods(ore, Math.Min(left, maxStack))));
Step(world, StepsOf(3600));
Assert.Equal(10, world.Hold.Held(new CultRecordKey("commodity:iron")));
Assert.Equal(0, world.Hold.Held(ore));
Assert.True(world.Station.Equipment.Single(equipped => equipped.Behaviors.Any(behavior => behavior is Facility)).Active.Value);
}
[Fact]
public void AnIdleFacilityTriesAgainWhenTheHoldChanges()
{
var world = Build();
Stock(world, IronFillers[0], 2);
Step(world, 3);
Assert.Equal(Stall.Inputs, world.Facility.Stall);
Assert.Null(world.Unit.Run);
Stock(world, IronFillers[0], 1);
Step(world, 1);
Assert.Equal(RecipeData.KeyOf(Iron), world.Unit.Run.Recipe.Key);
Assert.Equal(0, Held(world, IronFillers[0]));
}
// The bay's change count moves on every kind of change to its contents and on nothing else.
[Fact]
public void ABayCountsEveryChangeToWhatItHolds()
{
var world = Build();
var bay = world.Station.CargoBays[0];
var at = bay.Revision;
Assert.Equal(at, bay.Revision);
Assert.True(bay.TryStore(Goods("Slag", 5)));
Assert.True(bay.Revision > at);
at = bay.Revision;
Assert.True(bay.TryStore(Goods("Slag", 5)));
Assert.True(bay.Revision > at);
at = bay.Revision;
var stack = bay.Cargo.Keys.Single();
Assert.NotNull(bay.Remove(stack, 3));
Assert.True(bay.Revision > at);
at = bay.Revision;
Assert.Equal(7, bay.Count(((ItemInstance) stack).Data.Key));
Assert.Equal(at, bay.Revision);
bay.Remove(stack);
Assert.True(bay.Revision > at);
}
// Recipes.Fillers reads an index built once per catalog; it is rebuilt when a recipe changes.
[Fact]
public void FillersFollowTheCatalogThroughAChange()
{
var roles = _cache.GetAll<RecipeData>().SelectMany(recipe => recipe.Fills).Distinct().ToArray();
foreach (var role in roles)
{
var scan = _cache.GetAll<RecipeData>()
.Where(recipe => recipe.Fills.Contains(role) && Recipes.IsCommodity(_cache.Get(recipe.Output)))
.Select(recipe => recipe.Output.Key).OrderBy(key => key.Value, StringComparer.Ordinal).ToArray();
Assert.Equal(scan, Recipes.Fillers(_cache, role));
}
var slag = _cache.RefOf<ItemData>(_cache.GetByName<SimpleCommodityData>("Slag"));
Assert.DoesNotContain(slag.Key, Recipes.Fillers(_cache, "iron ore"));
_cache.Upsert(typeof(RecipeData), new RecipeData { Output = slag, Fills = { "iron ore" } }, RecipeData.KeyOf(slag.Key));
Assert.Contains(slag.Key, Recipes.Fillers(_cache, "iron ore"));
_cache.Remove(RecipeData.KeyOf(slag.Key));
Assert.DoesNotContain(slag.Key, Recipes.Fillers(_cache, "iron ore"));
Assert.Empty(Recipes.Fillers(_cache, "no such role"));
}
}