From 75e9d9690113fcc07956f606614d9a9f36fc8ee6 Mon Sep 17 00:00:00 2001 From: soul Date: Thu, 3 Dec 2026 00:37:52 +0100 Subject: [PATCH] Bays have one role set by their design; goods land only in bays of their role BayRole and CargoBayData.Role (by type), IngredientBayData and ProductBayData, SiloData is a product bay. StationWants reads Role: ingredient bays hold drawn goods in whole cells, product bays hold outputs and ordered goods, no fallback to every bay; Need and the IngredientCycles/ProductCycles knobs. LoadoutGenerator.FitRoleBays fits the role bays after FillInterior; gear stock goes to the Stock bays. IngredientShare, StockRoom and the first-non-silo gear pick are deleted. Facilities authors the two designs. Co-Authored-By: Claude Sonnet 5.5 --- Assets/Scripts/ServerShared/Entity.cs | 4 +- Assets/Scripts/ServerShared/ItemData.cs | 29 +++- .../Scripts/ServerShared/LoadoutGenerator.cs | 48 ++++-- Assets/Scripts/ServerShared/ScenarioStage.cs | 9 +- Assets/Scripts/ServerShared/StationWants.cs | 157 +++++++++++------- tools/AetherDb/Economy/Facilities.cs | 40 +++++ tools/AetherDb/EconomyDrain.cs | 6 +- 7 files changed, 209 insertions(+), 84 deletions(-) diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index fe7200c93..4faaa67ba 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -2467,8 +2467,8 @@ public class EquippedCargoBay : EquippedItem // Check whether the given item will fit when its origin is placed at the given coordinate public bool ItemFits(ItemInstance item, int2 cargoCoord) { - // A silo holds bulk only: gear, consumables and crafted sales never land in it. - if (Data is SiloData && !(item is ICommodityStack)) return false; + // An ingredient or product bay (a silo is one) holds bulk only: gear, consumables and crafted sales never land in it. + if (Data.Role != BayRole.Stock && !(item is ICommodityStack)) return false; var itemData = ItemManager.GetData(item); // Check every cell of the item's shape foreach (var i in itemData.Shape.Coordinates) diff --git a/Assets/Scripts/ServerShared/ItemData.cs b/Assets/Scripts/ServerShared/ItemData.cs index f084cdf30..6df547b55 100644 --- a/Assets/Scripts/ServerShared/ItemData.cs +++ b/Assets/Scripts/ServerShared/ItemData.cs @@ -479,6 +479,28 @@ public class CargoBayData : EquippableItemData public Shape InteriorShape; [IgnoreMember] public override HardpointType HardpointType => HardpointType.Tool; + + // What the bay is for, the design's and never an instance's (ruling station-bays-by-category): read from the type, the way HardpointType is. + // A plain cargo bay is the general hold; the role bays hold commodity stacks only. + [IgnoreMember] public virtual BayRole Role => BayRole.Stock; +} + +// A cargo bay's role (ruling station-bays-by-category): Stock holds anything (ship holds, a station's gear stock), Ingredients holds +// the goods a station's facilities and crew draw, Products the goods it makes and the goods its haul orders name. +public enum BayRole { Stock, Ingredients, Products } + +// A bay for what a station's facilities and crew draw (StationWants). Commodity stacks only. +[CultDocument("aetheria.ingredientbaydata", "1"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class IngredientBayData : CargoBayData +{ + [IgnoreMember] public override BayRole Role => BayRole.Ingredients; +} + +// A bay for what a station's facilities make and what its haul orders name (StationWants). Commodity stacks only. +[CultDocument("aetheria.productbaydata", "1"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class ProductBayData : CargoBayData +{ + [IgnoreMember] public override BayRole Role => BayRole.Products; } [CultDocument("aetheria.dockingbaydata", "1"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] @@ -488,11 +510,10 @@ public class DockingBayData : CargoBayData public int2 MaxSize; } -// A silo: bulk storage seated on a Facility row (idea stations-gear-map.one-mount-for-station-gear). It is a cargo bay that holds -// commodity stacks only, so gear, consumables and crafted sales never land in it; what a station buys for one is its haul -// orders' goods (StationWants). +// A silo: a product bay seated on a Facility row (idea stations-gear-map.one-mount-for-station-gear), listed by the kinds that +// carry it. Commodity stacks only, so gear, consumables and crafted sales never land in it. [CultDocument("aetheria.silodata", "1"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] -public class SiloData : CargoBayData +public class SiloData : ProductBayData { [IgnoreMember] public override HardpointType HardpointType => HardpointType.Facility; } diff --git a/Assets/Scripts/ServerShared/LoadoutGenerator.cs b/Assets/Scripts/ServerShared/LoadoutGenerator.cs index d6a9fa29b..ed221b00a 100644 --- a/Assets/Scripts/ServerShared/LoadoutGenerator.cs +++ b/Assets/Scripts/ServerShared/LoadoutGenerator.cs @@ -21,9 +21,9 @@ public class LoadoutGenerator // station draws 1 to the maximum. public const float StationConsumableChance = .25f; public const int StationConsumableUnits = 2; - // The share of a station's stock bay its generated gear may fill; the rest stays free for what the station buys (rulings - // no-market-absorption, station-intake-few-sorties). A first value of a sim-tuned knob (economy-numbers-are-sim-tuned-knobs): - // follow-up economy-balance-station-drain tunes it. + // The share of a station's Stock bays its generated gear may fill; pawned gear lands in the rest (ruling pawn-stock-in-stock-bay-share, + // read as the gear-stock bays), and what the station buys never does: that goes to its ingredient and product bays (ruling + // station-bays-by-category). A first value of a sim-tuned knob (economy-numbers-are-sim-tuned-knobs). public const float StationStockShare = .5f; public const float ShipConsumableChance = .1f; public const int ShipConsumableUnits = 1; @@ -138,18 +138,19 @@ public class LoadoutGenerator throw new InvalidLoadoutException("Failed to equip selected heater!"); FillInterior(entity); + FitRoleBays(entity); // The consumable goes in before the gear stock: sixteen gear picks drawn with replacement can fill a real hold, // and a roll that hit must leave the entity holding one (the ruled rate is the rule). With no consumable on // offer nothing is drawn here, so the gear draws are exactly what they were. StockConsumables(entity, StationConsumableChance, StationConsumableUnits); - // The gear stock goes to the first bay that is not a silo and stops short of StationStockShare of its cells, so a - // station's hold keeps room for what it buys (ruling no-market-absorption). All sixteen picks are still drawn, so no - // random stream moves; only storing stops. - var cargo = entity.CargoBays.First(bay => !(bay.Data is SiloData)); - var stockCells = (int) (cargo.Data.InteriorShape.Coordinates.Length * StationStockShare); - var stocked = cargo.Data.InteriorShape.Coordinates.Count(cell => cargo.Occupancy[cell.x, cell.y] != null); + // The gear stock goes to the Stock bays and stops short of StationStockShare of their cells together, so the rest stays free + // for pawned gear (ruling pawn-stock-in-stock-bay-share). All sixteen picks are still drawn, so no random stream moves; + // only storing stops. + var stockBays = entity.CargoBays.Where(bay => bay.Data.Role == BayRole.Stock).ToArray(); + var stockCells = (int) (stockBays.Sum(bay => bay.Data.InteriorShape.Coordinates.Length) * StationStockShare); + var stocked = stockBays.Sum(bay => bay.Data.InteriorShape.Coordinates.Count(cell => bay.Occupancy[cell.x, cell.y] != null)); var inventory = RandomProducts(16, 1, data => !(data is HullData hull && hull.HullType != HullType.Ship) && !(data is CargoBayData)) .OrderByDescending(entry => entry.design.Shape.Coordinates.Length); @@ -158,7 +159,7 @@ public class LoadoutGenerator var instance = ItemManager.CreateInstance(entry.product); var cells = entry.design.Shape.Coordinates.Length; if (stocked + cells > stockCells) continue; - if (cargo.TryStore(instance)) stocked += cells; + if (stockBays.Any(bay => bay.TryStore(instance))) stocked += cells; } entity.CanTow = hullData.CanTow; @@ -402,6 +403,31 @@ public class LoadoutGenerator } } + // Fits the ingredient bays then the product bays the station needs (StationWants.Need), one role bay at a time, into the interior + // FillInterior left. The bay is the role's design (the catalog's, its product by InstalledProduct): no Random draw. A bay that does not + // fit is a hull fault, named. + // + // CONJURE (ruling economy-is-never-faked): like EquipFacilities, every station is handed bays from a not-offered product no facility + // makes. Interim scaffolding, deleted with follow-up conjuring-site-deletions once bays come from production. + private void FitRoleBays(Entity entity) + { + var hullName = ItemManager.GetData(entity.Hull).Name; + foreach (var (role, type) in new[] { (BayRole.Ingredients, typeof(IngredientBayData)), (BayRole.Products, typeof(ProductBayData)) }) + { + var design = ItemManager.ItemData.GetAll().Where(bay => bay.GetType() == type).OrderBy(bay => bay.Name, StringComparer.Ordinal).FirstOrDefault(); + var need = StationWants.Need(entity, role); + while (need > 0 && entity.CargoBays.Where(bay => bay.Data.Role == role).Sum(bay => bay.Data.InteriorShape.Coordinates.Length) < need) + { + var product = design == null ? null : InstalledProduct(design); + if (product == null || !entity.TryEquip(ItemManager.CreateInstance(product) as EquippableItem)) + { + var cells = entity.CargoBays.Where(bay => bay.Data.Role == role).Sum(bay => bay.Data.InteriorShape.Coordinates.Length); + throw new InvalidLoadoutException($"Station hull '{hullName}' has no room for a {role} bay: needs {need} cells, has {cells}."); + } + } + } + } + // The product an installed design is made through, which may be not offered: this faction's own when it has one, else the first by // name. Null when no product makes it. The one choice of product for gear that is installed rather than drawn. private FactionProductData InstalledProduct(EquippableItemData design) @@ -463,7 +489,7 @@ public class LoadoutGenerator var emptyShape = entity.UnoccupiedSpace; var (cargoProduct, cargoData) = RandomProduct(3, item => - !(item is DockingBayData) && !(item is SiloData) && + !(item is DockingBayData) && item.Role == BayRole.Stock && item.Shape.FitsWithin(emptyShape, out _, out _), required: true); if (cargoData == null) throw new InvalidLoadoutException("No compatible cargo bay found for entity!"); diff --git a/Assets/Scripts/ServerShared/ScenarioStage.cs b/Assets/Scripts/ServerShared/ScenarioStage.cs index 2580c629b..a7879bba6 100644 --- a/Assets/Scripts/ServerShared/ScenarioStage.cs +++ b/Assets/Scripts/ServerShared/ScenarioStage.cs @@ -162,7 +162,7 @@ public class ZoneStage placement.Knows = target; } - // Items in the entity's first cargo bay, one per name. A name is an equippable or consumable design (open: the stage + // Items in the entity's first cargo bay (a station's commodities in the bays it lands them), one per name. A name is an equippable or consumable design (open: the stage // chooses its product) or a product of one (pinned), or a commodity (one unit: the crates an AmmoType weapon reloads // from); a name that is none of these is a failure. public void Cargo(Entity entity, params string[] names) @@ -176,7 +176,12 @@ public class ZoneStage var commodity = _items.ItemData.GetAll().FirstOrDefault(data => data.Name == name); if (commodity != null) { - if (bay == null || !bay.TryStore(new SimpleCommodity { Data = new CultRecordRef(_items.ItemData.RefOf(commodity).Key), Quantity = 1 })) + // A commodity staged into a station lands where the station would put it (StationWants.Bays: the demo fabricator's opening + // powder and nitrate reach its ingredient bays); a ship, or a good the station does not want, keeps the first bay. + var key = _items.ItemData.RefOf(commodity).Key; + var landing = StationWants.Bays(entity, key).ToArray(); + var part = new SimpleCommodity { Data = new CultRecordRef(key), Quantity = 1 }; + if (landing.Length > 0 ? !landing.Any(into => into.TryStore(part)) : bay == null || !bay.TryStore(part)) _failures.Add($"{where}: no room for {name}"); continue; } diff --git a/Assets/Scripts/ServerShared/StationWants.cs b/Assets/Scripts/ServerShared/StationWants.cs index 00e5248a2..cf6d2c7b4 100644 --- a/Assets/Scripts/ServerShared/StationWants.cs +++ b/Assets/Scripts/ServerShared/StationWants.cs @@ -6,22 +6,25 @@ using MessagePack; using Newtonsoft.Json; // What a station buys (aetheria-living-world:ruling:installed-gear-decides-what-a-station-buys): the goods its installed -// recipe facilities draw, the goods its installed habitation modules' tables name (the crew eats), and, when it carries a silo, -// the goods of the haul orders that start at its orbit (ruling transit-depots-buy-for-onward-haul). Derived on every call from the station's gear and the catalog, stored nowhere. -// StationServices.TrySellPart is gated by it and limited by the bays' room. +// recipe facilities draw, the goods its installed habitation modules' tables name (the crew eats), and, when it has a product bay, the +// goods of the haul orders that start at its orbit (ruling transit-depots-buy-for-onward-haul). Derived on every call from the station's +// gear and the catalog, stored nowhere. StationServices.TrySellPart is gated by it and limited by the bays' room. // -// Where goods land and how much of a product a station holds (cut facility-output-room). A station with a silo keeps what its -// facilities make there, and each product holds an even share of the silo: Allocation, floor(silo cells / products) x the -// product's MaxStack (a good a haul order names has a share of the silo as a product has). A recipe starts only when its product has room (CanStart), and a station draws an ore only while some recipe -// that takes it can start, so a full product stops its ores being bought while the station keeps running its other recipes. Prior -// art: X4's per-ware storage allocation (a full ware stops that production, the station keeps running the rest) and Factorio's -// per-product output slot. A station with no silo has no bound on outputs: they land in any bay and Room happens at the put. +// Where goods land (ruling station-bays-by-category): every bay has one role, its design's (CargoBayData.Role). Drawn and crew goods +// land only in the Ingredients bays; outputs and ordered goods only in the Products bays (a silo is one); gear and pawned goods never +// pass through here, they are the Stock bays'. A station with outputs and no product bay has no room for them. // -// How much of a drawn good a station holds (ruling stations-buy-ingredients-to-target-share): the other half of the same division of -// the hold. The stock bays' cells are shared among the ingredients of the installed recipes in proportion to the rate the facilities -// consume them (Holding), so no one ingredient arriving first can fill the bays and starve its partners; each stops being wanted at -// its share. Prior art: X4 allots storage per ware for what a station buys as for what it makes, and an order-up-to level per input -// is the inventory-control form of a cap on each input. Allocation is the output side, Holding the input side. +// How much of a product a station holds (cut facility-output-room): each product holds an even share of the product bays, Allocation, +// floor(product cells / products) x the product's MaxStack (a good a haul order names has a share as a product has). A recipe starts only +// when its product has room (CanStart), and a station draws an ore only while some recipe that takes it can start, so a full product stops +// its ores being bought while the station keeps running its other recipes. Prior art: X4's per-ware storage allocation (a full ware stops +// that production, the station keeps running the rest) and Factorio's per-product output slot. +// +// How much of a drawn good a station holds (ruling stations-buy-ingredients-to-target-share): the other half of the same division. The +// ingredient bays' cells are shared among the ingredients of the installed recipes in proportion to the rate the facilities consume them +// (Holding), whole cells per good, so no one ingredient arriving first can fill the bays and starve its partners; each stops being wanted +// at its share. How many cells of each role a generated station gets is Need, applied by LoadoutGenerator.FitRoleBays. Prior art: X4 allots +// storage per ware for what a station buys as for what it makes, and an order-up-to level per input is the inventory-control form of a cap. public static class StationWants { public static IReadOnlyCollection Of(Entity station) @@ -31,10 +34,12 @@ public static class StationWants return wants; } - // Where a bought or delivered good may land and how much of it: the non-silo bays, up to the good's Holding less what the station - // holds of it, when an installed recipe facility draws it (a drawn good is stock, never silo content); the silo bays, up to the - // good's share of the silo (Room), when the station wants it through a haul order (a transit depot holds goods in its silo, never - // in its stock bay). The one owner of where a good lands and how much; none when the station does not want it. + // The bays of a role. + public static IEnumerable RoleBays(Entity station, BayRole role) => station.CargoBays.Where(bay => bay.Data.Role == role); + + // Where a bought or delivered good may land and how much of it: the ingredient bays, up to the good's Holding less what they hold of + // it, when the station draws it; the product bays, up to the good's share (Room), when the station wants it through a haul order. + // The one owner of where a good lands and how much; none when the station does not want it. public static IEnumerable<(IReadOnlyList Bays, int Room)> Landing(Entity station, CultRecordKey good) => LandingOf(station, Drawn(station), Holding(station), Ordered(station).ToHashSet(), good); @@ -42,8 +47,11 @@ public static class StationWants IReadOnlyDictionary holding, HashSet ordered, CultRecordKey good) { if (drawn.Contains(good)) - yield return (station.CargoBays.Where(bay => !(bay.Data is SiloData)).ToArray(), Math.Max(0, holding[good] - station.CargoBays.Sum(bay => bay.Count(good)))); - if (ordered.Contains(good)) yield return (station.CargoBays.Where(bay => bay.Data is SiloData).ToArray(), Room(station, good)); + { + var bays = RoleBays(station, BayRole.Ingredients).ToArray(); + yield return (bays, Math.Max(0, holding[good] - bays.Sum(bay => bay.Count(good)))); + } + if (ordered.Contains(good)) yield return (RoleBays(station, BayRole.Products).ToArray(), Room(station, good)); } // Of the goods, those the station would take a unit of now: it wants the good (Landing), has room for it and a bay with a place for a @@ -59,28 +67,24 @@ public static class StationWants public static IEnumerable Bays(Entity station, CultRecordKey good) => Landing(station, good).SelectMany(landing => landing.Bays); - // The bays a facility's output may land in: the silo bays when the station has one, else every bay. The one owner of where - // a facility output lands. - public static IEnumerable OutputBays(Entity station, CultRecordKey good) => - station.CargoBays.Any(bay => bay.Data is SiloData) ? station.CargoBays.Where(bay => bay.Data is SiloData) : station.CargoBays; + // The bays a facility's output may land in: the product bays, none else. The one owner of where a facility output lands. + public static IEnumerable OutputBays(Entity station, CultRecordKey good) => RoleBays(station, BayRole.Products); - // The units of a good the station may hold in its silo: the silo's cells divided evenly among the distinct goods that land there, - // the outputs of its recipe facilities and the goods of its haul orders, each share worth that many full stacks of the good. Null - // (no bound) without a silo or a recipe facility (a depot with no facility holds what its orders name). Derived on every call, - // stored nowhere. + // The units of a good the station may hold in its product bays: their cells divided evenly among the distinct goods that land there, + // the outputs of its recipe facilities and the goods of its haul orders, each share worth that many full stacks of the good. Null (no + // bound) when no recipe facility makes anything (a depot holds what its orders name); 0 when it makes goods and has no product bay. + // Derived on every call, stored nowhere. public static int? Allocation(Entity station, CultRecordKey good) { - var silos = station.CargoBays.Where(bay => bay.Data is SiloData).ToArray(); - if (silos.Length == 0) return null; var outputs = Makes(station); if (outputs.Count == 0) return null; var slots = outputs.Concat(Ordered(station)).Distinct().Count(); - var cells = silos.Sum(bay => bay.Data.InteriorShape.Coordinates.Length); + var cells = RoleBays(station, BayRole.Products).Sum(bay => bay.Data.InteriorShape.Coordinates.Length); var stack = station.ItemManager.ItemData.Get(good)?.MaxStack ?? 0; return cells / slots * stack; } - // The units of a good that may still be stored in the silo: its share less what the output bays hold, int.MaxValue with no bound. + // The units of a good that may still be stored in the product bays: its share less what they hold, int.MaxValue with no bound. // The one decision of room: a recipe starts on it (CanStart, EntityHold.Room) and a sale of an ordered good stops at it. public static int Room(Entity station, CultRecordKey good) { @@ -130,65 +134,94 @@ 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' 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; + // How many stacks of one good's per-cycle draw a generated station's ingredient bays hold, and how many cycles of each product its + // product bays hold: balance knobs (ruling economy-numbers-are-sim-tuned-knobs), beside LoadoutGenerator.StationStockShare. + public const int IngredientCycles = 2; + public const int ProductCycles = 2; - // 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 cells of a role a station needs, the one measure FitRoleBays fits to. A cell holds one stack of one good, so each good takes at + // least one cell. Ingredients: per drawn good, the more of its floor and IngredientCycles x the units one combined cycle of the installed + // run lists takes of it, in cells of its stack, plus one cell per good only the crew's table names. Products: per made good, the more + // of one cell and ProductCycles x the units one combined cycle makes, in cells. Stock needs none. Derived on every call. + public static int Need(Entity station, BayRole role) + { + var catalog = station.ItemManager.ItemData; + if (role == BayRole.Ingredients) + { + var (floors, _, units) = Slots(station); + var cells = floors.Sum(floor => Math.Max(FloorCellsOf(catalog, floor.Key, floor.Value), (int) Math.Ceiling(IngredientCycles * units[floor.Key] / Stack(catalog, floor.Key) - 1e-9))); + return cells + CrewOnly(station, floors).Count(); + } + if (role != BayRole.Products) return 0; + var made = new Dictionary(); + foreach (var run in FacilityRuns(station)) + foreach (var recipe in run) + made[recipe.Output.Key] = (made.TryGetValue(recipe.Output.Key, out var count) ? count : 0) + recipe.OutputCount; + return made.Sum(good => Math.Max(1, (int) Math.Ceiling(ProductCycles * good.Value / Stack(catalog, good.Key) - 1e-9))); + } - // 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 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. + private static int FloorCellsOf(CultCache catalog, CultRecordKey good, int floor) => Math.Max(1, (int) Math.Ceiling(floor / (double) Stack(catalog, good) - 1e-9)); + + private static IEnumerable CrewOnly(Entity station, IReadOnlyDictionary floors) => Crew(station).Where(good => !floors.ContainsKey(good)).Distinct(); + + // The units of each drawn good the station will hold, the input side of the division of the hold, in whole cells of ingredient bay. + // 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 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 the cells of one cycle of + // the largest slot it fills (the floor, at least one cell); the cells left are divided by those parts, whole cells, so the shares together + // never exceed the ingredient bays' cells. A good only the crew's table names holds one cell. When the floors alone exceed the cells the + // hull is at fault: the shares are the floors (FloorCells reads the excess). Derived on every call, stored nowhere: a facility removed + // takes its shares with it. Stock above a share is kept (Room reads 0), never removed. public static IReadOnlyDictionary Holding(Entity station) { var catalog = station.ItemManager.ItemData; - var (floors, weights) = Slots(station); + var (floors, weights, _) = Slots(station); var total = weights.Values.Sum(); var holding = new Dictionary(); - var left = IngredientShare * StockRoom(station) - FloorCells(station, floors); + var left = BayCells(station) - FloorCells(station, floors) - CrewOnly(station, floors).Count(); 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; + var extra = left > 0 ? (int) Math.Floor(left * weights[good] / total + 1e-9) : 0; + holding[good] = (FloorCellsOf(catalog, good, floor) + extra) * Stack(catalog, good); } foreach (var good in Crew(station)) if (!holding.ContainsKey(good)) holding[good] = Stack(catalog, good); return holding; } + private static int BayCells(Entity station) => RoleBays(station, BayRole.Ingredients).Sum(bay => bay.Data.InteriorShape.Coordinates.Length); + private static int Stack(CultCache catalog, CultRecordKey good) => catalog.Get(good) is CompoundCommodityData compound ? compound.MaxStack : 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); + // The cells the floors and the crew's goods take: one cycle of each slot at least one cell per good. A hull whose floors exceed its + // ingredient cells cannot start a cycle of every slot at once. + public static int FloorCells(Entity station) + { + var floors = Slots(station).Floors; + return FloorCells(station, floors) + CrewOnly(station, floors).Count(); + } - private static double FloorCells(Entity station, IReadOnlyDictionary floors) => - floors.Sum(floor => (double) floor.Value / Stack(station.ItemManager.ItemData, floor.Key)); + private static int FloorCells(Entity station, IReadOnlyDictionary floors) => + floors.Sum(floor => FloorCellsOf(station.ItemManager.ItemData, floor.Key, floor.Value)); - // 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) + // Per drawn good of the installed recipe facilities: its floor (the largest count of a slot it fills), its weight (the sum, over the + // slots it can fill, of the slot's rate shared by that slot's fillers) and the units one combined cycle of every run list takes of it + // (the sum of its slots' counts, shared by their fillers). + private static (IReadOnlyDictionary Floors, IReadOnlyDictionary Weights, IReadOnlyDictionary Units) Slots(Entity station) { var catalog = station.ItemManager.ItemData; var floors = new Dictionary(); var weights = new Dictionary(); + var units = 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; + units[good] = (units.TryGetValue(good, out var taken) ? taken : 0) + (double) count / goods.Count; } } foreach (var run in FacilityRuns(station)) @@ -201,12 +234,12 @@ public static class StationWants foreach (var role in Recipes.RoleInputsOf(catalog, recipe)) Slot(role.Count / cycles, role.Count, Recipes.Fillers(catalog, role.Name)); } } - return (floors, weights); + return (floors, weights, units); } private static IEnumerable Ordered(Entity station) { - if (!(station is OrbitalEntity { OrbitData: var orbit }) || !orbit.IsSet() || !station.CargoBays.Any(bay => bay.Data is SiloData)) + if (!(station is OrbitalEntity { OrbitData: var orbit }) || !orbit.IsSet() || !station.CargoBays.Any(bay => bay.Data.Role == BayRole.Products)) return Enumerable.Empty(); return station.ItemManager.ItemData.GetAll().Where(order => order.From.Key.Equals(orbit)) .SelectMany(order => order.Goods.Select(good => good.Key)).ToArray(); diff --git a/tools/AetherDb/Economy/Facilities.cs b/tools/AetherDb/Economy/Facilities.cs index f9c234cbc..593b189ec 100644 --- a/tools/AetherDb/Economy/Facilities.cs +++ b/tools/AetherDb/Economy/Facilities.cs @@ -35,6 +35,14 @@ public sealed class Facilities : EconomyBatch private static readonly (string[] Kinds, string Id, string Name, string Description) Silo = (new[] { "trade-hub", "processing" }, "ore-silo", "Silo", "A sealed bulk store for the goods a station hauls or makes."); + // The role bays (ruling station-bays-by-category): every generated station is fitted the ingredient and product bays it needs + // (LoadoutGenerator.FitRoleBays). Plain crates, 1x1 on the hull with a 2x2 interior (four cells), each with a NotOffered product. + private static readonly (string Id, string Name, string Description, Func New)[] RoleBays = + { + ("ingredient", "Ingredient Bay", "A sealed crate for the goods a station's facilities and crew draw.", () => new IngredientBayData()), + ("product", "Product Bay", "A sealed crate for the goods a station's facilities make.", () => new ProductBayData()), + }; + // The kind's first facility design, or unset: the one lookup the recipe-writing batches use. public static CultRecordRef Of(CultCache catalog, string kindId) { @@ -83,6 +91,7 @@ public sealed class Facilities : EconomyBatch } AuthorSilo(author, catalog, (wanted, key) => Put(wanted, key)); + AuthorRoleBays(author, catalog, (wanted, key) => Put(wanted, key)); foreach (var kindKey in kinds.Concat(Silo.Kinds.Select(id => StationKindData.KeyOf(id).Value)).Distinct(StringComparer.Ordinal)) { var kind = catalog.Get(new CultRecordKey(kindKey)) ?? throw new InvalidOperationException($"Station kind '{kindKey}' is not in the catalog."); @@ -146,4 +155,35 @@ public sealed class Facilities : EconomyBatch Manufacturer = new CultRecordRef(maker.Key), NotOffered = true }, new CultRecordKey("product:facility:" + id)); } + + // The two role bay designs and their NotOffered products, each only where it differs, compared by fields as the silo is. + private static void AuthorRoleBays(EconomyAuthor author, CultCache catalog, Action put) + { + var shape = new Shape(1, 1); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var interior = new Shape(2, 2); + foreach (var cell in interior.AllCoordinates) interior[cell] = true; + var maker = MakerOf(catalog, StationKindData.KeyOf(Silo.Kinds[0]).Value); + foreach (var (id, name, description, create) in RoleBays) + { + var designKey = new CultRecordKey("bay:" + id); + var type = create().GetType(); + if (!(catalog.Get(designKey) is CargoBayData held && held.GetType() == type && held.Name == name && held.Description == description + && held.Durability == 20 && held.Mass == 20 && held.Price == 50 && held.Shape.Width == 1 && held.Shape.Height == 1 && held.Shape.Coordinates.Length == 1 + && held.InteriorShape.Width == 2 && held.InteriorShape.Height == 2 && held.InteriorShape.Coordinates.Length == 4 + && held.MinimumTemperature == ThermalMin && held.MaximumTemperature == ThermalMax && held.OptimalTemperature == ThermalOptimal && held.PlateauWidth == ThermalPlateau)) + { + var design = create(); + design.Name = name; design.Description = description; design.Shape = shape; design.InteriorShape = interior; + design.Durability = 20; design.Mass = 20; design.Price = 50; + design.MinimumTemperature = ThermalMin; design.MaximumTemperature = ThermalMax; design.OptimalTemperature = ThermalOptimal; design.PlateauWidth = ThermalPlateau; + author.Put(design, designKey); + } + put(new FactionProductData + { + Name = $"{maker.Faction.Name} {name}", Description = description, Design = new CultRecordRef(designKey), + Manufacturer = new CultRecordRef(maker.Key), NotOffered = true + }, new CultRecordKey("product:bay:" + id)); + } + } } diff --git a/tools/AetherDb/EconomyDrain.cs b/tools/AetherDb/EconomyDrain.cs index 49b9a807e..76c21231d 100644 --- a/tools/AetherDb/EconomyDrain.cs +++ b/tools/AetherDb/EconomyDrain.cs @@ -16,7 +16,7 @@ using GameCult.Caching; public sealed class BayIntake { public string Name; - public bool Silo; + public BayRole Role; public int Cells, Free; // Units of wanted ore the bay holds after the fill. public int Taken; @@ -246,7 +246,7 @@ public static class EconomyDrain { output.WriteLine($" {station.Role} {station.Name} ({station.Kind})"); foreach (var bay in station.Bays) - output.WriteLine($" bay {bay.Name} | {(bay.Silo ? "silo" : "stock")} | cells {bay.Cells} | free {bay.Free} | ore units at MaxStack: {(bay.Capacity.Count == 0 ? "none wanted" : string.Join("; ", bay.Capacity.GroupBy(c => c.Units).Select(g => $"{g.Key} each of {string.Join(", ", g.Select(c => c.Ore))}")))} | wanted ore held after the fill: {bay.Taken}"); + output.WriteLine($" bay {bay.Name} | {bay.Role.ToString().ToLowerInvariant()} | cells {bay.Cells} | free {bay.Free} | ore units at MaxStack: {(bay.Capacity.Count == 0 ? "none wanted" : string.Join("; ", bay.Capacity.GroupBy(c => c.Units).Select(g => $"{g.Key} each of {string.Join(", ", g.Select(c => c.Ore))}")))} | wanted ore held after the fill: {bay.Taken}"); output.WriteLine(station.Sorties.Count == 0 ? " sorties to fill: none (no usable sortie)" : $" sorties to fill: {station.Sorties.Count}{(station.Filled ? "" : "+ (the station took the whole hold of the last one or the cap on sorties ended it)")} | per sortie (hold as mined | wanted sold refused): {string.Join("; ", station.Sorties.Select(s => $"{s.Hold} | {s.Held} {s.Sold} {s.Refused}"))}"); @@ -299,7 +299,7 @@ public static class EconomyDrain var shape = bay.Data.InteriorShape; var cells = shape.AllCoordinates.Count(v => shape[v]); var used = shape.AllCoordinates.Count(v => shape[v] && bay.Occupancy[v.x, v.y] != null); - var intake = new BayIntake { Name = bay.Name, Silo = bay.Data is SiloData, Cells = cells, Free = cells - used }; + var intake = new BayIntake { Name = bay.Name, Role = bay.Data.Role, Cells = cells, Free = cells - used }; var at = station.CargoBays.ToList().IndexOf(bay); foreach (var ore in ores) {