diff --git a/AGENTS.md b/AGENTS.md index 2422446..401b6d9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,6 +30,9 @@ ## Architecture +- UXAssist production calculations must use immutable snapshots captured from loaded Proto, PrefabDesc, and Cargo data on the game thread. Keep the planner and fixed-building analyzer pure-managed, express material rates in double items per minute and power in watts, and report unknown material and power results independently with structured diagnostics. Convert native ticks, fixed-point speeds, and per-second rates explicitly. Use native facility-specific production and power rules; keep generation, accumulator charging and discharging, and Dyson-sphere demand separate. Require explicit resource and operating settings when they cannot be captured. Verify native rules against the original DLL and compile affected mods; leave in-game validation to a person rather than automated gameplay or save parsing. See [production architecture](UXAssist/docs/ProductionArchitecture.md). +- Production catalog synthetic recipe IDs are calculation-only negative output item IDs; never pass them to native recipe lookups or setters. Rebuild the catalog on game begin after preload mutations, and invalidate derived caches on `ProductionCatalogService.Changed`, including catalog clearing. Preserve accumulator coating through exchange and bound spray reuse by same-item output and demand. Live-selection operating overrides use signed object IDs; blueprint overrides use blueprint indices. Keep renewable generation at ideal rated conditions and do not count gas collectors' self-fueling as grid consumption. +- CheatEnabler belt-signal upstream statistics use the shared production planner's independent production and consumption ledgers. Cache per-item material results by catalog and spray settings, keep separate per-belt fractional accumulators, and never run the solver in the logic tick. Missing data must not interrupt item generation. - UXAssist Dark Fog buy-out belt signals keep each item ID, per-Metaverse rate, localization key, and embedded icon path in one definition. Name embedded icon files after the current English item names and synchronize resource includes and loader paths when renaming them. Preserve the legacy signal and saved-stock order. Rates represent equivalent single-material value: a native bundle of 10 Silicon-based Neurons, 10 Negentropy Singularities, and 10 Matter Recombinators per Metaverse corresponds to 30 of any one selected material per Metaverse. - Tech downgrades must validate the full dependency cascade and capacity reductions before changing game state. Recompute non-invertible bonuses from native defaults and surviving levels; replaying unrelated unlock side effects can corrupt inventory geometry and station limits. - Custom critical-warning text must participate in both `WarningSystem.hasCriticalWarning` and `WarningSystem.UpdateCriticalWarningText`; preserve native warnings and use one shared display priority. diff --git a/CheatEnabler/Patches/Factory/BeltSignalPatch.cs b/CheatEnabler/Patches/Factory/BeltSignalPatch.cs index a5a6b9e..0d5211e 100644 --- a/CheatEnabler/Patches/Factory/BeltSignalPatch.cs +++ b/CheatEnabler/Patches/Factory/BeltSignalPatch.cs @@ -5,8 +5,8 @@ using HarmonyLib; using UnityEngine; using UXAssist.Common; using UXAssist.Common.ModFeatures; +using UXAssist.Production; using GameLogicProc = UXAssist.Common.GameLogic; -using UXAssist.Common.GameConstants; namespace CheatEnabler.Patches.Factory; @@ -18,15 +18,22 @@ internal class BeltSignalGenerator : PatchImpl private static Dictionary> _portalTo; private static int _signalBeltsCapacity; private static bool _initialized; + private static ProductionCatalog _sourceCatalog; + private static ProductionItem _preferredProliferator; + private static readonly Dictionary<(int itemId, bool proliferated, bool sprayed), + IReadOnlyList> SourceCache = []; + private static readonly HashSet<(int itemId, bool proliferated, bool sprayed)> FailedSources = []; public static void Init() { GameLogicProc.OnGameEnd += ResetState; + ProductionCatalogService.Changed += OnProductionCatalogChanged; } public static void Uninit() { GameLogicProc.OnGameEnd -= ResetState; + ProductionCatalogService.Changed -= OnProductionCatalogChanged; } private static void ResetState() @@ -36,6 +43,15 @@ internal class BeltSignalGenerator : PatchImpl _portalFrom = null; _portalTo = null; _signalBeltsCapacity = 0; + ClearSourceCache(); + } + + private static void ClearSourceCache() + { + _sourceCatalog = null; + _preferredProliferator = null; + SourceCache.Clear(); + FailedSources.Clear(); } private class BeltSignal @@ -45,8 +61,7 @@ internal class BeltSignalGenerator : PatchImpl public byte Stack; public byte Inc; public int Progress; - public (int itemId, float itemCount, bool isExtra)[] Sources; - public float[] SourceProgress; + public BeltSignalSourceStats SourceStats; } protected override void OnEnable() @@ -61,6 +76,7 @@ internal class BeltSignalGenerator : PatchImpl _initialized = false; _signalBelts = null; _signalBeltsCapacity = 0; + ClearSourceCache(); } internal static void OnAltFormatChanged() @@ -97,12 +113,38 @@ internal class BeltSignalGenerator : PatchImpl } internal static void OnUseProliferatorChanged() + { + ClearSourceCache(); + RefreshSourceStats(true); + } + + private static void OnProductionCatalogChanged() + { + ClearSourceCache(); + RefreshSourceStats(false); + } + + private static void RefreshSourceStats(bool resetGenerationProgress) { if (_signalBelts == null) return; + if (ProductionCatalogService.Current == null) + { + foreach (var belts in _signalBelts) + { + if (belts == null) continue; + foreach (var belt in belts.Values) + { + belt.SourceStats = null; + if (resetGenerationProgress) belt.Progress = 0; + } + } + + return; + } + var factories = GameMain.data?.factories; if (factories == null) return; var factoryCount = GameMain.data.factoryCount; - var altFormat = FactoryPatch.BeltSignalNumberAltFormat.Value; for (var i = Math.Min(_signalBelts.Length, factoryCount) - 1; i >= 0; i--) { var factory = factories[i]; @@ -118,9 +160,8 @@ internal class BeltSignalGenerator : PatchImpl ref var belt = ref cargoTraffic.beltPool[beltId]; if (belt.id != beltId) continue; var signalBelt = pair.Value; - signalBelt.Progress = 0; - signalBelt.Sources = null; - signalBelt.SourceProgress = null; + if (resetGenerationProgress) signalBelt.Progress = 0; + signalBelt.SourceStats = null; AddSourcesToBeltSignal(signalBelt); } } @@ -129,7 +170,6 @@ internal class BeltSignalGenerator : PatchImpl private static void InitSignalBelts() { if (DSPGame.IsMenuDemo) return; - InitItemSources(); _signalBelts = new Dictionary[64]; _signalBeltsCapacity = 64; _portalFrom = []; @@ -231,14 +271,19 @@ internal class BeltSignalGenerator : PatchImpl var signalBelts = GetOrCreateSignalBelts(factory); if (signalBelts.TryGetValue(beltId, out var oldBeltSignal)) { - if (oldBeltSignal.SignalId == signalId && oldBeltSignal.SpeedLimit == speedLimit && oldBeltSignal.Stack == stack && oldBeltSignal.Inc == inc) return; + if (oldBeltSignal.SignalId == signalId && oldBeltSignal.SpeedLimit == speedLimit && + oldBeltSignal.Stack == stack && oldBeltSignal.Inc == inc) + { + if (!ReferenceEquals(_sourceCatalog, ProductionCatalogService.Current)) + AddSourcesToBeltSignal(oldBeltSignal); + return; + } oldBeltSignal.SpeedLimit = speedLimit; oldBeltSignal.Stack = (byte)stack; oldBeltSignal.Inc = (byte)inc; oldBeltSignal.Progress = 0; oldBeltSignal.SignalId = signalId; - oldBeltSignal.Sources = null; - oldBeltSignal.SourceProgress = null; + oldBeltSignal.SourceStats = null; AddSourcesToBeltSignal(oldBeltSignal); return; } @@ -256,61 +301,59 @@ internal class BeltSignalGenerator : PatchImpl private static void AddSourcesToBeltSignal(BeltSignal beltSignal) { + beltSignal.SourceStats = null; var itemId = beltSignal.SignalId; - if (itemId < 1000) return; - var result = new Dictionary(); - var extra = new Dictionary(); - var sprayedCount = 0f; - CalculateAllProductions(result, extra, ref sprayedCount, itemId); - - var proliferatorCount = 0f; - if (result.TryGetValue(ItemIds.ProliferatorMkIII, out var pv)) + if (itemId < 1000 || beltSignal.Stack == 0) return; + var catalog = ProductionCatalogService.Current; + if (!ReferenceEquals(_sourceCatalog, catalog)) { - proliferatorCount = pv; - result.Remove(ItemIds.ProliferatorMkIII); - } - if (FactoryPatch.BeltSignalUseProliferatorEnabled.Value) - { - if (beltSignal.Inc / beltSignal.Stack >= 4) - { - sprayedCount += 1f; - } - if (sprayedCount > 0) - { - proliferatorCount += sprayedCount / ProliferatorSpayCount; - } - } - if (proliferatorCount > 0f) - { - foreach (var p in ItemIds.ProliferatorSources) - { - result[p.Item1] = (result.TryGetValue(p.Item1, out var v) ? v : 0) + p.Item2 * proliferatorCount / ProliferatorDenom; - } + ClearSourceCache(); + _sourceCatalog = catalog; + _preferredProliferator = BeltSignalSourcePreset.SelectProliferator(catalog); } - result.Remove(itemId); - - var cnt = result.Count + extra.Count; - if (cnt == 0) + var proliferated = FactoryPatch.BeltSignalUseProliferatorEnabled.Value; + var sprayed = proliferated && _preferredProliferator != null && + beltSignal.Inc / beltSignal.Stack >= _preferredProliferator.ProliferationLevel; + var key = (itemId, proliferated, sprayed); + if (catalog == null) { - beltSignal.Sources = null; - beltSignal.SourceProgress = null; + LogSourceFailure(key, "Production data is not loaded."); return; } - var items = new (int itemId, float itemCount, bool isExtra)[cnt]; - var progress = new float[cnt]; - foreach (var p in extra) + if (FailedSources.Contains(key)) return; + if (!SourceCache.TryGetValue(key, out var rates)) { - items[--cnt] = (p.Key, p.Value, true); - } - foreach (var p in result) - { - items[--cnt] = (p.Key, p.Value, false); + try + { + var request = BeltSignalSourcePreset.Create(catalog, itemId, proliferated, sprayed); + var report = new ProductionPlanner(catalog).Calculate(request); + if (!report.MaterialComplete) + { + LogSourceFailure(key, string.Join("; ", report.Diagnostics.Select(diagnostic => diagnostic.Message))); + return; + } + + rates = BeltSignalSourceStats.FromReport(report, itemId); + } + catch (Exception exception) + { + LogSourceFailure(key, exception.ToString()); + return; + } + + SourceCache[key] = rates; } - beltSignal.Sources = items; - beltSignal.SourceProgress = progress; + if (rates.Count > 0) beltSignal.SourceStats = new BeltSignalSourceStats(rates); + } + + private static void LogSourceFailure((int itemId, bool proliferated, bool sprayed) key, string reason) + { + if (FailedSources.Add(key)) + CheatEnabler.Logger.LogWarning( + $"Belt signal upstream statistics for item {key.itemId} are suspended: {reason}"); } private static void SetSignalBeltPortalTo(int factory, int beltId, int number) @@ -570,26 +613,7 @@ internal class BeltSignalGenerator : PatchImpl if (hasSpeedLimit) beltSignal.Progress -= 3600; if (FactoryPatch.BeltSignalCountGenEnabled.Value) productRegister[signalId] += stack; if (!countRecipe) continue; - var sources = beltSignal.Sources; - if (sources == null) continue; - var progress = beltSignal.SourceProgress; - var stackf = (float)stack; - for (var i = sources.Length - 1; i >= 0; i--) - { - var newCnt = progress[i] + sources[i].itemCount * stackf; - if (newCnt > 0) - { - var itemId = sources[i].itemId; - var cnt = Mathf.CeilToInt(newCnt); - productRegister[itemId] += cnt; - if (!sources[i].isExtra) consumeRegister[itemId] += cnt; - progress[i] = newCnt - cnt; - } - else - { - progress[i] = newCnt; - } - } + beltSignal.SourceStats?.Apply(stack, productRegister, consumeRegister); continue; } @@ -612,179 +636,4 @@ internal class BeltSignalGenerator : PatchImpl ProcessBeltSignals(); } - /* BEGIN: Item sources calculation */ - // Item ID constants are provided by UXAssist.Common.GameConstants.ItemIds. - private const float ProliferatorDenom = 21f; - // One sprayed proliferator mk.III can spray 75 items, but one is used for spray itself, so the actual count is 74 - private const float ProliferatorSpayCount = 74f; - private static readonly Dictionary ItemSources = []; - private static bool _itemSourcesInitialized; - - private class ItemSource - { - public float Count; - public Dictionary From; - public Dictionary Extra; - } - - private static void InitItemSources() - { - if (_itemSourcesInitialized) return; - foreach (var vein in LDB.veins.dataArray) - { - ItemSources[vein.MiningItem] = new ItemSource { Count = 1 }; - } - - foreach (var ip in LDB.items.dataArray) - { - if (!string.IsNullOrEmpty(ip.MiningFrom)) - { - ItemSources[ip.ID] = new ItemSource { Count = 1 }; - } - } - - // Water, sulfuric acid, hydrogen, deuterium, photons - foreach (var itemId in ItemIds.ExtraOreItemIds) - { - ItemSources[itemId] = new ItemSource { Count = 1 }; - } - - var recipes = LDB.recipes.dataArray; - foreach (var recipe in recipes) - { - if (!recipe.Explicit || recipe.ID == 58 || recipe.ID == 121) continue; - var res = recipe.Results; - var rescnt = recipe.ResultCounts; - var len = res.Length; - for (var i = 0; i < len; i++) - { - if (ItemSources.ContainsKey(res[i])) continue; - var rs = new ItemSource { Count = rescnt[i], From = [] }; - var it = recipe.Items; - var itcnt = recipe.ItemCounts; - var len2 = it.Length; - for (var j = 0; j < len2; j++) - { - rs.From[it[j]] = itcnt[j]; - } - - if (len > 1) - { - rs.Extra = []; - for (var k = 0; k < len; k++) - { - if (i != k) - { - rs.Extra[res[k]] = rescnt[k]; - } - } - } - - ItemSources[res[i]] = rs; - } - } - - foreach (var recipe in recipes) - { - if (recipe.Explicit) continue; - var res = recipe.Results; - var rescnt = recipe.ResultCounts; - var len = res.Length; - for (var i = 0; i < len; i++) - { - if (ItemSources.ContainsKey(res[i])) continue; - var rs = new ItemSource { Count = rescnt[i], From = [], Extra = null }; - var it = recipe.Items; - var itcnt = recipe.ItemCounts; - var len2 = it.Length; - for (var j = 0; j < len2; j++) - { - rs.From[it[j]] = itcnt[j]; - } - - if (len > 1) - { - rs.Extra = []; - for (var k = 0; k < len; k++) - { - if (i != k) - { - rs.Extra[res[k]] = rescnt[k]; - } - } - } - - ItemSources[res[i]] = rs; - } - } - - _itemSourcesInitialized = true; - } - - private static void CalculateAllProductions(IDictionary result, IDictionary extra, ref float sprayedCount, int itemId, float count = 1f) - { - if (!ItemSources.TryGetValue(itemId, out var itemSource)) - { - return; - } - - var times = 1f; - if (Math.Abs(count - itemSource.Count) > 0.000001f) - { - times = count / itemSource.Count; - } - - result[itemId] = (result.TryGetValue(itemId, out var oldCount) ? oldCount : 0) + count; - if (itemSource.Extra != null) - { - foreach (var p in itemSource.Extra) - { - extra[p.Key] = (extra.TryGetValue(p.Key, out oldCount) ? oldCount : 0) + times * p.Value; - } - } - - if (itemId == ItemIds.ProliferatorMkIII || itemSource.From == null) return; - var useProliferator = FactoryPatch.BeltSignalUseProliferatorEnabled.Value; - if (useProliferator && ItemIds.ExtraProliferationItemIds.Contains(itemId)) - { - times *= 0.8f; - } - foreach (var p in itemSource.From) - { - var value = p.Value * times; - if (useProliferator && !ItemIds.NoProliferationItemIds.Contains(p.Key)) sprayedCount += value; - if (extra.TryGetValue(p.Key, out var rcount)) - { - if (value <= rcount) - { - if (value == rcount) - { - extra.Remove(p.Key); - } - else - { - extra[p.Key] = rcount - value; - } - continue; - } - extra.Remove(p.Key); - value -= rcount; - } - if (result.TryGetValue(p.Key, out rcount)) - { - rcount -= value; - if (rcount <= 0) - { - result.Remove(p.Key); - } - else - { - result[p.Key] = rcount; - } - continue; - } - CalculateAllProductions(result, extra, ref sprayedCount, p.Key, value); - } - } - /* END: Item sources calculation */ } diff --git a/CheatEnabler/Patches/Factory/BeltSignalSourceStats.cs b/CheatEnabler/Patches/Factory/BeltSignalSourceStats.cs new file mode 100644 index 0000000..21167fe --- /dev/null +++ b/CheatEnabler/Patches/Factory/BeltSignalSourceStats.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UXAssist.Common.GameConstants; +using UXAssist.Production; + +namespace CheatEnabler.Patches.Factory; + +internal readonly struct BeltSignalSourceRate +{ + public int ItemId { get; } + public double ProductionPerItem { get; } + public double ConsumptionPerItem { get; } + + public BeltSignalSourceRate(int itemId, double productionPerItem, double consumptionPerItem) + { + ItemId = itemId; + ProductionPerItem = productionPerItem; + ConsumptionPerItem = consumptionPerItem; + } +} + +internal sealed class BeltSignalSourceStats +{ + private readonly double[] _productionProgress; + private readonly double[] _consumptionProgress; + + public IReadOnlyList Rates { get; } + + public BeltSignalSourceStats(IReadOnlyList rates) + { + Rates = rates; + _productionProgress = new double[rates.Count]; + _consumptionProgress = new double[rates.Count]; + } + + public static IReadOnlyList FromReport(ProductionReport report, int targetItemId) + { + if (report == null || !report.MaterialComplete) + throw new InvalidOperationException("A complete material report is required for belt statistics."); + + var rates = new List(); + foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId)) + { + var produced = flow.GrossProduction + flow.ExternalImports - + (flow.ItemId == targetItemId ? flow.Delivered : 0); + var consumed = flow.GrossConsumption; + if (!ValidRate(produced) || !ValidRate(consumed)) + throw new InvalidOperationException("The production report contains an invalid belt statistics rate."); + if (produced > 0 || consumed > 0) + rates.Add(new BeltSignalSourceRate(flow.ItemId, Math.Max(0, produced), consumed)); + } + + return Array.AsReadOnly(rates.ToArray()); + } + + public void Apply(int stack, int[] productRegister, int[] consumeRegister) + { + for (var index = 0; index < Rates.Count; index++) + { + var rate = Rates[index]; + Accumulate(rate.ProductionPerItem, stack, ref _productionProgress[index], + productRegister, rate.ItemId); + Accumulate(rate.ConsumptionPerItem, stack, ref _consumptionProgress[index], + consumeRegister, rate.ItemId); + } + } + + private static bool ValidRate(double rate) + { + return rate >= -1e-7 && rate < int.MaxValue / 4.0 && + !double.IsNaN(rate) && !double.IsInfinity(rate); + } + + private static void Accumulate(double rate, int stack, ref double progress, int[] register, int itemId) + { + if (rate <= 0) return; + var total = progress + rate * stack; + if (total <= 0) + { + progress = total; + return; + } + + var count = (int)Math.Ceiling(total); + register[itemId] += count; + progress = total - count; + } +} + +internal static class BeltSignalSourcePreset +{ + public static ProductionItem SelectProliferator(ProductionCatalog catalog) + { + return catalog?.Items.Values.Where(item => item.ProliferationLevel > 0 && item.SpraysPerItem > 0) + .OrderByDescending(item => item.ProliferationLevel) + .ThenByDescending(item => item.SpraysPerItem) + .ThenBy(item => item.Id).FirstOrDefault(); + } + + public static ProductionPlanRequest Create(ProductionCatalog catalog, int itemId, + bool useProliferator, bool sprayDeliveredItem) + { + var request = new ProductionPlanRequest + { + ProliferationEnabled = useProliferator, + ProliferatorItemId = useProliferator ? SelectProliferator(catalog)?.Id ?? 0 : 0, + SelfSprayProliferator = useProliferator + }; + request.Targets.Add(new ProductionTarget(itemId, 1)); + foreach (var externalItemId in ItemIds.ExtraOreItemIds) + { + if (catalog.Items.ContainsKey(externalItemId)) request.ExternalMaterials.Add(externalItemId); + } + + if (!useProliferator) return request; + if (sprayDeliveredItem) request.SprayDeliveredItems.Add(itemId); + foreach (var item in catalog.Items.Values) + { + if (!catalog.Recipes.TryGetValue(item.DefaultRecipeId, out var recipe) || + !recipe.Outputs.ContainsKey(item.Id) || recipe.Inputs.Count == 0) continue; + request.ProliferationModeByItem[item.Id] = ItemIds.NoProliferationItemIds.Contains(item.Id) + ? ProliferationMode.None + : ItemIds.ExtraProliferationItemIds.Contains(item.Id) && recipe.Productive + ? ProliferationMode.ExtraProducts : ProliferationMode.Speedup; + } + + return request; + } +} diff --git a/UXAssist/Common/GameConstants/ItemIds.cs b/UXAssist/Common/GameConstants/ItemIds.cs index 038f68a..1c41adb 100644 --- a/UXAssist/Common/GameConstants/ItemIds.cs +++ b/UXAssist/Common/GameConstants/ItemIds.cs @@ -78,6 +78,7 @@ public static class ItemIds public const int HydrogenFuelRod = 6001; public const int DeuteronFuelRod = 6002; public const int AntimatterFuelRod = 6003; + public const int StrangeAnnihilationFuelRod = 1804; public const int StrangeMatter = 6004; public const int Foundation = 6005; public const int Metaverse = 6006; // also called property/meta-data item diff --git a/UXAssist/Production/AccumulatorExchangeAdapter.cs b/UXAssist/Production/AccumulatorExchangeAdapter.cs new file mode 100644 index 0000000..693a67c --- /dev/null +++ b/UXAssist/Production/AccumulatorExchangeAdapter.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UXAssist.Production; + +public sealed class AccumulatorExchangeAdapter : IProductionProcessAdapter +{ + public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building) + { + return recipe?.Category == ProductionRecipeCategory.Exchange || + recipe == null && building?.Kind == ProductionBuildingKind.Exchanger; + } + + public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building, + ProliferationMode mode, int level, IReadOnlyDictionary operatingParameters, + out ProductionProcess process, out ProductionDiagnostic diagnostic) + { + process = null; + diagnostic = null; + if (building != null && building.Kind != ProductionBuildingKind.Exchanger) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding, + "This building cannot charge or discharge accumulators.", recipeId: recipe?.Id ?? 0, + buildingItemId: building.ItemId); + return false; + } + + if (mode != ProliferationMode.None && mode != ProliferationMode.Speedup) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "Accumulator exchange supports native speedup only.", recipeId: recipe?.Id ?? 0); + return false; + } + + var speedBonus = 0.0; + if (mode != ProliferationMode.None && + (level <= 0 || !catalog.TryGetProliferation(level, out speedBonus, out _, out _))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "The accumulator proliferation level is unavailable.", recipeId: recipe?.Id ?? 0); + return false; + } + + var state = 0; + if (recipe != null) + { + if (recipe.Inputs.Count != 1 || recipe.Outputs.Count != 1 || + recipe.Inputs.Single().Value != 1 || recipe.Outputs.Single().Value != 1) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, + "Accumulator exchange requires one empty/full item conversion.", recipeId: recipe.Id); + return false; + } + + var inputId = recipe.Inputs.Single().Key; + var outputId = recipe.Outputs.Single().Key; + state = building == null || inputId == building.EmptyAccumulatorItemId && + outputId == building.FullAccumulatorItemId ? 1 : + inputId == building.FullAccumulatorItemId && + outputId == building.EmptyAccumulatorItemId ? -1 : 0; + if (state == 0) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The exchanger's accumulator items do not match the recipe.", recipeId: recipe.Id); + return false; + } + } + else if (operatingParameters == null || + !operatingParameters.TryGetValue("Mode0", out var selectedMode) || + double.IsNaN(selectedMode) || double.IsInfinity(selectedMode) || + selectedMode != Math.Truncate(selectedMode) || + selectedMode < -1 || selectedMode > 1) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Provide the exchanger's native charging, discharging, or idle mode.", + buildingItemId: building?.ItemId ?? 0); + return false; + } + else + { + state = (int)selectedMode; + } + + if (recipe != null && operatingParameters != null && + operatingParameters.TryGetValue("Mode0", out var requestedMode) && requestedMode != state) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The exchanger's operating mode conflicts with the selected recipe.", recipeId: recipe.Id); + return false; + } + + var inputItem = recipe?.Inputs.Single().Key ?? + (state == 1 ? building.EmptyAccumulatorItemId : building.FullAccumulatorItemId); + var outputItem = recipe?.Outputs.Single().Key ?? + (state == 1 ? building.FullAccumulatorItemId : building.EmptyAccumulatorItemId); + if (state != 0 && (inputItem <= 0 || outputItem <= 0)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The exchanger's accumulator items are unavailable.", buildingItemId: building?.ItemId ?? 0); + return false; + } + + if (building != null && state != 0 && + (!FinitePositive(building.ExchangeRateWatts) || !FinitePositive(building.AccumulatorEnergyJoules))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The exchanger's energy capacity is unavailable.", buildingItemId: building.ItemId); + return false; + } + + var effectiveWatts = building == null || state == 0 ? 0 : building.ExchangeRateWatts * (1 + speedBonus); + var cycles = building == null ? 0 : state == 0 ? 1 : + effectiveWatts * 60 / building.AccumulatorEnergyJoules; + var inputs = state == 0 ? Array.Empty>() : + new[] { new KeyValuePair(inputItem, 1) }; + var outputs = state == 0 ? Array.Empty>() : + new[] { new KeyValuePair(outputItem, 1) }; + process = new ProductionProcess(recipe?.Id ?? 0, building?.ItemId ?? 0, + state == 0 ? ProliferationMode.None : mode, state == 0 ? 0 : level, + inputs, outputs, cycles, state == 1 ? effectiveWatts : building?.IdlePowerWatts ?? 0, + building != null, accumulatorChargingWatts: state == 1 ? effectiveWatts : 0, + accumulatorDischargingWatts: state == -1 ? effectiveWatts : 0, + sprayedInputsPerCycle: state == 0 ? 0 : 1, + preservedSpraysPerCycle: mode == ProliferationMode.None + ? Array.Empty>() : outputs); + return true; + } + + private static bool FinitePositive(double value) + { + return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value); + } +} diff --git a/UXAssist/Production/BlueprintSelectionReader.cs b/UXAssist/Production/BlueprintSelectionReader.cs new file mode 100644 index 0000000..ba78c26 --- /dev/null +++ b/UXAssist/Production/BlueprintSelectionReader.cs @@ -0,0 +1,494 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UXAssist.Production; + +public sealed class BlueprintSelectionContext +{ + public Dictionary> OperatingParametersByIndex { get; } = + new Dictionary>(); + public Dictionary> OperatingParametersByObjectId { get; } = + new Dictionary>(); +} + +public sealed class BlueprintSelectionCapture +{ + public IReadOnlyList Buildings { get; } + public IReadOnlyList Diagnostics { get; } + + public BlueprintSelectionCapture(IEnumerable buildings, + IEnumerable diagnostics) + { + Buildings = Array.AsReadOnly(buildings.ToArray()); + Diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + public FactoryBlackBoxRequest CreateRequest(bool proliferationEnabled) + { + var request = new FactoryBlackBoxRequest { ProliferationEnabled = proliferationEnabled }; + request.Buildings.AddRange(Buildings); + request.CaptureDiagnostics.AddRange(Diagnostics); + return request; + } +} + +public static class BlueprintSelectionReader +{ + public static BlueprintSelectionCapture Capture(PlanetFactory factory, IEnumerable selectedObjectIds) + { + return Capture(factory, selectedObjectIds, null); + } + + public static BlueprintSelectionCapture Capture(PlanetFactory factory, IEnumerable selectedObjectIds, + BlueprintSelectionContext context) + { + if (factory == null || ProductionCatalogService.Current == null) + return Failure(ProductionDiagnosticCode.DataNotReady, "Factory or production data is not loaded."); + if (selectedObjectIds == null) + return Failure(ProductionDiagnosticCode.InvalidRequest, "The selected object IDs are required."); + + var snapshots = new List(); + var diagnostics = new List(); + var seen = new HashSet(); + foreach (var objectId in selectedObjectIds) + { + if (!seen.Add(objectId)) + { + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.DuplicateSelection, + "A blueprint-selected object ID is repeated.")); + continue; + } + + if (!IsLiveObject(factory, objectId)) + { + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "A blueprint-selected object no longer exists.")); + continue; + } + + var parameters = new BuildingParameters(); + if (!parameters.CopyFromFactoryObject(objectId, factory, false)) + { + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The selected building's settings could not be captured.")); + continue; + } + + if (!ProductionCatalogService.Current.Buildings.ContainsKey(parameters.itemId)) continue; + var operation = new Dictionary(); + var mode = GetMode(parameters); + var speedFactor = GetLiveSpeed(factory, objectId, parameters.type, operation); + AddSettings(parameters, operation); + var kind = ProductionCatalogService.Current.Buildings[parameters.itemId].Kind; + if (parameters.type == BuildingType.Lab && operation.ContainsKey("ResearchMode")) + CaptureResearchSettings(factory, operation); + if (kind == ProductionBuildingKind.Miner) + CaptureMiningSettings(factory, objectId, + ProductionCatalogService.Current.Buildings[parameters.itemId], operation); + if (kind == ProductionBuildingKind.Collector) + CaptureCollectionSettings(factory, operation); + if (kind == ProductionBuildingKind.FuelGenerator) + CaptureFuelSettings(factory, objectId, operation); + if (kind == ProductionBuildingKind.RayReceiver) + CaptureRaySettings(factory, objectId, operation); + if (kind == ProductionBuildingKind.Ejector || kind == ProductionBuildingKind.Silo) + CaptureLaunchSettings(factory, objectId, kind, operation); + if (context?.OperatingParametersByObjectId.TryGetValue(objectId, out var supplied) == true && supplied != null) + { + foreach (var entry in supplied) operation[entry.Key] = entry.Value; + } + + var recipeId = kind == ProductionBuildingKind.Fractionator + ? GetLiveFractionationRecipe(factory, objectId) : parameters.recipeId; + if (kind == ProductionBuildingKind.Fractionator && + operation.TryGetValue("FluidItemId", out var fluidItemId)) + recipeId = FindFractionationRecipe((int)fluidItemId); + ReportMissingSettings(kind, parameters, operation, diagnostics); + if (kind == ProductionBuildingKind.Fractionator && recipeId == 0) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The fractionator's input item is not selected.", buildingItemId: parameters.itemId)); + snapshots.Add(new ProductionBuildingSnapshot(objectId, parameters.itemId, recipeId, 1, + mode, speedFactor, operation)); + } + + return new BlueprintSelectionCapture(snapshots, diagnostics); + } + + public static BlueprintSelectionCapture FromBlueprint(IEnumerable buildings, + BlueprintSelectionContext context = null) + { + if (ProductionCatalogService.Current == null) + return Failure(ProductionDiagnosticCode.DataNotReady, "Production data is not loaded."); + if (buildings == null) + return Failure(ProductionDiagnosticCode.InvalidRequest, "A blueprint building list is required."); + + var snapshots = new List(); + var diagnostics = new List(); + var seen = new HashSet(); + foreach (var blueprint in buildings) + { + if (blueprint == null) + { + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "A blueprint building is missing.")); + continue; + } + + if (!seen.Add(blueprint.index)) + { + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.DuplicateSelection, + "A blueprint building index is repeated.")); + continue; + } + + var model = LDB.models.Select(blueprint.modelIndex); + if (model?.prefabDesc == null || LDB.items.Select(blueprint.itemId) == null) + { + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.UnknownItem, + "A blueprint building's model or item is unknown.", buildingItemId: blueprint.itemId)); + continue; + } + + if (!ProductionCatalogService.Current.Buildings.ContainsKey(blueprint.itemId)) continue; + + var parameters = new BuildingParameters + { + type = ClassifyNativeType(model.prefabDesc), + itemId = blueprint.itemId, + modelIndex = blueprint.modelIndex, + recipeId = blueprint.recipeId, + filterId = blueprint.filterId + }; + parameters.FromParamsArray(blueprint.parameters); + var operation = new Dictionary(); + AddSettings(parameters, operation); + if (context?.OperatingParametersByIndex.TryGetValue(blueprint.index, out var supplied) == true) + { + foreach (var entry in supplied) operation[entry.Key] = entry.Value; + } + + var kind = ProductionCatalogService.Current.Buildings[blueprint.itemId].Kind; + var recipeId = blueprint.recipeId; + if (kind == ProductionBuildingKind.Fractionator && + operation.TryGetValue("FluidItemId", out var fluidItemId)) + recipeId = FindFractionationRecipe((int)fluidItemId); + ReportMissingSettings(kind, parameters, operation, diagnostics); + if (kind == ProductionBuildingKind.Fractionator && recipeId == 0) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "A blueprint fractionator needs its input item.", buildingItemId: blueprint.itemId)); + snapshots.Add(new ProductionBuildingSnapshot(0, blueprint.itemId, recipeId, 1, + GetMode(parameters), operatingParameters: operation)); + } + + return new BlueprintSelectionCapture(snapshots, diagnostics); + } + + private static BlueprintSelectionCapture Failure(ProductionDiagnosticCode code, string message) + { + return new BlueprintSelectionCapture(Array.Empty(), + new[] { new ProductionDiagnostic(code, message) }); + } + + private static bool IsLiveObject(PlanetFactory factory, int objectId) + { + if (objectId > 0) + return factory.entityPool != null && objectId < factory.entityCursor && + objectId < factory.entityPool.Length && factory.entityPool[objectId].id == objectId; + if (objectId >= 0 || objectId == int.MinValue) return false; + var prebuildId = -objectId; + return factory.prebuildPool != null && prebuildId < factory.prebuildCursor && + prebuildId < factory.prebuildPool.Length && factory.prebuildPool[prebuildId].id == prebuildId; + } + + private static double? GetLiveSpeed(PlanetFactory factory, int objectId, BuildingType type, + IDictionary operation) + { + if (objectId <= 0) return null; + ref var entity = ref factory.entityPool[objectId]; + var system = factory.factorySystem; + if (type == BuildingType.Assembler && entity.assemblerId > 0 && system?.assemblerPool != null && + entity.assemblerId < system.assemblerPool.Length && + system.assemblerPool[entity.assemblerId].id == entity.assemblerId) + return system.assemblerPool[entity.assemblerId].speed / 10000.0; + if (type == BuildingType.Lab && entity.labId > 0 && system?.labPool != null && + entity.labId < system.labPool.Length && system.labPool[entity.labId].id == entity.labId) + { + ref var lab = ref system.labPool[entity.labId]; + if (lab.researchMode && lab.techId > 0) operation["TechId"] = lab.techId; + return lab.speed / 10000.0; + } + + return null; + } + + private static int GetLiveFractionationRecipe(PlanetFactory factory, int objectId) + { + if (objectId <= 0 || factory.factorySystem?.fractionatorPool == null) return 0; + var fractionatorId = factory.entityPool[objectId].fractionatorId; + var pool = factory.factorySystem.fractionatorPool; + return fractionatorId > 0 && fractionatorId < pool.Length && pool[fractionatorId].id == fractionatorId + ? FindFractionationRecipe(pool[fractionatorId].fluidId) : 0; + } + + private static void CaptureMiningSettings(PlanetFactory factory, int objectId, ProductionBuilding building, + IDictionary operation) + { + var history = factory.gameData?.history; + if (history != null) operation["MiningSpeedMultiplier"] = history.miningSpeedScale; + if (building.MinerKind == ProductionMinerKind.Water && factory.planet?.waterItemId > 0) + operation["ResourceItemId"] = factory.planet.waterItemId; + if (objectId <= 0 || factory.factorySystem?.minerPool == null) return; + + var minerId = factory.entityPool[objectId].minerId; + var pool = factory.factorySystem.minerPool; + if (minerId <= 0 || minerId >= pool.Length || pool[minerId].id != minerId) return; + ref var miner = ref pool[minerId]; + operation["MachineSpeedFactor"] = miner.speed / ProductionUnits.FixedPointScale; + operation["SpeedDamper"] = miner.speedDamper; + if (building.MinerKind == ProductionMinerKind.Water || miner.veinCount <= 0 || + miner.veins == null || miner.veinCount > miner.veins.Length || factory.veinPool == null) return; + + var resourceItemId = 0; + for (var index = 0; index < miner.veinCount; index++) + { + var veinId = miner.veins[index]; + if (veinId <= 0 || veinId >= factory.veinPool.Length || + factory.veinPool[veinId].id != veinId || factory.veinPool[veinId].productId <= 0 || + resourceItemId != 0 && resourceItemId != factory.veinPool[veinId].productId) return; + resourceItemId = factory.veinPool[veinId].productId; + } + + operation["ResourceItemId"] = resourceItemId; + if (building.MinerKind == ProductionMinerKind.Vein) + operation["VeinCount"] = miner.veinCount; + else if (building.MinerKind == ProductionMinerKind.Oil) + operation["OilUnits"] = factory.veinPool[miner.veins[0]].amount * VeinData.oilSpeedMultiplier; + } + + private static void CaptureCollectionSettings(PlanetFactory factory, + IDictionary operation) + { + var planet = factory.planet; + if (planet?.gasItems == null || planet.gasSpeeds == null || + planet.gasItems.Length != planet.gasSpeeds.Length) return; + operation["GasCount"] = planet.gasItems.Length; + operation["GasTotalHeat"] = planet.gasTotalHeat; + if (factory.gameData?.history != null) + operation["MiningSpeedMultiplier"] = factory.gameData.history.miningSpeedScale; + for (var index = 0; index < planet.gasItems.Length; index++) + { + operation[$"GasItemId{index}"] = planet.gasItems[index]; + operation[$"GasSpeedPerSecond{index}"] = planet.gasSpeeds[index]; + } + } + + private static void CaptureResearchSettings(PlanetFactory factory, + IDictionary operation) + { + var history = factory.gameData?.history; + if (history == null) return; + operation["ResearchSpeed"] = history.techSpeed; + if (!operation.ContainsKey("TechId") && history.currentTech > 0) + operation["TechId"] = history.currentTech; + } + + private static void CaptureFuelSettings(PlanetFactory factory, int objectId, + IDictionary operation) + { + if (objectId <= 0 || factory.powerSystem?.genPool == null) return; + var generatorId = factory.entityPool[objectId].powerGenId; + var pool = factory.powerSystem.genPool; + if (generatorId <= 0 || generatorId >= pool.Length || pool[generatorId].id != generatorId) return; + var fuelId = pool[generatorId].curFuelId > 0 ? pool[generatorId].curFuelId : pool[generatorId].fuelId; + if (fuelId > 0) operation["FuelItemId"] = fuelId; + } + + private static void CaptureRaySettings(PlanetFactory factory, int objectId, + IDictionary operation) + { + if (factory.gameData?.history != null) + operation["SolarEnergyLossRate"] = factory.gameData.history.solarEnergyLossRate; + if (objectId <= 0 || factory.powerSystem?.genPool == null) return; + var generatorId = factory.entityPool[objectId].powerGenId; + var pool = factory.powerSystem.genPool; + if (generatorId <= 0 || generatorId >= pool.Length || pool[generatorId].id != generatorId) return; + ref var generator = ref pool[generatorId]; + operation["Mode0"] = generator.productId; + operation["LensItemId"] = generator.catalystPoint > 0 || generator.catalystCount > 0 + ? generator.catalystPoint > 0 && generator.curCatalystId > 0 + ? generator.curCatalystId : generator.catalystId : 0; + } + + private static void CaptureLaunchSettings(PlanetFactory factory, int objectId, + ProductionBuildingKind kind, IDictionary operation) + { + if (objectId <= 0 || factory.factorySystem == null) return; + ref var entity = ref factory.entityPool[objectId]; + var system = factory.factorySystem; + if (kind == ProductionBuildingKind.Silo) + { + var siloId = entity.siloId; + if (system.siloPool == null || siloId <= 0 || siloId >= system.siloPool.Length || + system.siloPool[siloId].id != siloId) return; + operation["BoostEnabled"] = system.siloPool[siloId].boost ? 1 : 0; + operation["LaunchAvailable"] = factory.dysonSphere != null && + factory.dysonSphere.GetAutoNodeCount() > 0 ? 1 : 0; + return; + } + + var ejectorId = entity.ejectorId; + if (system.ejectorPool == null || ejectorId <= 0 || ejectorId >= system.ejectorPool.Length || + system.ejectorPool[ejectorId].id != ejectorId) return; + ref var ejector = ref system.ejectorPool[ejectorId]; + operation["BoostEnabled"] = ejector.boost ? 1 : 0; + var swarm = factory.dysonSphere?.swarm; + operation["LaunchAvailable"] = 0; + if (swarm?.orbits == null) return; + if (ejector.autoOrbit) + { + for (var orbitId = 1; orbitId < swarm.orbitCursor; orbitId++) + { + if (swarm.orbits[orbitId].id != orbitId || !swarm.orbits[orbitId].enabled) continue; + operation["LaunchAvailable"] = 1; + break; + } + } + else if (ejector.orbitId > 0 && ejector.orbitId < swarm.orbitCursor && + swarm.orbits[ejector.orbitId].id == ejector.orbitId && + swarm.orbits[ejector.orbitId].enabled) + { + operation["LaunchAvailable"] = 1; + } + } + + private static int FindFractionationRecipe(int inputItemId) + { + var recipes = RecipeProto.fractionatorRecipes; + if (inputItemId <= 0 || recipes == null) return 0; + foreach (var recipe in recipes) + { + if (recipe.Items.Length == 1 && recipe.Items[0] == inputItemId) return recipe.ID; + } + + return 0; + } + + private static void AddSettings(BuildingParameters parameters, IDictionary operation) + { + operation["Mode0"] = parameters.mode0; + operation["Mode1"] = parameters.mode1; + operation["Mode2"] = parameters.mode2; + operation["FilterItemId"] = parameters.filterId; + if (parameters.type == BuildingType.Lab && parameters.mode0 == 2) + operation["ResearchMode"] = 1; + } + + private static void ReportMissingSettings(ProductionBuildingKind kind, BuildingParameters parameters, + IReadOnlyDictionary operation, ICollection diagnostics) + { + var requiredKey = parameters.type == BuildingType.Lab && parameters.mode0 == 2 ? "TechId" : + kind == ProductionBuildingKind.Miner ? "ResourceItemId" : + kind == ProductionBuildingKind.Collector ? "GasCount" : + kind == ProductionBuildingKind.FuelGenerator ? "FuelItemId" : + kind == ProductionBuildingKind.Fractionator ? "CirculatingItemsPerMinute" : null; + if (requiredKey != null && !operation.ContainsKey(requiredKey)) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + $"The selected building needs the {requiredKey} operating parameter.", + buildingItemId: parameters.itemId)); + if (parameters.type == BuildingType.Lab && parameters.mode0 == 2 && + !operation.ContainsKey("ResearchSpeed")) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The research lab needs the current research technology speed.", + buildingItemId: parameters.itemId)); + if (kind == ProductionBuildingKind.Fractionator && !operation.ContainsKey("StackSize")) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The fractionator needs its circulating stack size.", buildingItemId: parameters.itemId)); + if (kind == ProductionBuildingKind.RayReceiver) + { + if (!operation.ContainsKey("LensItemId")) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The receiver needs a lens item ID, or zero for no lens.", buildingItemId: parameters.itemId)); + if (!operation.ContainsKey("SolarEnergyLossRate")) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The receiver needs the solar energy loss technology setting.", + buildingItemId: parameters.itemId)); + } + if (kind == ProductionBuildingKind.Collector) + { + if (!operation.ContainsKey("GasTotalHeat") || + !operation.ContainsKey("MiningSpeedMultiplier")) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The collector needs the planet's gas energy and current mining technology speed.", + buildingItemId: parameters.itemId)); + if (operation.TryGetValue("GasCount", out var count) && count > 0 && count <= 16 && + count == Math.Truncate(count)) + { + for (var index = 0; index < (int)count; index++) + { + if (operation.ContainsKey($"GasItemId{index}") && + operation.ContainsKey($"GasSpeedPerSecond{index}")) continue; + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + $"The collector needs gas item and speed for resource {index}.", + buildingItemId: parameters.itemId)); + } + } + } + if (kind == ProductionBuildingKind.Ejector || kind == ProductionBuildingKind.Silo) + { + if (!operation.ContainsKey("LaunchAvailable")) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The launcher needs a usable orbit or Dyson-sphere node setting.", + buildingItemId: parameters.itemId)); + var boostKey = kind == ProductionBuildingKind.Ejector ? "Mode1" : "Mode0"; + if (operation.TryGetValue(boostKey, out var boostMode) && boostMode == 1 && + !operation.ContainsKey("BoostEnabled")) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The launcher needs its current sandbox boost setting.", + buildingItemId: parameters.itemId)); + } + if (kind == ProductionBuildingKind.Miner) + { + if (!operation.ContainsKey("MiningSpeedMultiplier")) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The miner needs the current mining technology speed.", buildingItemId: parameters.itemId)); + var minerKind = ProductionCatalogService.Current.Buildings[parameters.itemId].MinerKind; + var factorName = minerKind == ProductionMinerKind.Vein ? "VeinCount" : + minerKind == ProductionMinerKind.Oil ? "OilUnits" : null; + if (factorName != null && !operation.ContainsKey(factorName)) + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + $"The miner needs its {factorName} resource factor.", buildingItemId: parameters.itemId)); + } + } + + private static ProliferationMode GetMode(BuildingParameters parameters) + { + if (parameters.type != BuildingType.Assembler && parameters.type != BuildingType.Lab) + return ProliferationMode.None; + + var recipeId = parameters.recipeId; + var filterId = parameters.filterId; + var mode0 = parameters.mode0; + var mode1 = parameters.mode1; + if (parameters.type == BuildingType.Assembler) + BuildingParameters.SimpleParamFromParamsArray(parameters.type, parameters.parameters, + ref recipeId, ref filterId, ref mode0, ref mode1); + var recipe = LDB.recipes.Select(recipeId); + return mode1 == 1 || recipe != null && !recipe.productive + ? ProliferationMode.Speedup : ProliferationMode.ExtraProducts; + } + + private static BuildingType ClassifyNativeType(PrefabDesc prefab) + { + if (prefab.isAssembler) return BuildingType.Assembler; + if (prefab.isLab) return BuildingType.Lab; + if (prefab.isEjector) return BuildingType.Ejector; + if (prefab.isSilo) return BuildingType.Silo; + if (prefab.isPowerExchanger) return BuildingType.Exchanger; + if (prefab.gammaRayReceiver) return BuildingType.Gamma; + if (prefab.minerType != EMinerType.None) return BuildingType.Miner; + if (prefab.isPowerGen && prefab.fuelMask == 4) return BuildingType.ArtifacialStar; + if (prefab.geothermal) return BuildingType.Geothermal; + return BuildingType.Other; + } +} diff --git a/UXAssist/Production/FactoryBlackBoxAnalyzer.cs b/UXAssist/Production/FactoryBlackBoxAnalyzer.cs new file mode 100644 index 0000000..eb0fedc --- /dev/null +++ b/UXAssist/Production/FactoryBlackBoxAnalyzer.cs @@ -0,0 +1,273 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UXAssist.Production; + +public sealed class ProductionBuildingSnapshot +{ + public int ObjectId { get; } + public int BuildingItemId { get; } + public int RecipeId { get; } + public int Count { get; } + public ProliferationMode ProliferationMode { get; } + public double? SpeedFactor { get; } + public IReadOnlyDictionary OperatingParameters { get; } + + public ProductionBuildingSnapshot(int objectId, int buildingItemId, int recipeId, int count, + ProliferationMode proliferationMode, double? speedFactor = null, + IEnumerable> operatingParameters = null) + { + ObjectId = objectId; + BuildingItemId = buildingItemId; + RecipeId = recipeId; + Count = count; + ProliferationMode = proliferationMode; + SpeedFactor = speedFactor; + OperatingParameters = new System.Collections.ObjectModel.ReadOnlyDictionary( + operatingParameters?.ToDictionary(entry => entry.Key, entry => entry.Value) ?? + new Dictionary()); + } +} + +public sealed class FactoryBlackBoxRequest +{ + public List Buildings { get; } = new List(); + public List CaptureDiagnostics { get; } = new List(); + public bool ProliferationEnabled { get; set; } +} + +public sealed class FactoryBlackBoxAnalyzer +{ + private readonly ProductionCatalog _catalog; + private readonly ProcessEvaluator _evaluator; + + public FactoryBlackBoxAnalyzer(ProductionCatalog catalog, ProcessEvaluator evaluator = null) + { + _catalog = catalog; + _evaluator = evaluator ?? new ProcessEvaluator(); + } + + public ProductionReport Analyze(FactoryBlackBoxRequest request) + { + if (_catalog == null) + return ProductionReport.Failure(new ProductionDiagnostic(ProductionDiagnosticCode.DataNotReady, + "Production data is not loaded.")); + if (request == null) + return ProductionReport.Failure(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "A building selection is required.")); + + var diagnostics = new List(request.CaptureDiagnostics); + var groups = new List(); + var grossProduction = new SortedDictionary(); + var grossConsumption = new SortedDictionary(); + var producers = new Dictionary>(); + var consumers = new Dictionary>(); + var smallestProducer = new Dictionary(); + var selectedIds = new HashSet(); + var skippedSelection = diagnostics.Any(diagnostic => + diagnostic.Code == ProductionDiagnosticCode.InvalidRequest || + diagnostic.Code == ProductionDiagnosticCode.UnknownItem || + diagnostic.Code == ProductionDiagnosticCode.DataNotReady); + var materialComplete = !skippedSelection; + var powerComplete = !skippedSelection; + var consumptionWatts = 0.0; + var generationWatts = 0.0; + var chargingWatts = 0.0; + var dischargingWatts = 0.0; + var dysonRequirementWatts = 0.0; + + foreach (var snapshot in request.Buildings) + { + if (snapshot == null || snapshot.Count <= 0) + { + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "A selected building has an invalid count.")); + materialComplete = false; + powerComplete = false; + continue; + } + + if (snapshot.ObjectId != 0 && !selectedIds.Add(snapshot.ObjectId)) + { + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.DuplicateSelection, + "A selected building was already included.", buildingItemId: snapshot.BuildingItemId)); + continue; + } + + if (!_catalog.Buildings.TryGetValue(snapshot.BuildingItemId, out var building)) + { + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, + "The selected building is not supported by the catalog.", + buildingItemId: snapshot.BuildingItemId)); + materialComplete = false; + powerComplete = false; + continue; + } + + if (snapshot.RecipeId != 0 && + snapshot.OperatingParameters.TryGetValue("ResearchMode", out var activeResearchMode) && + activeResearchMode > 0) + { + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "A research-mode lab cannot also run a manufacturing recipe.", + recipeId: snapshot.RecipeId, buildingItemId: snapshot.BuildingItemId)); + materialComplete = false; + powerComplete = false; + continue; + } + + if (snapshot.RecipeId == 0 && (building.Kind == ProductionBuildingKind.Ordinary || + building.Kind == ProductionBuildingKind.Auxiliary)) + { + if (building.Kind == ProductionBuildingKind.Auxiliary || + !snapshot.OperatingParameters.TryGetValue("ResearchMode", out var researchMode) || + researchMode <= 0) + { + var idleWatts = (building.Kind == ProductionBuildingKind.Auxiliary + ? building.WorkingPowerWatts : building.IdlePowerWatts) * snapshot.Count; + consumptionWatts += idleWatts; + groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count, + idleWatts, idleWatts, Array.Empty>(), + Array.Empty>())); + continue; + } + } + + ProductionRecipe recipe = null; + if (snapshot.RecipeId != 0 && !_catalog.Recipes.TryGetValue(snapshot.RecipeId, out recipe)) + { + diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.UnknownRecipe, + "The selected building's recipe is missing.", recipeId: snapshot.RecipeId, + buildingItemId: snapshot.BuildingItemId)); + materialComplete = false; + powerComplete = false; + continue; + } + + if (snapshot.SpeedFactor.HasValue) + building = new ProductionBuilding(building.ItemId, building.Category, snapshot.SpeedFactor.Value, + building.WorkingPowerWatts, building.IdlePowerWatts, building.Kind, + building.RatedGenerationWatts, building.ExchangeRateWatts, + building.AccumulatorEnergyJoules, building.EmptyAccumulatorItemId, + building.FullAccumulatorItemId, building.RenewableSource, + building.MinerKind, building.MiningPeriodTicks, + building.FuelMask, building.FuelUseWatts, + building.PowerProductItemId, building.PowerProductEnergyJoules, + building.CatalystMask, building.LaunchChargeTicks, + building.LaunchCooldownTicks, building.AmmunitionItemId, + building.CollectorSpeedMultiplier); + var mode = request.ProliferationEnabled + ? building.Kind == ProductionBuildingKind.Fractionator + ? ProliferationMode.Speedup : building.Kind == ProductionBuildingKind.Exchanger && + snapshot.OperatingParameters.TryGetValue("Mode0", out var exchangerMode) && exchangerMode != 0 + ? ProliferationMode.Speedup : building.Kind == ProductionBuildingKind.FuelGenerator + ? ProliferationMode.Speedup : building.Kind == ProductionBuildingKind.RayReceiver + ? snapshot.OperatingParameters.TryGetValue("LensItemId", out var lensId) && lensId > 0 + ? ProliferationMode.Speedup : ProliferationMode.None + : building.Kind == ProductionBuildingKind.Collector + ? ProliferationMode.None + : building.Category == ProductionRecipeCategory.Research && snapshot.RecipeId == 0 && + snapshot.OperatingParameters.TryGetValue("ResearchMode", out var researchModeSetting) && + researchModeSetting > 0 ? ProliferationMode.ExtraProducts + : building.Kind == ProductionBuildingKind.Ejector || + building.Kind == ProductionBuildingKind.Silo + ? ProliferationMode.Speedup + : snapshot.ProliferationMode + : ProliferationMode.None; + if (!_evaluator.TryEvaluate(_catalog, recipe, building, mode, + mode == ProliferationMode.None ? 0 : _catalog.MaximumProliferationLevel, + snapshot.OperatingParameters, out var process, out var diagnostic)) + { + diagnostics.Add(diagnostic); + if (building.Kind != ProductionBuildingKind.RenewableGenerator) materialComplete = false; + powerComplete = false; + continue; + } + + if (diagnostic != null) diagnostics.Add(diagnostic); + if (!process.PowerKnown) powerComplete = false; + var cycleRate = process.CyclesPerBuildingPerMinute; + var output = Scale(process.OutputsPerCycle, cycleRate * snapshot.Count); + var input = Scale(process.InputsPerCycle, cycleRate * snapshot.Count); + var groupIndex = groups.Count; + foreach (var flow in output) + { + Add(grossProduction, flow.Key, flow.Value); + AddGroup(producers, flow.Key, groupIndex); + var perBuildingNet = (process.OutputsPerCycle[flow.Key] - + (process.InputsPerCycle.TryGetValue(flow.Key, out var consumed) ? consumed : 0)) * cycleRate; + if (perBuildingNet > 1e-9 && + (!smallestProducer.TryGetValue(flow.Key, out var previous) || perBuildingNet < previous)) + smallestProducer[flow.Key] = perBuildingNet; + } + + foreach (var flow in input) + { + Add(grossConsumption, flow.Key, flow.Value); + AddGroup(consumers, flow.Key, groupIndex); + } + + var watts = process.WorkingPowerWatts * snapshot.Count; + consumptionWatts += watts; + generationWatts += process.GenerationWatts * snapshot.Count; + chargingWatts += process.AccumulatorChargingWatts * snapshot.Count; + dischargingWatts += process.AccumulatorDischargingWatts * snapshot.Count; + dysonRequirementWatts += (process.DysonSphereRequirementWatts ?? 0) * snapshot.Count; + groups.Add(new ProductionGroupFlow(process, snapshot.Count, cycleRate * snapshot.Count, + snapshot.Count, snapshot.Count, watts, watts, output, input, + process.GenerationWatts * snapshot.Count, process.AccumulatorChargingWatts * snapshot.Count, + process.AccumulatorDischargingWatts * snapshot.Count, + process.DysonSphereRequirementWatts * snapshot.Count, + cycleRate * snapshot.Count * process.LaunchesPerCycle, + cycleRate * snapshot.Count * process.ResearchHashesPerCycle)); + } + + var flows = new List(); + var allItems = new SortedSet(grossProduction.Keys); + allItems.UnionWith(grossConsumption.Keys); + foreach (var itemId in allItems) + { + var produced = grossProduction.TryGetValue(itemId, out var p) ? p : 0; + var consumed = grossConsumption.TryGetValue(itemId, out var c) ? c : 0; + var net = produced - consumed; + var threshold = smallestProducer.TryGetValue(itemId, out var single) ? single : 0; + var isFinalProduct = produced > 1e-9 && consumed <= 1e-9; + flows.Add(new ProductionItemFlow(itemId, produced, consumed, 0, 0, 0, + Math.Max(0, net), Math.Max(0, -net), isFinalProduct, + !isFinalProduct && consumed > 1e-9 && net > 1e-9 && threshold > 0 && + net + 1e-9 >= threshold, + threshold, producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty(), + consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty())); + } + + var power = powerComplete ? new ProductionPower(consumptionWatts, consumptionWatts, generationWatts, + chargingWatts, dischargingWatts, dysonRequirementWatts, + ProductionPowerScope.SelectedFacilities) : null; + var status = materialComplete && powerComplete && diagnostics.Count == 0 + ? ProductionStatus.Complete : materialComplete || powerComplete || groups.Count > 0 + ? ProductionStatus.Partial : ProductionStatus.Failed; + return new ProductionReport(status, materialComplete, powerComplete, flows, groups, diagnostics, power); + } + + private static Dictionary Scale(IReadOnlyDictionary flows, double factor) + { + return flows.ToDictionary(entry => entry.Key, entry => entry.Value * factor); + } + + private static void Add(IDictionary flows, int itemId, double count) + { + flows[itemId] = (flows.TryGetValue(itemId, out var previous) ? previous : 0) + count; + } + + private static void AddGroup(IDictionary> groups, int itemId, int index) + { + if (!groups.TryGetValue(itemId, out var indices)) + { + indices = new List(); + groups[itemId] = indices; + } + + indices.Add(index); + } +} diff --git a/UXAssist/Production/FractionationProcessAdapter.cs b/UXAssist/Production/FractionationProcessAdapter.cs new file mode 100644 index 0000000..4df9731 --- /dev/null +++ b/UXAssist/Production/FractionationProcessAdapter.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UXAssist.Production; + +public sealed class FractionationProcessAdapter : IProductionProcessAdapter +{ + public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building) + { + return recipe?.Category == ProductionRecipeCategory.Fractionate; + } + + public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building, + ProliferationMode mode, int level, IReadOnlyDictionary operatingParameters, + out ProductionProcess process, out ProductionDiagnostic diagnostic) + { + process = null; + diagnostic = null; + if (recipe.Inputs.Count != 1 || recipe.Outputs.Count != 1 || + !FinitePositive(recipe.Inputs.Values.Single()) || + !FinitePositive(recipe.Outputs.Values.Single()) || + mode != ProliferationMode.None && mode != ProliferationMode.Speedup) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, + "Fractionation requires one input, one output, and the native acceleration mode.", + recipeId: recipe.Id); + return false; + } + + if (building != null && building.Kind != ProductionBuildingKind.Fractionator) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding, + "The selected building cannot fractionate items.", recipeId: recipe.Id, + buildingItemId: building.ItemId); + return false; + } + + var speedBonus = 0.0; + var powerMultiplier = 1.0; + if (mode == ProliferationMode.Speedup && + (level <= 0 || !catalog.TryGetProliferation(level, out speedBonus, out _, out powerMultiplier))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "The fractionator's proliferation level is unavailable.", recipeId: recipe.Id); + return false; + } + + var throughput = 0.0; + if (building != null) + { + if (operatingParameters == null || + !operatingParameters.TryGetValue("CirculatingItemsPerMinute", out throughput) || + !operatingParameters.TryGetValue("StackSize", out var stackSize) || + !FinitePositive(throughput) || !FinitePositive(stackSize) || + stackSize > 4 || throughput > stackSize * 30 * ProductionUnits.SecondsPerMinute + 1e-9) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Provide circulating items per minute and a valid stack size for the fractionator.", + recipeId: recipe.Id, buildingItemId: building.ItemId); + return false; + } + } + + var input = recipe.Inputs.Single(); + var output = recipe.Outputs.Single(); + var probability = Math.Min(1, output.Value / input.Value * (1 + speedBonus)); + var throughputPerSecond = throughput / ProductionUnits.SecondsPerMinute; + var watts = building == null ? 0 : building.WorkingPowerWatts * + (1 + Math.Max(0, throughputPerSecond - 30) * 0.05) * powerMultiplier; + process = new ProductionProcess(recipe.Id, building?.ItemId ?? 0, mode, + mode == ProliferationMode.None ? 0 : level, + new[] { new KeyValuePair(input.Key, probability) }, + new[] { new KeyValuePair(output.Key, probability) }, + throughput, watts, building != null, throughput); + return true; + } + + private static bool FinitePositive(double value) + { + return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value); + } +} diff --git a/UXAssist/Production/FuelGenerationAdapter.cs b/UXAssist/Production/FuelGenerationAdapter.cs new file mode 100644 index 0000000..95c0d09 --- /dev/null +++ b/UXAssist/Production/FuelGenerationAdapter.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; + +namespace UXAssist.Production; + +public sealed class FuelGenerationAdapter : IProductionProcessAdapter +{ + public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building) + { + return recipe == null && building?.Kind == ProductionBuildingKind.FuelGenerator; + } + + public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building, + ProliferationMode mode, int level, IReadOnlyDictionary operatingParameters, + out ProductionProcess process, out ProductionDiagnostic diagnostic) + { + process = null; + diagnostic = null; + if (operatingParameters == null || + !operatingParameters.TryGetValue("FuelItemId", out var fuelId) || + fuelId <= 0 || fuelId > int.MaxValue || fuelId != Math.Truncate(fuelId) || + !catalog.Items.TryGetValue((int)fuelId, out var fuel) || + fuel.HeatValueJoules <= 0 || (fuel.FuelTypeMask & building.FuelMask) == 0) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Select a fuel item compatible with the generator's native fuel mask.", + buildingItemId: building.ItemId); + return false; + } + + if (mode != ProliferationMode.None && mode != ProliferationMode.Speedup && + mode != ProliferationMode.ExtraProducts || + mode == ProliferationMode.ExtraProducts && !fuel.ProductiveFuel) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "The fuel cannot use the requested proliferation mode.", buildingItemId: building.ItemId); + return false; + } + + if (building.FuelUseWatts <= 0 || building.RatedGenerationWatts <= 0 || + double.IsNaN(building.FuelUseWatts) || double.IsNaN(building.RatedGenerationWatts)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, + "The generator's fuel consumption or power rating is unavailable.", + buildingItemId: building.ItemId); + return false; + } + + var speedBonus = 0.0; + var extraBonus = 0.0; + if (mode != ProliferationMode.None && + (level <= 0 || !catalog.TryGetProliferation(level, out speedBonus, out extraBonus, out _))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "The fuel's proliferation level is unavailable.", buildingItemId: building.ItemId); + return false; + } + + var boostFactor = 1.0; + if (building.FuelMask == 4) + { + if (!operatingParameters.TryGetValue("Mode0", out var boostMode) || + (boostMode != 0 && boostMode != 1)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Select the artificial star's native boost setting.", buildingItemId: building.ItemId); + return false; + } + + boostFactor = (boostMode == 1 ? 100 : 1) * fuel.StarOutputMultiplier; + } + + var proliferationFactor = mode == ProliferationMode.None ? 1 : + fuel.ProductiveFuel ? 1 + extraBonus : 1 + speedBonus; + var generation = building.RatedGenerationWatts * proliferationFactor * boostFactor; + var burnedFuel = building.FuelUseWatts * (fuel.ProductiveFuel ? 1 : proliferationFactor) * + boostFactor * 60 / fuel.HeatValueJoules; + if (double.IsInfinity(generation) || double.IsInfinity(burnedFuel) || burnedFuel <= 0 || + double.IsNaN(generation) || double.IsNaN(burnedFuel)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The selected fuel produces an invalid generation rate.", buildingItemId: building.ItemId); + return false; + } + + process = new ProductionProcess(0, building.ItemId, + mode == ProliferationMode.None ? mode : fuel.ProductiveFuel + ? ProliferationMode.ExtraProducts : ProliferationMode.Speedup, + mode == ProliferationMode.None ? 0 : level, + new[] { new KeyValuePair(fuel.Id, 1) }, + Array.Empty>(), burnedFuel, + building.WorkingPowerWatts, true, generationWatts: generation); + return true; + } +} diff --git a/UXAssist/Production/GasCollectionAdapter.cs b/UXAssist/Production/GasCollectionAdapter.cs new file mode 100644 index 0000000..0ef16fe --- /dev/null +++ b/UXAssist/Production/GasCollectionAdapter.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; + +namespace UXAssist.Production; + +public sealed class GasCollectionAdapter : IProductionProcessAdapter +{ + public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building) + { + return building?.Kind == ProductionBuildingKind.Collector; + } + + public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building, + ProliferationMode mode, int level, IReadOnlyDictionary operatingParameters, + out ProductionProcess process, out ProductionDiagnostic diagnostic) + { + process = null; + diagnostic = null; + if (recipe != null || mode != ProliferationMode.None) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding, + "Gas collection has no recipe or native proliferation mode.", + recipeId: recipe?.Id ?? 0, buildingItemId: building.ItemId); + return false; + } + + if (operatingParameters == null || + !operatingParameters.TryGetValue("GasCount", out var gasCount) || + gasCount < 1 || gasCount > 16 || gasCount != Math.Truncate(gasCount) || + !operatingParameters.TryGetValue("GasTotalHeat", out var totalHeat) || + !FiniteNonnegative(totalHeat) || + !operatingParameters.TryGetValue("MiningSpeedMultiplier", out var miningSpeed) || + !FinitePositive(miningSpeed) || building.CollectorSpeedMultiplier <= 0 || + !FiniteNonnegative(building.WorkingPowerWatts)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Provide the planet's gas composition, total fuel energy, mining speed and collector speed.", + buildingItemId: building.ItemId); + return false; + } + + var workCost = building.WorkingPowerWatts / building.CollectorSpeedMultiplier; + var recovery = totalHeat == 0 ? 1 : 1 - workCost / totalHeat; + if (recovery == 0) recovery = 1; + var techRate = totalHeat - workCost <= 0 ? 1 : + (miningSpeed * totalHeat - workCost) / (totalHeat - workCost); + if (!FinitePositive(recovery) || !FinitePositive(techRate)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The selected gas flow cannot sustain the collector's native energy consumption.", + buildingItemId: building.ItemId); + return false; + } + + var outputs = new List>(); + for (var index = 0; index < (int)gasCount; index++) + { + if (!operatingParameters.TryGetValue($"GasItemId{index}", out var itemId) || + itemId <= 0 || itemId > int.MaxValue || itemId != Math.Truncate(itemId) || + !catalog.Items.ContainsKey((int)itemId) || + !operatingParameters.TryGetValue($"GasSpeedPerSecond{index}", out var gasSpeed) || + !FiniteNonnegative(gasSpeed)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Each collected gas needs a valid item ID and native gas speed.", + buildingItemId: building.ItemId); + return false; + } + + var rate = gasSpeed * ProductionUnits.SecondsPerMinute * + building.CollectorSpeedMultiplier * recovery * techRate; + if (!FiniteNonnegative(rate)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "A gas production rate is outside the supported range.", + itemId: (int)itemId, buildingItemId: building.ItemId); + return false; + } + + if (rate > 0) outputs.Add(new KeyValuePair((int)itemId, rate)); + } + + process = new ProductionProcess(0, building.ItemId, ProliferationMode.None, 0, + Array.Empty>(), outputs, + 1, 0, true); + return true; + } + + private static bool FiniteNonnegative(double value) + { + return value >= 0 && !double.IsNaN(value) && !double.IsInfinity(value); + } + + private static bool FinitePositive(double value) + { + return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value); + } +} diff --git a/UXAssist/Production/LaunchProcessAdapter.cs b/UXAssist/Production/LaunchProcessAdapter.cs new file mode 100644 index 0000000..7119354 --- /dev/null +++ b/UXAssist/Production/LaunchProcessAdapter.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; + +namespace UXAssist.Production; + +public sealed class LaunchProcessAdapter : IProductionProcessAdapter +{ + public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building) + { + return building?.Kind == ProductionBuildingKind.Ejector || building?.Kind == ProductionBuildingKind.Silo; + } + + public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building, + ProliferationMode mode, int level, IReadOnlyDictionary operatingParameters, + out ProductionProcess process, out ProductionDiagnostic diagnostic) + { + process = null; + diagnostic = null; + if (recipe != null) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding, + "Launchers consume ammunition without producing a recipe item.", recipeId: recipe.Id, + buildingItemId: building.ItemId); + return false; + } + + if (mode != ProliferationMode.None && mode != ProliferationMode.Speedup) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "Launch ammunition supports native speedup only.", buildingItemId: building.ItemId); + return false; + } + + if (operatingParameters == null || + !operatingParameters.TryGetValue("LaunchAvailable", out var launchAvailable) || + (launchAvailable != 0 && launchAvailable != 1)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Specify whether a usable orbit or Dyson-sphere node is available.", + buildingItemId: building.ItemId); + return false; + } + + if (launchAvailable == 0) + { + process = new ProductionProcess(0, building.ItemId, ProliferationMode.None, 0, + Array.Empty>(), Array.Empty>(), + 1, building.IdlePowerWatts, true); + return true; + } + + if (building.LaunchChargeTicks <= 0 || building.LaunchCooldownTicks <= 0 || + building.AmmunitionItemId <= 0 || !catalog.Items.ContainsKey(building.AmmunitionItemId)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, + "The launcher's native ammunition or cycle timings are unavailable.", + buildingItemId: building.ItemId); + return false; + } + + var boostModeKey = building.Kind == ProductionBuildingKind.Ejector ? "Mode1" : "Mode0"; + if (!operatingParameters.TryGetValue(boostModeKey, out var boostMode) || + (boostMode != 0 && boostMode != 1) || + boostMode == 1 && !operatingParameters.ContainsKey("BoostEnabled")) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Provide the launcher's native boost mode and whether sandbox boost is active.", + buildingItemId: building.ItemId); + return false; + } + + var boosted = operatingParameters.TryGetValue("BoostEnabled", out var boostEnabled) && + boostEnabled == 1; + if (operatingParameters.ContainsKey("BoostEnabled") && + (boostEnabled != 0 && boostEnabled != 1 || boosted && boostMode != 1)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The sandbox boost setting conflicts with the launcher's native mode.", + buildingItemId: building.ItemId); + return false; + } + + var speedBonus = 0.0; + var powerMultiplier = 1.0; + if (mode != ProliferationMode.None && + (level <= 0 || !catalog.TryGetProliferation(level, out speedBonus, out _, out powerMultiplier))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "The launch ammunition's proliferation level is unavailable.", + buildingItemId: building.ItemId); + return false; + } + + var nativeStep = Math.Truncate(10000 * (1 + speedBonus) + 0.1) * (boosted ? 10 : 1); + if (nativeStep <= 0 || double.IsInfinity(nativeStep) || double.IsNaN(nativeStep)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The launcher's native speed is outside the supported range.", buildingItemId: building.ItemId); + return false; + } + + var cycleTicks = Math.Ceiling(building.LaunchChargeTicks * 10000.0 / nativeStep) + + Math.Ceiling(building.LaunchCooldownTicks * 10000.0 / nativeStep); + var launchesPerMinute = 3600.0 / cycleTicks; + if (launchesPerMinute <= 0 || double.IsInfinity(launchesPerMinute) || + double.IsNaN(launchesPerMinute)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The launcher cycle is outside the supported range.", buildingItemId: building.ItemId); + return false; + } + + process = new ProductionProcess(0, building.ItemId, mode, + mode == ProliferationMode.None ? 0 : level, + new[] { new KeyValuePair(building.AmmunitionItemId, 1) }, + Array.Empty>(), launchesPerMinute, + building.WorkingPowerWatts * powerMultiplier, true, launchesPerCycle: 1); + return true; + } +} diff --git a/UXAssist/Production/MiningProcessAdapter.cs b/UXAssist/Production/MiningProcessAdapter.cs new file mode 100644 index 0000000..05b5970 --- /dev/null +++ b/UXAssist/Production/MiningProcessAdapter.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; + +namespace UXAssist.Production; + +public sealed class MiningProcessAdapter : IProductionProcessAdapter +{ + public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building) + { + return recipe == null && building?.Kind == ProductionBuildingKind.Miner; + } + + public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building, + ProliferationMode mode, int level, IReadOnlyDictionary operatingParameters, + out ProductionProcess process, out ProductionDiagnostic diagnostic) + { + process = null; + diagnostic = null; + if (building.MiningPeriodTicks <= 0 || building.MinerKind == ProductionMinerKind.None) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, + "The mining building has no native period or resource type.", buildingItemId: building.ItemId); + return false; + } + + if (operatingParameters == null || + !operatingParameters.TryGetValue("ResourceItemId", out var outputId) || + !ValidItemId(outputId) || !catalog.Items.ContainsKey((int)outputId) || + !operatingParameters.TryGetValue("MiningSpeedMultiplier", out var miningSpeed) || + !FinitePositive(miningSpeed)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Provide the resource item and mining technology speed.", buildingItemId: building.ItemId); + return false; + } + + var resourceFactor = 1.0; + if (building.MinerKind == ProductionMinerKind.Vein && + (!operatingParameters.TryGetValue("VeinCount", out resourceFactor) || + resourceFactor != Math.Truncate(resourceFactor) || !FinitePositive(resourceFactor))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Provide the number of covered veins.", buildingItemId: building.ItemId); + return false; + } + + if (building.MinerKind == ProductionMinerKind.Oil && + (!operatingParameters.TryGetValue("OilUnits", out resourceFactor) || + !FinitePositive(resourceFactor))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Provide the covered oil well's native flow factor.", buildingItemId: building.ItemId); + return false; + } + + var machineSpeed = 1.0; + if (operatingParameters.TryGetValue("MachineSpeedFactor", out var suppliedSpeed)) + { + if (!FinitePositive(suppliedSpeed)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The miner speed factor must be positive.", buildingItemId: building.ItemId); + return false; + } + + machineSpeed = suppliedSpeed; + } + + var speedDamper = 1.0; + if (operatingParameters.TryGetValue("SpeedDamper", out var suppliedDamper)) + { + if (!FinitePositive(suppliedDamper)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The miner speed damper must be positive.", buildingItemId: building.ItemId); + return false; + } + + speedDamper = suppliedDamper; + } + + var perMinute = ProductionUnits.TicksPerMinute * ProductionUnits.FixedPointScale / + building.MiningPeriodTicks * miningSpeed * machineSpeed * speedDamper * resourceFactor; + var powerRatio = speedDamper * machineSpeed * machineSpeed; + var workingWatts = building.WorkingPowerWatts * powerRatio + + building.IdlePowerWatts * (1 - powerRatio); + if (!FinitePositive(perMinute) || workingWatts < 0 || + double.IsNaN(workingWatts) || double.IsInfinity(workingWatts)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The mineral output rate or power demand is outside the supported range.", + buildingItemId: building.ItemId); + return false; + } + + process = new ProductionProcess(0, building.ItemId, ProliferationMode.None, 0, + Array.Empty>(), + new[] { new KeyValuePair((int)outputId, 1) }, + perMinute, workingWatts, true); + return true; + } + + private static bool ValidItemId(double value) + { + return value > 0 && value <= int.MaxValue && value == Math.Truncate(value); + } + + private static bool FinitePositive(double value) + { + return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value); + } +} diff --git a/UXAssist/Production/ProcessEvaluator.cs b/UXAssist/Production/ProcessEvaluator.cs new file mode 100644 index 0000000..cc3ab63 --- /dev/null +++ b/UXAssist/Production/ProcessEvaluator.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UXAssist.Production; + +public sealed class ProcessEvaluator +{ + private readonly IProductionProcessAdapter[] _adapters; + + public ProcessEvaluator(IEnumerable adapters = null) + { + _adapters = (adapters ?? Array.Empty()) + .Concat(new IProductionProcessAdapter[] + { + new FractionationProcessAdapter(), + new AccumulatorExchangeAdapter(), + new RenewableGenerationAdapter(), + new MiningProcessAdapter(), + new FuelGenerationAdapter(), + new RayReceiverAdapter(), + new LaunchProcessAdapter(), + new GasCollectionAdapter(), + new ResearchProcessAdapter() + }).ToArray(); + } + + public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building, + ProliferationMode mode, int level, IReadOnlyDictionary operatingParameters, + out ProductionProcess process, out ProductionDiagnostic diagnostic) + { + process = null; + diagnostic = null; + if (catalog == null) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.DataNotReady, "Production data is not loaded."); + return false; + } + + foreach (var adapter in _adapters) + { + if (adapter.CanEvaluate(recipe, building)) + return adapter.TryEvaluate(catalog, recipe, building, mode, level, operatingParameters, + out process, out diagnostic); + } + + if (recipe == null) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, + "No process adapter supports the selected building without a recipe.", + buildingItemId: building?.ItemId ?? 0); + return false; + } + + if (!IsOrdinary(recipe.Category)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, + "The recipe requires a special-process adapter.", recipeId: recipe.Id, + buildingItemId: building?.ItemId ?? 0); + return false; + } + + if (building != null && (building.Category != recipe.Category || !FinitePositive(building.SpeedFactor) || + !FiniteNonnegative(building.WorkingPowerWatts))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding, + "The selected building cannot execute this recipe.", recipeId: recipe.Id, + buildingItemId: building.ItemId); + return false; + } + + if (recipe.TimeTicks <= 0 || !ValidFlows(recipe.Inputs) || !ValidFlows(recipe.Outputs) || + !Enum.IsDefined(typeof(ProliferationMode), mode)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The recipe or proliferation mode is invalid.", recipeId: recipe.Id); + return false; + } + + var speedBonus = 0.0; + var extraBonus = 0.0; + var powerMultiplier = 1.0; + if (mode != ProliferationMode.None) + { + if (recipe.Inputs.Count == 0 || level < 1 || + !catalog.TryGetProliferation(level, out speedBonus, out extraBonus, + out powerMultiplier) || + mode == ProliferationMode.ExtraProducts && !recipe.Productive) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "The selected proliferation mode or level is unavailable for this recipe.", recipeId: recipe.Id); + return false; + } + } + + var outputMultiplier = mode == ProliferationMode.ExtraProducts ? 1 + extraBonus : 1; + var cycleMultiplier = mode == ProliferationMode.Speedup ? 1 + speedBonus : 1; + var cycles = building == null ? 0 : + ProductionUnits.TicksPerMinute * building.SpeedFactor / recipe.TimeTicks * cycleMultiplier; + var power = building == null ? 0 : building.WorkingPowerWatts * powerMultiplier; + process = new ProductionProcess(recipe.Id, building?.ItemId ?? 0, mode, + mode == ProliferationMode.None ? 0 : level, recipe.Inputs, + recipe.Outputs.Select(output => new KeyValuePair(output.Key, output.Value * outputMultiplier)), + cycles, power, building != null); + return true; + } + + private static bool IsOrdinary(ProductionRecipeCategory category) + { + return category == ProductionRecipeCategory.Assemble || category == ProductionRecipeCategory.Smelt || + category == ProductionRecipeCategory.Chemical || category == ProductionRecipeCategory.Refine || + category == ProductionRecipeCategory.Particle || category == ProductionRecipeCategory.Research; + } + + private static bool ValidFlows(IReadOnlyDictionary flows) + { + return flows.All(flow => flow.Key > 0 && flow.Value > 0 && !double.IsNaN(flow.Value) && + !double.IsInfinity(flow.Value)); + } + + private static bool FinitePositive(double value) + { + return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value); + } + + private static bool FiniteNonnegative(double value) + { + return value >= 0 && !double.IsNaN(value) && !double.IsInfinity(value); + } +} diff --git a/UXAssist/Production/ProductionCatalogReader.cs b/UXAssist/Production/ProductionCatalogReader.cs new file mode 100644 index 0000000..5721016 --- /dev/null +++ b/UXAssist/Production/ProductionCatalogReader.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UXAssist.Common; +using UXAssist.Common.GameConstants; +using GameLogicProc = UXAssist.Common.GameLogic; + +namespace UXAssist.Production; + +public static class ProductionCatalogReader +{ + public static ProductionCatalog Capture() + { + var itemProtos = LDB.items?.dataArray; + var recipeProtos = LDB.recipes?.dataArray; + if (itemProtos == null || itemProtos.Length == 0 || recipeProtos == null || recipeProtos.Length == 0) + return null; + + var naturalItems = new HashSet(); + if (LDB.veins?.dataArray != null) + { + foreach (var vein in LDB.veins.dataArray) + { + if (vein != null && vein.MiningItem > 0) naturalItems.Add(vein.MiningItem); + } + } + + var proliferators = new HashSet(); + var buildings = new List(); + foreach (var item in itemProtos) + { + if (item?.prefabDesc == null) continue; + var prefab = item.prefabDesc; + if (prefab.isSpraycoster && prefab.incItemId != null) + proliferators.UnionWith(prefab.incItemId); + + var category = prefab.isLab ? ProductionRecipeCategory.Research : + prefab.isAssembler ? MapCategory(prefab.assemblerRecipeType) : ProductionRecipeCategory.None; + var kind = ClassifyBuilding(prefab); + if (category == ProductionRecipeCategory.None && kind == ProductionBuildingKind.Ordinary) continue; + var speed = prefab.isLab ? prefab.labAssembleSpeed : prefab.assemblerSpeed; + buildings.Add(new ProductionBuilding(item.ID, category, speed / 10000.0, + prefab.workEnergyPerTick * 60.0, prefab.idleEnergyPerTick * 60.0, kind, + prefab.genEnergyPerTick * 60.0, prefab.exchangeEnergyPerTick * 60.0, + prefab.maxExcEnergy, prefab.emptyId, prefab.fullId, + prefab.windForcedPower ? RenewablePowerSource.Wind : + prefab.photovoltaic ? RenewablePowerSource.Solar : + prefab.geothermal ? RenewablePowerSource.Geothermal : RenewablePowerSource.None, + prefab.minerType == EMinerType.Vein ? ProductionMinerKind.Vein : + prefab.minerType == EMinerType.Oil ? ProductionMinerKind.Oil : + prefab.minerType == EMinerType.Water ? ProductionMinerKind.Water : ProductionMinerKind.None, + prefab.minerPeriod, prefab.fuelMask, prefab.useFuelPerTick * 60.0, + prefab.powerProductId, prefab.powerProductHeat, prefab.powerCatalystMask, + prefab.isEjector ? prefab.ejectorChargeFrame : prefab.siloChargeFrame, + prefab.isEjector ? prefab.ejectorColdFrame : prefab.siloColdFrame, + prefab.isEjector ? prefab.ejectorBulletId : prefab.siloBulletId, + prefab.stationCollectSpeed)); + } + + var defaultRecipes = new Dictionary(); + var recipes = new List(); + foreach (var recipe in recipeProtos) + { + if (recipe == null || recipe.Items == null || recipe.ItemCounts == null || + recipe.Results == null || recipe.ResultCounts == null || + recipe.Items.Length != recipe.ItemCounts.Length || + recipe.Results.Length != recipe.ResultCounts.Length) continue; + + recipes.Add(new ProductionRecipe(recipe.ID, MapCategory(recipe.Type), recipe.TimeSpend, recipe.productive, + PairFlows(recipe.Items, recipe.ItemCounts), PairFlows(recipe.Results, recipe.ResultCounts))); + for (var resultIndex = 0; resultIndex < recipe.Results.Length; resultIndex++) + { + var productId = recipe.Results[resultIndex]; + if (!defaultRecipes.TryGetValue(productId, out var old) || resultIndex < old.resultIndex) + defaultRecipes[productId] = (recipe.ID, resultIndex); + } + } + + AddSpecialRecipes(itemProtos, buildings, recipes, defaultRecipes); + + var items = new List(); + foreach (var item in itemProtos) + { + if (item == null) continue; + var defaultRecipeId = item.maincraft?.ID ?? + (defaultRecipes.TryGetValue(item.ID, out var fallback) ? fallback.recipeId : 0); + var isProliferator = proliferators.Contains(item.ID); + items.Add(new ProductionItem(item.ID, defaultRecipeId, + naturalItems.Contains(item.ID) || !string.IsNullOrEmpty(item.MiningFrom), + ItemIds.DarkFogItemIds.Contains(item.ID), isProliferator ? item.Ability : 0, + isProliferator ? item.HpMax : 0, item.HeatValue, item.FuelType, + item.Productive, item.ID == ItemIds.StrangeAnnihilationFuelRod ? 2 : 1, + item.CatalystType, item.CatalystType > 0 ? item.Ability * 0.01 : 0)); + } + + var matrixIds = new HashSet(LabComponent.matrixIds); + var technologies = new List(); + if (LDB.techs?.dataArray != null) + { + foreach (var tech in LDB.techs.dataArray) + { + if (tech == null || !tech.IsLabTech || tech.Items == null || tech.ItemPoints == null || + tech.Items.Length != tech.ItemPoints.Length) continue; + var requirements = new Dictionary(); + for (var index = 0; index < tech.Items.Length; index++) + { + if (matrixIds.Contains(tech.Items[index])) + requirements[tech.Items[index]] = tech.ItemPoints[index]; + } + + technologies.Add(new ProductionTechnology(tech.ID, requirements)); + } + } + + return new ProductionCatalog(items, recipes, buildings, + (double[])Cargo.accTableMilli.Clone(), (double[])Cargo.incTableMilli.Clone(), + (double[])Cargo.powerTableRatio.Clone(), technologies); + } + + private static void AddSpecialRecipes(IEnumerable itemProtos, + IEnumerable buildings, ICollection recipes, + IDictionary defaultRecipes) + { + var itemIds = new HashSet(itemProtos.Where(item => item != null).Select(item => item.ID)); + var recipeIds = new HashSet(recipes.Select(recipe => recipe.Id)); + foreach (var building in buildings.OrderBy(building => building.ItemId)) + { + var inputItemId = 0; + int outputItemId; + ProductionRecipeCategory category; + if (building.Kind == ProductionBuildingKind.Exchanger) + { + inputItemId = building.EmptyAccumulatorItemId; + outputItemId = building.FullAccumulatorItemId; + category = ProductionRecipeCategory.Exchange; + if (inputItemId <= 0 || inputItemId == outputItemId || !itemIds.Contains(inputItemId)) continue; + } + else if (building.Kind == ProductionBuildingKind.RayReceiver) + { + outputItemId = building.PowerProductItemId; + category = ProductionRecipeCategory.PhotonStore; + } + else + { + continue; + } + + if (outputItemId <= 0 || !itemIds.Contains(outputItemId) || !recipeIds.Add(-outputItemId)) continue; + var inputs = inputItemId == 0 ? Array.Empty>() : + new[] { new KeyValuePair(inputItemId, 1) }; + recipes.Add(new ProductionRecipe(-outputItemId, category, 1, false, inputs, + new[] { new KeyValuePair(outputItemId, 1) })); + if (!defaultRecipes.ContainsKey(outputItemId)) defaultRecipes[outputItemId] = (-outputItemId, 0); + } + } + + private static IEnumerable> PairFlows(int[] itemIds, int[] counts) + { + for (var index = 0; index < itemIds.Length; index++) + yield return new KeyValuePair(itemIds[index], counts[index]); + } + + private static ProductionRecipeCategory MapCategory(ERecipeType type) + { + switch (type) + { + case ERecipeType.Smelt: return ProductionRecipeCategory.Smelt; + case ERecipeType.Chemical: return ProductionRecipeCategory.Chemical; + case ERecipeType.Refine: return ProductionRecipeCategory.Refine; + case ERecipeType.Assemble: return ProductionRecipeCategory.Assemble; + case ERecipeType.Particle: return ProductionRecipeCategory.Particle; + case ERecipeType.Research: return ProductionRecipeCategory.Research; + case ERecipeType.Fractionate: return ProductionRecipeCategory.Fractionate; + case ERecipeType.Exchange: return ProductionRecipeCategory.Exchange; + case ERecipeType.PhotonStore: return ProductionRecipeCategory.PhotonStore; + default: return ProductionRecipeCategory.None; + } + } + + private static ProductionBuildingKind ClassifyBuilding(PrefabDesc prefab) + { + if (prefab.isLab || prefab.isAssembler) return ProductionBuildingKind.Ordinary; + if (prefab.isFractionator) return ProductionBuildingKind.Fractionator; + if (prefab.isPowerExchanger) return ProductionBuildingKind.Exchanger; + if (prefab.gammaRayReceiver) return ProductionBuildingKind.RayReceiver; + if (prefab.minerType != EMinerType.None) return ProductionBuildingKind.Miner; + if (prefab.isCollectStation) return ProductionBuildingKind.Collector; + if (prefab.isEjector) return ProductionBuildingKind.Ejector; + if (prefab.isSilo) return ProductionBuildingKind.Silo; + if (prefab.isPowerGen) + return prefab.photovoltaic || prefab.windForcedPower || prefab.geothermal + ? ProductionBuildingKind.RenewableGenerator : ProductionBuildingKind.FuelGenerator; + if (prefab.isPowerConsumer && !prefab.isStation && !prefab.isDispenser) + return ProductionBuildingKind.Auxiliary; + return ProductionBuildingKind.Ordinary; + } +} + +public static class ProductionCatalogService +{ + private static ProductionCatalog _current; + private static bool _initialized; + + public static ProductionCatalog Current => _current; + public static event Action Changed; + + public static void Init() + { + if (_initialized) return; + _initialized = true; + GameLogicProc.OnDataLoaded += Rebuild; + GameLogicProc.OnGameBegin += Rebuild; + GameLogicProc.OnGameEnd += Clear; + } + + public static void Uninit() + { + if (!_initialized) return; + _initialized = false; + GameLogicProc.OnDataLoaded -= Rebuild; + GameLogicProc.OnGameBegin -= Rebuild; + GameLogicProc.OnGameEnd -= Clear; + Clear(); + } + + public static void Rebuild() + { + _current = ProductionCatalogReader.Capture(); + Changed.InvokeSafe(UXAssist.Logger, nameof(Changed)); + } + + private static void Clear() + { + if (_current == null) return; + _current = null; + Changed.InvokeSafe(UXAssist.Logger, nameof(Changed)); + } +} diff --git a/UXAssist/Production/ProductionModel.cs b/UXAssist/Production/ProductionModel.cs new file mode 100644 index 0000000..ad7f7b1 --- /dev/null +++ b/UXAssist/Production/ProductionModel.cs @@ -0,0 +1,355 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; + +namespace UXAssist.Production; + +public enum ProductionRecipeCategory +{ + None, + Smelt, + Chemical, + Refine, + Assemble, + Particle, + Research, + Fractionate, + Exchange, + PhotonStore +} + +internal static class ProductionUnits +{ + internal const double SecondsPerMinute = 60; + internal const double TicksPerSecond = 60; + internal const double TicksPerMinute = SecondsPerMinute * TicksPerSecond; + internal const double FixedPointScale = 10000; +} + +public enum ProliferationMode +{ + None, + Speedup, + ExtraProducts +} + +public enum ProductionBuildingKind +{ + Ordinary, + Fractionator, + Exchanger, + RayReceiver, + Miner, + Collector, + FuelGenerator, + RenewableGenerator, + Ejector, + Silo, + Auxiliary +} + +public enum RenewablePowerSource +{ + None, + Wind, + Solar, + Geothermal +} + +public enum ProductionMinerKind +{ + None, + Vein, + Oil, + Water +} + +public enum ProductionDiagnosticCode +{ + DataNotReady, + UnknownItem, + UnknownRecipe, + MissingBuilding, + IncompatibleBuilding, + UnsupportedProcess, + UnsupportedProliferation, + InvalidRequest, + DuplicateSelection, + MissingOperatingParameter, + Infeasible, + Unbounded, + IterationLimit, + Cancelled, + ConservationFailure +} + +public sealed class ProductionDiagnostic +{ + public ProductionDiagnosticCode Code { get; } + public string Message { get; } + public int ItemId { get; } + public int RecipeId { get; } + public int BuildingItemId { get; } + + public ProductionDiagnostic(ProductionDiagnosticCode code, string message, int itemId = 0, int recipeId = 0, + int buildingItemId = 0) + { + Code = code; + Message = message; + ItemId = itemId; + RecipeId = recipeId; + BuildingItemId = buildingItemId; + } +} + +public sealed class ProductionItem +{ + public int Id { get; } + public int DefaultRecipeId { get; } + public bool IsNatural { get; } + public bool IsDarkFogMaterial { get; } + public int ProliferationLevel { get; } + public int SpraysPerItem { get; } + public long HeatValueJoules { get; } + public int FuelTypeMask { get; } + public bool ProductiveFuel { get; } + public double StarOutputMultiplier { get; } + public int CatalystTypeMask { get; } + public double CatalystAbilityMultiplier { get; } + + public ProductionItem(int id, int defaultRecipeId, bool isNatural, bool isDarkFogMaterial, + int proliferationLevel, int spraysPerItem, long heatValueJoules = 0, int fuelTypeMask = 0, + bool productiveFuel = false, double starOutputMultiplier = 1, int catalystTypeMask = 0, + double catalystAbilityMultiplier = 0) + { + Id = id; + DefaultRecipeId = defaultRecipeId; + IsNatural = isNatural; + IsDarkFogMaterial = isDarkFogMaterial; + ProliferationLevel = proliferationLevel; + SpraysPerItem = spraysPerItem; + HeatValueJoules = heatValueJoules; + FuelTypeMask = fuelTypeMask; + ProductiveFuel = productiveFuel; + StarOutputMultiplier = starOutputMultiplier; + CatalystTypeMask = catalystTypeMask; + CatalystAbilityMultiplier = catalystAbilityMultiplier; + } +} + +public sealed class ProductionRecipe +{ + public int Id { get; } + public bool IsSynthetic => Id < 0; + public ProductionRecipeCategory Category { get; } + public int TimeTicks { get; } + public bool Productive { get; } + public IReadOnlyDictionary Inputs { get; } + public IReadOnlyDictionary Outputs { get; } + + public ProductionRecipe(int id, ProductionRecipeCategory category, int timeTicks, bool productive, + IEnumerable> inputs, IEnumerable> outputs) + { + Id = id; + Category = category; + TimeTicks = timeTicks; + Productive = productive; + Inputs = CopyFlows(inputs); + Outputs = CopyFlows(outputs); + } + + internal static IReadOnlyDictionary CopyFlows(IEnumerable> flows) + { + var result = new Dictionary(); + foreach (var flow in flows) + { + result[flow.Key] = result.TryGetValue(flow.Key, out var count) ? count + flow.Value : flow.Value; + } + + return new ReadOnlyDictionary(result); + } +} + +public sealed class ProductionTechnology +{ + public int Id { get; } + public IReadOnlyDictionary MatrixPointsPerHash { get; } + + public ProductionTechnology(int id, IEnumerable> matrixPointsPerHash) + { + Id = id; + MatrixPointsPerHash = ProductionRecipe.CopyFlows(matrixPointsPerHash); + } +} + +public sealed class ProductionBuilding +{ + public int ItemId { get; } + public ProductionRecipeCategory Category { get; } + public double SpeedFactor { get; } + public double WorkingPowerWatts { get; } + public double IdlePowerWatts { get; } + public ProductionBuildingKind Kind { get; } + public double RatedGenerationWatts { get; } + public double ExchangeRateWatts { get; } + public double AccumulatorEnergyJoules { get; } + public int EmptyAccumulatorItemId { get; } + public int FullAccumulatorItemId { get; } + public RenewablePowerSource RenewableSource { get; } + public ProductionMinerKind MinerKind { get; } + public int MiningPeriodTicks { get; } + public int FuelMask { get; } + public double FuelUseWatts { get; } + public int PowerProductItemId { get; } + public double PowerProductEnergyJoules { get; } + public int CatalystMask { get; } + public int LaunchChargeTicks { get; } + public int LaunchCooldownTicks { get; } + public int AmmunitionItemId { get; } + public int CollectorSpeedMultiplier { get; } + + public ProductionBuilding(int itemId, ProductionRecipeCategory category, double speedFactor, + double workingPowerWatts, double idlePowerWatts, + ProductionBuildingKind kind = ProductionBuildingKind.Ordinary, double ratedGenerationWatts = 0, + double exchangeRateWatts = 0, double accumulatorEnergyJoules = 0, + int emptyAccumulatorItemId = 0, int fullAccumulatorItemId = 0, + RenewablePowerSource renewableSource = RenewablePowerSource.None, + ProductionMinerKind minerKind = ProductionMinerKind.None, int miningPeriodTicks = 0, + int fuelMask = 0, double fuelUseWatts = 0, int powerProductItemId = 0, + double powerProductEnergyJoules = 0, int catalystMask = 0, + int launchChargeTicks = 0, int launchCooldownTicks = 0, int ammunitionItemId = 0, + int collectorSpeedMultiplier = 0) + { + ItemId = itemId; + Category = category; + SpeedFactor = speedFactor; + WorkingPowerWatts = workingPowerWatts; + IdlePowerWatts = idlePowerWatts; + Kind = kind; + RatedGenerationWatts = ratedGenerationWatts; + ExchangeRateWatts = exchangeRateWatts; + AccumulatorEnergyJoules = accumulatorEnergyJoules; + EmptyAccumulatorItemId = emptyAccumulatorItemId; + FullAccumulatorItemId = fullAccumulatorItemId; + RenewableSource = renewableSource; + MinerKind = minerKind; + MiningPeriodTicks = miningPeriodTicks; + FuelMask = fuelMask; + FuelUseWatts = fuelUseWatts; + PowerProductItemId = powerProductItemId; + PowerProductEnergyJoules = powerProductEnergyJoules; + CatalystMask = catalystMask; + LaunchChargeTicks = launchChargeTicks; + LaunchCooldownTicks = launchCooldownTicks; + AmmunitionItemId = ammunitionItemId; + CollectorSpeedMultiplier = collectorSpeedMultiplier; + } +} + +public sealed class ProductionCatalog +{ + private readonly double[] _speedBonus; + private readonly double[] _extraBonus; + private readonly double[] _powerMultiplier; + + public IReadOnlyDictionary Items { get; } + public IReadOnlyDictionary Recipes { get; } + public IReadOnlyDictionary Buildings { get; } + public IReadOnlyDictionary Technologies { get; } + public int MaximumProliferationLevel { get; } + + public ProductionCatalog(IEnumerable items, IEnumerable recipes, + IEnumerable buildings, double[] speedBonus, double[] extraBonus, double[] powerMultiplier, + IEnumerable technologies = null) + { + Items = new ReadOnlyDictionary(items.ToDictionary(item => item.Id)); + Recipes = new ReadOnlyDictionary(recipes.ToDictionary(recipe => recipe.Id)); + Buildings = new ReadOnlyDictionary(buildings.ToDictionary(building => building.ItemId)); + Technologies = new ReadOnlyDictionary( + (technologies ?? Array.Empty()).ToDictionary(tech => tech.Id)); + _speedBonus = (double[])speedBonus.Clone(); + _extraBonus = (double[])extraBonus.Clone(); + _powerMultiplier = (double[])powerMultiplier.Clone(); + MaximumProliferationLevel = Items.Values.Where(item => item.SpraysPerItem > 0) + .Select(item => item.ProliferationLevel).DefaultIfEmpty(0).Max(); + } + + public bool TryGetProliferation(int level, out double speedBonus, out double extraBonus, + out double powerMultiplier) + { + speedBonus = 0; + extraBonus = 0; + powerMultiplier = 1; + if (level < 0 || level >= _speedBonus.Length || level >= _extraBonus.Length || + level >= _powerMultiplier.Length) return false; + speedBonus = _speedBonus[level]; + extraBonus = _extraBonus[level]; + powerMultiplier = _powerMultiplier[level]; + return true; + } +} + +public sealed class ProductionProcess +{ + public int RecipeId { get; } + public int BuildingItemId { get; } + public ProliferationMode ProliferationMode { get; } + public int ProliferationLevel { get; } + public IReadOnlyDictionary InputsPerCycle { get; } + public IReadOnlyDictionary OutputsPerCycle { get; } + public double CyclesPerBuildingPerMinute { get; } + public double WorkingPowerWatts { get; } + public bool HasBuilding { get; } + public double CirculatingItemsPerBuildingPerMinute { get; } + public double GenerationWatts { get; } + public double AccumulatorChargingWatts { get; } + public double AccumulatorDischargingWatts { get; } + public double? DysonSphereRequirementWatts { get; } + public double SprayedInputsPerCycle { get; } + public IReadOnlyDictionary PreservedSpraysPerCycle { get; } + public bool PowerKnown { get; } + public double LaunchesPerCycle { get; } + public double ResearchHashesPerCycle { get; } + + public ProductionProcess(int recipeId, int buildingItemId, ProliferationMode proliferationMode, + int proliferationLevel, IEnumerable> inputsPerCycle, + IEnumerable> outputsPerCycle, double cyclesPerBuildingPerMinute, + double workingPowerWatts, bool hasBuilding, double circulatingItemsPerBuildingPerMinute = 0, + double generationWatts = 0, double accumulatorChargingWatts = 0, + double accumulatorDischargingWatts = 0, double? dysonSphereRequirementWatts = 0, + double? sprayedInputsPerCycle = null, bool powerKnown = true, double launchesPerCycle = 0, + double researchHashesPerCycle = 0, + IEnumerable> preservedSpraysPerCycle = null) + { + RecipeId = recipeId; + BuildingItemId = buildingItemId; + ProliferationMode = proliferationMode; + ProliferationLevel = proliferationLevel; + InputsPerCycle = ProductionRecipe.CopyFlows(inputsPerCycle); + OutputsPerCycle = ProductionRecipe.CopyFlows(outputsPerCycle); + CyclesPerBuildingPerMinute = cyclesPerBuildingPerMinute; + WorkingPowerWatts = workingPowerWatts; + HasBuilding = hasBuilding; + CirculatingItemsPerBuildingPerMinute = circulatingItemsPerBuildingPerMinute; + GenerationWatts = generationWatts; + AccumulatorChargingWatts = accumulatorChargingWatts; + AccumulatorDischargingWatts = accumulatorDischargingWatts; + DysonSphereRequirementWatts = dysonSphereRequirementWatts; + SprayedInputsPerCycle = sprayedInputsPerCycle ?? InputsPerCycle.Values.Sum(); + PreservedSpraysPerCycle = ProductionRecipe.CopyFlows( + preservedSpraysPerCycle ?? Array.Empty>()); + PowerKnown = powerKnown; + LaunchesPerCycle = launchesPerCycle; + ResearchHashesPerCycle = researchHashesPerCycle; + } +} + +public interface IProductionProcessAdapter +{ + bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building); + + bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building, + ProliferationMode mode, int level, IReadOnlyDictionary operatingParameters, + out ProductionProcess process, out ProductionDiagnostic diagnostic); +} diff --git a/UXAssist/Production/ProductionPlanRequest.cs b/UXAssist/Production/ProductionPlanRequest.cs new file mode 100644 index 0000000..0602e91 --- /dev/null +++ b/UXAssist/Production/ProductionPlanRequest.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; + +namespace UXAssist.Production; + +public sealed class ProductionTarget +{ + public int ItemId { get; } + public double ItemsPerMinute { get; } + + public ProductionTarget(int itemId, double itemsPerMinute) + { + ItemId = itemId; + ItemsPerMinute = itemsPerMinute; + } +} + +public sealed class ProductionPlanRequest +{ + public List Targets { get; } = new List(); + public HashSet ExternalMaterials { get; } = new HashSet(); + public Dictionary RecipeByItem { get; } = new Dictionary(); + public Dictionary ProliferationModeByItem { get; } = + new Dictionary(); + public Dictionary BuildingByRecipe { get; } = new Dictionary(); + public Dictionary BuildingByCategory { get; } = + new Dictionary(); + public Dictionary KnownExternalSurplus { get; } = new Dictionary(); + public HashSet SprayDeliveredItems { get; } = new HashSet(); + public Dictionary> OperatingParametersByRecipe { get; } = + new Dictionary>(); + public List AuxiliaryBuildings { get; } = new List(); + public bool ProliferationEnabled { get; set; } + public int ProliferatorItemId { get; set; } + public bool SelfSprayProliferator { get; set; } + public int IterationBudget { get; set; } = 20000; +} diff --git a/UXAssist/Production/ProductionPlanner.Report.cs b/UXAssist/Production/ProductionPlanner.Report.cs new file mode 100644 index 0000000..47f6ae1 --- /dev/null +++ b/UXAssist/Production/ProductionPlanner.Report.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UXAssist.Production; + +public sealed partial class ProductionPlanner +{ + private ProductionReport BuildReport(ProductionPlanRequest request, IDictionary targets, int[] rows, + ProductionProcess[] processes, int[] importItems, double[] solution, int importStart, int surplusStart, + int proliferatorItemId, double spraysPerBottle, List warnings, + int[] reusableSprayItems, int sprayCreditStart) + { + var remainingSprayCredits = new Dictionary(); + for (var index = 0; index < reusableSprayItems.Length; index++) + remainingSprayCredits[reusableSprayItems[index]] = solution[sprayCreditStart + index]; + var grossProduction = new Dictionary(); + var grossConsumption = new Dictionary(); + var producers = new Dictionary>(); + var consumers = new Dictionary>(); + var groups = new List(); + var activeRecipes = new HashSet(); + var powerComplete = true; + var workingPower = 0.0; + var peakPower = 0.0; + var generationWatts = 0.0; + var chargingWatts = 0.0; + var dischargingWatts = 0.0; + var dysonRequirementWatts = 0.0; + for (var index = 0; index < processes.Length; index++) + { + var executions = solution[index]; + if (executions <= 1e-9) continue; + var process = processes[index]; + activeRecipes.Add(process.RecipeId); + var output = ScaleFlows(process.OutputsPerCycle, executions); + var input = ScaleFlows(process.InputsPerCycle, executions); + if (proliferatorItemId > 0 && process.ProliferationMode != ProliferationMode.None && + process.SprayedInputsPerCycle > 0) + { + var sprays = process.SprayedInputsPerCycle * executions; + foreach (var itemId in reusableSprayItems) + { + var reused = Math.Min(remainingSprayCredits[itemId], + SprayedInputAmount(process, itemId) * executions); + remainingSprayCredits[itemId] -= reused; + sprays -= reused; + } + + if (sprays > 0) AddFlow(input, proliferatorItemId, sprays / spraysPerBottle); + } + + var groupIndex = groups.Count; + foreach (var flow in output) + { + AddFlow(grossProduction, flow.Key, flow.Value); + AddGroup(producers, flow.Key, groupIndex); + } + + foreach (var flow in input) + { + AddFlow(grossConsumption, flow.Key, flow.Value); + AddGroup(consumers, flow.Key, groupIndex); + } + + double? equivalentBuildings = null; + int? deploymentCount = null; + double? consumedWatts = null; + double? peakWatts = null; + if (process.HasBuilding && process.CyclesPerBuildingPerMinute > 0) + { + equivalentBuildings = executions / process.CyclesPerBuildingPerMinute; + if (!process.PowerKnown) powerComplete = false; + if (equivalentBuildings.Value > int.MaxValue || double.IsInfinity(equivalentBuildings.Value)) + { + powerComplete = false; + warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The rounded deployment count exceeds the supported range.", recipeId: process.RecipeId)); + } + else + { + deploymentCount = Math.Max(1, (int)Math.Ceiling(equivalentBuildings.Value - 1e-9)); + consumedWatts = equivalentBuildings.Value * process.WorkingPowerWatts; + peakWatts = deploymentCount.Value * process.WorkingPowerWatts; + workingPower += consumedWatts.Value; + peakPower += peakWatts.Value; + generationWatts += equivalentBuildings.Value * process.GenerationWatts; + chargingWatts += equivalentBuildings.Value * process.AccumulatorChargingWatts; + dischargingWatts += equivalentBuildings.Value * process.AccumulatorDischargingWatts; + dysonRequirementWatts += equivalentBuildings.Value * (process.DysonSphereRequirementWatts ?? 0); + } + } + else + { + powerComplete = false; + if (!warnings.Any(warning => warning.RecipeId == process.RecipeId && + (warning.Code == ProductionDiagnosticCode.MissingBuilding || + warning.Code == ProductionDiagnosticCode.IncompatibleBuilding))) + warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingBuilding, + "Select a building to calculate power for this recipe.", recipeId: process.RecipeId)); + } + + groups.Add(new ProductionGroupFlow(process, equivalentBuildings ?? 0, executions, equivalentBuildings, + deploymentCount, consumedWatts, peakWatts, output, input, + equivalentBuildings * process.GenerationWatts, + equivalentBuildings * process.AccumulatorChargingWatts, + equivalentBuildings * process.AccumulatorDischargingWatts, + equivalentBuildings * process.DysonSphereRequirementWatts, + executions * process.LaunchesPerCycle, + executions * process.ResearchHashesPerCycle)); + } + + var auxiliaryIds = new HashSet(); + foreach (var auxiliary in request.AuxiliaryBuildings) + { + if (auxiliary == null || auxiliary.Count <= 0 || auxiliary.RecipeId != 0) + { + powerComplete = false; + warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "Auxiliary power requires a positive building count and no production recipe.")); + continue; + } + + if (auxiliary.ObjectId != 0 && !auxiliaryIds.Add(auxiliary.ObjectId)) + { + warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.DuplicateSelection, + "An auxiliary building was selected more than once.", + buildingItemId: auxiliary.BuildingItemId)); + continue; + } + + if (!_catalog.Buildings.TryGetValue(auxiliary.BuildingItemId, out var building) || + building.Kind != ProductionBuildingKind.Auxiliary || + building.WorkingPowerWatts < 0 || double.IsInfinity(building.WorkingPowerWatts) || + double.IsNaN(building.WorkingPowerWatts) || + double.IsInfinity(building.WorkingPowerWatts * auxiliary.Count)) + { + powerComplete = false; + warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, + "The auxiliary building has no rated working power.", + buildingItemId: auxiliary.BuildingItemId)); + continue; + } + + var watts = building.WorkingPowerWatts * auxiliary.Count; + workingPower += watts; + peakPower += watts; + var process = new ProductionProcess(0, building.ItemId, ProliferationMode.None, 0, + Array.Empty>(), Array.Empty>(), + 1, building.WorkingPowerWatts, true); + groups.Add(new ProductionGroupFlow(process, auxiliary.Count, 0, auxiliary.Count, + auxiliary.Count, watts, watts, Array.Empty>(), + Array.Empty>())); + } + + if (proliferatorItemId > 0 && request.SprayDeliveredItems.Count > 0) + { + var sprays = request.SprayDeliveredItems.Sum(itemId => targets[itemId]); + foreach (var itemId in reusableSprayItems) + { + if (request.SprayDeliveredItems.Contains(itemId)) sprays -= remainingSprayCredits[itemId]; + } + + if (sprays > 0) AddFlow(grossConsumption, proliferatorItemId, sprays / spraysPerBottle); + } + + var imports = new Dictionary(); + for (var index = 0; index < importItems.Length; index++) + imports[importItems[index]] = solution[importStart + index]; + + var itemFlows = new List(); + for (var index = 0; index < rows.Length; index++) + { + var itemId = rows[index]; + var produced = grossProduction.TryGetValue(itemId, out var production) ? production : 0; + var consumed = grossConsumption.TryGetValue(itemId, out var consumption) ? consumption : 0; + var imported = imports.TryGetValue(itemId, out var externalImport) ? externalImport : 0; + var known = request.KnownExternalSurplus.TryGetValue(itemId, out var knownSupply) ? knownSupply : 0; + var delivered = targets.TryGetValue(itemId, out var target) ? target : 0; + var surplus = solution[surplusStart + index]; + var finalProduct = produced > 1e-9 && consumed <= 1e-9; + itemFlows.Add(new ProductionItemFlow(itemId, produced, consumed, imported, known, delivered, surplus, + imported, finalProduct, produced > 1e-9 && consumed > 1e-9 && surplus > 1e-9, + 0, producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty(), + consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty())); + } + + var diagnostics = warnings.Where(warning => warning.RecipeId == 0 || activeRecipes.Contains(warning.RecipeId)) + .ToList(); + var power = powerComplete ? new ProductionPower(workingPower, peakPower, generationWatts, + chargingWatts, dischargingWatts, dysonRequirementWatts, + request.AuxiliaryBuildings.Count == 0 ? ProductionPowerScope.ProductionBuildings : + ProductionPowerScope.ProductionBuildingsAndAuxiliary) : null; + var status = powerComplete && diagnostics.Count == 0 ? ProductionStatus.Complete : ProductionStatus.Partial; + return new ProductionReport(status, true, powerComplete, itemFlows, groups, diagnostics, power); + } + + private static Dictionary ScaleFlows(IReadOnlyDictionary flows, double multiplier) + { + return flows.ToDictionary(flow => flow.Key, flow => flow.Value * multiplier); + } + + private static void AddGroup(IDictionary> groups, int itemId, int groupIndex) + { + if (!groups.TryGetValue(itemId, out var indices)) + { + indices = new List(); + groups[itemId] = indices; + } + + indices.Add(groupIndex); + } +} diff --git a/UXAssist/Production/ProductionPlanner.cs b/UXAssist/Production/ProductionPlanner.cs new file mode 100644 index 0000000..04f36fc --- /dev/null +++ b/UXAssist/Production/ProductionPlanner.cs @@ -0,0 +1,305 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace UXAssist.Production; + +public sealed partial class ProductionPlanner +{ + private readonly ProductionCatalog _catalog; + private readonly ProcessEvaluator _evaluator; + + public ProductionPlanner(ProductionCatalog catalog, ProcessEvaluator evaluator = null) + { + _catalog = catalog; + _evaluator = evaluator ?? new ProcessEvaluator(); + } + + public ProductionReport Calculate(ProductionPlanRequest request, CancellationToken cancellation = default) + { + if (_catalog == null) + return ProductionReport.Failure(new ProductionDiagnostic(ProductionDiagnosticCode.DataNotReady, + "Production data is not loaded.")); + if (request == null || request.IterationBudget <= 0) + return Fail(ProductionDiagnosticCode.InvalidRequest, "A valid plan request and iteration budget are required."); + if (cancellation.IsCancellationRequested) + return Fail(ProductionDiagnosticCode.Cancelled, "The production plan was cancelled."); + + var targets = new SortedDictionary(); + foreach (var target in request.Targets) + { + if (target == null || target.ItemId <= 0 || !ValidNonnegative(target.ItemsPerMinute)) + return Fail(ProductionDiagnosticCode.InvalidRequest, "A target has an invalid item or rate."); + AddFlow(targets, target.ItemId, target.ItemsPerMinute); + if (!ValidNonnegative(targets[target.ItemId])) + return Fail(ProductionDiagnosticCode.InvalidRequest, "The combined target rate is too large."); + } + + foreach (var surplus in request.KnownExternalSurplus) + { + if (surplus.Key <= 0 || !ValidNonnegative(surplus.Value)) + return Fail(ProductionDiagnosticCode.InvalidRequest, "Known external surplus must be nonnegative."); + if (!_catalog.Items.ContainsKey(surplus.Key)) + return Fail(ProductionDiagnosticCode.UnknownItem, "An external-surplus item is unknown.", surplus.Key); + } + + if (request.SprayDeliveredItems.Any(itemId => !targets.ContainsKey(itemId))) + return Fail(ProductionDiagnosticCode.InvalidRequest, "Finished-product spraying requires a target item."); + if (!request.ProliferationEnabled && request.SprayDeliveredItems.Count > 0) + return Fail(ProductionDiagnosticCode.InvalidRequest, "Finished-product spraying requires proliferation."); + + var processes = new SortedDictionary<(int recipeId, int buildingId, ProliferationMode mode, int level), + ProductionProcess>(); + var externalItems = new SortedSet(); + var pending = new SortedSet(targets.Keys); + var visited = new HashSet(); + var warnings = new List(); + var hasSprayedInputs = false; + var hasSprayedTargets = request.SprayDeliveredItems.Any(id => targets[id] > 0); + ProductionItem proliferator = null; + if (request.ProliferationEnabled) + { + if (!_catalog.Items.TryGetValue(request.ProliferatorItemId, out proliferator) || + proliferator.SpraysPerItem <= 0 || proliferator.ProliferationLevel <= 0 || + proliferator.ProliferationLevel > _catalog.MaximumProliferationLevel) + return Fail(ProductionDiagnosticCode.InvalidRequest, "Select a valid proliferator item.", + request.ProliferatorItemId); + if (hasSprayedTargets) pending.Add(proliferator.Id); + } + + while (pending.Count > 0) + { + if (cancellation.IsCancellationRequested) + return Fail(ProductionDiagnosticCode.Cancelled, "The production plan was cancelled."); + var itemId = pending.Min; + pending.Remove(itemId); + if (!visited.Add(itemId)) continue; + if (!_catalog.Items.TryGetValue(itemId, out var item)) + return Fail(ProductionDiagnosticCode.UnknownItem, "A required item is unknown.", itemId); + + var hasExplicitRecipe = request.RecipeByItem.TryGetValue(itemId, out var recipeId); + if (item.IsDarkFogMaterial || request.ExternalMaterials.Contains(itemId) || + item.IsNatural && !hasExplicitRecipe) + { + externalItems.Add(itemId); + continue; + } + + if (!hasExplicitRecipe) recipeId = item.DefaultRecipeId; + if (recipeId == 0 || !_catalog.Recipes.TryGetValue(recipeId, out var recipe)) + return Fail(ProductionDiagnosticCode.UnknownRecipe, "An item has no selected production recipe.", itemId); + if (!recipe.Outputs.ContainsKey(itemId)) + return Fail(ProductionDiagnosticCode.InvalidRequest, "The selected recipe does not produce the item.", + itemId, recipeId); + + request.OperatingParametersByRecipe.TryGetValue(recipeId, out var parameters); + var mode = ProliferationMode.None; + if (request.ProliferationEnabled) + mode = request.ProliferationModeByItem.TryGetValue(itemId, out var selectedMode) + ? selectedMode : DefaultProliferationMode(recipe, parameters); + var level = mode == ProliferationMode.None ? 0 : proliferator.ProliferationLevel; + var buildingId = request.BuildingByRecipe.TryGetValue(recipeId, out var recipeBuildingId) + ? recipeBuildingId + : request.BuildingByCategory.TryGetValue(recipe.Category, out var categoryBuildingId) + ? categoryBuildingId : 0; + _catalog.Buildings.TryGetValue(buildingId, out var building); + if (buildingId > 0 && building == null) + warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingBuilding, + "The selected building is missing; material rates remain available.", itemId, recipeId, buildingId)); + + if (!_evaluator.TryEvaluate(_catalog, recipe, building, mode, level, parameters, + out var process, out var diagnostic)) + { + if (diagnostic.Code != ProductionDiagnosticCode.IncompatibleBuilding || + !_evaluator.TryEvaluate(_catalog, recipe, null, mode, level, parameters, + out process, out _)) + return ProductionReport.Failure(diagnostic); + warnings.Add(diagnostic); + } + else if (diagnostic != null) + { + warnings.Add(diagnostic); + } + + processes[(recipeId, buildingId, mode, level)] = process; + foreach (var input in process.InputsPerCycle.Keys) pending.Add(input); + if (mode == ProliferationMode.None || process.SprayedInputsPerCycle <= 0) continue; + hasSprayedInputs = true; + pending.Add(proliferator.Id); + } + + var sprayDemand = hasSprayedInputs || hasSprayedTargets; + var spraysPerBottle = 0.0; + if (sprayDemand) + { + spraysPerBottle = proliferator.SpraysPerItem; + if (request.SelfSprayProliferator) + { + _catalog.TryGetProliferation(proliferator.ProliferationLevel, out _, out var bonus, out _); + spraysPerBottle += Math.Floor(proliferator.SpraysPerItem * bonus + 0.1) - 1; + } + + if (spraysPerBottle <= 0) + return Fail(ProductionDiagnosticCode.InvalidRequest, "The selected proliferator has no usable sprays.", + proliferator.Id); + } + + var selectedProcesses = processes.Values.ToArray(); + var reusableSprayItems = sprayDemand + ? selectedProcesses.Where(process => process.ProliferationMode != ProliferationMode.None) + .SelectMany(process => process.PreservedSpraysPerCycle.Keys).Distinct().OrderBy(itemId => itemId).ToArray() + : Array.Empty(); + var itemIds = new SortedSet(targets.Keys); + itemIds.UnionWith(request.KnownExternalSurplus.Keys); + itemIds.UnionWith(externalItems); + foreach (var process in selectedProcesses) + { + itemIds.UnionWith(process.InputsPerCycle.Keys); + itemIds.UnionWith(process.OutputsPerCycle.Keys); + } + + if (sprayDemand) itemIds.Add(proliferator.Id); + var rows = itemIds.ToArray(); + var rowByItem = rows.Select((id, index) => (id, index)) + .ToDictionary(entry => entry.id, entry => entry.index); + var importItems = externalItems.ToArray(); + var processCount = selectedProcesses.Length; + var importStart = processCount; + var surplusStart = importStart + importItems.Length; + var sprayCreditStart = surplusStart + rows.Length; + var spraySupplySlackStart = sprayCreditStart + reusableSprayItems.Length; + var sprayDemandSlackStart = spraySupplySlackStart + reusableSprayItems.Length; + var columnCount = sprayDemandSlackStart + reusableSprayItems.Length; + var constraintCount = rows.Length + reusableSprayItems.Length * 2; + var matrix = new double[constraintCount, columnCount]; + var rhs = new double[constraintCount]; + var priorityProcesses = new double[columnCount]; + var priorityImports = new double[columnCount]; + var prioritySprayReuse = new double[columnCount]; + var prioritySurplus = new double[columnCount]; + + for (var index = 0; index < processCount; index++) + { + var process = selectedProcesses[index]; + priorityProcesses[index] = 1; + foreach (var input in process.InputsPerCycle) matrix[rowByItem[input.Key], index] -= input.Value; + foreach (var output in process.OutputsPerCycle) matrix[rowByItem[output.Key], index] += output.Value; + if (process.ProliferationMode != ProliferationMode.None && process.SprayedInputsPerCycle > 0) + matrix[rowByItem[proliferator.Id], index] -= + process.SprayedInputsPerCycle / spraysPerBottle; + } + + for (var index = 0; index < importItems.Length; index++) + { + matrix[rowByItem[importItems[index]], importStart + index] = 1; + priorityImports[importStart + index] = 1; + } + + for (var index = 0; index < rows.Length; index++) + { + var itemId = rows[index]; + var target = targets.TryGetValue(itemId, out var amount) ? amount : 0; + rhs[index] = target - (request.KnownExternalSurplus.TryGetValue(itemId, out var known) ? known : 0); + if (sprayDemand && itemId == proliferator.Id) + rhs[index] += request.SprayDeliveredItems.Sum(targetId => targets[targetId]) / spraysPerBottle; + matrix[index, surplusStart + index] = -1; + prioritySurplus[surplusStart + index] = 1; + } + + for (var index = 0; index < reusableSprayItems.Length; index++) + { + var itemId = reusableSprayItems[index]; + var supplyRow = rows.Length + index * 2; + var demandRow = supplyRow + 1; + for (var processIndex = 0; processIndex < processCount; processIndex++) + { + var process = selectedProcesses[processIndex]; + if (process.ProliferationMode != ProliferationMode.None && + process.PreservedSpraysPerCycle.TryGetValue(itemId, out var preserved)) + matrix[supplyRow, processIndex] = preserved; + matrix[demandRow, processIndex] = SprayedInputAmount(process, itemId); + } + + matrix[supplyRow, sprayCreditStart + index] = -1; + matrix[supplyRow, spraySupplySlackStart + index] = -1; + matrix[demandRow, sprayCreditStart + index] = -1; + matrix[demandRow, sprayDemandSlackStart + index] = -1; + matrix[rowByItem[proliferator.Id], sprayCreditStart + index] = 1 / spraysPerBottle; + if (request.SprayDeliveredItems.Contains(itemId)) rhs[demandRow] = -targets[itemId]; + prioritySprayReuse[sprayCreditStart + index] = -1; + } + + var solution = TwoPhaseSimplex.Solve(matrix, rhs, + new[] { priorityProcesses, priorityImports, prioritySprayReuse, prioritySurplus }, + request.IterationBudget, cancellation); + if (solution.Status != LinearSolveStatus.Optimal) + return SolverFailure(solution.Status); + for (var row = 0; row < constraintCount; row++) + { + var balance = -rhs[row]; + for (var column = 0; column < columnCount; column++) + balance += matrix[row, column] * solution.Values[column]; + if (Math.Abs(balance) > 1e-7 * Math.Max(1, Math.Abs(rhs[row]))) + return Fail(ProductionDiagnosticCode.ConservationFailure, + "The solved production ledger does not conserve this item.", + row < rows.Length ? rows[row] : reusableSprayItems[(row - rows.Length) / 2]); + } + + return BuildReport(request, targets, rows, selectedProcesses, importItems, solution.Values, + importStart, surplusStart, sprayDemand ? proliferator.Id : 0, spraysPerBottle, warnings, + reusableSprayItems, sprayCreditStart); + } + + private static double SprayedInputAmount(ProductionProcess process, int itemId) + { + if (process.ProliferationMode == ProliferationMode.None || process.SprayedInputsPerCycle <= 0 || + !process.InputsPerCycle.TryGetValue(itemId, out var amount)) return 0; + if (process.InputsPerCycle.Count == 1) return Math.Min(amount, process.SprayedInputsPerCycle); + return process.SprayedInputsPerCycle == process.InputsPerCycle.Values.Sum() ? amount : 0; + } + + private static ProliferationMode DefaultProliferationMode(ProductionRecipe recipe, + IReadOnlyDictionary operatingParameters) + { + if (recipe.Category == ProductionRecipeCategory.Fractionate || + recipe.Category == ProductionRecipeCategory.Exchange) return ProliferationMode.Speedup; + if (recipe.Category == ProductionRecipeCategory.PhotonStore) + return operatingParameters != null && + operatingParameters.TryGetValue("LensItemId", out var lensItemId) && lensItemId > 0 + ? ProliferationMode.Speedup : ProliferationMode.None; + if (recipe.Inputs.Count == 0) return ProliferationMode.None; + return recipe.Productive ? ProliferationMode.ExtraProducts : ProliferationMode.Speedup; + } + + private static bool ValidNonnegative(double value) + { + return value >= 0 && !double.IsNaN(value) && !double.IsInfinity(value); + } + + private static void AddFlow(IDictionary flows, int itemId, double amount) + { + flows[itemId] = (flows.TryGetValue(itemId, out var old) ? old : 0) + amount; + } + + private static ProductionReport Fail(ProductionDiagnosticCode code, string message, int itemId = 0, + int recipeId = 0) + { + return ProductionReport.Failure(new ProductionDiagnostic(code, message, itemId, recipeId)); + } + + private static ProductionReport SolverFailure(LinearSolveStatus status) + { + switch (status) + { + case LinearSolveStatus.Infeasible: + return Fail(ProductionDiagnosticCode.Infeasible, "The selected processes cannot satisfy the targets."); + case LinearSolveStatus.Unbounded: + return Fail(ProductionDiagnosticCode.Unbounded, "The production model is unbounded."); + case LinearSolveStatus.IterationLimit: + return Fail(ProductionDiagnosticCode.IterationLimit, "The simplex iteration budget was exhausted."); + default: + return Fail(ProductionDiagnosticCode.Cancelled, "The production plan was cancelled."); + } + } +} diff --git a/UXAssist/Production/ProductionReports.cs b/UXAssist/Production/ProductionReports.cs new file mode 100644 index 0000000..875b93a --- /dev/null +++ b/UXAssist/Production/ProductionReports.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; + +namespace UXAssist.Production; + +public enum ProductionStatus +{ + Complete, + Partial, + Failed, + DataNotReady +} + +public enum ProductionPowerScope +{ + ProductionBuildings, + SelectedFacilities, + ProductionBuildingsAndAuxiliary +} + +public sealed class ProductionPower +{ + public double ConsumptionWatts { get; } + public double PeakConsumptionWatts { get; } + public double GenerationWatts { get; } + public double AccumulatorChargingWatts { get; } + public double AccumulatorDischargingWatts { get; } + public double DysonSphereRequirementWatts { get; } + public ProductionPowerScope Scope { get; } + + public ProductionPower(double consumptionWatts, double peakConsumptionWatts, double generationWatts, + double accumulatorChargingWatts, double accumulatorDischargingWatts, double dysonSphereRequirementWatts, + ProductionPowerScope scope) + { + ConsumptionWatts = consumptionWatts; + PeakConsumptionWatts = peakConsumptionWatts; + GenerationWatts = generationWatts; + AccumulatorChargingWatts = accumulatorChargingWatts; + AccumulatorDischargingWatts = accumulatorDischargingWatts; + DysonSphereRequirementWatts = dysonSphereRequirementWatts; + Scope = scope; + } +} + +public sealed class ProductionItemFlow +{ + public int ItemId { get; } + public double GrossProduction { get; } + public double GrossConsumption { get; } + public double NetFlow => GrossProduction - GrossConsumption; + public double ExternalImports { get; } + public double KnownExternalSupply { get; } + public double Delivered { get; } + public double Surplus { get; } + public double RequiredExternalSupply { get; } + public bool IsFinalProduct { get; } + public bool IsExcessIntermediate { get; } + public double SingleBuildingSurplusThreshold { get; } + public IReadOnlyList ProducerGroups { get; } + public IReadOnlyList ConsumerGroups { get; } + + public ProductionItemFlow(int itemId, double grossProduction, double grossConsumption, double externalImports, + double knownExternalSupply, double delivered, double surplus, double requiredExternalSupply, + bool isFinalProduct, bool isExcessIntermediate, double singleBuildingSurplusThreshold, + IEnumerable producerGroups, IEnumerable consumerGroups) + { + ItemId = itemId; + GrossProduction = grossProduction; + GrossConsumption = grossConsumption; + ExternalImports = externalImports; + KnownExternalSupply = knownExternalSupply; + Delivered = delivered; + Surplus = surplus; + RequiredExternalSupply = requiredExternalSupply; + IsFinalProduct = isFinalProduct; + IsExcessIntermediate = isExcessIntermediate; + SingleBuildingSurplusThreshold = singleBuildingSurplusThreshold; + ProducerGroups = Array.AsReadOnly(producerGroups.ToArray()); + ConsumerGroups = Array.AsReadOnly(consumerGroups.ToArray()); + } +} + +public sealed class ProductionGroupFlow +{ + public ProductionProcess Process { get; } + public double BuildingCount { get; } + public double ExecutionsPerMinute { get; } + public double? EquivalentBuildings { get; } + public int? RoundedDeploymentCount { get; } + public double? ConsumptionWatts { get; } + public double? PeakConsumptionWatts { get; } + public double? GenerationWatts { get; } + public double? AccumulatorChargingWatts { get; } + public double? AccumulatorDischargingWatts { get; } + public double? DysonSphereRequirementWatts { get; } + public double LaunchesPerMinute { get; } + public double ResearchHashesPerMinute { get; } + public IReadOnlyDictionary GrossProduction { get; } + public IReadOnlyDictionary GrossConsumption { get; } + + public ProductionGroupFlow(ProductionProcess process, double buildingCount, double executionsPerMinute, + double? equivalentBuildings, int? roundedDeploymentCount, double? consumptionWatts, + double? peakConsumptionWatts, + IEnumerable> grossProduction, + IEnumerable> grossConsumption, double? generationWatts = 0, + double? accumulatorChargingWatts = 0, double? accumulatorDischargingWatts = 0, + double? dysonSphereRequirementWatts = 0, double launchesPerMinute = 0, + double researchHashesPerMinute = 0) + { + Process = process; + BuildingCount = buildingCount; + ExecutionsPerMinute = executionsPerMinute; + EquivalentBuildings = equivalentBuildings; + RoundedDeploymentCount = roundedDeploymentCount; + ConsumptionWatts = consumptionWatts; + PeakConsumptionWatts = peakConsumptionWatts; + GenerationWatts = generationWatts; + AccumulatorChargingWatts = accumulatorChargingWatts; + AccumulatorDischargingWatts = accumulatorDischargingWatts; + DysonSphereRequirementWatts = dysonSphereRequirementWatts; + LaunchesPerMinute = launchesPerMinute; + ResearchHashesPerMinute = researchHashesPerMinute; + GrossProduction = ProductionRecipe.CopyFlows(grossProduction); + GrossConsumption = ProductionRecipe.CopyFlows(grossConsumption); + } +} + +public sealed class ProductionReport +{ + public ProductionStatus Status { get; } + public bool MaterialComplete { get; } + public bool PowerComplete { get; } + public IReadOnlyDictionary ItemFlows { get; } + public IReadOnlyList Groups { get; } + public IReadOnlyList Diagnostics { get; } + public ProductionPower Power { get; } + public double LaunchesPerMinute => Groups.Sum(group => group.LaunchesPerMinute); + public double ResearchHashesPerMinute => Groups.Sum(group => group.ResearchHashesPerMinute); + + public ProductionReport(ProductionStatus status, bool materialComplete, bool powerComplete, + IEnumerable itemFlows, IEnumerable groups, + IEnumerable diagnostics, ProductionPower power) + { + Status = status; + MaterialComplete = materialComplete; + PowerComplete = powerComplete; + ItemFlows = new ReadOnlyDictionary(itemFlows.ToDictionary(flow => flow.ItemId)); + Groups = Array.AsReadOnly(groups.ToArray()); + Diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + Power = power; + } + + internal static ProductionReport Failure(ProductionDiagnostic diagnostic) + { + return new ProductionReport(diagnostic.Code == ProductionDiagnosticCode.DataNotReady + ? ProductionStatus.DataNotReady : ProductionStatus.Failed, + false, false, Array.Empty(), Array.Empty(), + new[] { diagnostic }, null); + } +} diff --git a/UXAssist/Production/RayReceiverAdapter.cs b/UXAssist/Production/RayReceiverAdapter.cs new file mode 100644 index 0000000..db0e1e7 --- /dev/null +++ b/UXAssist/Production/RayReceiverAdapter.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; + +namespace UXAssist.Production; + +public sealed class RayReceiverAdapter : IProductionProcessAdapter +{ + public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building) + { + return building?.Kind == ProductionBuildingKind.RayReceiver || + recipe?.Category == ProductionRecipeCategory.PhotonStore; + } + + public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building, + ProliferationMode mode, int level, IReadOnlyDictionary operatingParameters, + out ProductionProcess process, out ProductionDiagnostic diagnostic) + { + process = null; + diagnostic = null; + if (building?.Kind != ProductionBuildingKind.RayReceiver) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingBuilding, + "Select a ray receiver to evaluate photon generation.", recipeId: recipe?.Id ?? 0); + return false; + } + + if (building.RatedGenerationWatts <= 0 || !Finite(building.RatedGenerationWatts) || + (recipe != null && (recipe.Category != ProductionRecipeCategory.PhotonStore || + recipe.Inputs.Count != 0 || recipe.Outputs.Count != 1 || + !recipe.Outputs.ContainsKey(building.PowerProductItemId)))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding, + "The receiver's native photon product or power rating does not match the recipe.", + recipeId: recipe?.Id ?? 0, buildingItemId: building.ItemId); + return false; + } + + var photonMode = recipe != null; + if (operatingParameters == null) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Provide the receiver's operating settings.", buildingItemId: building.ItemId); + return false; + } + + var hasMode = operatingParameters.TryGetValue("Mode0", out var selectedMode); + if (!hasMode && !photonMode || + hasMode && (selectedMode != 0 && selectedMode != building.PowerProductItemId || + photonMode && selectedMode != building.PowerProductItemId)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Select the receiver's grid or native photon operating mode.", + recipeId: recipe?.Id ?? 0, buildingItemId: building.ItemId); + return false; + } + + if (recipe == null && selectedMode > 0) photonMode = true; + if (photonMode && (building.PowerProductItemId <= 0 || + building.PowerProductEnergyJoules <= 0 || + !Finite(building.PowerProductEnergyJoules) || + !catalog.Items.ContainsKey(building.PowerProductItemId))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The ray receiver has no valid native photon product or required photon energy.", + buildingItemId: building.ItemId); + return false; + } + + if (!operatingParameters.TryGetValue("LensItemId", out var lensId) || + lensId < 0 || lensId > int.MaxValue || lensId != Math.Truncate(lensId)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Provide the receiver's lens item ID, or zero for no lens.", buildingItemId: building.ItemId); + return false; + } + + ProductionItem lens = null; + if (lensId > 0 && (!catalog.Items.TryGetValue((int)lensId, out lens) || + (lens.CatalystTypeMask & building.CatalystMask) == 0 || + lens.CatalystAbilityMultiplier <= 0 || !Finite(lens.CatalystAbilityMultiplier))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The selected item is not a compatible ray-receiver lens.", + itemId: (int)lensId, buildingItemId: building.ItemId); + return false; + } + + if (mode != ProliferationMode.None && mode != ProliferationMode.Speedup || + mode == ProliferationMode.Speedup && lens == null) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "Only an installed lens can receive native ray-receiver speedup.", buildingItemId: building.ItemId); + return false; + } + + var speedBonus = 0.0; + if (mode != ProliferationMode.None && + (level <= 0 || !catalog.TryGetProliferation(level, out speedBonus, out _, out _))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "The lens's proliferation level is unavailable.", buildingItemId: building.ItemId); + return false; + } + + var energyWatts = building.RatedGenerationWatts * 2.5 * + (lens?.CatalystAbilityMultiplier ?? 1) * + (1 + speedBonus) * (photonMode ? 8 : 1); + var cyclesPerMinute = photonMode + ? energyWatts * 60 / building.PowerProductEnergyJoules : 1; + if (cyclesPerMinute <= 0 || !Finite(cyclesPerMinute) || !Finite(energyWatts)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The receiver's native output is outside the supported range.", buildingItemId: building.ItemId); + return false; + } + + var lossKnown = operatingParameters.TryGetValue("SolarEnergyLossRate", out var solarLoss); + if (lossKnown && (solarLoss < 0 || solarLoss >= 1 || !Finite(solarLoss))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "Solar energy loss must be a finite fraction below one.", buildingItemId: building.ItemId); + return false; + } + + if (!lossKnown) + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "The Dyson-sphere power requirement needs the current solar energy loss technology setting.", + buildingItemId: building.ItemId); + + var lensFlow = lens == null ? Array.Empty>() : + new[] { new KeyValuePair(lens.Id, 0.1 / cyclesPerMinute) }; + var productFlow = photonMode + ? new[] { new KeyValuePair(building.PowerProductItemId, 1) } + : Array.Empty>(); + process = new ProductionProcess(recipe?.Id ?? 0, building.ItemId, mode, + mode == ProliferationMode.None ? 0 : level, lensFlow, productFlow, + cyclesPerMinute, building.WorkingPowerWatts, true, + generationWatts: photonMode ? 0 : energyWatts, + dysonSphereRequirementWatts: lossKnown ? energyWatts / (1 - solarLoss * 0.6) : (double?)null, + powerKnown: lossKnown); + return true; + } + + private static bool Finite(double value) + { + return !double.IsNaN(value) && !double.IsInfinity(value); + } +} diff --git a/UXAssist/Production/RenewableGenerationAdapter.cs b/UXAssist/Production/RenewableGenerationAdapter.cs new file mode 100644 index 0000000..83bd942 --- /dev/null +++ b/UXAssist/Production/RenewableGenerationAdapter.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; + +namespace UXAssist.Production; + +public sealed class RenewableGenerationAdapter : IProductionProcessAdapter +{ + public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building) + { + return recipe == null && building?.Kind == ProductionBuildingKind.RenewableGenerator; + } + + public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building, + ProliferationMode mode, int level, IReadOnlyDictionary operatingParameters, + out ProductionProcess process, out ProductionDiagnostic diagnostic) + { + process = null; + diagnostic = null; + if (building.RenewableSource == RenewablePowerSource.None || + building.RatedGenerationWatts < 0 || double.IsNaN(building.RatedGenerationWatts) || + double.IsInfinity(building.RatedGenerationWatts)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, + "The generator has no renewable power rating.", buildingItemId: building.ItemId); + return false; + } + + process = new ProductionProcess(0, building.ItemId, ProliferationMode.None, 0, + Array.Empty>(), Array.Empty>(), + 1, building.WorkingPowerWatts, true, + generationWatts: building.RatedGenerationWatts); + return true; + } +} diff --git a/UXAssist/Production/ResearchProcessAdapter.cs b/UXAssist/Production/ResearchProcessAdapter.cs new file mode 100644 index 0000000..d85d7ec --- /dev/null +++ b/UXAssist/Production/ResearchProcessAdapter.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; + +namespace UXAssist.Production; + +public sealed class ResearchProcessAdapter : IProductionProcessAdapter +{ + public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building) + { + return recipe == null && building?.Kind == ProductionBuildingKind.Ordinary && + building.Category == ProductionRecipeCategory.Research; + } + + public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building, + ProliferationMode mode, int level, IReadOnlyDictionary operatingParameters, + out ProductionProcess process, out ProductionDiagnostic diagnostic) + { + process = null; + diagnostic = null; + if (operatingParameters == null || + !operatingParameters.TryGetValue("ResearchMode", out var researchMode) || researchMode != 1 || + !operatingParameters.TryGetValue("TechId", out var techId) || + techId <= 0 || techId > int.MaxValue || techId != Math.Truncate(techId) || + !operatingParameters.TryGetValue("ResearchSpeed", out var researchSpeed) || + !FinitePositive(researchSpeed)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, + "Research mode needs a lab technology and current research speed.", + buildingItemId: building.ItemId); + return false; + } + + if (!catalog.Technologies.TryGetValue((int)techId, out var tech)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The selected technology is not a lab-research technology.", + buildingItemId: building.ItemId); + return false; + } + + if (mode != ProliferationMode.None && mode != ProliferationMode.ExtraProducts) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "Research proliferation creates extra hashes, not faster research cycles.", + buildingItemId: building.ItemId); + return false; + } + + var extraBonus = 0.0; + var powerMultiplier = 1.0; + if (mode == ProliferationMode.ExtraProducts && + (level <= 0 || !catalog.TryGetProliferation(level, out _, out extraBonus, + out powerMultiplier))) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation, + "The matrix proliferation level is unavailable.", buildingItemId: building.ItemId); + return false; + } + + var baseHashes = 3600.0 * researchSpeed; + var hashRate = baseHashes * (1 + extraBonus); + var workingWatts = building.WorkingPowerWatts * powerMultiplier; + if (!FinitePositive(hashRate) || !FinitePositive(workingWatts)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The research hash rate or power demand is outside the supported range.", + buildingItemId: building.ItemId); + return false; + } + + var inputs = new List>(); + foreach (var requirement in tech.MatrixPointsPerHash) + { + if (!catalog.Items.ContainsKey(requirement.Key) || !FinitePositive(requirement.Value) || + !FinitePositive(researchSpeed * requirement.Value)) + { + diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "The technology has an invalid matrix point requirement.", + itemId: requirement.Key, buildingItemId: building.ItemId); + return false; + } + + inputs.Add(new KeyValuePair(requirement.Key, + researchSpeed * requirement.Value)); + } + + process = new ProductionProcess(0, building.ItemId, mode, + mode == ProliferationMode.None ? 0 : level, inputs, + Array.Empty>(), 1, workingWatts, true, + researchHashesPerCycle: hashRate); + return true; + } + + private static bool FinitePositive(double value) + { + return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value); + } +} diff --git a/UXAssist/Production/TwoPhaseSimplex.cs b/UXAssist/Production/TwoPhaseSimplex.cs new file mode 100644 index 0000000..b4b774c --- /dev/null +++ b/UXAssist/Production/TwoPhaseSimplex.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.Threading; + +namespace UXAssist.Production; + +internal enum LinearSolveStatus +{ + Optimal, + Infeasible, + Unbounded, + IterationLimit, + Cancelled +} + +internal sealed class LinearSolveResult +{ + internal LinearSolveStatus Status { get; } + internal double[] Values { get; } + + internal LinearSolveResult(LinearSolveStatus status, double[] values = null) + { + Status = status; + Values = values; + } +} + +internal static class TwoPhaseSimplex +{ + private const double PivotTolerance = 1e-10; + private const double ReducedTolerance = 1e-8; + + internal static LinearSolveResult Solve(double[,] coefficients, double[] rightHandSide, + IReadOnlyList objectives, int iterationBudget, CancellationToken cancellation) + { + var rowCount = rightHandSide.Length; + var columnCount = coefficients.GetLength(1); + if (coefficients.GetLength(0) != rowCount || iterationBudget <= 0) + throw new ArgumentException("The linear system or iteration budget is invalid."); + foreach (var objective in objectives) + { + if (objective.Length != columnCount) + throw new ArgumentException("An objective has an incorrect number of columns."); + } + + if (rowCount == 0) + return new LinearSolveResult(LinearSolveStatus.Optimal, new double[columnCount]); + + var width = columnCount + rowCount; + var tableau = new double[rowCount, width + 1]; + var basis = new int[rowCount]; + for (var row = 0; row < rowCount; row++) + { + var scale = 0.0; + for (var column = 0; column < columnCount; column++) + { + if (double.IsNaN(coefficients[row, column]) || double.IsInfinity(coefficients[row, column])) + throw new ArgumentException("The constraint matrix contains a non-finite number."); + scale = Math.Max(scale, Math.Abs(coefficients[row, column])); + } + + if (double.IsNaN(rightHandSide[row]) || double.IsInfinity(rightHandSide[row])) + throw new ArgumentException("The right-hand side contains a non-finite number."); + if (scale == 0) + { + if (Math.Abs(rightHandSide[row]) > PivotTolerance) + return new LinearSolveResult(LinearSolveStatus.Infeasible); + scale = 1; + } + + var sign = rightHandSide[row] < 0 ? -1 : 1; + for (var column = 0; column < columnCount; column++) + tableau[row, column] = sign * coefficients[row, column] / scale; + tableau[row, columnCount + row] = 1; + tableau[row, width] = sign * rightHandSide[row] / scale; + basis[row] = columnCount + row; + } + + var artificialObjective = new double[width]; + for (var row = 0; row < rowCount; row++) artificialObjective[columnCount + row] = 1; + var iterations = 0; + var firstStatus = Optimize(tableau, basis, artificialObjective, Array.Empty(), + columnCount, ref iterations, iterationBudget, cancellation); + if (firstStatus != LinearSolveStatus.Optimal) + return new LinearSolveResult(firstStatus == LinearSolveStatus.Unbounded + ? LinearSolveStatus.Infeasible : firstStatus); + + for (var row = 0; row < rowCount; row++) + { + if (basis[row] < columnCount) continue; + if (Math.Abs(tableau[row, width]) > ReducedTolerance) + return new LinearSolveResult(LinearSolveStatus.Infeasible); + + for (var column = 0; column < columnCount; column++) + { + if (Contains(basis, column) || Math.Abs(tableau[row, column]) <= PivotTolerance) continue; + Pivot(tableau, basis, row, column); + break; + } + } + + var optimizedObjectives = new List(); + foreach (var objective in objectives) + { + var costs = new double[width]; + Array.Copy(objective, costs, columnCount); + var status = Optimize(tableau, basis, costs, optimizedObjectives, columnCount, + ref iterations, iterationBudget, cancellation); + if (status != LinearSolveStatus.Optimal) return new LinearSolveResult(status); + optimizedObjectives.Add(costs); + } + + var values = new double[columnCount]; + for (var row = 0; row < rowCount; row++) + { + if (basis[row] < columnCount) + values[basis[row]] = Math.Max(0, tableau[row, width]); + } + + return new LinearSolveResult(LinearSolveStatus.Optimal, values); + } + + private static LinearSolveStatus Optimize(double[,] tableau, int[] basis, double[] costs, + IReadOnlyList previousCosts, int enteringLimit, ref int iterations, int budget, + CancellationToken cancellation) + { + var rowCount = basis.Length; + var rightColumn = tableau.GetLength(1) - 1; + while (true) + { + if (cancellation.IsCancellationRequested) return LinearSolveStatus.Cancelled; + var entering = -1; + for (var column = 0; column < enteringLimit; column++) + { + if (Contains(basis, column) || ReducedCost(tableau, basis, costs, column) >= -ReducedTolerance) + continue; + var preservesPrevious = true; + foreach (var previous in previousCosts) + { + if (Math.Abs(ReducedCost(tableau, basis, previous, column)) <= ReducedTolerance) continue; + preservesPrevious = false; + break; + } + + if (preservesPrevious) + { + entering = column; + break; + } + } + + if (entering < 0) return LinearSolveStatus.Optimal; + if (iterations >= budget) return LinearSolveStatus.IterationLimit; + + var leaving = -1; + var minRatio = double.PositiveInfinity; + for (var row = 0; row < rowCount; row++) + { + var coefficient = tableau[row, entering]; + if (coefficient <= PivotTolerance) continue; + var ratio = Math.Max(0, tableau[row, rightColumn]) / coefficient; + if (ratio < minRatio - ReducedTolerance || + Math.Abs(ratio - minRatio) <= ReducedTolerance && + (leaving < 0 || basis[row] < basis[leaving])) + { + minRatio = ratio; + leaving = row; + } + } + + if (leaving < 0) return LinearSolveStatus.Unbounded; + Pivot(tableau, basis, leaving, entering); + iterations++; + } + } + + private static double ReducedCost(double[,] tableau, int[] basis, double[] costs, int column) + { + var reduced = costs[column]; + for (var row = 0; row < basis.Length; row++) + reduced -= costs[basis[row]] * tableau[row, column]; + return reduced; + } + + private static bool Contains(int[] basis, int column) + { + foreach (var basic in basis) + { + if (basic == column) return true; + } + + return false; + } + + private static void Pivot(double[,] tableau, int[] basis, int pivotRow, int pivotColumn) + { + var rowCount = basis.Length; + var width = tableau.GetLength(1); + var divisor = tableau[pivotRow, pivotColumn]; + for (var column = 0; column < width; column++) + tableau[pivotRow, column] /= divisor; + + for (var row = 0; row < rowCount; row++) + { + if (row == pivotRow) continue; + var factor = tableau[row, pivotColumn]; + if (factor == 0) continue; + for (var column = 0; column < width; column++) + tableau[row, column] -= factor * tableau[pivotRow, column]; + tableau[row, pivotColumn] = 0; + } + + tableau[pivotRow, pivotColumn] = 1; + basis[pivotRow] = pivotColumn; + } +} diff --git a/UXAssist/UXAssist.cs b/UXAssist/UXAssist.cs index 3030187..b2c0355 100644 --- a/UXAssist/UXAssist.cs +++ b/UXAssist/UXAssist.cs @@ -17,6 +17,7 @@ using UXAssist.Functions.Factory; using UXAssist.Patches; using UXAssist.Patches.Factory; using UXAssist.Patches.Logistics; +using UXAssist.Production; using UXAssist.UI; using Util = UXAssist.Common.Util; using GameLogicProc = UXAssist.Common.GameLogic; @@ -239,6 +240,7 @@ public class UXAssist : BaseUnityPlugin, IModCanSave // UI Patches GameLogicProc.Enable(true); + ProductionCatalogService.Init(); UIConfigWindow.Init(); @@ -280,6 +282,7 @@ public class UXAssist : BaseUnityPlugin, IModCanSave _patches?.Do(type => type.GetMethod("Uninit")?.Invoke(null, null)); MyWindowManager.Enable(false); + ProductionCatalogService.Uninit(); GameLogicProc.Enable(false); } diff --git a/UXAssist/UXAssist.csproj b/UXAssist/UXAssist.csproj index 1a9d36b..a2006ab 100644 --- a/UXAssist/UXAssist.csproj +++ b/UXAssist/UXAssist.csproj @@ -10,6 +10,7 @@ + diff --git a/UXAssist/docs/ProductionArchitecture.md b/UXAssist/docs/ProductionArchitecture.md new file mode 100644 index 0000000..695c12f --- /dev/null +++ b/UXAssist/docs/ProductionArchitecture.md @@ -0,0 +1,100 @@ +# Production Calculation Architecture + +UXAssist exposes a shared production catalog, a material planner, a fixed-building black box analyzer, and blueprint capture. These APIs calculate reports; they do not change DSP production, replace factory updates, or provide a calculator UI. + +## Data and lifecycle + +- `ProductionCatalogService.Current` is an immutable snapshot of loaded item, recipe, technology, building, `PrefabDesc`, and `Cargo` data. The service rebuilds after data preload and on game begin, so changes made by later preload callbacks are captured. It clears the snapshot when a game ends. It can be `null` before preload. Subscribe to `ProductionCatalogService.Changed` to invalidate derived reports and retry against the current snapshot; the event also reports clearing the catalog. +- Capture a live blueprint selection on the game thread. The planner, black box analyzer, adapters, and simplex implementation read only immutable snapshots and managed request data. They do not retain game component references or inspect current inventories during calculation. +- Material rates use `double` items per minute; process executions, hashes, and launches are also per minute. Native simulation runs at 60 ticks per second, so recipe cycle rates use 3,600 ticks per minute, not 60. Convert fixed-point speed values by 10,000 and energy per tick to watts by 60. Gas speeds arrive in items per second and must also be converted to per-minute outputs. Round only for display and for the separately reported building deployment count. +- A report carries separate `MaterialComplete` and `PowerComplete` flags, `Diagnostics`, individual `ItemFlows`, and `Groups`. `ProductionPower` is `null` if any power requirement is unknown; a group's unknown Dyson-sphere demand is also `null`. Do not interpret an absent power result as zero. + +Accumulator charging and critical photon production have no native `RecipeProto` entries. The catalog adds calculation-only recipes from the captured exchanger and receiver metadata, with stable IDs equal to the negative output item ID. `ProductionRecipe.IsSynthetic` identifies these entries. Resolve them through `ProductionCatalog.Recipes`, never through `LDB.recipes` or a native building recipe setter. They supply default routes only when no native recipe provides one. + +## Global production planning + +Select a target and, if desired, a building for the recipe or its category: + +```csharp +var request = new ProductionPlanRequest(); +request.Targets.Add(new ProductionTarget(itemId, 60)); +request.BuildingByCategory[ProductionRecipeCategory.Assemble] = assemblerItemId; +request.ExternalMaterials.Add(rawResourceItemId); + +var report = new ProductionPlanner(ProductionCatalogService.Current).Calculate(request); +if (report.MaterialComplete) +{ + var rawImportsPerMinute = report.ItemFlows[rawResourceItemId].ExternalImports; +} +``` + +The solver includes all selected recipes, coproducts, finite external supplies, permitted imports, and proliferator consumption in one material balance. It never silently chooses another recipe. Explicit boundaries and Dark Fog materials are external; natural items are external unless an explicit recipe overrides their default collection source. Without a building choice, material flows that do not depend on that choice remain available, but building power is incomplete. An explicit extra-products mode for a recipe without that native capability is an error. + +When proliferation is enabled, ordinary recipes default to their native extra-products or acceleration capability. Fractionation and accumulator exchange use acceleration; a ray receiver uses acceleration only with a lens. Per-item choices can override these defaults when the process supports the selected mode. + +`SelfSprayProliferator` uses the captured spray count and extra-products bonus to calculate effective sprays per produced proliferator, including the spray spent coating the proliferator itself. `SprayDeliveredItems` adds spraying for requested deliveries. Accumulators retain their coating during both charging and discharging: adapters expose `PreservedSpraysPerCycle`, and the planner credits that coating only against demand for the same item. Each credit is bounded by both preserved output and sprayed input or delivery demand, so coating is neither created nor charged twice. Credits reduce proliferator consumption, not material quantities. The solver minimizes process executions, then imports, maximizes valid spray reuse, and finally minimizes remaining surplus. + +`GrossProduction` and `GrossConsumption` are independent ledgers. `NetFlow` is their difference; imports, known supply, target delivery, and surplus remain separate fields. `Power.ConsumptionWatts` uses equivalent fully utilized buildings, whereas `PeakConsumptionWatts` uses rounded deployment counts. Fixed layout power is not inferred: add explicitly selected sorters, spray coaters, or other non-logistics auxiliary devices to `request.AuxiliaryBuildings`. The power scope then changes from `ProductionBuildings` to `ProductionBuildingsAndAuxiliary`. + +## Fixed-building analysis + +The black box evaluates each selected building at full load, even if another selected building cannot provide all its inputs. It does not simulate belt layouts, startup storage, or logistics throughput. Missing inputs appear as `RequiredExternalSupply`; byproducts and internal deficits retain producer and consumer group attribution. A positive intermediate balance is classified as excess only when it reaches the smallest net per-building output among actual producers of that item. The underlying fractional ledger is never discarded. + +```csharp +var capture = BlueprintSelectionReader.Capture(factory, selectedObjectIds); +var selection = capture.CreateRequest(proliferationEnabled: true); +var report = new FactoryBlackBoxAnalyzer(ProductionCatalogService.Current).Analyze(selection); +``` + +`Capture` accepts existing entity IDs and negative prebuild IDs. Its optional third argument is a `BlueprintSelectionContext`; use `OperatingParametersByObjectId` to supply missing settings keyed by those same signed IDs. `FromBlueprint(blueprintBuildings, context)` captures a blueprint without live game objects and uses `OperatingParametersByIndex`, keyed by blueprint index. Supplied settings override captured values before validation. In particular, fractionator circulation and stack size must describe the intended full-load input, not transient inventory contents; `FluidItemId` can identify the input when the fractionator has not been filled. + +The capture is read-only and does not alter the game's selection. `CreateRequest` carries capture diagnostics into the analyzer, so stale or unrecognized selected objects cannot turn into a falsely complete empty report. Duplicate selected IDs are diagnosed and counted once. Assembler proliferation modes are decoded from the native parameter array; lab modes use their native mode field. Nonproductive recipes use native acceleration rather than an invalid extra-products mode. + +The global proliferation switch uses the highest level supported by the captured proliferator items while preserving each production building's acceleration or extra-products setting. It also controls fuel and launch-ammunition proliferation. The black box assumes input coating is supplied externally and does not add proliferator consumption for that coating. + +## Special-process settings + +All parameters below are numbers in a building snapshot's `OperatingParameters`. A live capture supplies available values from the selected factory; either capture path may need supplementary context. Do not infer missing resource coverage, inventory contents, research technology, orbit readiness, or sandbox settings. Planner callers supply recipe-specific values through `OperatingParametersByRecipe`, including for synthetic recipes. + +| Facility | Settings and behavior | +| --- | --- | +| Fractionator | A fractionation recipe, `CirculatingItemsPerMinute`, and `StackSize`. The throughput limit is 30 cargo per second times the stack size, or `1800 * StackSize` items per minute. Only successful conversions consume inputs; circulation changes throughput and power without becoming an external material input. The native power formula uses items per second, not per minute. | +| Energy exchanger | `Mode0`: charging `1`, discharging `-1`, idle `0`. Charging converts empty accumulators to full ones and draws grid power. Discharging converts them back and is reported as discharge capacity, not generation. Coating accelerates both directions and is preserved on the output accumulator. | +| Ray receiver | `Mode0`: `0` for grid generation or its native photon item ID; `LensItemId`: zero or a compatible catalyst; `SolarEnergyLossRate`: technology loss fraction. Missing loss leaves photon flows available but Dyson power incomplete. Ideal full illumination and warmup use the native 2.5 warmup factor, eightfold photon mode energy, and one lens per 36,000 game ticks. Grid generation and Dyson demand are separate. | +| Renewable generator | Wind, solar, and geothermal use ideal standard conditions and their rated generation. Local wind strength, day/night illumination, and geothermal ground heat do not modify this full-load model. | +| Miner or water extractor | `ResourceItemId`, `MiningSpeedMultiplier`, and `VeinCount` or `OilUnits` for the matching resource. Optional `MachineSpeedFactor` and `SpeedDamper` default to 1. Live capture records raw miner speed divided by 10,000 separately from the damper. Output scales by speed times damper; power uses `ratio = SpeedDamper * MachineSpeedFactor * MachineSpeedFactor` and `workingWatts * ratio + idleWatts * (1 - ratio)`. | +| Gas collector | `GasCount`, `GasTotalHeat`, `MiningSpeedMultiplier`, and each `GasItemId{n}` and `GasSpeedPerSecond{n}`. Native self-power recovery and collection technology scale all gas outputs, which are reported per minute. Collector working energy reduces recovered gas; it is not counted again as grid consumption. | +| Fuel generator | `FuelItemId` compatible with the generator. Artificial stars also require native `Mode0` (sandbox boost). Output and burned fuel follow the native fuel type and proliferation rule. | +| EM-rail ejector or vertical launching silo | `LaunchAvailable` plus the native boost mode (`Mode1` for ejectors, `Mode0` for silos); boosted modes also require `BoostEnabled`. An available ideal target consumes one ammunition item per completed charge/cooldown cycle. Proliferation changes both launch speed and working power. `LaunchesPerMinute` is separate from item production. | +| Research-mode lab | `ResearchMode = 1`, `TechId`, and `ResearchSpeed`. The captured technology supplies matrix point requirements. Native matrix proliferation increases hashes and power, not matrix input per base hash; `ResearchHashesPerMinute` is separate from item production. | + +The ejector and silo assume a usable orbit or node when `LaunchAvailable = 1`; their native geometric visibility and construction schedules are outside this full-load model. Power reports exclude logistics stations, distributors, transport, and mecha charging. Auxiliary power must come from an explicitly supplied list. + +## CheatEnabler migration + +The belt-signal generator uses `ProductionPlanner` material reports, not its former recursive ingredient table. Its caller-side preset chooses a proliferator with valid captured Proto capabilities and permits legacy natural-source boundaries only when those item IDs exist in the catalog. For each generated target unit, it records upstream gross production plus external imports, subtracts the already delivered target, and applies gross consumption independently. Each belt keeps separate fractional progress for production and consumption, while per-unit reports are cached by item, spray configuration, and catalog. `ProductionCatalogService.Changed` invalidates cached reports and refreshes existing belts; clearing the catalog drops their derived statistics without accessing unloaded factory objects. The game logic tick applies cached rates only. Request construction, calculation, and report conversion fail softly: if data is missing or calculation fails, only additional upstream statistics pause and a warning explains why; item generation and its own configured count switch remain unchanged. + +## Validation + +Use compilation and static review for development checks: + +```powershell +dotnet build UXAssist/UXAssist.csproj -c Release --no-restore +dotnet build CheatEnabler/CheatEnabler.csproj -c Release --no-restore +git diff --check +``` + +Compare special mechanics against method bodies in the original DSP DLL; the publicized repository reference is not an implementation source. Builds and DLL inspection do not establish in-game correctness. In-game acceptance is manual; automated tests and save parsing are not required. + +Use a test game for the following manual checks. Compare full-load rates only with sufficient inputs, power, and output capacity; do not compare a throttled statistics window with theoretical capacity. + +- Check ordinary production and mining against native cycle periods and the per-minute UI. A 60-tick recipe at unit speed completes 60 cycles per minute before proliferation. +- Capture assemblers in acceleration and extra-products modes, nonproductive recipes, prebuilds, and stacked labs. Confirm that each captured mode and building count matches the selection. +- Supply fractionator circulation and stack context. For native 1% fractionation with fully sprayed input, 1,800 circulating items per minute yield 36 conversions per minute; at stack size 4, 7,200 circulating items per minute yield 144. Check throughput-dependent power separately. +- Request full accumulators and critical photons through the catalog's default synthetic routes. Confirm that missing building or receiver-loss settings produce incomplete power rather than an invented result. +- Charge and discharge sprayed accumulators, then consume or deliver them with spraying enabled. Confirm acceleration in both directions and no repeated spray charge for inherited coating. Compare self-spraying enabled and disabled. +- Select miners at different machine speeds, a gas collector, and renewable generators. Check native miner power scaling, per-minute gas output without added grid demand, and ideal rated renewable power rather than local conditions. +- Select ray receivers in both modes, fuel generators, ejectors, and silos. Toggle proliferation and compare working power, generation, accumulator exchange, and Dyson demand as separate quantities. +- Remove an upstream producer from a mixed production selection. Confirm that downstream capacity is unchanged and the missing material appears as required external supply. Check intermediate excess around the smallest selected producer's net output threshold. +- Combine planner targets with shared coproducts, explicit raw-material boundaries, and alternate selected recipes. Confirm material conservation, shared surplus reuse, and no introduction of unselected recipes. +- Toggle belt-signal proliferation and reload a game. Confirm that existing belts use the new catalog, item generation continues, and fractional production and consumption statistics remain independent. diff --git a/UXAssist/docs/ProductionArchitecturePlan.md b/UXAssist/docs/ProductionArchitecturePlan.md new file mode 100644 index 0000000..d58cec3 --- /dev/null +++ b/UXAssist/docs/ProductionArchitecturePlan.md @@ -0,0 +1,190 @@ +# UXAssist Production Planner and Factory Black Box Analysis Plan + +Status: Implemented. Automated acceptance uses synthetic calculations and project builds; in-game verification is a separate manual step. The maintained interface and behavior reference is [ProductionArchitecture.md](ProductionArchitecture.md). + +This document records the architecture plan agreed during the planning discussion on September 26, 2026. It is an implementation handoff; consult the maintained architecture reference for current behavior. + +## 1. Goals and Scope + +Introduce a shared production model in UXAssist with two independent calculation entry points: + +- **Production planner:** Start from target items and required rates, then calculate upstream production, external material requirements, proliferator consumption, final surplus, and power requirements. +- **Factory black box analyzer:** Start from a fixed building list and calculate material flows and power at full load. Do not replace game production updates or reduce downstream output automatically when upstream supply is insufficient. +- Deliver reusable C# interfaces, a blueprint-selection adapter, and migration of CheatEnabler's existing upstream calculation in v1. Do not add a complete calculator UI or a black box analysis window. +- Do not simulate belt reachability, logistics throughput, startup inventory, or transportation scheduling. Treat identical items inside a black box as shareable. +- Represent material rates as `double` values in items per minute and public power values in watts. Preserve fractional values during calculation and format them only for presentation. + +**Default assumption, not explicitly confirmed:** Joint planning may expand an already selected production line to supply another target through its coproducts. It must not introduce an unselected recipe, and any additional primary products must appear in the final surplus report. This was the last unanswered planning question; the recommended option is the default for this handoff. + +This document-only task does not include implementation or changes to `AGENTS.md`. Keep implementation documentation in English. After implementation, agent guidance should contain only durable architecture rules or a reference to the maintained architecture document, not this plan's task history. + +## 2. Shared Production Model and Interfaces + +### 2.1 Data and Lifecycle + +- Read recipes, items, buildings, and resources from loaded `LDB` data, Proto objects, and `PrefabDesc`. Read game rules not represented by Proto data, such as proliferation multipliers, from the game's `Cargo` tables. Implement special mechanics against the original game DLL, not the stripped publicized assembly. +- Do not use an external recipe database or copy the reference calculator's data files. The algorithm reference is `DSPCalculator/dsp-calc`; it is not a runtime data dependency. +- Capture immutable data snapshots on the game thread. The calculation core must not access Unity objects, current inventories, or mutable component pools. This keeps it independently testable and permits off-thread calculation after capture. +- Return `DataNotReady` before preload completes and retry through `GameLogic.OnDataLoaded`. Invalidate relevant caches when the catalog is rebuilt, calculation settings change, or a game session ends. +- Return structured diagnostics for missing recipes, building selections, and special operating parameters. Track material-result and power-result completeness separately; never silently represent unknown values as zero. + +### 2.2 Public Entry Points + +| Interface | Input and responsibility | Output | +| --- | --- | --- | +| `ProductionPlanner.Calculate` | Targets, external-material boundaries, recipe and proliferation policies, and building selections | External material requirements, delivered targets, final surplus, process details, and power | +| `FactoryBlackBoxAnalyzer.Analyze` | Building snapshots, a global proliferation switch, and required special operating parameters | Aggregate flows, per-item shortages and surplus, final products, and power | +| `BlueprintSelectionReader.Capture` | A `PlanetFactory` and the object IDs selected in blueprint mode | Building snapshots without retained mutable game-object references | +| `BlueprintSelectionReader.FromBlueprint` | A `BlueprintBuilding` list and supplementary context | The same building-snapshot format, with missing settings identified explicitly | + +The shared report retains `GrossProduction`, `GrossConsumption`, `NetFlow`, and per-building-group details. A report containing only raw materials and final products is insufficient for diagnostics and migration of production statistics. + +### 2.3 Normalized Production Processes + +Each process records its recipe or special-process identifier, inputs, outputs, building capability, effective proliferation strategy, and power terms. The same recipe with different buildings or strategies produces distinct processes. Do not average unlike processes before evaluating them. + +Use a common evaluator for ordinary assembling, smelting, chemical processing, refining, particle processing, and matrix production. Use dedicated adapters for the following mechanics: + +| Mechanic | Required behavior | +| --- | --- | +| Fractionation | Separate circulating throughput from net material consumption. Use native probability, proliferation, stacking, throughput, and power rules. Unconverted circulating material is not an external material consumption. | +| Accumulator charging and discharging | Preserve empty/full item conversion, energy accounting, and proliferation inheritance. Charging consumes electricity; report discharge separately rather than treating it as newly generated energy. | +| Photons and ray receivers | Distinguish photon generation from electricity generation and account for lens consumption. Keep Dyson-sphere-side energy requirements separate from factory-grid demand. | +| Mining, water extraction, and collection | Determine outputs from the actual resource type, coverage, or caller-supplied resource configuration. Do not invent vein counts or collection conditions. | +| Fuel generators, ejectors, silos, and research mode | Use native fuel, proliferation, and cycle rules. Count ammunition, fuel, and matrices as consumed items. Report launches and research hashes separately instead of inventing item outputs. | + +Provide an extensible process-adapter interface for special mechanics. Report unsupported production buildings rather than silently omitting them. + +## 3. Architecture One: Production Planner + +### 3.1 Request Configuration + +`ProductionPlanRequest` contains: + +- **Targets:** Item IDs and required delivery rates per minute. Merge duplicate targets before solving. +- **External-material boundaries:** Allow any intermediate item to be treated as an external input. Dark Fog materials are always external inputs; do not model enemy drops or their conditions. +- **Recipe choices:** Select a primary recipe for each product. Direct production uses only selected recipes, while coproducts from other selected processes can satisfy demand. +- **Proliferation settings:** Whether proliferation is enabled, the proliferator item, whether it is self-sprayed, and per-product choices of no proliferation, speedup, or extra products. +- **Building selections:** Per-recipe choices override per-building-category choices. Do not automatically choose the highest-tier building. +- **Additional configuration:** Known external surplus, operating parameters for special processes, and an optional auxiliary-building list. + +When no primary recipe is specified, prefer the valid default production recipe provided by the Proto data. An explicit production recipe for a naturally obtainable resource overrides its default collection source. Explicitly marking an item as an external material stops its upstream expansion. + +When proliferation is enabled without a per-product override, ordinary recipes follow the native available mode: extra products when supported, otherwise speedup. An explicit request for an unsupported extra-products mode is a configuration error, not permission to silently select another mode. + +### 3.2 Global Material-Balance Solver + +Use a global material matrix and linear programming, rather than recursively calculating each target independently and merging the results afterward. + +Define: + +- `A`: Net input/output matrix for the selected production processes. +- `x`: Process executions per minute. +- `r`: Allowed external material imports per minute. +- `s`: Fixed external surplus supplied by the caller per minute. +- `d`: Target delivery rates per minute. +- `u`: Final surplus rates per minute. + +The model satisfies: + +`A * x + r + s = d + u` + +Process execution rates, external imports, and final surplus are nonnegative. Import variables exist only for items permitted as external materials. + +- Include all targets, coproduct reuse, cyclic recipes, and proliferator production in the same model so traversal order cannot change the result. +- Generate only selected recipes and required special processes. Keep separate variables for distinct proliferation or building configurations. +- Use a deterministic v1 objective: first minimize total process executions, then external imports, then remaining surplus. This is not a claim of minimum power, minimum building count, or minimum mineral value. +- Implement an internal pure-managed two-phase simplex solver. Do not introduce a JavaScript runtime or a native solver dependency. +- Include scaling, deterministic pivot selection, an iteration budget, cancellation, and a post-solve conservation check. Return diagnostics on failure rather than an unverified successful result. + +### 3.3 Proliferator Self-Spraying + +- Derive spray demand from the actual input flows requiring spraying under their production strategies. +- Derive base sprays per bottle and additional sprays after self-spraying from Proto data and native rules. Also deduct the spray consumed by coating that bottle itself. +- Include proliferator manufacturing and its own upstream inputs in the same solver model. Do not retain fixed proliferator ingredient tables or a fixed effective-sprays-per-bottle constant. +- Support optional spraying of delivered target items so the existing belt-signal feature can express its finished-product spraying requirements. +- Exclude initial seed inventory for cyclic processes from steady-state per-minute demand, but keep cyclic processes identifiable in the result. + +### 3.4 Power and Results + +- Return all external material requirements, delivered targets, final surplus, and the full intermediate production/consumption ledger. +- Evaluate ordinary production power from the selected building's speed, working power, and proliferation power increase. Do not add idle power a second time to an already applicable working-power value. +- Use equivalent fully utilized building counts for the power needed to meet target flow. Report rounded deployment counts and their peak power separately; do not round the material model. +- Without a building selection, still calculate material results that do not depend on that choice, but mark power results incomplete. +- Do not infer sorter or spray-coater counts from recipes without a layout. Include auxiliary power only when the caller supplies the auxiliary-building list, and identify the reported power scope explicitly. +- Exclude logistics transportation and charging. Include accumulator charging used as a production process and report Dyson-sphere-side requirements separately. + +## 4. Architecture Two: Factory Black Box Analyzer + +### 4.1 Building Lists and Blueprint Capture + +- Each production-building snapshot identifies its building type, recipe, actual speedup/extra-products mode, and required speed or special-process settings. +- Decode blueprint-selection settings using the native `BuildingParameters` semantics instead of maintaining an unverified independent parameter-index table. +- Deduplicate and validate object IDs. Support prebuilds and stacked labs. Analyze a prebuild using its known intended completed configuration, and report missing settings explicitly. +- Capture must not refresh, modify, or clear the user's blueprint selection. Do not carry mutable component references into background calculation. + +### 4.2 Proliferation and Full-Load Assumptions + +- Expose only a global no-proliferation/full-proliferation choice. Do not infer proliferation levels from current input buffers or offer per-building level overrides in v1. +- Determine the maximum level from the capabilities of available proliferator items, not the last index in a multiplier table. +- Preserve each building's actual speedup/extra-products mode. +- Turning the global switch off also disables proliferation effects for fuel, ejectors, silos, and other special consumers. +- When enabled, assume required inputs were sprayed outside the black box. Do not add proliferator demand or a self-spraying production chain. A selected building that manufactures proliferators still contributes its ordinary recipe flows. +- Evaluate all configured processes at full load. A material deficit represents the external supply needed to sustain that capacity; it does not reduce downstream theoretical output. + +### 4.3 Balances and the One-Building Surplus Threshold + +The black box has fixed recipes and building counts, so it does not need simplex optimization. Reuse the shared process evaluator, then aggregate each building's flows by item: + +`NetFlow = GrossProduction - GrossConsumption` + +- A negative net flow is the required external supply of that raw material or intermediate item. +- A positive output without any internal consumer is a final product. Do not apply the intermediate-surplus threshold to it. +- For an intermediate item, the surplus threshold is the smallest positive net output of one actual upstream building in the selection. Include its tier, actual proliferation mode, and any consumption of the same item by that process. +- Classify positive intermediate surplus as excess only when it reaches this threshold. A positive balance smaller than one such building's capacity is normally balanced. +- Keep numerical tolerance separate from the business threshold. Preserve all fractional ledger values; classification must not alter the true net flow. +- Retain producer-group and consumer-group attribution so every intermediate balance can be explained. Excess equivalent to one building does not, by itself, establish that the building can safely be removed. + +Example: two upstream buildings produce net rates of 60 and 120 items per minute. If internal consumption is 150, the remaining 30 is normally balanced. If consumption is 120, the remaining 60 reaches the threshold and is reported as excess. + +### 4.4 Power and Generation + +- Evaluate wind, solar, geothermal, and ray-receiver generation in a standard ideal environment: standard environmental multipliers, full illumination, completed continuous-receiving warmup, and sufficient Dyson sphere supply. Do not use current day/night conditions or temporary energy starvation. +- Treat technology, speed settings, fuel, and operating mode as separate parameters, not environmental assumptions. Capture settings that can be determined from the selection and request missing information explicitly. +- Sum rated demand for selected production buildings and non-logistics auxiliary facilities, including sorters and spray coaters. Buildings without a configured production process contribute idle demand. +- Calculate generation using fuel properties and native proliferation rules. Do not apply a single manufacturing-building power multiplier to every generator. +- Report consumption, generation, accumulator charging/discharging capacity, and Dyson-sphere-side requirements separately. A net-power value must not replace the breakdown. +- Exclude logistics stations, distributors, transportation, and mecha charging in v1. + +## 5. Implementation, Migration, and Acceptance + +### 5.1 Implementation Order + +1. Build the immutable catalog, public report types, and shared process evaluator. Cover ordinary recipes and proliferation first. +2. Implement special-process adapters, the planner's matrix compiler, and the solver. Verify cyclic and multi-target conservation. +3. Implement black box aggregation, the single-building surplus threshold, and blueprint-selection adapters. +4. Replace the upstream-source calculation in `CheatEnabler/Patches/Factory/BeltSignalPatch.cs`, starting at `AddSourcesToBeltSignal`. Remove the old recursive algorithm from the active calculation path. +5. Add English architecture documentation and usage examples. After implementation, update `AGENTS.md` only with stable architecture guidance or a documentation reference, not the plan or investigation history. + +### 5.2 Existing-Feature Compatibility + +- Preserve existing configuration keys, statistics switches, item generation, speed limits, and portal behavior. +- Translate the old policy into a caller-side preset using Proto-validated item identifiers. Do not preserve incorrect hard-coded ingredient lists or incorrect statistics as compatibility requirements. +- Apply production and consumption ledgers independently. A single quantity plus an `isExtra` flag cannot represent all cases. Avoid counting delivered target items twice. +- Cache per-unit results by item and relevant settings, and retain independent fractional accumulators. The game logic tick applies precomputed results; it does not run the solver. +- When data is not ready or calculation fails, suspend the affected additional upstream statistics and report the reason without blocking existing item generation. + +### 5.3 Acceptance Scenarios + +| Area | Required scenarios | +| --- | --- | +| Ordinary production | Building tiers, recipe durations, extra products, speedup, and nonproductive recipes agree with native data and mechanics. | +| Global balancing | Multiple targets share coproducts; target order does not affect results; intermediate items can be external inputs; cyclic refining, external surplus, and infeasible settings are handled. | +| Self-spraying | Cover each proliferator grade, self-spraying on/off, proliferator manufacturing, and finished-product spraying without duplicate charges. | +| Black box flows | Cover mixed building tiers and modes, shortages at every intermediate stage, the minimum single-building net-capacity threshold, and fractional final-product rates. Shortages do not reduce downstream full-load output. | +| Special power rules | Verify fractionation circulation, accumulator round trips, photon/grid separation, different fuels, ejectors, and research mode. Disabling the global proliferation switch also affects special facilities. | +| Boundaries and migration | Cover empty selections, duplicate/stale IDs, prebuilds, stacked buildings, missing special settings, session transitions, calls before preload, and target statistics without double counting. | + +Use an independent check program consistent with the repository's existing check-tool approach. Validate calculations with synthetic game-free scenarios and verify special mechanics against the original game DLL. In-game behavior should be checked separately by a person; parsing real saves is not an acceptance requirement for this calculation infrastructure. + +Implementation acceptance runs the UXAssist and CheatEnabler Release builds, the relevant checks, and `git diff --check`. Use the repository's normal build form, `dotnet build /.csproj -c Release --no-restore`. If shared-constant changes affect additional dependent projects, build those projects as well. diff --git a/UXAssist/tools/ProductionCheck/Directory.Build.props b/UXAssist/tools/ProductionCheck/Directory.Build.props new file mode 100644 index 0000000..bcec9f1 --- /dev/null +++ b/UXAssist/tools/ProductionCheck/Directory.Build.props @@ -0,0 +1,7 @@ + + + net8.0 + latest + true + + diff --git a/UXAssist/tools/ProductionCheck/ProductionCheck.csproj b/UXAssist/tools/ProductionCheck/ProductionCheck.csproj new file mode 100644 index 0000000..752d1aa --- /dev/null +++ b/UXAssist/tools/ProductionCheck/ProductionCheck.csproj @@ -0,0 +1,13 @@ + + + Exe + false + + + + + + + + diff --git a/UXAssist/tools/ProductionCheck/Program.cs b/UXAssist/tools/ProductionCheck/Program.cs new file mode 100644 index 0000000..f33e0da --- /dev/null +++ b/UXAssist/tools/ProductionCheck/Program.cs @@ -0,0 +1,1150 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using CheatEnabler.Patches.Factory; +using UXAssist.Common.GameConstants; +using UXAssist.Production; + +internal static class Program +{ + private static int _checks; + + private static void Main() + { + OrdinaryEvaluation(); + CoproductsAndTargetOrder(); + IntermediateBoundary(); + ExternalSurplusAndNaturalOverrides(); + ClosedLoopAndInfeasible(); + ProliferatorSupply(); + ProliferatorGradesAndFinishedSpraying(); + BlackBoxBalancesAndThreshold(); + BlackBoxMixedModesAndDeficits(); + FractionationFlow(); + AccumulatorRoundTrip(); + RenewableGeneration(); + MiningResources(); + GasCollection(); + FuelGenerators(); + RayReceiverPowerAndPhotons(); + LauncherCyclesAndAmmunition(); + ResearchHashesAndMatrices(); + PlannerAuxiliaryPower(); + InvalidConfiguration(); + BeltSignalStatistics(); + BeltSignalPreset(); + Console.WriteLine($"ProductionCheck: {_checks} checks passed."); + } + + private static void OrdinaryEvaluation() + { + var catalog = Catalog(); + var evaluator = new ProcessEvaluator(); + var recipe = catalog.Recipes[101]; + var building = catalog.Buildings[10]; + Check(evaluator.TryEvaluate(catalog, recipe, building, ProliferationMode.None, 0, null, + out var plain, out _), "ordinary process evaluates"); + Equal(1, plain.CyclesPerBuildingPerMinute, "recipe tick duration"); + Equal(1000, plain.WorkingPowerWatts, "working watts"); + Check(evaluator.TryEvaluate(catalog, recipe, building, ProliferationMode.Speedup, 4, null, + out var speedup, out _), "speedup process evaluates"); + Equal(2, speedup.CyclesPerBuildingPerMinute, "speedup capacity"); + Equal(1000, speedup.WorkingPowerWatts / 2.5, "speedup power multiplier"); + Check(evaluator.TryEvaluate(catalog, recipe, building, ProliferationMode.ExtraProducts, 4, null, + out var extra, out _), "extra process evaluates"); + Equal(2.5, extra.OutputsPerCycle[2], "extra product count"); + Equal(1, extra.InputsPerCycle[1], "extra mode input count"); + Equal(1, extra.CyclesPerBuildingPerMinute, "extra mode speed"); + } + + private static void CoproductsAndTargetOrder() + { + var planner = new ProductionPlanner(Catalog()); + var request = Request((3, 60), (4, 30)); + var first = planner.Calculate(request); + Check(first.MaterialComplete && first.PowerComplete, "multi-target plan complete"); + Equal(30, first.ItemFlows[1].ExternalImports, "ore import reused across targets"); + Equal(0, first.Groups.Where(group => group.Process.RecipeId == 103) + .Sum(group => group.ExecutionsPerMinute), "selected but unnecessary recipe unused"); + Equal(30, first.ItemFlows[4].Delivered, "coproduct target delivered once"); + Equal(60, first.ItemFlows[3].GrossProduction, "first product produced"); + + var reverse = planner.Calculate(Request((4, 30), (3, 60))); + foreach (var flow in first.ItemFlows) + { + Equal(flow.Value.GrossProduction, reverse.ItemFlows[flow.Key].GrossProduction, "target order production"); + Equal(flow.Value.ExternalImports, reverse.ItemFlows[flow.Key].ExternalImports, "target order imports"); + } + + var duplicate = planner.Calculate(Request((3, 15), (3, 45), (4, 30))); + Equal(60, duplicate.ItemFlows[3].Delivered, "duplicate targets merged"); + Equal(30, duplicate.ItemFlows[1].ExternalImports, "duplicate targets do not duplicate inputs"); + } + + private static void IntermediateBoundary() + { + var request = Request((3, 60)); + request.ExternalMaterials.Add(2); + var report = new ProductionPlanner(Catalog()).Calculate(request); + Check(report.MaterialComplete, "intermediate boundary complete"); + Equal(60, report.ItemFlows[2].ExternalImports, "intermediate supplied externally"); + Check(!report.ItemFlows.ContainsKey(1), "upstream ore no longer required"); + Equal(60000, report.Power.ConsumptionWatts, "power is based on utilized building capacity"); + } + + private static void ExternalSurplusAndNaturalOverrides() + { + var planner = new ProductionPlanner(Catalog()); + var request = Request((3, 60), (4, 30)); + request.KnownExternalSurplus[2] = 20; + request.KnownExternalSurplus[4] = 10; + var report = planner.Calculate(request); + Check(report.MaterialComplete, "joint plan accepts two known external supplies"); + Equal(20, report.ItemFlows[1].ExternalImports, + "known intermediate supply displaces upstream ore imports"); + Equal(20, report.ItemFlows[2].KnownExternalSupply, + "known intermediate is not counted as a mined external import"); + Equal(10, report.ItemFlows[4].Surplus, + "external coproduct supply becomes a visible final surplus"); + Equal(0, report.Groups.Where(group => group.Process.RecipeId == 103) + .Sum(group => group.ExecutionsPerMinute), "external surplus does not introduce an extra recipe"); + foreach (var flow in report.ItemFlows.Values) + Equal(flow.Delivered + flow.Surplus, + flow.NetFlow + flow.ExternalImports + flow.KnownExternalSupply, + $"item {flow.ItemId} conserves total production and supply"); + + request.ExternalMaterials.Add(2); + var boundary = planner.Calculate(request); + Equal(40, boundary.ItemFlows[2].ExternalImports, + "external intermediate boundary stops upstream expansion after known supply"); + Equal(0, boundary.ItemFlows[1].ExternalImports, + "unused coproduct recipe does not import upstream ore across the boundary"); + + var catalog = new ProductionCatalog(new[] + { + new ProductionItem(11, 301, true, false, 0, 0), + new ProductionItem(12, 0, true, false, 0, 0), + new ProductionItem(13, 302, false, true, 0, 0) + }, new[] + { + Recipe(301, new[] { (12, 2.0) }, new[] { (11, 1.0) }), + Recipe(302, new[] { (12, 2.0) }, new[] { (13, 1.0) }) + }, Array.Empty(), new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 }); + var nativeResource = new ProductionPlanner(catalog); + var natural = nativeResource.Calculate(new ProductionPlanRequest + { + Targets = { new ProductionTarget(11, 1) } + }); + Equal(1, natural.ItemFlows[11].ExternalImports, + "natural item is external even when a default manufacturing recipe exists"); + var explicitRecipe = new ProductionPlanRequest(); + explicitRecipe.Targets.Add(new ProductionTarget(11, 1)); + explicitRecipe.RecipeByItem[11] = 301; + var manufactured = nativeResource.Calculate(explicitRecipe); + Equal(2, manufactured.ItemFlows[12].ExternalImports, + "explicit natural-item recipe uses its actual inputs"); + Check(!manufactured.ItemFlows[11].ExternalImports.Equals(1), + "explicit natural-item recipe replaces natural import"); + var darkFog = new ProductionPlanRequest(); + darkFog.Targets.Add(new ProductionTarget(13, 1)); + darkFog.RecipeByItem[13] = 302; + Equal(1, nativeResource.Calculate(darkFog).ItemFlows[13].ExternalImports, + "Dark Fog resource remains external even with an explicit recipe"); + } + + private static void ClosedLoopAndInfeasible() + { + var items = new[] + { + new ProductionItem(11, 201, false, false, 0, 0), + new ProductionItem(12, 202, false, false, 0, 0) + }; + var productive = new[] + { + Recipe(201, new[] { (12, 1.0) }, new[] { (11, 2.0) }), + Recipe(202, new[] { (11, 1.0) }, new[] { (12, 2.0) }) + }; + var catalog = new ProductionCatalog(items, productive, Array.Empty(), + new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 }); + var result = new ProductionPlanner(catalog).Calculate(Request((11, 3))); + Check(result.MaterialComplete && !result.PowerComplete, "cyclic material plan with unspecified power"); + Equal(2, result.Groups.Single(group => group.Process.RecipeId == 201).ExecutionsPerMinute, + "cyclic first process rate"); + Equal(1, result.Groups.Single(group => group.Process.RecipeId == 202).ExecutionsPerMinute, + "cyclic second process rate"); + Equal(0, result.ItemFlows[12].Surplus, "cyclic intermediate balance"); + + var noGain = new[] + { + Recipe(201, new[] { (12, 1.0) }, new[] { (11, 1.0) }), + Recipe(202, new[] { (11, 1.0) }, new[] { (12, 1.0) }) + }; + var impossible = new ProductionCatalog(items, noGain, Array.Empty(), + new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 }); + var failure = new ProductionPlanner(impossible).Calculate(Request((11, 3))); + Check(failure.Diagnostics.Single().Code == ProductionDiagnosticCode.Infeasible, "infeasible loop diagnosed"); + } + + private static void ProliferatorSupply() + { + var planner = new ProductionPlanner(Catalog()); + var request = Request((2, 2)); + request.ProliferationEnabled = true; + request.ProliferatorItemId = 5; + request.SelfSprayProliferator = true; + var report = planner.Calculate(request); + Check(report.MaterialComplete, "self-spraying plan complete"); + var sprayDemand = report.Groups.Sum(group => group.Process.ProliferationMode == ProliferationMode.None + ? 0 : group.Process.InputsPerCycle.Values.Sum() * group.ExecutionsPerMinute) / 74; + Equal(sprayDemand, report.Groups.Sum(group => group.GrossConsumption.GetValueOrDefault(5) - + group.Process.InputsPerCycle.GetValueOrDefault(5) * group.ExecutionsPerMinute), + "spray demand included in ledger"); + Equal(0, report.ItemFlows[5].Surplus, "spray production balances use"); + + request.SprayDeliveredItems.Add(2); + var finished = planner.Calculate(request); + Equal(2.0 / 74, finished.ItemFlows[5].GrossConsumption - + finished.Groups.Sum(group => group.GrossConsumption.GetValueOrDefault(5)), + "finished product spraying charged separately"); + } + + private static void ProliferatorGradesAndFinishedSpraying() + { + var grades = new[] + { + (id: 11, level: 1, sprays: 12, effective: 12.0, bonus: 0.125), + (id: 12, level: 2, sprays: 24, effective: 27.0, bonus: 0.2), + (id: 13, level: 3, sprays: 60, effective: 74.0, bonus: 0.25) + }; + var items = new List + { + new ProductionItem(1, 0, true, false, 0, 0), + new ProductionItem(2, 101, false, false, 0, 0) + }; + var recipes = new List + { + Recipe(101, new[] { (1, 1.0) }, new[] { (2, 1.0) }) + }; + foreach (var grade in grades) + { + items.Add(new ProductionItem(grade.id, 200 + grade.level, + false, false, grade.level, grade.sprays)); + recipes.Add(Recipe(200 + grade.level, new[] { (1, 2.0) }, + new[] { (grade.id, 1.0) }, productive: false)); + } + + var catalog = new ProductionCatalog(items, recipes, Array.Empty(), + new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.25, 0.3 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + Equal(3, catalog.MaximumProliferationLevel, + "available bottles, not the last table index, set maximum proliferation level"); + + foreach (var grade in grades) + { + var request = new ProductionPlanRequest + { + ProliferationEnabled = true, + ProliferatorItemId = grade.id, + SelfSprayProliferator = true + }; + request.Targets.Add(new ProductionTarget(2, 1)); + request.ProliferationModeByItem[grade.id] = ProliferationMode.None; + var planner = new ProductionPlanner(catalog); + var intermediateOnly = planner.Calculate(request); + Check(intermediateOnly.MaterialComplete, + $"grade {grade.level} can manufacture its own proliferator supply"); + + request.SprayDeliveredItems.Add(2); + var selfSprayed = planner.Calculate(request); + var targetCycles = 1 / (1 + grade.bonus); + var bottlesUsed = (targetCycles + 1) / grade.effective; + Check(selfSprayed.MaterialComplete, + $"grade {grade.level} self-sprayed supply remains feasible"); + Equal(bottlesUsed, selfSprayed.ItemFlows[grade.id].GrossConsumption, + $"grade {grade.level} bottle use includes finished-product spray exactly once"); + Equal(bottlesUsed, selfSprayed.ItemFlows[grade.id].GrossProduction, + $"grade {grade.level} proliferator manufacturing balances sprayed demand"); + Equal(1 / grade.effective, + selfSprayed.ItemFlows[grade.id].GrossConsumption - + intermediateOnly.ItemFlows[grade.id].GrossConsumption, + $"grade {grade.level} finished-product spray has no duplicate charge"); + Equal(targetCycles + 2 * bottlesUsed, selfSprayed.ItemFlows[1].ExternalImports, + $"grade {grade.level} manufacturing uses recipe-derived raw materials"); + + request.SelfSprayProliferator = false; + var untreated = planner.Calculate(request); + Equal((targetCycles + 1) / grade.sprays, + untreated.ItemFlows[grade.id].GrossConsumption, + $"grade {grade.level} disabled self-spraying uses base bottle capacity"); + } + } + + private static void InvalidConfiguration() + { + var planner = new ProductionPlanner(null); + Check(planner.Calculate(Request((2, 1))).Status == ProductionStatus.DataNotReady, + "preload not ready reported"); + var catalog = Catalog(); + var evaluator = new ProcessEvaluator(); + var nonproductive = Recipe(301, new[] { (1, 1.0) }, new[] { (2, 1.0) }, false); + Check(!evaluator.TryEvaluate(catalog, nonproductive, null, ProliferationMode.ExtraProducts, 4, + null, out _, out var diagnostic) && + diagnostic.Code == ProductionDiagnosticCode.UnsupportedProliferation, + "nonproductive recipe rejects extra-products mode"); + var request = Request((2, 1)); + request.BuildingByRecipe.Clear(); + request.BuildingByCategory.Clear(); + var partial = new ProductionPlanner(catalog).Calculate(request); + Check(partial.MaterialComplete && !partial.PowerComplete && partial.Power == null, + "missing building does not invent watts"); + var cancelled = new CancellationToken(true); + Check(new ProductionPlanner(catalog).Calculate(Request((2, 1)), cancelled) + .Diagnostics.Single().Code == ProductionDiagnosticCode.Cancelled, "cancellation diagnosed"); + var emptyPlan = new ProductionPlanner(catalog).Calculate(new ProductionPlanRequest()); + Check(emptyPlan.MaterialComplete && emptyPlan.PowerComplete && emptyPlan.ItemFlows.Count == 0, + "empty production plan is a complete empty report"); + var emptyBox = new FactoryBlackBoxAnalyzer(catalog).Analyze(new FactoryBlackBoxRequest()); + Check(emptyBox.MaterialComplete && emptyBox.PowerComplete && emptyBox.Groups.Count == 0, + "empty building selection is a complete empty report"); + var staleCapture = new FactoryBlackBoxRequest(); + staleCapture.CaptureDiagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, + "A selected object no longer exists.")); + var incompleteBox = new FactoryBlackBoxAnalyzer(catalog).Analyze(staleCapture); + Check(!incompleteBox.MaterialComplete && !incompleteBox.PowerComplete && + incompleteBox.Status == ProductionStatus.Failed, + "a stale object discarded during capture cannot become a complete empty analysis"); + } + + private static void FractionationFlow() + { + var catalog = new ProductionCatalog(new[] + { + new ProductionItem(1, 0, true, false, 0, 0), + new ProductionItem(2, 501, false, false, 0, 0), + new ProductionItem(3, 0, true, false, 4, 60) + }, new[] + { + new ProductionRecipe(501, ProductionRecipeCategory.Fractionate, 1, false, + new[] { new KeyValuePair(1, 100) }, + new[] { new KeyValuePair(2, 1) }) + }, new[] + { + new ProductionBuilding(30, ProductionRecipeCategory.None, 0, 1000, 100, + ProductionBuildingKind.Fractionator) + }, new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + var request = new FactoryBlackBoxRequest(); + request.Buildings.Add(new ProductionBuildingSnapshot(301, 30, 501, 1, ProliferationMode.None, + operatingParameters: new Dictionary + { + ["CirculatingItemsPerMinute"] = 120, + ["StackSize"] = 4 + })); + var analyzer = new FactoryBlackBoxAnalyzer(catalog); + var plain = analyzer.Analyze(request); + Check(plain.MaterialComplete && plain.PowerComplete, "native fractionation inputs valid"); + Equal(1.2, plain.ItemFlows[1].RequiredExternalSupply, "circulating fluid not an external import"); + Equal(1.2, plain.ItemFlows[2].GrossProduction, "native fractionation probability"); + Equal(5500, plain.Power.ConsumptionWatts, "native fractionation throughput power"); + Equal(120, plain.Groups[0].Process.CirculatingItemsPerBuildingPerMinute, + "fractionation reports circulation separately"); + + request.ProliferationEnabled = true; + var sprayed = analyzer.Analyze(request); + Equal(2.4, sprayed.ItemFlows[2].GrossProduction, "native fractionation speedup probability"); + Equal(13750, sprayed.Power.ConsumptionWatts, "native fractionation proliferation power"); + + var bad = new FactoryBlackBoxRequest(); + bad.Buildings.Add(new ProductionBuildingSnapshot(301, 30, 501, 1, ProliferationMode.None)); + Check(new FactoryBlackBoxAnalyzer(catalog).Analyze(bad).Diagnostics.Single().Code == + ProductionDiagnosticCode.MissingOperatingParameter, "missing throughput diagnosed"); + } + + private static void AccumulatorRoundTrip() + { + var catalog = new ProductionCatalog(new[] + { + new ProductionItem(10, 0, true, false, 0, 0), + new ProductionItem(11, 601, false, false, 0, 0), + new ProductionItem(6, 0, true, false, 4, 60) + }, new[] + { + new ProductionRecipe(601, ProductionRecipeCategory.Exchange, 1, false, + new[] { new KeyValuePair(10, 1) }, + new[] { new KeyValuePair(11, 1) }) + }, new[] + { + new ProductionBuilding(100, ProductionRecipeCategory.None, 0, 0, 0, + ProductionBuildingKind.Exchanger, exchangeRateWatts: 3600, + accumulatorEnergyJoules: 216000, emptyAccumulatorItemId: 10, fullAccumulatorItemId: 11) + }, new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + var request = new FactoryBlackBoxRequest(); + request.Buildings.Add(new ProductionBuildingSnapshot(1001, 100, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary { ["Mode0"] = 1 })); + request.Buildings.Add(new ProductionBuildingSnapshot(1002, 100, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary { ["Mode0"] = -1 })); + var analyzer = new FactoryBlackBoxAnalyzer(catalog); + var plain = analyzer.Analyze(request); + Check(plain.MaterialComplete && plain.PowerComplete, "accumulator round trip complete"); + Equal(1, plain.Groups[0].GrossProduction[11], "native charge item rate"); + Equal(1, plain.Groups[1].GrossProduction[10], "native discharge item rate"); + Equal(0, plain.ItemFlows[10].NetFlow, "empty accumulator balances"); + Equal(0, plain.ItemFlows[11].NetFlow, "full accumulator balances"); + Equal(3600, plain.Power.ConsumptionWatts, "charging draws grid power"); + Equal(3600, plain.Power.AccumulatorChargingWatts, "charging capacity separately reported"); + Equal(3600, plain.Power.AccumulatorDischargingWatts, "discharging capacity separately reported"); + Equal(0, plain.Power.GenerationWatts, "discharging is not generation"); + + request.ProliferationEnabled = true; + var sprayed = analyzer.Analyze(request); + Equal(2, sprayed.Groups[0].GrossProduction[11], "sprayed charge speed"); + Equal(2, sprayed.Groups[1].GrossProduction[10], "sprayed discharge speed"); + Equal(7200, sprayed.Power.AccumulatorChargingWatts, "sprayed charge power"); + Equal(7200, sprayed.Power.AccumulatorDischargingWatts, "sprayed discharge capacity"); + Check(!sprayed.ItemFlows.ContainsKey(6), "black box assumes externally sprayed accumulators"); + + var plan = Request((11, 2)); + plan.BuildingByRecipe[601] = 100; + plan.ProliferationEnabled = true; + plan.ProliferatorItemId = 6; + var result = new ProductionPlanner(catalog).Calculate(plan); + Check(result.MaterialComplete && result.PowerComplete, "accumulator charging plan complete"); + Equal(2, result.ItemFlows[10].ExternalImports, "empty accumulators imported once"); + Equal(2.0 / 60, result.ItemFlows[6].ExternalImports, "spray charged for charging inputs"); + Equal(7200, result.Power.AccumulatorChargingWatts, "planner reports grid charging demand"); + } + + private static void RenewableGeneration() + { + var catalog = new ProductionCatalog(Array.Empty(), Array.Empty(), + new[] + { + new ProductionBuilding(90, ProductionRecipeCategory.None, 0, 0, 0, + ProductionBuildingKind.RenewableGenerator, ratedGenerationWatts: 3600, + renewableSource: RenewablePowerSource.Wind), + new ProductionBuilding(91, ProductionRecipeCategory.None, 0, 0, 0, + ProductionBuildingKind.RenewableGenerator, ratedGenerationWatts: 5400, + renewableSource: RenewablePowerSource.Solar), + new ProductionBuilding(92, ProductionRecipeCategory.None, 0, 0, 0, + ProductionBuildingKind.RenewableGenerator, ratedGenerationWatts: 7200, + renewableSource: RenewablePowerSource.Geothermal) + }, new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 }); + var request = new FactoryBlackBoxRequest(); + request.Buildings.Add(new ProductionBuildingSnapshot(90, 90, 0, 1, ProliferationMode.None)); + request.Buildings.Add(new ProductionBuildingSnapshot(91, 91, 0, 1, ProliferationMode.None)); + request.Buildings.Add(new ProductionBuildingSnapshot(92, 92, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary { ["GeothermalStrength"] = 0.5 })); + var report = new FactoryBlackBoxAnalyzer(catalog).Analyze(request); + Check(report.MaterialComplete && report.PowerComplete, "ideal renewable generation complete"); + Equal(12600, report.Power.GenerationWatts, "wind solar geothermal watts distinguished"); + Equal(0, report.Power.ConsumptionWatts, "renewable generation is not demand"); + Check(report.ItemFlows.Count == 0, "renewable generators do not invent products"); + + request.Buildings[2] = new ProductionBuildingSnapshot(92, 92, 0, 1, ProliferationMode.None); + var incomplete = new FactoryBlackBoxAnalyzer(catalog).Analyze(request); + Check(incomplete.MaterialComplete && !incomplete.PowerComplete && incomplete.Power == null, + "unknown ground heat leaves only power incomplete"); + Check(incomplete.Diagnostics.Single().Code == ProductionDiagnosticCode.MissingOperatingParameter, + "missing geothermal strength diagnosed"); + } + + private static void MiningResources() + { + var catalog = new ProductionCatalog(new[] + { + new ProductionItem(1, 0, true, false, 0, 0), + new ProductionItem(2, 0, true, false, 0, 0), + new ProductionItem(3, 0, true, false, 0, 0) + }, Array.Empty(), new[] + { + new ProductionBuilding(20, ProductionRecipeCategory.None, 0, 1200, 0, + ProductionBuildingKind.Miner, minerKind: ProductionMinerKind.Vein, miningPeriodTicks: 600000), + new ProductionBuilding(21, ProductionRecipeCategory.None, 0, 1400, 0, + ProductionBuildingKind.Miner, minerKind: ProductionMinerKind.Oil, miningPeriodTicks: 600000), + new ProductionBuilding(22, ProductionRecipeCategory.None, 0, 1000, 0, + ProductionBuildingKind.Miner, minerKind: ProductionMinerKind.Water, miningPeriodTicks: 600000) + }, new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 }); + var request = new FactoryBlackBoxRequest { ProliferationEnabled = true }; + request.Buildings.Add(new ProductionBuildingSnapshot(20, 20, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary + { + ["ResourceItemId"] = 1, + ["VeinCount"] = 4, + ["MiningSpeedMultiplier"] = 2 + })); + request.Buildings.Add(new ProductionBuildingSnapshot(21, 21, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary + { + ["ResourceItemId"] = 2, + ["OilUnits"] = 2.5, + ["MiningSpeedMultiplier"] = 2 + })); + request.Buildings.Add(new ProductionBuildingSnapshot(22, 22, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary + { + ["ResourceItemId"] = 3, + ["MiningSpeedMultiplier"] = 2 + })); + var analyzer = new FactoryBlackBoxAnalyzer(catalog); + var report = analyzer.Analyze(request); + Check(report.MaterialComplete && report.PowerComplete, "native vein oil water mining complete"); + Equal(8, report.ItemFlows[1].GrossProduction, "vein coverage multiplies native rate"); + Equal(5, report.ItemFlows[2].GrossProduction, "oil resource factor retained"); + Equal(2, report.ItemFlows[3].GrossProduction, "water pump uses planet resource type"); + Equal(3600, report.Power.ConsumptionWatts, "each mining facility draws working power"); + Check(!report.ItemFlows.ContainsKey(0), "miners never invent zero-ID resources"); + + request.Buildings[0] = new ProductionBuildingSnapshot(20, 20, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary + { + ["ResourceItemId"] = 1, + ["MiningSpeedMultiplier"] = 2 + }); + var missing = analyzer.Analyze(request); + Check(!missing.MaterialComplete && !missing.PowerComplete, + "unknown vein coverage does not claim a complete report"); + Check(missing.Diagnostics.Single().Code == ProductionDiagnosticCode.MissingOperatingParameter, + "missing vein coverage diagnosed"); + } + + private static void FuelGenerators() + { + var catalog = new ProductionCatalog(new[] + { + new ProductionItem(10, 0, true, false, 0, 0, heatValueJoules: 216000, + fuelTypeMask: 1, productiveFuel: true), + new ProductionItem(11, 0, true, false, 0, 0, heatValueJoules: 216000, + fuelTypeMask: 1), + new ProductionItem(12, 0, true, false, 0, 0, heatValueJoules: 216000, + fuelTypeMask: 2), + new ProductionItem(1804, 0, true, false, 0, 0, heatValueJoules: 1000000, + fuelTypeMask: 4, productiveFuel: true, starOutputMultiplier: 2), + new ProductionItem(50, 0, true, false, 4, 60) + }, Array.Empty(), new[] + { + new ProductionBuilding(30, ProductionRecipeCategory.None, 0, 0, 0, + ProductionBuildingKind.FuelGenerator, ratedGenerationWatts: 1000, + fuelMask: 1, fuelUseWatts: 500), + new ProductionBuilding(31, ProductionRecipeCategory.None, 0, 0, 0, + ProductionBuildingKind.FuelGenerator, ratedGenerationWatts: 10000, + fuelMask: 4, fuelUseWatts: 5000) + }, new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + var analyzer = new FactoryBlackBoxAnalyzer(catalog); + var request = new FactoryBlackBoxRequest(); + request.Buildings.Add(new ProductionBuildingSnapshot(30, 30, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary { ["FuelItemId"] = 10 })); + var plain = analyzer.Analyze(request); + Check(plain.MaterialComplete && plain.PowerComplete, "native fuel generator complete"); + Equal(1000, plain.Power.GenerationWatts, "rated generator output without proliferation"); + Equal(500.0 * 60 / 216000, plain.ItemFlows[10].GrossConsumption, + "productive fuel burn rate without proliferation"); + + request.ProliferationEnabled = true; + var sprayedProductive = analyzer.Analyze(request); + Equal(1250, sprayedProductive.Power.GenerationWatts, + "productive fuel increases generator output by extra-products bonus"); + Equal(plain.ItemFlows[10].GrossConsumption, sprayedProductive.ItemFlows[10].GrossConsumption, + "productive fuel output gain does not burn extra fuel"); + Check(!sprayedProductive.ItemFlows.ContainsKey(50), "black box does not manufacture sprays"); + + request.Buildings[0] = new ProductionBuildingSnapshot(30, 30, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary { ["FuelItemId"] = 11 }); + var sprayedOrdinary = analyzer.Analyze(request); + Equal(2000, sprayedOrdinary.Power.GenerationWatts, "ordinary fuel acceleration increases output"); + Equal(500.0 * 2 * 60 / 216000, sprayedOrdinary.ItemFlows[11].GrossConsumption, + "ordinary fuel acceleration also burns more fuel"); + + request.Buildings[0] = new ProductionBuildingSnapshot(30, 30, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary { ["FuelItemId"] = 12 }); + Check(analyzer.Analyze(request).Diagnostics.Single().Code == + ProductionDiagnosticCode.MissingOperatingParameter, "native fuel mask rejects incompatible fuel"); + + var evaluator = new ProcessEvaluator(); + var invalidFuelMode = new Dictionary { ["FuelItemId"] = 11 }; + Check(!evaluator.TryEvaluate(catalog, null, catalog.Buildings[30], + ProliferationMode.ExtraProducts, 4, invalidFuelMode, out _, out var fuelDiagnostic) && + fuelDiagnostic.Code == ProductionDiagnosticCode.UnsupportedProliferation, + "explicit unsupported fuel productivity mode is rejected"); + + request.ProliferationEnabled = false; + request.Buildings[0] = new ProductionBuildingSnapshot(31, 31, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary + { + ["FuelItemId"] = 1804, + ["Mode0"] = 1 + }); + var star = analyzer.Analyze(request); + Equal(2000000, star.Power.GenerationWatts, "star boost and special fuel native multiplier"); + Equal(60, star.ItemFlows[1804].GrossConsumption, + "star generation accounts for boosted fuel burn"); + } + + private static void BlackBoxBalancesAndThreshold() + { + var items = new[] + { + new ProductionItem(1, 0, true, false, 0, 0), + new ProductionItem(2, 401, false, false, 0, 0), + new ProductionItem(3, 402, false, false, 0, 0) + }; + var recipes = new[] + { + new ProductionRecipe(401, ProductionRecipeCategory.Assemble, 60, true, + new[] { new KeyValuePair(1, 1) }, + new[] { new KeyValuePair(2, 60) }), + new ProductionRecipe(402, ProductionRecipeCategory.Assemble, 60, true, + new[] { new KeyValuePair(2, 150) }, + new[] { new KeyValuePair(3, 1) }) + }; + var catalog = new ProductionCatalog(items, recipes, + new[] + { + new ProductionBuilding(10, ProductionRecipeCategory.Assemble, 1, 1000, 100), + new ProductionBuilding(20, ProductionRecipeCategory.Assemble, 2, 3000, 300) + }, new[] { 0.0, 1.0 }, new[] { 0.0, 0.25 }, new[] { 1.0, 2.5 }); + var analyzer = new FactoryBlackBoxAnalyzer(catalog); + var request = new FactoryBlackBoxRequest(); + request.Buildings.Add(new ProductionBuildingSnapshot(100, 10, 401, 1, ProliferationMode.None)); + request.Buildings.Add(new ProductionBuildingSnapshot(101, 20, 401, 1, ProliferationMode.None)); + request.Buildings.Add(new ProductionBuildingSnapshot(102, 10, 402, 1, ProliferationMode.None)); + var report = analyzer.Analyze(request); + Check(report.MaterialComplete && report.PowerComplete, "fixed-building black box complete"); + Equal(180, report.ItemFlows[2].GrossProduction, "tiers retain separate capacities"); + Equal(150, report.ItemFlows[2].GrossConsumption, "downstream runs at full load"); + Equal(30, report.ItemFlows[2].Surplus, "fractional intermediate balance retained"); + Equal(60, report.ItemFlows[2].SingleBuildingSurplusThreshold, "smallest actual producer threshold"); + Check(!report.ItemFlows[2].IsExcessIntermediate, "sub-threshold surplus is normally balanced"); + Equal(2, report.ItemFlows[2].ProducerGroups.Count, "producer groups retained"); + Equal(1, report.ItemFlows[2].ConsumerGroups.Count, "consumer groups retained"); + Equal(3, report.ItemFlows[1].RequiredExternalSupply, "shortage is not silently suppressed"); + Equal(1, report.ItemFlows[3].Surplus, "unconsumed output is final product"); + Check(report.ItemFlows[3].IsFinalProduct, "final output is unthresholded"); + + request.Buildings.RemoveAt(2); + request.Buildings.Add(new ProductionBuildingSnapshot(102, 10, 402, 1, ProliferationMode.None, + speedFactor: 0.8)); + var atThreshold = analyzer.Analyze(request); + Equal(60, atThreshold.ItemFlows[2].Surplus, "intermediate at threshold"); + Check(atThreshold.ItemFlows[2].IsExcessIntermediate, "threshold reached qualifies as excess"); + + request.Buildings.Add(new ProductionBuildingSnapshot(102, 10, 402, 1, ProliferationMode.None)); + var duplicate = analyzer.Analyze(request); + Check(duplicate.Diagnostics.Single().Code == ProductionDiagnosticCode.DuplicateSelection, + "duplicate object IDs diagnosed and deduplicated"); + Equal(60, duplicate.ItemFlows[2].Surplus, "duplicate objects do not double-count"); + + request.Buildings.Clear(); + request.Buildings.Add(new ProductionBuildingSnapshot(200, 10, 0, 1, ProliferationMode.None)); + var idle = analyzer.Analyze(request); + Equal(100, idle.Power.ConsumptionWatts, "unconfigured building contributes idle demand"); + } + + private static void BlackBoxMixedModesAndDeficits() + { + var catalog = new ProductionCatalog(new[] + { + new ProductionItem(1, 0, true, false, 0, 0), + new ProductionItem(2, 501, false, false, 0, 0), + new ProductionItem(3, 0, false, false, 3, 60), + new ProductionItem(4, 502, false, false, 0, 0) + }, new[] + { + Recipe(501, new[] { (1, 1.0) }, new[] { (2, 1.0) }), + Recipe(502, new[] { (2, 3.0) }, new[] { (4, 0.5) }) + }, new[] + { + new ProductionBuilding(10, ProductionRecipeCategory.Assemble, 1, 1000, 100), + new ProductionBuilding(20, ProductionRecipeCategory.Assemble, 2, 3000, 300) + }, new[] { 0.0, 0.25, 0.5, 1.0, 1.5 }, + new[] { 0.0, 0.125, 0.2, 0.25, 0.3 }, + new[] { 1.0, 1.3, 1.7, 2.5, 3.0 }); + var request = new FactoryBlackBoxRequest { ProliferationEnabled = true }; + request.Buildings.Add(new ProductionBuildingSnapshot(1, 10, 501, 1, + ProliferationMode.ExtraProducts)); + request.Buildings.Add(new ProductionBuildingSnapshot(2, 20, 501, 1, + ProliferationMode.Speedup)); + request.Buildings.Add(new ProductionBuildingSnapshot(-3, 10, 501, 1, + ProliferationMode.None)); + request.Buildings.Add(new ProductionBuildingSnapshot(4, 10, 502, 3, + ProliferationMode.None)); + var analyzer = new FactoryBlackBoxAnalyzer(catalog); + var sprayed = analyzer.Analyze(request); + Check(sprayed.MaterialComplete && sprayed.PowerComplete, + "selected building tiers retain their distinct native modes"); + Equal(6.25, sprayed.ItemFlows[2].GrossProduction, + "mixed extra, speedup, and plain modes produce distinct rates"); + Equal(9, sprayed.ItemFlows[2].GrossConsumption, + "downstream runs at full capacity despite intermediate shortage"); + Equal(2.75, sprayed.ItemFlows[2].RequiredExternalSupply, + "theoretical intermediate shortage is not hidden by downstream output"); + Equal(1.5, sprayed.ItemFlows[4].Surplus, + "fractional final-product rate remains unrounded"); + Equal(6, sprayed.ItemFlows[1].RequiredExternalSupply, + "raw resource shortage is reported alongside intermediate shortage"); + Equal(14000, sprayed.Power.ConsumptionWatts, + "mixed manufacturing and unsprayed consumers use separate power modes"); + + request.ProliferationEnabled = false; + var plain = analyzer.Analyze(request); + Equal(4, plain.ItemFlows[2].GrossProduction, + "global no-proliferation removes speed and extra-product effects"); + Equal(5000 + 3000, plain.Power.ConsumptionWatts, + "global no-proliferation restores native power for every tier"); + Equal(1.5, plain.ItemFlows[4].GrossProduction, + "disabling proliferation does not throttle a shorted downstream recipe"); + } + + private static void BeltSignalStatistics() + { + var report = new ProductionPlanner(Catalog()).Calculate(Request((3, 1))); + Check(report.MaterialComplete, "belt source plan has complete materials without selected special power"); + var rates = BeltSignalSourceStats.FromReport(report, 3); + Check(rates.All(rate => rate.ItemId != 3), "delivered target is not added to upstream product register"); + Equal(0.5, rates.Single(rate => rate.ItemId == 1).ProductionPerItem, + "external raw material is a source product"); + Equal(0.5, rates.Single(rate => rate.ItemId == 1).ConsumptionPerItem, + "external raw material is also consumed by the recipe"); + Equal(0.5, rates.Single(rate => rate.ItemId == 4).ProductionPerItem, + "coproduct is recorded without consumption"); + + var registers = new int[100]; + var consumption = new int[100]; + var stats = new BeltSignalSourceStats(rates); + stats.Apply(1, registers, consumption); + stats.Apply(1, registers, consumption); + Equal(1, registers[1], "fractional source production is retained across generated items"); + Equal(1, consumption[1], "fractional source consumption is retained independently"); + Equal(2, registers[2], "intermediate production uses the gross ledger"); + Equal(2, consumption[2], "intermediate consumption uses the gross ledger"); + Equal(1, registers[4], "coproduct is not produced twice across two insertions"); + Equal(0, consumption[4], "unused coproduct is not consumed"); + Equal(0, registers[3], "generated target is not counted by upstream statistics"); + + var asymmetrical = new ProductionReport(ProductionStatus.Complete, true, true, + new[] { new ProductionItemFlow(7, 0.25, 0.75, 0, 0, 0, 0, 0, + false, false, 0, Array.Empty(), Array.Empty()) }, + Array.Empty(), Array.Empty(), null); + var independent = new BeltSignalSourceStats(BeltSignalSourceStats.FromReport(asymmetrical, 8)); + for (var insertion = 0; insertion < 4; insertion++) + independent.Apply(1, registers, consumption); + Equal(1, registers[7], "quarter-rate production has its own fractional progress"); + Equal(3, consumption[7], "three-quarter-rate consumption has its own fractional progress"); + + var natural = new ProductionPlanner(Catalog()).Calculate(Request((1, 1))); + Check(BeltSignalSourceStats.FromReport(natural, 1).Count == 0, + "an externally sourced target has no duplicate statistics"); + } + + private static void BeltSignalPreset() + { + var items = new[] + { + new ProductionItem(ItemIds.Water, 0, true, false, 0, 0), + new ProductionItem(ItemIds.ProliferatorMkIII, 201, false, false, 4, 75), + new ProductionItem(ItemIds.Steel, 202, false, false, 0, 0), + new ProductionItem(ItemIds.SpaceWarper, 203, false, false, 0, 0), + new ProductionItem(ItemIds.TitaniumGlass, 204, false, false, 0, 0) + }; + var recipes = new[] + { + Recipe(201, new[] { (ItemIds.Water, 1.0) }, + new[] { (ItemIds.ProliferatorMkIII, 1.0) }), + Recipe(202, new[] { (ItemIds.Water, 1.0) }, new[] { (ItemIds.Steel, 1.0) }), + Recipe(203, new[] { (ItemIds.Water, 1.0) }, new[] { (ItemIds.SpaceWarper, 1.0) }), + Recipe(204, new[] { (ItemIds.Water, 1.0) }, new[] { (ItemIds.TitaniumGlass, 1.0) }, + productive: false) + }; + var catalog = new ProductionCatalog(items, recipes, Array.Empty(), + new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + var request = BeltSignalSourcePreset.Create(catalog, ItemIds.Steel, true, true); + Check(request.ExternalMaterials.SetEquals(new[] { ItemIds.Water }), + "only known natural belt source IDs become external materials"); + Equal(ItemIds.ProliferatorMkIII, request.ProliferatorItemId, + "belt policy uses the available proliferator item"); + Check(request.SelfSprayProliferator && request.SprayDeliveredItems.Contains(ItemIds.Steel), + "self-spray and delivered-item spraying are request settings"); + Check(request.ProliferationModeByItem[ItemIds.Steel] == ProliferationMode.ExtraProducts, + "productive legacy extra-products choice maps to a native mode"); + Check(request.ProliferationModeByItem[ItemIds.SpaceWarper] == ProliferationMode.None, + "legacy disabled item keeps its no-proliferation preset"); + Check(request.ProliferationModeByItem[ItemIds.TitaniumGlass] == ProliferationMode.Speedup, + "unsupported extra-products choice falls back to native speedup"); + var report = new ProductionPlanner(catalog).Calculate(request); + Check(report.MaterialComplete, "belt preset resolves the proliferator's recipe and raw materials"); + Check(report.ItemFlows[ItemIds.ProliferatorMkIII].GrossConsumption > 0, + "belt preset accounts for finished-item and upstream spray consumption"); + + var updatedItems = new[] + { + items[0], items[2], new ProductionItem(9999, 205, false, false, 4, 80) + }; + var updatedRecipes = new[] + { + recipes[1], Recipe(205, new[] { (ItemIds.Water, 1.0) }, new[] { (9999, 1.0) }) + }; + var updatedCatalog = new ProductionCatalog(updatedItems, updatedRecipes, + Array.Empty(), new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + var updated = BeltSignalSourcePreset.Create(updatedCatalog, ItemIds.Steel, true, false); + Equal(9999, updated.ProliferatorItemId, "updated game data selects a valid proliferator instead of a stale ID"); + } + + private static void RayReceiverPowerAndPhotons() + { + var receiver = new ProductionBuilding(51, ProductionRecipeCategory.None, 1, 0, 0, + ProductionBuildingKind.RayReceiver, ratedGenerationWatts: 1000, + powerProductItemId: 456, powerProductEnergyJoules: 100000, catalystMask: 1); + var items = new[] + { + new ProductionItem(123, 0, false, false, 0, 0, + catalystTypeMask: 1, catalystAbilityMultiplier: 2), + new ProductionItem(456, 999, false, false, 0, 0), + new ProductionItem(789, 0, false, false, 4, 75) + }; + var photonRecipe = new ProductionRecipe(999, ProductionRecipeCategory.PhotonStore, 60, false, + Array.Empty>(), + new[] { new KeyValuePair(456, 1) }); + var catalog = new ProductionCatalog(items, new[] { photonRecipe }, new[] { receiver }, + new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + var parameters = new Dictionary + { + ["Mode0"] = 456, ["LensItemId"] = 0, ["SolarEnergyLossRate"] = 0.25 + }; + var analyzer = new FactoryBlackBoxAnalyzer(catalog); + var request = new FactoryBlackBoxRequest(); + request.Buildings.Add(new ProductionBuildingSnapshot(1, 51, 0, 1, + ProliferationMode.None, operatingParameters: parameters)); + var photons = analyzer.Analyze(request); + Check(photons.MaterialComplete && photons.PowerComplete, "native photon process evaluates at full warmup"); + Equal(12, photons.ItemFlows[456].GrossProduction, "photon rate uses eightfold Dyson power"); + Equal(0, photons.Power.GenerationWatts, "photon mode does not contribute grid generation"); + Equal(20000 / 0.85, photons.Power.DysonSphereRequirementWatts, + "photon Dyson demand uses warmed-up loss technology"); + + parameters["Mode0"] = 0; + request.Buildings[0] = new ProductionBuildingSnapshot(1, 51, 0, 1, + ProliferationMode.None, operatingParameters: parameters); + var grid = analyzer.Analyze(request); + Check(!grid.ItemFlows.ContainsKey(456), "grid mode does not invent photon products"); + Equal(2500, grid.Power.GenerationWatts, "grid mode reports receiver generation"); + Equal(2500 / 0.85, grid.Power.DysonSphereRequirementWatts, + "grid mode keeps Dyson power separate from local generation"); + + parameters["Mode0"] = 456; + parameters["LensItemId"] = 123; + request.Buildings[0] = new ProductionBuildingSnapshot(1, 51, 0, 1, + ProliferationMode.None, operatingParameters: parameters); + request.ProliferationEnabled = true; + var sprayed = analyzer.Analyze(request); + Equal(48, sprayed.ItemFlows[456].GrossProduction, + "lens ability and native speedup multiply photon production"); + Equal(0.1, sprayed.ItemFlows[123].GrossConsumption, + "ray receiver consumes one lens per 36000 ticks, not 3600 ticks"); + Equal(80000 / 0.85, sprayed.Power.DysonSphereRequirementWatts, + "lens and proliferation change the Dyson requirement"); + request.ProliferationEnabled = false; + var unproliferated = analyzer.Analyze(request); + Equal(24, unproliferated.ItemFlows[456].GrossProduction, + "disabling global proliferation leaves lens ability but removes speedup"); + Equal(0.1, unproliferated.ItemFlows[123].GrossConsumption, + "unproliferated lens still wears at its native rate"); + + var plan = new ProductionPlanRequest(); + plan.Targets.Add(new ProductionTarget(456, 24)); + plan.ExternalMaterials.Add(123); + plan.BuildingByRecipe[999] = 51; + plan.OperatingParametersByRecipe[999] = parameters; + var planned = new ProductionPlanner(catalog).Calculate(plan); + Check(planned.MaterialComplete && planned.PowerComplete, "photon planning uses the ray receiver adapter"); + Equal(0.1, planned.ItemFlows[123].ExternalImports, + "planner accounts for lenses as external inputs when selected"); + Equal(1, planned.Groups.Single().EquivalentBuildings.Value, + "photon plan uses equivalent receivers for peak and Dyson demand"); + + parameters.Remove("SolarEnergyLossRate"); + request.Buildings[0] = new ProductionBuildingSnapshot(1, 51, 0, 1, + ProliferationMode.None, operatingParameters: parameters); + var missingTechnology = analyzer.Analyze(request); + Check(missingTechnology.MaterialComplete && !missingTechnology.PowerComplete, + "missing solar-loss technology does not discard photon material results"); + Check(missingTechnology.Groups.Single().DysonSphereRequirementWatts == null, + "unknown Dyson power is not reported as zero"); + Check(missingTechnology.Diagnostics.Any(d => d.Code == ProductionDiagnosticCode.MissingOperatingParameter), + "missing solar-loss technology is diagnosed"); + } + + private static void LauncherCyclesAndAmmunition() + { + var catalog = new ProductionCatalog(new[] + { + new ProductionItem(101, 0, false, false, 0, 0), + new ProductionItem(102, 0, false, false, 0, 0), + new ProductionItem(103, 0, false, false, 4, 75) + }, Array.Empty(), new[] + { + new ProductionBuilding(71, ProductionRecipeCategory.None, 0, 1200, 120, + ProductionBuildingKind.Ejector, launchChargeTicks: 10, + launchCooldownTicks: 20, ammunitionItemId: 101), + new ProductionBuilding(72, ProductionRecipeCategory.None, 0, 3600, 360, + ProductionBuildingKind.Silo, launchChargeTicks: 60, + launchCooldownTicks: 60, ammunitionItemId: 102) + }, new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + var ejectorSettings = new Dictionary { ["Mode1"] = 0, ["LaunchAvailable"] = 1 }; + var siloSettings = new Dictionary { ["Mode0"] = 0, ["LaunchAvailable"] = 1 }; + var request = new FactoryBlackBoxRequest(); + request.Buildings.Add(new ProductionBuildingSnapshot(1, 71, 0, 1, + ProliferationMode.None, operatingParameters: ejectorSettings)); + request.Buildings.Add(new ProductionBuildingSnapshot(2, 72, 0, 1, + ProliferationMode.None, operatingParameters: siloSettings)); + var analyzer = new FactoryBlackBoxAnalyzer(catalog); + var ordinary = analyzer.Analyze(request); + Check(ordinary.MaterialComplete && ordinary.PowerComplete, "both launch facilities evaluate"); + Equal(120, ordinary.ItemFlows[101].GrossConsumption, "sails consumed per native ejector cycle"); + Equal(30, ordinary.ItemFlows[102].GrossConsumption, "rockets consumed per native silo cycle"); + Equal(150, ordinary.LaunchesPerMinute, "launch rate reported without invented item outputs"); + Equal(4800, ordinary.Power.ConsumptionWatts, "launchers draw working power at full load"); + Check(ordinary.ItemFlows.Values.All(flow => flow.GrossProduction == 0), + "launches do not appear as fabricated product items"); + + request.ProliferationEnabled = true; + var sprayed = analyzer.Analyze(request); + Equal(240, sprayed.ItemFlows[101].GrossConsumption, "ammo speedup shortens both ejector phases"); + Equal(60, sprayed.ItemFlows[102].GrossConsumption, "ammo speedup shortens both silo phases"); + Equal(4800, sprayed.Power.ConsumptionWatts, "launchers do not use manufacturing power multiplier"); + + ejectorSettings["Mode1"] = 1; + ejectorSettings["BoostEnabled"] = 1; + request.Buildings[0] = new ProductionBuildingSnapshot(1, 71, 0, 1, + ProliferationMode.None, operatingParameters: ejectorSettings); + var accelerated = analyzer.Analyze(request); + Equal(1800, accelerated.ItemFlows[101].GrossConsumption, + "native boosted ejector cannot complete a phase in less than one tick"); + request.ProliferationEnabled = false; + accelerated = analyzer.Analyze(request); + Equal(1200, accelerated.ItemFlows[101].GrossConsumption, + "disabling the global switch removes ammunition speedup even with sandbox boost"); + + ejectorSettings.Remove("BoostEnabled"); + request.Buildings[0] = new ProductionBuildingSnapshot(1, 71, 0, 1, + ProliferationMode.None, operatingParameters: ejectorSettings); + var missingBoost = analyzer.Analyze(request); + Check(!missingBoost.MaterialComplete && missingBoost.Diagnostics.Any(d => + d.Code == ProductionDiagnosticCode.MissingOperatingParameter), + "native sandbox boost state is required for a boosted launcher blueprint"); + + ejectorSettings["LaunchAvailable"] = 0; + ejectorSettings["Mode1"] = 0; + request.Buildings[0] = new ProductionBuildingSnapshot(1, 71, 0, 1, + ProliferationMode.None, operatingParameters: ejectorSettings); + var idle = analyzer.Analyze(request); + Equal(120, idle.Power.ConsumptionWatts - 3600, "launcher without an orbit draws only idle demand"); + Equal(30, idle.LaunchesPerMinute, "launcher without an orbit does not consume ammunition"); + } + + private static void GasCollection() + { + var catalog = new ProductionCatalog(new[] + { + new ProductionItem(111, 0, true, false, 0, 0), + new ProductionItem(112, 0, true, false, 0, 0), + new ProductionItem(113, 0, false, false, 4, 75) + }, Array.Empty(), new[] + { + new ProductionBuilding(81, ProductionRecipeCategory.None, 0, 1000, 100, + ProductionBuildingKind.Collector, collectorSpeedMultiplier: 5) + }, new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + var settings = new Dictionary + { + ["GasCount"] = 2, ["GasTotalHeat"] = 1000, ["MiningSpeedMultiplier"] = 2, + ["GasItemId0"] = 111, ["GasSpeedPerSecond0"] = 0.5, + ["GasItemId1"] = 112, ["GasSpeedPerSecond1"] = 0.2 + }; + var request = new FactoryBlackBoxRequest { ProliferationEnabled = true }; + request.Buildings.Add(new ProductionBuildingSnapshot(1, 81, 0, 1, + ProliferationMode.None, operatingParameters: settings)); + var analyzer = new FactoryBlackBoxAnalyzer(catalog); + var report = analyzer.Analyze(request); + Check(report.MaterialComplete && report.PowerComplete, "gas collection uses captured planet resources"); + Equal(4.5, report.ItemFlows[111].GrossProduction, + "native gas self-power recovery and mining technology scale first resource"); + Equal(1.8, report.ItemFlows[112].GrossProduction, + "second gas resource is not lost by a single-output adapter"); + Equal(1000, report.Power.ConsumptionWatts, "gas collection includes native energy demand"); + + settings.Remove("GasSpeedPerSecond1"); + request.Buildings[0] = new ProductionBuildingSnapshot(1, 81, 0, 1, + ProliferationMode.None, operatingParameters: settings); + var missing = analyzer.Analyze(request); + Check(!missing.MaterialComplete && missing.Diagnostics.Any(d => + d.Code == ProductionDiagnosticCode.MissingOperatingParameter), + "unavailable gas composition is diagnosed instead of inventing outputs"); + } + + private static void ResearchHashesAndMatrices() + { + var tech = new ProductionTechnology(401, new[] + { + new KeyValuePair(6001, 2), new KeyValuePair(6002, 1) + }); + var catalog = new ProductionCatalog(new[] + { + new ProductionItem(6001, 0, false, false, 0, 0), + new ProductionItem(6002, 0, false, false, 0, 0), + new ProductionItem(7000, 0, false, false, 4, 75) + }, Array.Empty(), new[] + { + new ProductionBuilding(91, ProductionRecipeCategory.Research, 1, 1000, 100) + }, new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }, new[] { tech }); + var settings = new Dictionary + { + ["ResearchMode"] = 1, ["TechId"] = 401, ["ResearchSpeed"] = 0.5 + }; + var request = new FactoryBlackBoxRequest(); + request.Buildings.Add(new ProductionBuildingSnapshot(1, 91, 0, 1, + ProliferationMode.Speedup, operatingParameters: settings)); + var analyzer = new FactoryBlackBoxAnalyzer(catalog); + var plain = analyzer.Analyze(request); + Check(plain.MaterialComplete && plain.PowerComplete, "lab research mode has full-load flows"); + Equal(1800, plain.ResearchHashesPerMinute, "native research speed sets base hashes per minute"); + Equal(1, plain.ItemFlows[6001].GrossConsumption, + "matrix consumption uses technology's points per hash"); + Equal(0.5, plain.ItemFlows[6002].GrossConsumption, "fractional matrix consumption is retained"); + Equal(0, plain.ItemFlows[6002].GrossProduction, "research hashes are not item products"); + Equal(1000, plain.Power.ConsumptionWatts, "unsprayed research uses native working power"); + + request.ProliferationEnabled = true; + var sprayed = analyzer.Analyze(request); + Equal(2250, sprayed.ResearchHashesPerMinute, "native proliferation grants extra research hashes"); + Equal(1, sprayed.ItemFlows[6001].GrossConsumption, + "extra hashes do not consume additional matrices"); + Equal(2500, sprayed.Power.ConsumptionWatts, + "research-mode lab uses native proliferation power increase"); + Check(sprayed.Groups.Single().Process.ProliferationMode == ProliferationMode.ExtraProducts, + "research mode does not mistake copied assembler speedup setting for hash mode"); + + settings.Remove("TechId"); + request.Buildings[0] = new ProductionBuildingSnapshot(1, 91, 0, 1, + ProliferationMode.None, operatingParameters: settings); + var missing = analyzer.Analyze(request); + Check(!missing.MaterialComplete && missing.Diagnostics.Any(d => + d.Code == ProductionDiagnosticCode.MissingOperatingParameter), + "missing technology cannot silently report zero matrices"); + + request.Buildings[0] = new ProductionBuildingSnapshot(1, 91, 0, 1, + ProliferationMode.None); + var idle = analyzer.Analyze(request); + Equal(100, idle.Power.ConsumptionWatts, "unconfigured lab contributes native idle demand"); + } + + private static void PlannerAuxiliaryPower() + { + var baseCatalog = Catalog(); + var catalog = new ProductionCatalog(baseCatalog.Items.Values, + baseCatalog.Recipes.Values, baseCatalog.Buildings.Values.Concat(new[] + { + new ProductionBuilding(90, ProductionRecipeCategory.None, 0, 200, 20, + ProductionBuildingKind.Auxiliary) + }), new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + var planner = new ProductionPlanner(catalog); + var request = Request((3, 60)); + var ordinary = planner.Calculate(request); + request.AuxiliaryBuildings.Add(new ProductionBuildingSnapshot(1, 90, 0, 2, + ProliferationMode.None)); + var withAuxiliary = planner.Calculate(request); + Check(withAuxiliary.MaterialComplete && withAuxiliary.PowerComplete, + "layout-supplied auxiliary building has complete power accounting"); + Equal(ordinary.Power.ConsumptionWatts + 400, withAuxiliary.Power.ConsumptionWatts, + "two sorters contribute rated working demand without recipe material changes"); + Equal(400, withAuxiliary.Groups.Single(group => group.Process?.BuildingItemId == 90).ConsumptionWatts.Value, + "auxiliary facility is independently attributable in the group breakdown"); + Check(withAuxiliary.Power.Scope == ProductionPowerScope.ProductionBuildingsAndAuxiliary, + "planner explicitly identifies auxiliary power scope"); + Equal(ordinary.ItemFlows[1].ExternalImports, withAuxiliary.ItemFlows[1].ExternalImports, + "auxiliary layout does not change solved materials"); + + request.AuxiliaryBuildings.Add(new ProductionBuildingSnapshot(1, 90, 0, 1, + ProliferationMode.None)); + var duplicate = planner.Calculate(request); + Equal(withAuxiliary.Power.ConsumptionWatts, duplicate.Power.ConsumptionWatts, + "duplicate auxiliary IDs are not counted twice"); + Check(duplicate.Diagnostics.Any(d => d.Code == ProductionDiagnosticCode.DuplicateSelection), + "duplicate auxiliary IDs are diagnosed"); + + request.AuxiliaryBuildings.Clear(); + request.AuxiliaryBuildings.Add(new ProductionBuildingSnapshot(2, 999, 0, 1, + ProliferationMode.None)); + var missing = planner.Calculate(request); + Check(missing.MaterialComplete && !missing.PowerComplete, + "missing auxiliary rating does not discard complete material ledger"); + } + + private static ProductionPlanRequest Request(params (int id, double rate)[] targets) + { + var request = new ProductionPlanRequest(); + foreach (var target in targets) request.Targets.Add(new ProductionTarget(target.id, target.rate)); + request.BuildingByCategory[ProductionRecipeCategory.Assemble] = 10; + return request; + } + + private static ProductionCatalog Catalog() + { + var items = new[] + { + new ProductionItem(1, 0, true, false, 0, 0), + new ProductionItem(2, 101, false, false, 0, 0), + new ProductionItem(3, 102, false, false, 0, 0), + new ProductionItem(4, 103, false, false, 0, 0), + new ProductionItem(5, 104, false, false, 4, 60) + }; + var recipes = new[] + { + Recipe(101, new[] { (1, 1.0) }, new[] { (2, 2.0) }), + Recipe(102, new[] { (2, 1.0) }, new[] { (3, 1.0), (4, 0.5) }), + Recipe(103, new[] { (1, 1.0) }, new[] { (4, 1.0) }), + Recipe(104, new[] { (1, 1.0) }, new[] { (5, 1.0) }) + }; + return new ProductionCatalog(items, recipes, + new[] { new ProductionBuilding(10, ProductionRecipeCategory.Assemble, 1, 1000, 200) }, + new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + } + + private static ProductionRecipe Recipe(int id, (int id, double count)[] input, + (int id, double count)[] output, bool productive = true) + { + return new ProductionRecipe(id, ProductionRecipeCategory.Assemble, 60, productive, + input.Select(flow => new KeyValuePair(flow.id, flow.count)), + output.Select(flow => new KeyValuePair(flow.id, flow.count))); + } + + private static void Check(bool condition, string message) + { + if (!condition) throw new InvalidOperationException(message); + _checks++; + } + + private static void Equal(double expected, double actual, string message) + { + Check(Math.Abs(expected - actual) < 1e-6, $"{message}: expected {expected}, got {actual}"); + } +}