diff --git a/Assets/Scripts/ServerShared/Behaviors/Facility.cs b/Assets/Scripts/ServerShared/Behaviors/Facility.cs index 90a663ae4..d882e2a8f 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Facility.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Facility.cs @@ -1,9 +1,10 @@ +using System.Collections.Generic; using MessagePack; using Newtonsoft.Json; // The facility gear a station carries to run recipes: a GearData of HardpointType Facility whose Behaviors hold one of these. The type // says where it mounts (a hull's Facility rows), this says it runs recipes. It holds no field of its own: which recipes a facility -// runs is derived from RecipeData.Facility, so no list is stored here. +// runs is derived from RecipeData.Facility, so no list is stored here. A facility is installed gear, never a consumable's effect. [Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] public class FacilityData : BehaviorData { @@ -13,15 +14,32 @@ public class FacilityData : BehaviorData } public override Behavior CreateInstance(ConsumableItemEffect item) { - return new Facility(this, item); + throw new System.InvalidOperationException($"{item.Data.Name} cannot carry a facility: a facility is installed gear, never a consumable effect."); } } -// The installed facility that will run its recipes (ruling demand-consumed-inputs-processed-by-facilities). It runs nothing until -// follow-up facility-production: LoadoutGenerator.EquipFacilities seats it on a station's Facility row, and it is priced and carried, -// and that is all. +// The installed facility (ruling demand-consumed-inputs-processed-by-facilities). It ticks once per zone step, from EquippedItem.Update +// while the item is active, and on screen only; an unloaded zone is frozen and the strategic tick (target r3 cut 8) calls the same +// Production.Advance for what is off screen. Its recipes are the run list of its design, fixed for a run because the catalog is. public class Facility : Behavior { - public Facility(FacilityData data, EquippedItem item) : base(data, item) { } - public Facility(FacilityData data, ConsumableItemEffect item) : base(data, item) { } + private readonly IReadOnlyList _runList; + private EntityHold _hold; + + // Why the facility advanced no further this step: derived by Advance every step, never stored on the unit. + public Stall Stall { get; private set; } + + public Facility(FacilityData data, EquippedItem item) : base(data, item) + { + _runList = Production.RunList(ItemManager.ItemData, Item.EquippableItem.Data.Key); + } + + public override bool Execute(float dt) + { + _hold ??= new EntityHold(Entity); + var (run, stall) = Production.Advance(ItemManager.ItemData, _runList, Item.EquippableItem.Run, dt, _hold); + Item.EquippableItem.Run = run; + Stall = stall; + return true; + } } diff --git a/Assets/Scripts/ServerShared/ItemInstance.cs b/Assets/Scripts/ServerShared/ItemInstance.cs index efb369964..6e94cc049 100644 --- a/Assets/Scripts/ServerShared/ItemInstance.cs +++ b/Assets/Scripts/ServerShared/ItemInstance.cs @@ -96,6 +96,10 @@ public class EquippableItem : CraftedItemInstance // it from the schematic UI; from then on PowerBus only ever reads it, never derives it. An old run store // missing key 12 deserializes to this same field initializer, so no migration is needed (ยง Cut 5). [JsonProperty("powerTier"), Key(12)] public int PowerTier = PowerTiers.Unassigned; + + // A facility's cycle in progress: per-unit installation state like PowerTier, null on everything but a facility that has started + // a cycle. Its one writer is Facility.Execute, storing Production.Advance's result. 13 is CompoundCommodity's, so 14. + [JsonProperty("run"), Key(14)] public FacilityRun Run; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/Production.cs b/Assets/Scripts/ServerShared/Production.cs new file mode 100644 index 000000000..36b354c2e --- /dev/null +++ b/Assets/Scripts/ServerShared/Production.cs @@ -0,0 +1,184 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using GameCult.Caching; +using MessagePack; +using Newtonsoft.Json; + +// A facility's cycle in progress, on the installed unit (EquippableItem.Run): the recipe it last ran or is running, and the sim +// seconds of the running cycle. Progress 0 is idle, and Recipe is then the round-robin cursor. Written only by Facility.Execute +// from Production.Advance's result; the inputs of a running cycle are already taken and live nowhere else. +[MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class FacilityRun +{ + [JsonProperty("recipe"), Key(0)] public CultRecordRef Recipe; + [JsonProperty("progress"), Key(1)] public double Progress; +} + +// Why a facility is not advancing, derived on each call and stored nowhere. +public enum Stall { None, Inputs, Room, Unrunnable } + +// Where a facility's goods are: its host's bays on screen, a stock ledger off screen. Each write is whole or nothing. +public interface IProductionHold +{ + int Held(CultRecordKey design); + bool TryTake(IReadOnlyList<(CultRecordKey design, int units)> units); + bool TryPut(CultRecordKey design, int units); +} + +// The one rule for a facility cycle: which recipe starts, which units it takes, how far it has run, what it stores. On screen its +// one caller is Facility.Execute, with one zone step; off screen the strategic tick calls it with a longer span. It reads no +// random, no clock and no crew. +public static class Production +{ + // A recipe a facility can run today: it takes something, and makes a simple commodity (a graded output needs a lot). + public static bool Runs(CultCache catalog, RecipeData recipe) => + !Recipes.IsRaw(catalog, recipe) && catalog.Get(recipe.Output) is SimpleCommodityData; + + // The recipes a facility design runs, in recipe-key order. Derived from the catalog, never stored. + public static IReadOnlyList RunList(CultCache catalog, CultRecordKey facilityDesign) => + Recipes.RunOn(catalog, facilityDesign).Where(recipe => Runs(catalog, recipe)).ToArray(); + + // The units one cycle of the recipe takes from the hold, summed per design: Inputs, then Upkeep, then each role slot filled + // greedily across Recipes.Fillers order. Null when the hold is short of any. + public static IReadOnlyList<(CultRecordKey design, int units)> Take(CultCache catalog, RecipeData recipe, IProductionHold hold) + { + var need = new List<(CultRecordKey design, int units)>(); + void Add(CultRecordKey design, int units) + { + var at = need.FindIndex(entry => entry.design.Equals(design)); + if (at < 0) need.Add((design, units)); + else need[at] = (design, need[at].units + units); + } + int Needed(CultRecordKey design) => need.Where(entry => entry.design.Equals(design)).Sum(entry => entry.units); + + foreach (var input in recipe.Inputs) Add(input.Commodity.Key, input.Count); + foreach (var upkeep in recipe.Upkeep) Add(upkeep.Commodity.Key, upkeep.Count); + if (need.Any(entry => hold.Held(entry.design) < entry.units)) return null; + + foreach (var role in Recipes.RoleInputsOf(catalog, recipe)) + { + var left = role.Count; + foreach (var filler in Recipes.Fillers(catalog, role.Name)) + { + var units = Math.Min(left, hold.Held(filler) - Needed(filler)); + if (units < 1) continue; + Add(filler, units); + left -= units; + if (left == 0) break; + } + if (left > 0) return null; + } + return need; + } + + // The facility's state after `seconds` of sim time, and why it is not advancing. An idle facility (run null or Progress 0) + // 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. + public static (FacilityRun run, Stall stall) Advance(CultCache catalog, IReadOnlyList runList, FacilityRun run, + double seconds, IProductionHold hold) + { + if (runList.Count == 0) return (run, Stall.Unrunnable); + while (true) + { + if (run == null || run.Progress <= 0) + { + if (seconds <= 0) return (run, Stall.None); + var cursor = run == null ? -1 : IndexOf(runList, run.Recipe.Key); + RecipeData start = null; + for (var step = 1; step <= runList.Count && start == null; step++) + { + var candidate = runList[(cursor + step + runList.Count) % runList.Count]; + var units = Take(catalog, candidate, hold); + if (units != null && hold.TryTake(units)) start = candidate; + } + if (start == null) return (run, Stall.Inputs); + run = new FacilityRun { Recipe = new CultRecordRef(RecipeData.KeyOf(start.Output.Key)), Progress = 0 }; + } + + var recipe = catalog.Get(run.Recipe); + var progress = run.Progress; + if (progress < recipe.Cycle) + { + var spent = Math.Min(seconds, recipe.Cycle - progress); + progress += spent; + seconds -= spent; + } + if (progress < recipe.Cycle) return (new FacilityRun { Recipe = run.Recipe, Progress = progress }, Stall.None); + if (!hold.TryPut(recipe.Output.Key, recipe.OutputCount)) + return (new FacilityRun { Recipe = run.Recipe, Progress = recipe.Cycle }, Stall.Room); + run = new FacilityRun { Recipe = run.Recipe, Progress = 0 }; + if (seconds <= 0) return (run, Stall.None); + } + } + + private static int IndexOf(IReadOnlyList runList, CultRecordKey recipe) + { + for (var at = 0; at < runList.Count; at++) + if (RecipeData.KeyOf(runList[at].Output.Key).Equals(recipe)) return at; + return -1; + } +} + +// An entity's bays as a production hold. Takes go bay by bay in cell order, so a take never depends on how the stacks came to +// lie; a take or a put that cannot finish puts everything back. +public sealed class EntityHold : IProductionHold +{ + private readonly Entity _entity; + + public EntityHold(Entity entity) => _entity = entity; + + public int Held(CultRecordKey design) => _entity.CargoBays.Sum(bay => bay.Count(design)); + + public bool TryTake(IReadOnlyList<(CultRecordKey design, int units)> units) + { + var taken = new List<(EquippedCargoBay bay, ItemInstance part, int2 origin)>(); + foreach (var (design, count) in units) + { + var left = count; + foreach (var bay in _entity.CargoBays) + { + var stacks = new List(); + foreach (var cell in bay.Data.InteriorShape.Coordinates) + { + var held = bay.Occupancy[cell.x, cell.y]; + if (held is ICommodityStack && held.Data.Key.Equals(design) && !stacks.Contains(held)) stacks.Add(held); + } + foreach (var stack in stacks) + { + if (left == 0) break; + var origin = bay.Cargo[stack]; + var part = bay.Remove(stack, Math.Min(left, ((ICommodityStack) stack).Quantity)); + taken.Add((bay, part, origin)); + left -= ((ICommodityStack) part).Quantity; + } + } + if (left == 0) continue; + for (var at = taken.Count - 1; at >= 0; at--) taken[at].bay.TryStore(taken[at].part, taken[at].origin); + return false; + } + return true; + } + + public bool TryPut(CultRecordKey design, int units) + { + var data = _entity.ItemManager.ItemData.Get(design); + var stored = 0; + for (var left = units; left > 0;) + { + var chunk = Math.Min(left, data.MaxStack); + var part = new SimpleCommodity { Data = new CultRecordRef(design), Quantity = chunk }; + if (!_entity.CargoBays.Any(bay => bay.TryStore(part))) + { + if (stored > 0) TryTake(new[] { (design, stored) }); + return false; + } + stored += chunk; + left -= chunk; + } + return true; + } +} diff --git a/Assets/Scripts/ServerShared/Production.cs.meta b/Assets/Scripts/ServerShared/Production.cs.meta new file mode 100644 index 000000000..c56d9203a --- /dev/null +++ b/Assets/Scripts/ServerShared/Production.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 450f5de3887646f385e4142c577202b7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Recipes.cs b/Assets/Scripts/ServerShared/Recipes.cs index 6b42b45fa..785ff3867 100644 --- a/Assets/Scripts/ServerShared/Recipes.cs +++ b/Assets/Scripts/ServerShared/Recipes.cs @@ -110,8 +110,8 @@ public class OutsideMarketRow [Key(5)] [CultElementId] public string Id = ""; } -// The one reader of recipes: which recipe makes a good, a recipe's role slots (RoleInputsOf), which commodities fill a role, and -// what a good is by its recipe. +// The one reader of recipes: which recipe makes a good, a recipe's role slots (RoleInputsOf), which commodities fill a role, which +// recipes a facility design runs (RunOn), and what a good is by its recipe. public static class Recipes { public static RecipeData RecipeOf(CultCache catalog, ItemData item) => @@ -147,4 +147,12 @@ public static class Recipes .Select(recipe => recipe.Output.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. + public static RecipeData[] RunOn(CultCache catalog, CultRecordKey facilityDesign) => + catalog.GetAll() + .Where(recipe => recipe.Facility.IsSet() && recipe.Facility.Key.Equals(facilityDesign)) + .OrderBy(recipe => RecipeData.KeyOf(recipe.Output.Key).Value, StringComparer.Ordinal) + .ToArray(); }