diff --git a/Assets/Scripts/ServerShared/StationWants.cs b/Assets/Scripts/ServerShared/StationWants.cs index cb228d1fa..3fd6077db 100644 --- a/Assets/Scripts/ServerShared/StationWants.cs +++ b/Assets/Scripts/ServerShared/StationWants.cs @@ -130,47 +130,77 @@ public static class StationWants .SelectMany(unit => unit.Behaviors.Select(behavior => behavior.Data).OfType()) .SelectMany(habitation => habitation.Table.Where(row => row.Commodity.IsSet()).Select(row => row.Commodity.Key)); - // The share of the stock bays' cells that the facility ingredients may fill together: a balance knob (ruling + // The share of the stock bays' room, after the gear stock, that the facility ingredients may fill together: a balance knob (ruling // economy-numbers-are-sim-tuned-knobs), beside LoadoutGenerator.StationStockShare, which is the gear stock's. public const float IngredientShare = 1.0f; + // The stock bays' cells that gear (anything that is not a commodity stack) does not occupy: the room the ingredients divide. + public static int StockRoom(Entity station) => + station.CargoBays.Where(bay => !(bay.Data is SiloData)) + .Sum(bay => bay.Data.InteriorShape.Coordinates.Count(cell => bay.Occupancy[cell.x, cell.y] == null || bay.Occupancy[cell.x, cell.y] is ICommodityStack)); + // The units of each drawn good the station will hold, the input side of the division of the hold. Every installed recipe facility // unit consumes round-robin over its run list, so each slot of each recipe (an Input, an Upkeep, a role) is taken at count / (sum of - // the list's cycles); a role slot is taken from any one of its fillers, so each filler may fill the whole slot. W is the sum of the - // slot rates, and a good holds IngredientShare of the stock cells in MaxStack units, times the part of W its slots carry, never - // less than the largest count of a slot it fills (one cycle can always start). A good only the crew's table names holds one stack. - // Derived on every call, stored nowhere: a facility removed takes its shares with it. Held is counted over every bay, so a product - // the station also consumes counts toward its share, and stock above a share is kept (Room reads 0), never removed. + // the list's cycles). A role slot is one slot: its rate is shared evenly by the goods that can fill it, so the shares of a good are the + // part of W (the sum of the slot rates) its slots carry. Every good first holds one cycle of the largest slot it fills (Floor), so + // a cycle can always start; the rest of IngredientShare x StockRoom, in MaxStack units, is divided by those parts, so the shares + // together never exceed the target. When the floors alone exceed it the hull is at fault: the shares are the floors (FloorCells + // reads the excess). A good only the crew's table names holds one stack. Derived on every call, stored nowhere: a facility removed + // takes its shares with it. Held is counted over every bay, so a product the station also consumes counts toward its share, and + // stock above a share is kept (Room reads 0), never removed. public static IReadOnlyDictionary Holding(Entity station) { var catalog = station.ItemManager.ItemData; - var slots = new List<(double Rate, int Count, IReadOnlyCollection Goods)>(); + var (floors, weights) = Slots(station); + var total = weights.Values.Sum(); + var holding = new Dictionary(); + var left = IngredientShare * StockRoom(station) - FloorCells(station, floors); + foreach (var (good, floor) in floors) + { + // The share is a ratio of whole numbers: a quotient that is 8 to the last digit must not floor to 7. + var extra = left > 0 ? (int) Math.Floor(left * Stack(catalog, good) * weights[good] / total + 1e-9) : 0; + holding[good] = floor + extra; + } + foreach (var good in Crew(station)) + if (!holding.ContainsKey(good)) holding[good] = Stack(catalog, good); + return holding; + } + + private static int Stack(CultCache catalog, CultRecordKey good) => catalog.Get(good)?.MaxStack ?? 1; + + // The cells the floors take: each good's one-cycle floor in MaxStack units. A hull whose floors exceed its stock room cannot start a cycle + // of every slot at once. + public static double FloorCells(Entity station) => FloorCells(station, Slots(station).Floors); + + private static double FloorCells(Entity station, IReadOnlyDictionary floors) => + floors.Sum(floor => (double) floor.Value / Stack(station.ItemManager.ItemData, floor.Key)); + + // Per drawn good of the installed recipe facilities: its floor (the largest count of a slot it fills) and its weight (the sum, over the + // slots it can fill, of the slot's rate shared by that slot's fillers). + private static (IReadOnlyDictionary Floors, IReadOnlyDictionary Weights) Slots(Entity station) + { + var catalog = station.ItemManager.ItemData; + var floors = new Dictionary(); + var weights = new Dictionary(); + void Slot(double rate, int count, IReadOnlyCollection goods) + { + foreach (var good in goods) + { + floors[good] = Math.Max(floors.TryGetValue(good, out var floor) ? floor : 0, count); + weights[good] = (weights.TryGetValue(good, out var weight) ? weight : 0) + rate / goods.Count; + } + } foreach (var run in FacilityRuns(station)) { var cycles = run.Sum(recipe => (double) recipe.Cycle); if (cycles <= 0) continue; foreach (var recipe in run) { - foreach (var input in recipe.Inputs.Concat(recipe.Upkeep)) - slots.Add((input.Count / cycles, input.Count, new[] { input.Commodity.Key })); - foreach (var role in Recipes.RoleInputsOf(catalog, recipe)) - slots.Add((role.Count / cycles, role.Count, Recipes.Fillers(catalog, role.Name))); + foreach (var input in recipe.Inputs.Concat(recipe.Upkeep)) Slot(input.Count / cycles, input.Count, new[] { input.Commodity.Key }); + foreach (var role in Recipes.RoleInputsOf(catalog, recipe)) Slot(role.Count / cycles, role.Count, Recipes.Fillers(catalog, role.Name)); } } - var cells = station.CargoBays.Where(bay => !(bay.Data is SiloData)).Sum(bay => bay.Data.InteriorShape.Coordinates.Length); - var total = slots.Sum(slot => slot.Rate); - var holding = new Dictionary(); - int Stack(CultRecordKey good) => catalog.Get(good)?.MaxStack ?? 1; - foreach (var good in slots.SelectMany(slot => slot.Goods).Distinct()) - { - var fills = slots.Where(slot => slot.Goods.Contains(good)).ToArray(); - // The share is a ratio of whole numbers: a quotient that is 8 to the last digit must not floor to 7. - var share = (int) Math.Floor(IngredientShare * cells * Stack(good) * fills.Sum(slot => slot.Rate) / total + 1e-9); - holding[good] = Math.Max(share, fills.Max(slot => slot.Count)); - } - foreach (var good in Crew(station)) - if (!holding.ContainsKey(good)) holding[good] = Stack(good); - return holding; + return (floors, weights); } private static IEnumerable Ordered(Entity station) diff --git a/tests/Aetheria.Shared.Tests/EconomyDrainTests.cs b/tests/Aetheria.Shared.Tests/EconomyDrainTests.cs index a8baf4a4e..810b68a33 100644 --- a/tests/Aetheria.Shared.Tests/EconomyDrainTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyDrainTests.cs @@ -51,14 +51,14 @@ public sealed class EconomyDrainTests // The sortie rig after Boot was lifted out of it, on the shipped catalog, read at the commit before the extraction; re-read at the authored starter // (131/73/58, 1295, 131 mined at the generated one): Light Lasers on the Energy mounts instead of the seed-1 draw. What the refinery buys of the - // 120 mined units is its shares of the stock bay (cut stationwants-ingredient-share): 37 sold and 83 refused (971 credits: the shares let the dear ores land that a Nickel-Iron intake crowded out, - // against 72 sold and 970 unbounded); the mined units and the sortie's time are the rig's own and did not move. + // 120 mined units is its shares of the stock room the gear stock leaves (cut stationwants-ingredient-share): 10 sold and 110 refused for 851 + // credits, against 72 sold for 970 with an unbounded intake; the mined units and the sortie's time are the rig's own and did not move. [Fact] public void SortieOutputUnchangedByBoot() { var sample = Seed1.Value.Single(); - Assert.Equal((120, 37, 83), (sample.Units, sample.UnitsSold, sample.UnitsRefused)); - Assert.Equal(971, sample.SellValue); + Assert.Equal((120, 10, 110), (sample.Units, sample.UnitsSold, sample.UnitsRefused)); + Assert.Equal(851, sample.SellValue); Assert.Equal(150, sample.SimSeconds, 3); Assert.Equal(120, sample.Mined.Sum(m => m.Units)); } diff --git a/tests/Aetheria.Shared.Tests/StationWantsTests.cs b/tests/Aetheria.Shared.Tests/StationWantsTests.cs index adfe74b08..26acb8b62 100644 --- a/tests/Aetheria.Shared.Tests/StationWantsTests.cs +++ b/tests/Aetheria.Shared.Tests/StationWantsTests.cs @@ -278,12 +278,21 @@ public sealed partial class RunStartTests // A ratio of whole numbers that is 8 to the last digit floors to 8. private static int Floored(double share) => (int) Math.Floor(share + 1e-9); - private static int StockCells(Entity station) => - station.CargoBays.Where(bay => !(bay.Data is SiloData)).Sum(bay => bay.Data.InteriorShape.Coordinates.Length); + // A good's floor (the largest count of a slot it fills) and its weight (the slots' rates, each shared by the slot's fillers), from the slots above. + private static (int Floor, double Weight) FloorAndWeight(List<(double Rate, int Count, CultRecordKey[] Goods)> slots, CultRecordKey good) + { + var fills = slots.Where(slot => slot.Goods.Contains(good)).ToArray(); + return (fills.Max(slot => slot.Count), fills.Sum(slot => slot.Rate / slot.Goods.Length)); + } - // The proportional share of a good before the floor, from the slots read above. - private double Proportional(Entity station, List<(double Rate, int Count, CultRecordKey[] Goods)> slots, CultRecordKey good) => - StationWants.IngredientShare * StockCells(station) * MaxStack(good) * slots.Where(slot => slot.Goods.Contains(good)).Sum(slot => slot.Rate) / slots.Sum(slot => slot.Rate); + // What a good holds by the rule, worked out here from the catalog: its floor, and its weight's part of what the floors leave of the target. + private int Expected(Entity station, List<(double Rate, int Count, CultRecordKey[] Goods)> slots, CultRecordKey good) + { + var goods = slots.SelectMany(slot => slot.Goods).Distinct().ToArray(); + var left = StationWants.IngredientShare * StationWants.StockRoom(station) - goods.Sum(other => (double) FloorAndWeight(slots, other).Floor / MaxStack(other)); + var (floor, weight) = FloorAndWeight(slots, good); + return floor + (left > 0 ? Floored(left * MaxStack(good) * weight / slots.Sum(slot => slot.Rate)) : 0); + } // Puts exactly `units` of the good in the station's stock bays, after taking out what is there. private static void Hold(Entity station, CultRecordKey good, int units) @@ -334,33 +343,26 @@ public sealed partial class RunStartTests Assert.Equal(SaleRefusal.NoRoom, StationServices.TrySellPart(hold, refinery, left, ref credits).Refusal); } - // The split is by the rate the installed recipes consume each slot at: every drawn good holds its slots' part of the stock cells, so the - // iron ore Steel takes three to one over the other inputs holds three times what they do, and the two metal roles add their fillers' slots. + // The split is by the rate the installed recipes consume each slot at: after its one-cycle floor, every drawn good holds its slots' part of what + // the floors leave of the target, so the ore Steel takes three to one over the others holds more of it, and a role's fillers share the role's part. [Fact] public void TheShareFollowsTheRecipesSlots() { var refinery = DemoStation("processing"); var slots = SlotsOf(refinery); + // The generated gear stock leaves the shipped refinery next to no room over its floors, so the split is read with the gear put away. + foreach (var bay in refinery.CargoBays) + foreach (var gear in bay.Cargo.Keys.Where(item => !(item is ICommodityStack)).ToList()) bay.Remove(gear); var holding = StationWants.Holding(refinery); Assert.Equal(slots.SelectMany(slot => slot.Goods).Distinct().OrderBy(good => good.Value, StringComparer.Ordinal), holding.Keys.OrderBy(good => good.Value, StringComparer.Ordinal)); - foreach (var good in holding.Keys) - { - var count = slots.Where(slot => slot.Goods.Contains(good)).Max(slot => slot.Count); - Assert.Equal(Math.Max(Floored(Proportional(refinery, slots, good)), count), holding[good]); - } - // Two goods whose shares are above their floors hold units in the ratio of their slot rates, to a unit of rounding. - var free = holding.Keys.Where(good => Floored(Proportional(refinery, slots, good)) > slots.Where(slot => slot.Goods.Contains(good)).Max(slot => slot.Count)).ToArray(); - Assert.True(free.Length >= 2, $"{free.Length} goods above their floor"); - var most = free.OrderByDescending(good => Proportional(refinery, slots, good)).First(); - var least = free.OrderBy(good => Proportional(refinery, slots, good)).First(); - Assert.True(Proportional(refinery, slots, most) > 1.5 * Proportional(refinery, slots, least), "the split is not even"); - Assert.True(holding[most] > holding[least]); + foreach (var good in holding.Keys) Assert.Equal(Expected(refinery, slots, good), holding[good]); + var extra = holding.Keys.ToDictionary(good => good, good => holding[good] - FloorAndWeight(slots, good).Floor); + Assert.True(extra.Values.Max() > 2 * Math.Max(1, extra.Values.Where(units => units > 0).Min()), "the split is not even"); } - // A role slot may be filled by any one of its fillers, so each filler may fill the whole slot: the fillers of a role that fill nothing - // else all hold the slot's own share. + // A role slot is one slot, not one per filler: the fillers of a role that fill nothing else hold the same, each its even part of the slot's rate. [Fact] - public void ARoleFillerHoldsItsRolesShare() + public void ARoleFillerHoldsItsPartOfTheRole() { var refinery = DemoStation("processing"); var slots = SlotsOf(refinery); @@ -371,43 +373,58 @@ public sealed partial class RunStartTests var alone = slot.Goods.Where(good => slots.Count(other => other.Goods.Contains(good)) == 1).ToArray(); if (alone.Length < 2) continue; checkedRoles++; - var own = Math.Max(Floored(StationWants.IngredientShare * StockCells(refinery) * MaxStack(alone[0]) * slot.Rate / slots.Sum(other => other.Rate)), slot.Count); - Assert.All(alone, good => Assert.Equal(own, holding[good])); + Assert.All(alone, good => Assert.Equal(holding[alone[0]], holding[good])); + Assert.Equal(Expected(refinery, slots, alone[0]), holding[alone[0]]); } Assert.True(checkedRoles > 0, "no role slot has two fillers that fill nothing else"); } - // Every slot can start a cycle: a good holds at least the most any slot it fills takes. No shipped facility has enough slots to push a - // proportional share under one cycle, so the catalog is edited (a recipe gains an input of 400 units a cycle) until some slots do. + // Every slot can start a cycle: a good holds at least the most any slot it fills takes, and on the shipped refinery the target leaves so + // little over the floors that some goods sit at theirs. [Fact] public void AShareIsAtLeastOneCycle() { var refinery = DemoStation("processing"); - void Holds(bool floorBinds) - { - var slots = SlotsOf(refinery); - var holding = StationWants.Holding(refinery); - var floored = 0; - foreach (var good in holding.Keys) - { - var count = slots.Where(slot => slot.Goods.Contains(good)).Max(slot => slot.Count); - Assert.True(holding[good] >= count, $"{_cache.Get(good).Name}: {holding[good]} held for a slot of {count}"); - if (Floored(Proportional(refinery, slots, good)) < count) - { - floored++; - Assert.Equal(count, holding[good]); - } - } - Assert.Equal(floorBinds, floored > 0); - } - Holds(floorBinds: false); + var slots = SlotsOf(refinery); + var holding = StationWants.Holding(refinery); + foreach (var good in holding.Keys) + Assert.True(holding[good] >= FloorAndWeight(slots, good).Floor, $"{_cache.Get(good).Name}: {holding[good]} held for a slot of {FloorAndWeight(slots, good).Floor}"); + Assert.Contains(holding.Keys, good => holding[good] == FloorAndWeight(slots, good).Floor); + } + // The shares together never exceed the target, IngredientShare of the stock room the gear stock leaves: in cells, whatever the room (gear + // put away widens it) and the shape of the slots. The first goods to arrive cannot fill a bay the shares overcommit. + [Fact] + public void SharesNeverSumAboveTheTarget() + { + var refinery = DemoStation("processing"); + double Cells() => StationWants.Holding(refinery).Where(share => SlotsOf(refinery).Any(slot => slot.Goods.Contains(share.Key))).Sum(share => (double) share.Value / MaxStack(share.Key)); + var room = StationWants.StockRoom(refinery); + Assert.True(room > 0); + Assert.True(Cells() <= StationWants.IngredientShare * room + 1e-9, $"{Cells()} cells of shares for a target of {StationWants.IngredientShare * room}"); + Assert.True(Cells() > StationWants.IngredientShare * room - 1.5, "the shares leave most of the target unused"); + foreach (var bay in refinery.CargoBays) + foreach (var gear in bay.Cargo.Keys.Where(item => !(item is ICommodityStack)).ToList()) bay.Remove(gear); + var wider = StationWants.StockRoom(refinery); + Assert.True(wider > room); + Assert.True(Cells() <= StationWants.IngredientShare * wider + 1e-9, $"{Cells()} cells of shares for a target of {StationWants.IngredientShare * wider}"); + Assert.True(Cells() > StationWants.IngredientShare * wider - 1.5); + } + + // A hull whose one-cycle floors exceed its stock room cannot start a cycle of every slot at once: FloorCells reads the excess, and the shares + // are the floors. The catalog is edited (a refinery recipe gains an input of 400 units a cycle) to make the shipped hull overflow. + [Fact] + public void FloorsBeyondTheRoomAreAHullFault() + { + var refinery = DemoStation("processing"); + Assert.True(StationWants.FloorCells(refinery) <= StationWants.StockRoom(refinery), $"the shipped refinery's floors take {StationWants.FloorCells(refinery)} of {StationWants.StockRoom(refinery)} cells"); var design = refinery.Equipment.Select(unit => _items.GetData(unit.EquippableItem)).Single(data => StationKinds.IsRecipeFacility(data)); var recipe = Production.RunList(_cache, _cache.RefOf(design).Key).First(candidate => candidate.Inputs.Count > 0); - var ballast = GoodNamed("Regolith"); - recipe.Inputs.Add(new CommodityCount { Commodity = new CultRecordRef(ballast), Count = 400 }); + recipe.Inputs.Add(new CommodityCount { Commodity = new CultRecordRef(GoodNamed("Regolith")), Count = 400 }); _cache.Upsert(typeof(RecipeData), recipe, RecipeData.KeyOf(recipe.Output.Key)); - Holds(floorBinds: true); + Assert.True(StationWants.FloorCells(refinery) > StationWants.StockRoom(refinery)); + var slots = SlotsOf(refinery); + Assert.All(StationWants.Holding(refinery), share => Assert.Equal(FloorAndWeight(slots, share.Key).Floor, share.Value)); } // One cap for every buyer: at its share a good is refused by the player's sale, the ore sale, a hauler's delivery and the hauler's door @@ -419,7 +436,7 @@ public sealed partial class RunStartTests var station = world.Refinery; var good = world.Good; var share = StationWants.Holding(station)[good]; - Assert.InRange(share, 2, 70); + Assert.InRange(share, 1, 70); var hold = world.Player.CargoBays[0]; var credits = 0; void Carry(EquippedCargoBay bay, int units) diff --git a/tools/AetherDb/EconomyDrain.cs b/tools/AetherDb/EconomyDrain.cs index b9984da00..49b9a807e 100644 --- a/tools/AetherDb/EconomyDrain.cs +++ b/tools/AetherDb/EconomyDrain.cs @@ -225,7 +225,9 @@ public static class EconomyDrain foreach (var facility in station.Facilities.Where(f => sample.Supplied && f.Saturated.Count > 0 && f.HorizonEnd == Stall.Room)) faults.Add(new EconomyFault(HSaturated, where, $"{facility.Name} ends the {sample.HorizonHours:0.##} h horizon stalled Room with {string.Join(", ", facility.Saturated)} at their share of the silo (first at {(station.FirstSaturated ?? 0) / 3600:0.##} h) and nothing taking them out: the station buys {station.WantedEnd} of the {station.WantedStart} goods it wanted and cannot use the ore it holds. Outflow is follow-up demo-fabricator-region and region-haul-legs.")); foreach (var facility in station.Facilities.Where(f => !(sample.Supplied && f.Saturated.Count > 0 && f.HorizonEnd == Stall.Room) && f.OresLeft.Count > 0 && (f.HorizonEnd == Stall.Room || f.HorizonEnd == Stall.Inputs))) - faults.Add(new EconomyFault(HStall, where, $"{facility.Name} ends the {sample.HorizonHours:0.##} h horizon stalled {facility.HorizonEnd} with {string.Join(", ", facility.OresLeft)} still held: the station does not drain what it took.")); + faults.Add(new EconomyFault(HStall, where, facility.HorizonEnd == Stall.Inputs + ? $"{facility.Name} ends the {sample.HorizonHours:0.##} h horizon stalled Inputs holding {string.Join(", ", facility.OresLeft)}: no recipe that takes them can start, because a partner input has not arrived (supply-bound; the station is not failing to drain)." + : $"{facility.Name} ends the {sample.HorizonHours:0.##} h horizon stalled {facility.HorizonEnd} with {string.Join(", ", facility.OresLeft)} still held: the station does not drain what it took.")); if (station.WindowDisagreements.Count > 0) faults.Add(new EconomyFault(HSim, where, $"the {sample.WindowSeconds:0.##} s window by steps and by spans disagree: {string.Join("; ", station.WindowDisagreements)}.")); }