mirror of
https://github.com/soarqin/DSP_Mods.git
synced 2026-11-19 17:05:20 +08:00
fix(production): correct blueprint power and planner edge cases
Read the Advanced Mining Machine speed stored with station settings in prebuild and blueprint captures, and count charging power nodes such as Satellite Substations at their idle draw. Skip recipes that consume their own product when choosing an item's default recipe, so Refined Oil uses Plasma Refining instead of Reforming Refine. Run each planner recipe in one proliferation mode and report conflicting explicit modes, keep material flows for recipe types the catalog does not know, and attribute receiver warnings to their recipe. Compare simplex ratio ties relatively and drive out near-zero artificials without amplifying residuals. Bound the steady-state reduction so lossless cycles cannot stall blueprint descriptions, and choose power units after rounding. Remove redundant code: share the numeric and flow helpers, and drop the unused IsExcessIntermediate threshold, legacy constructor and Capture overloads, the multi-field updater, and the unused proliferator source table.
This commit is contained in:
1 parent
4839f868e1
commit
d941de2810
24 files changed
+463
-404
No files matched your search
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -68,8 +69,7 @@ public sealed class AccumulatorExchangeAdapter : IProductionProcessAdapter
|
||||
}
|
||||
else if (operatingParameters == null ||
|
||||
!operatingParameters.TryGetValue("Mode0", out var selectedMode) ||
|
||||
double.IsNaN(selectedMode) || double.IsInfinity(selectedMode) ||
|
||||
selectedMode != Math.Truncate(selectedMode) ||
|
||||
!Finite(selectedMode) || selectedMode != Math.Truncate(selectedMode) ||
|
||||
selectedMode < -1 || selectedMode > 1)
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
|
||||
@@ -126,9 +126,4 @@ public sealed class AccumulatorExchangeAdapter : IProductionProcessAdapter
|
||||
? Array.Empty<KeyValuePair<int, double>>() : outputs);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool FinitePositive(double value)
|
||||
{
|
||||
return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
|
||||
}
|
||||
}
|
||||
@@ -42,17 +42,15 @@ internal sealed class BlackBoxItemClassification
|
||||
{
|
||||
public bool IsFinalProduct { get; }
|
||||
public bool IsResearchProduct { get; }
|
||||
public bool IsIntermediate { get; }
|
||||
public double IntermediateShortage { get; }
|
||||
public double? OverbuildSurplus { get; }
|
||||
public double? CoproductSurplus { get; }
|
||||
|
||||
public BlackBoxItemClassification(bool isFinalProduct, bool isResearchProduct, bool isIntermediate,
|
||||
double intermediateShortage, double? overbuildSurplus, double? coproductSurplus)
|
||||
public BlackBoxItemClassification(bool isFinalProduct, bool isResearchProduct, double intermediateShortage,
|
||||
double? overbuildSurplus, double? coproductSurplus)
|
||||
{
|
||||
IsFinalProduct = isFinalProduct;
|
||||
IsResearchProduct = isResearchProduct;
|
||||
IsIntermediate = isIntermediate;
|
||||
IntermediateShortage = intermediateShortage;
|
||||
OverbuildSurplus = overbuildSurplus;
|
||||
CoproductSurplus = coproductSurplus;
|
||||
@@ -62,6 +60,7 @@ internal sealed class BlackBoxItemClassification
|
||||
internal static class BlackBoxMaterialClassifier
|
||||
{
|
||||
internal const double Tolerance = 1e-9;
|
||||
private const int MaximumSteadyStatePasses = 10000;
|
||||
|
||||
private sealed class ReductionGroup
|
||||
{
|
||||
@@ -148,7 +147,7 @@ internal static class BlackBoxMaterialClassifier
|
||||
overbuild = Math.Min(Math.Max(0, originalNet),
|
||||
Math.Max(0, originalNet - remainingBalance[itemId]));
|
||||
var necessaryJointProduction = groups.Sum(group => NecessaryJointProduction(group, itemId,
|
||||
originalBalance, remainingBalance, protectedItems, intermediateItems));
|
||||
originalBalance, remainingBalance, protectedItems));
|
||||
var internalConsumption = groups.Sum(group =>
|
||||
group.Source.NetPerBuilding.TryGetValue(itemId, out var amount) && amount < -Tolerance
|
||||
? -amount * (group.Count - group.Removed) : 0);
|
||||
@@ -161,17 +160,17 @@ internal static class BlackBoxMaterialClassifier
|
||||
var isResearchProduct = finalKnown && researchMatrixSinks.Contains(itemId) && originalNet > Tolerance;
|
||||
classification[itemId] = new BlackBoxItemClassification(
|
||||
finalKnown && finalItems.Contains(itemId) || isResearchProduct, isResearchProduct,
|
||||
isIntermediate, isIntermediate ? Math.Max(0, -originalNet) : 0, overbuild, coproduct);
|
||||
isIntermediate ? Math.Max(0, -originalNet) : 0, overbuild, coproduct);
|
||||
}
|
||||
|
||||
steadyStateBalance = CalculateSteadyStateBalance(groups, originalBalance, remainingBalance,
|
||||
protectedItems, intermediateItems);
|
||||
protectedItems);
|
||||
return classification;
|
||||
}
|
||||
|
||||
private static double NecessaryJointProduction(ReductionGroup group, int itemId,
|
||||
IReadOnlyDictionary<int, double> originalBalance, IReadOnlyDictionary<int, double> remainingBalance,
|
||||
ISet<int> protectedItems, ISet<int> intermediateItems)
|
||||
ISet<int> protectedItems)
|
||||
{
|
||||
var retained = group.Count - group.Removed;
|
||||
if (retained == 0 || !group.Source.HasJointProducts ||
|
||||
@@ -182,10 +181,7 @@ internal static class BlackBoxMaterialClassifier
|
||||
foreach (var flow in group.Source.NetPerBuilding)
|
||||
{
|
||||
if (flow.Key == itemId || flow.Value <= Tolerance) continue;
|
||||
double minimum;
|
||||
if (protectedItems.Contains(flow.Key)) minimum = originalBalance[flow.Key];
|
||||
else if (intermediateItems.Contains(flow.Key)) minimum = Math.Min(0, originalBalance[flow.Key]);
|
||||
else continue;
|
||||
var minimum = MinimumBalance(flow.Key, originalBalance, protectedItems);
|
||||
var available = Math.Floor((remainingBalance[flow.Key] - minimum + Tolerance) / flow.Value);
|
||||
removable = Math.Min(removable, Math.Max(0, available));
|
||||
}
|
||||
@@ -195,14 +191,15 @@ internal static class BlackBoxMaterialClassifier
|
||||
|
||||
private static IReadOnlyDictionary<int, double> CalculateSteadyStateBalance(
|
||||
IReadOnlyList<ReductionGroup> groups, IReadOnlyDictionary<int, double> originalBalance,
|
||||
IReadOnlyDictionary<int, double> remainingBalance, ISet<int> protectedItems, ISet<int> intermediateItems)
|
||||
IReadOnlyDictionary<int, double> remainingBalance, ISet<int> protectedItems)
|
||||
{
|
||||
var balance = remainingBalance.ToDictionary(entry => entry.Key, entry => entry.Value);
|
||||
var available = groups.ToDictionary(group => group, group => (double)(group.Count - group.Removed));
|
||||
bool changed;
|
||||
do
|
||||
// A lossless cycle, such as charging and discharging accumulators, can pass a tiny leftover around
|
||||
// indefinitely; stopping early only leaves the input estimate conservative.
|
||||
for (var pass = 0; pass < MaximumSteadyStatePasses; pass++)
|
||||
{
|
||||
changed = false;
|
||||
var changed = false;
|
||||
foreach (var group in groups)
|
||||
{
|
||||
if (!group.Source.NetPerBuilding.Values.Any(value => value > Tolerance)) continue;
|
||||
@@ -210,10 +207,7 @@ internal static class BlackBoxMaterialClassifier
|
||||
foreach (var flow in group.Source.NetPerBuilding)
|
||||
{
|
||||
if (flow.Value <= Tolerance) continue;
|
||||
double minimum;
|
||||
if (protectedItems.Contains(flow.Key)) minimum = originalBalance[flow.Key];
|
||||
else if (intermediateItems.Contains(flow.Key)) minimum = Math.Min(0, originalBalance[flow.Key]);
|
||||
else continue;
|
||||
var minimum = MinimumBalance(flow.Key, originalBalance, protectedItems);
|
||||
reducible = Math.Min(reducible, Math.Max(0, (balance[flow.Key] - minimum) / flow.Value));
|
||||
}
|
||||
|
||||
@@ -223,11 +217,21 @@ internal static class BlackBoxMaterialClassifier
|
||||
available[group] -= reducible;
|
||||
changed = true;
|
||||
}
|
||||
} while (changed);
|
||||
|
||||
if (!changed) break;
|
||||
}
|
||||
|
||||
return balance;
|
||||
}
|
||||
|
||||
// Every positive process output is a protected or intermediate item. Protected balances may not fall below
|
||||
// their full-load value, and intermediates may not gain a new or larger shortage.
|
||||
private static double MinimumBalance(int itemId, IReadOnlyDictionary<int, double> originalBalance,
|
||||
ISet<int> protectedItems)
|
||||
{
|
||||
return protectedItems.Contains(itemId) ? originalBalance[itemId] : Math.Min(0, originalBalance[itemId]);
|
||||
}
|
||||
|
||||
private static bool CanRemove(IReadOnlyDictionary<int, double> netPerBuilding,
|
||||
IReadOnlyDictionary<int, double> originalBalance, IReadOnlyDictionary<int, double> remainingBalance,
|
||||
ISet<int> protectedItems, ISet<int> intermediateItems)
|
||||
|
||||
@@ -2,7 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -64,6 +64,7 @@ public sealed class BlueprintDescriptionText
|
||||
public static class BlueprintDescriptionFormatter
|
||||
{
|
||||
private const double Tolerance = 1e-9;
|
||||
private static readonly string[] PowerUnits = { "W", "kW", "MW", "GW", "TW" };
|
||||
|
||||
public static BlueprintDescriptionText Format(ProductionReport report, Func<int, string> itemTag,
|
||||
BlueprintDescriptionLabels labels)
|
||||
@@ -153,18 +154,27 @@ public static class BlueprintDescriptionFormatter
|
||||
{
|
||||
if (!watts.HasValue) return labels.Unknown;
|
||||
var value = watts.Value;
|
||||
if (value >= 1e12) return FormatNumber(value / 1e12) + "TW";
|
||||
if (value >= 1e9) return FormatNumber(value / 1e9) + "GW";
|
||||
if (value >= 1e6) return FormatNumber(value / 1e6) + "MW";
|
||||
if (value >= 1e3) return FormatNumber(value / 1e3) + "kW";
|
||||
return FormatNumber(value) + "W";
|
||||
var unit = 0;
|
||||
// Choose the unit after rounding so that 999.999 W displays as 1kW rather than 1000W.
|
||||
while (unit < PowerUnits.Length - 1 && RoundForDisplay(value) >= 1000)
|
||||
{
|
||||
value /= 1000;
|
||||
unit++;
|
||||
}
|
||||
|
||||
return FormatNumber(value) + PowerUnits[unit];
|
||||
}
|
||||
|
||||
private static double RoundForDisplay(double value)
|
||||
{
|
||||
return Math.Round(value, value < 1 ? 3 : 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
private static string FormatNumber(double value)
|
||||
{
|
||||
if (double.IsNaN(value) || double.IsInfinity(value) || value < 0)
|
||||
if (!FiniteNonnegative(value))
|
||||
throw new InvalidOperationException("A blueprint report contains an invalid rate or power value.");
|
||||
var rounded = Math.Round(value, value < 1 ? 3 : 2, MidpointRounding.AwayFromZero);
|
||||
var rounded = RoundForDisplay(value);
|
||||
if (rounded > 0 || value == 0)
|
||||
return rounded.ToString(value < 1 ? "0.###" : "0.##", CultureInfo.InvariantCulture);
|
||||
var precise = value.ToString("0.######", CultureInfo.InvariantCulture);
|
||||
@@ -215,74 +225,41 @@ public static class BlueprintDescriptionFields
|
||||
return true;
|
||||
}
|
||||
|
||||
public static BlueprintFieldUpdateResult TryUpdate(string existing, IReadOnlyList<BlueprintDescriptionField> fields,
|
||||
// Updates the first matching field in place and drops other matches; a null value removes them all. A new field
|
||||
// is appended only when it fits, so other fields are never removed to make room.
|
||||
public static BlueprintFieldUpdateResult TryUpdate(string existing, BlueprintDescriptionField field,
|
||||
int maximumFields, Func<string, string> escape, Func<string, string> unescape, out string updated)
|
||||
{
|
||||
updated = existing;
|
||||
if (fields == null || escape == null || unescape == null)
|
||||
throw new ArgumentNullException(fields == null ? nameof(fields) : escape == null ? nameof(escape) : nameof(unescape));
|
||||
if (field == null || escape == null || unescape == null)
|
||||
throw new ArgumentNullException(field == null ? nameof(field) : escape == null ? nameof(escape) : nameof(unescape));
|
||||
if (maximumFields < 0 || !IsNativeFormatValid(existing))
|
||||
return BlueprintFieldUpdateResult.InvalidFields;
|
||||
|
||||
var generated = field.Value == null ? null : escape(field.Title) + ":" + escape(field.Value);
|
||||
var parts = (existing ?? "").Split(';');
|
||||
var matches = new int[parts.Length];
|
||||
var found = new bool[fields.Count];
|
||||
var nativeCount = 0;
|
||||
var removedCount = 0;
|
||||
var entries = new List<string>();
|
||||
var replaced = false;
|
||||
for (var index = 0; index < parts.Length - 1; index++)
|
||||
{
|
||||
var delimiter = parts[index].IndexOf(':');
|
||||
nativeCount++;
|
||||
var name = unescape(parts[index].Substring(0, delimiter));
|
||||
for (var fieldIndex = 0; fieldIndex < fields.Count; fieldIndex++)
|
||||
if (!field.Matches(unescape(parts[index].Substring(0, parts[index].IndexOf(':')))))
|
||||
{
|
||||
if (!fields[fieldIndex].Matches(name)) continue;
|
||||
if (fields[fieldIndex].Value == null || found[fieldIndex])
|
||||
{
|
||||
matches[index] = -1;
|
||||
removedCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
matches[index] = fieldIndex + 1;
|
||||
found[fieldIndex] = true;
|
||||
}
|
||||
break;
|
||||
entries.Add(parts[index]);
|
||||
}
|
||||
else if (generated != null && !replaced)
|
||||
{
|
||||
entries.Add(generated);
|
||||
replaced = true;
|
||||
}
|
||||
}
|
||||
|
||||
var missingCount = 0;
|
||||
for (var index = 0; index < fields.Count; index++)
|
||||
if (!found[index] && fields[index].Value != null) missingCount++;
|
||||
if (nativeCount - removedCount + missingCount > maximumFields)
|
||||
return BlueprintFieldUpdateResult.CapacityExceeded;
|
||||
|
||||
var serialized = new StringBuilder();
|
||||
for (var index = 0; index < parts.Length - 1; index++)
|
||||
if (generated != null && !replaced)
|
||||
{
|
||||
var match = matches[index];
|
||||
if (match < 0) continue;
|
||||
if (match > 0)
|
||||
{
|
||||
var field = fields[match - 1];
|
||||
serialized.Append(escape(field.Title)).Append(':').Append(escape(field.Value));
|
||||
}
|
||||
else
|
||||
{
|
||||
serialized.Append(parts[index]);
|
||||
}
|
||||
|
||||
serialized.Append(';');
|
||||
if (entries.Count >= maximumFields) return BlueprintFieldUpdateResult.CapacityExceeded;
|
||||
entries.Add(generated);
|
||||
}
|
||||
|
||||
for (var index = 0; index < fields.Count; index++)
|
||||
{
|
||||
if (!found[index] && fields[index].Value != null)
|
||||
serialized.Append(escape(fields[index].Title)).Append(':').Append(escape(fields[index].Value))
|
||||
.Append(';');
|
||||
}
|
||||
|
||||
updated = serialized.ToString();
|
||||
updated = string.Concat(entries.Select(entry => entry + ";"));
|
||||
return BlueprintFieldUpdateResult.Updated;
|
||||
}
|
||||
}
|
||||
@@ -35,13 +35,11 @@ public sealed class BlueprintSelectionCapture
|
||||
|
||||
public static class BlueprintSelectionReader
|
||||
{
|
||||
public static BlueprintSelectionCapture Capture(PlanetFactory factory, IEnumerable<int> selectedObjectIds)
|
||||
{
|
||||
return Capture(factory, selectedObjectIds, null);
|
||||
}
|
||||
// Native station parameters store charging power at this index, followed by other station settings.
|
||||
private const int StationSettingsIndex = 320;
|
||||
|
||||
public static BlueprintSelectionCapture Capture(PlanetFactory factory, IEnumerable<int> selectedObjectIds,
|
||||
BlueprintSelectionContext context)
|
||||
BlueprintSelectionContext context = null)
|
||||
{
|
||||
var catalog = ProductionCatalogService.Current;
|
||||
if (factory == null || catalog == null)
|
||||
@@ -81,21 +79,18 @@ public static class BlueprintSelectionReader
|
||||
var operation = new Dictionary<string, double>();
|
||||
var speedFactor = GetLiveSpeed(factory, objectId, parameters.type, operation);
|
||||
AddSettings(parameters, operation);
|
||||
var storedParameters = objectId < 0 ? factory.prebuildPool[-objectId].parameters : null;
|
||||
if (building.Kind == ProductionBuildingKind.Logistics)
|
||||
{
|
||||
if (objectId > 0)
|
||||
CaptureLiveChargePower(factory, objectId, operation);
|
||||
else
|
||||
{
|
||||
ref var prebuild = ref factory.prebuildPool[-objectId];
|
||||
CaptureStoredChargePower(building, parameters, prebuild.parameters, operation);
|
||||
}
|
||||
if (objectId > 0) CaptureLiveChargePower(factory, objectId, operation);
|
||||
else CaptureStoredChargePower(building, parameters, storedParameters, operation);
|
||||
}
|
||||
if (operation.ContainsKey("ResearchMode")) CaptureResearchSettings(factory, operation);
|
||||
switch (building.Kind)
|
||||
{
|
||||
case ProductionBuildingKind.Miner:
|
||||
CaptureMiningSettings(factory, objectId, building, operation);
|
||||
if (objectId < 0) CaptureStoredMinerSpeed(parameters, storedParameters, operation);
|
||||
break;
|
||||
case ProductionBuildingKind.Collector:
|
||||
CaptureCollectionSettings(factory, operation);
|
||||
@@ -177,6 +172,8 @@ public static class BlueprintSelectionReader
|
||||
operation["ResearchMatrixSink"] = 1;
|
||||
if (building.Kind == ProductionBuildingKind.Logistics)
|
||||
CaptureStoredChargePower(building, parameters, blueprint.parameters, operation);
|
||||
else if (building.Kind == ProductionBuildingKind.Miner)
|
||||
CaptureStoredMinerSpeed(parameters, blueprint.parameters, operation);
|
||||
ApplySupplied(context?.OperatingParametersByIndex, blueprint.index, operation);
|
||||
snapshots.Add(CreateSnapshot(catalog, building, 0, parameters, parameters.recipeId, null, operation,
|
||||
diagnostics));
|
||||
@@ -231,8 +228,9 @@ public static class BlueprintSelectionReader
|
||||
{
|
||||
case BuildingType.Station:
|
||||
if (storedParameters != null &&
|
||||
storedParameters.Length >= BuildingParameters.kStationParamsLength && storedParameters[320] > 0)
|
||||
watts = storedParameters[320] * ProductionUnits.TicksPerSecond;
|
||||
storedParameters.Length >= BuildingParameters.kStationParamsLength &&
|
||||
storedParameters[StationSettingsIndex] > 0)
|
||||
watts = storedParameters[StationSettingsIndex] * ProductionUnits.TicksPerSecond;
|
||||
break;
|
||||
case BuildingType.Dispenser:
|
||||
if (storedParameters != null && storedParameters.Length >= BuildingParameters.kAddonParamsLength)
|
||||
@@ -250,6 +248,17 @@ public static class BlueprintSelectionReader
|
||||
operation["ChargePowerWatts"] = watts;
|
||||
}
|
||||
|
||||
// Advanced Mining Machines store their speed with the station settings; native construction restores it.
|
||||
private static void CaptureStoredMinerSpeed(BuildingParameters parameters, int[] storedParameters,
|
||||
IDictionary<string, double> operation)
|
||||
{
|
||||
if (parameters.type == BuildingType.Station && storedParameters != null &&
|
||||
storedParameters.Length >= BuildingParameters.kStationParamsLength &&
|
||||
storedParameters[StationSettingsIndex] > 0 && storedParameters[StationSettingsIndex + 9] > 0)
|
||||
operation["MachineSpeedFactor"] =
|
||||
storedParameters[StationSettingsIndex + 9] / ProductionUnits.FixedPointScale;
|
||||
}
|
||||
|
||||
private static ProductionBuildingSnapshot CreateSnapshot(ProductionCatalog catalog, ProductionBuilding building,
|
||||
int objectId, BuildingParameters parameters, int recipeId, double? speedFactor,
|
||||
Dictionary<string, double> operation, ICollection<ProductionDiagnostic> diagnostics)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -64,7 +65,6 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
var grossConsumption = new SortedDictionary<int, double>();
|
||||
var producers = new Dictionary<int, List<int>>();
|
||||
var consumers = new Dictionary<int, List<int>>();
|
||||
var smallestProducer = new Dictionary<int, double>();
|
||||
var hasResearchMatrixSink = false;
|
||||
var uncertainDemandItems = new HashSet<int>();
|
||||
var selectedIds = new HashSet<int>();
|
||||
@@ -137,8 +137,7 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
|
||||
"The selected logistics facility needs its configured charging power.",
|
||||
buildingItemId: snapshot.BuildingItemId));
|
||||
else if (chargePowerWatts < 0 || double.IsNaN(chargePowerWatts) ||
|
||||
double.IsInfinity(chargePowerWatts * snapshot.Count))
|
||||
else if (!FiniteNonnegative(chargePowerWatts * snapshot.Count))
|
||||
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The selected logistics charging power must be finite and nonnegative.",
|
||||
buildingItemId: snapshot.BuildingItemId));
|
||||
@@ -147,9 +146,7 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
|
||||
if (logisticsWatts.HasValue) logisticsConsumptionWatts += logisticsWatts.Value;
|
||||
else logisticsPowerComplete = false;
|
||||
groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count,
|
||||
logisticsWatts, logisticsWatts, Array.Empty<KeyValuePair<int, double>>(),
|
||||
Array.Empty<KeyValuePair<int, double>>()));
|
||||
groups.Add(PowerOnlyGroup(snapshot.Count, logisticsWatts));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -163,9 +160,7 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
var idleWatts = (building.Kind == ProductionBuildingKind.Auxiliary
|
||||
? building.WorkingPowerWatts : building.IdlePowerWatts) * snapshot.Count;
|
||||
factoryConsumptionWatts += idleWatts;
|
||||
groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count,
|
||||
idleWatts, idleWatts, Array.Empty<KeyValuePair<int, double>>(),
|
||||
Array.Empty<KeyValuePair<int, double>>()));
|
||||
groups.Add(PowerOnlyGroup(snapshot.Count, idleWatts));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -208,9 +203,7 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
{
|
||||
if (!IsResearchModeLab(building, snapshot)) totalPowerKnown = false;
|
||||
factoryConsumptionWatts += knownWatts;
|
||||
groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count,
|
||||
knownWatts, knownWatts, Array.Empty<KeyValuePair<int, double>>(),
|
||||
Array.Empty<KeyValuePair<int, double>>()));
|
||||
groups.Add(PowerOnlyGroup(snapshot.Count, knownWatts));
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -222,26 +215,20 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
|
||||
if (diagnostic != null) diagnostics.Add(diagnostic);
|
||||
if (!process.PowerKnown) totalPowerKnown = false;
|
||||
if (process.WorkingPowerWatts < 0 || double.IsNaN(process.WorkingPowerWatts) ||
|
||||
double.IsInfinity(process.WorkingPowerWatts * snapshot.Count)) factoryPowerComplete = false;
|
||||
if (!FiniteNonnegative(process.WorkingPowerWatts * snapshot.Count)) factoryPowerComplete = false;
|
||||
var cycleRate = process.CyclesPerBuildingPerMinute;
|
||||
var output = Scale(process.OutputsPerCycle, cycleRate * snapshot.Count);
|
||||
var input = Scale(process.InputsPerCycle, cycleRate * snapshot.Count);
|
||||
var output = ScaleFlows(process.OutputsPerCycle, cycleRate * snapshot.Count);
|
||||
var input = ScaleFlows(process.InputsPerCycle, cycleRate * snapshot.Count);
|
||||
var groupIndex = groups.Count;
|
||||
foreach (var flow in output)
|
||||
{
|
||||
Add(grossProduction, flow.Key, flow.Value);
|
||||
AddFlow(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);
|
||||
AddFlow(grossConsumption, flow.Key, flow.Value);
|
||||
AddGroup(consumers, flow.Key, groupIndex);
|
||||
}
|
||||
|
||||
@@ -273,19 +260,13 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
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 classification = classifications[itemId];
|
||||
var isFinalProduct = classification.IsFinalProduct;
|
||||
flows.Add(new ProductionItemFlow(itemId, produced, consumed, 0, 0, 0,
|
||||
Math.Max(0, net), Math.Max(0, -net), isFinalProduct,
|
||||
classification.IsIntermediate && !matrixSinkItems.Contains(itemId) &&
|
||||
net > 1e-9 && threshold > 0 &&
|
||||
net + 1e-9 >= threshold,
|
||||
threshold, producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty<int>(),
|
||||
Math.Max(0, net), Math.Max(0, -net), classification.IsFinalProduct,
|
||||
producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty<int>(),
|
||||
consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty<int>(),
|
||||
classification.IntermediateShortage, classification.OverbuildSurplus,
|
||||
classification.CoproductSurplus,
|
||||
steadyStateBalance == null ? null : Math.Max(0, -steadyStateBalance[itemId]),
|
||||
classification.CoproductSurplus, Math.Max(0, -steadyStateBalance[itemId]),
|
||||
classification.IsResearchProduct));
|
||||
}
|
||||
|
||||
@@ -335,17 +316,13 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
watts = 0;
|
||||
if (IsResearchModeLab(building, snapshot))
|
||||
{
|
||||
// Research-mode labs only receive extra products, and only when a proliferation level exists.
|
||||
var multiplier = 1.0;
|
||||
if (mode != ProliferationMode.None)
|
||||
{
|
||||
if (mode != ProliferationMode.ExtraProducts) return false;
|
||||
if (_catalog.MaximumProliferationLevel > 0 &&
|
||||
!_catalog.TryGetProliferation(_catalog.MaximumProliferationLevel,
|
||||
out _, out _, out multiplier)) return false;
|
||||
}
|
||||
|
||||
if (mode != ProliferationMode.None &&
|
||||
!_catalog.TryGetProliferation(_catalog.MaximumProliferationLevel, out _, out _, out multiplier))
|
||||
return false;
|
||||
watts = building.WorkingPowerWatts * multiplier * snapshot.Count;
|
||||
return watts > 0 && !double.IsNaN(watts) && !double.IsInfinity(watts);
|
||||
return FinitePositive(watts);
|
||||
}
|
||||
|
||||
if (diagnostic?.Code != ProductionDiagnosticCode.MissingOperatingParameter) return false;
|
||||
@@ -354,10 +331,10 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
|
||||
var speed = snapshot.OperatingParameters.TryGetValue("MachineSpeedFactor", out var capturedSpeed)
|
||||
? capturedSpeed : 1;
|
||||
if (speed <= 0 || double.IsNaN(speed) || double.IsInfinity(speed)) return false;
|
||||
if (!FinitePositive(speed)) return false;
|
||||
var ratio = speed * speed;
|
||||
watts = (building.WorkingPowerWatts * ratio + building.IdlePowerWatts * (1 - ratio)) * snapshot.Count;
|
||||
return watts >= 0 && !double.IsNaN(watts) && !double.IsInfinity(watts);
|
||||
return FiniteNonnegative(watts);
|
||||
}
|
||||
|
||||
private static bool IsResearchModeLab(ProductionBuilding building, ProductionBuildingSnapshot snapshot)
|
||||
@@ -367,24 +344,9 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
snapshot.OperatingParameters.TryGetValue("ResearchMode", out var researchMode) && researchMode == 1;
|
||||
}
|
||||
|
||||
private static Dictionary<int, double> Scale(IReadOnlyDictionary<int, double> flows, double factor)
|
||||
private static ProductionGroupFlow PowerOnlyGroup(int count, double? watts)
|
||||
{
|
||||
return flows.ToDictionary(entry => entry.Key, entry => entry.Value * factor);
|
||||
}
|
||||
|
||||
private static void Add(IDictionary<int, double> flows, int itemId, double count)
|
||||
{
|
||||
flows[itemId] = (flows.TryGetValue(itemId, out var previous) ? previous : 0) + count;
|
||||
}
|
||||
|
||||
private static void AddGroup(IDictionary<int, List<int>> groups, int itemId, int index)
|
||||
{
|
||||
if (!groups.TryGetValue(itemId, out var indices))
|
||||
{
|
||||
indices = new List<int>();
|
||||
groups[itemId] = indices;
|
||||
}
|
||||
|
||||
indices.Add(index);
|
||||
return new ProductionGroupFlow(null, count, 0, count, count, watts, watts,
|
||||
Array.Empty<KeyValuePair<int, double>>(), Array.Empty<KeyValuePair<int, double>>());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -75,9 +76,4 @@ public sealed class FractionationProcessAdapter : IProductionProcessAdapter
|
||||
throughput, watts, building != null, throughput);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool FinitePositive(double value)
|
||||
{
|
||||
return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -17,8 +18,7 @@ public sealed class FuelGenerationAdapter : IProductionProcessAdapter
|
||||
process = null;
|
||||
diagnostic = null;
|
||||
if (operatingParameters == null ||
|
||||
!operatingParameters.TryGetValue("FuelItemId", out var fuelId) ||
|
||||
fuelId <= 0 || fuelId > int.MaxValue || fuelId != Math.Truncate(fuelId) ||
|
||||
!operatingParameters.TryGetValue("FuelItemId", out var fuelId) || !PositiveId(fuelId) ||
|
||||
!catalog.Items.TryGetValue((int)fuelId, out var fuel) ||
|
||||
fuel.HeatValueJoules <= 0 || (fuel.FuelTypeMask & building.FuelMask) == 0)
|
||||
{
|
||||
@@ -37,8 +37,7 @@ public sealed class FuelGenerationAdapter : IProductionProcessAdapter
|
||||
return false;
|
||||
}
|
||||
|
||||
if (building.FuelUseWatts <= 0 || building.RatedGenerationWatts <= 0 ||
|
||||
double.IsNaN(building.FuelUseWatts) || double.IsNaN(building.RatedGenerationWatts))
|
||||
if (!FinitePositive(building.FuelUseWatts) || !FinitePositive(building.RatedGenerationWatts))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
|
||||
"The generator's fuel consumption or power rating is unavailable.",
|
||||
@@ -73,8 +72,7 @@ public sealed class FuelGenerationAdapter : IProductionProcessAdapter
|
||||
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))
|
||||
if (!Finite(generation) || !FinitePositive(burnedFuel))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The selected fuel produces an invalid generation rate.", buildingItemId: building.ItemId);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -55,8 +56,7 @@ public sealed class GasCollectionAdapter : IProductionProcessAdapter
|
||||
var outputs = new List<KeyValuePair<int, double>>();
|
||||
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) ||
|
||||
if (!operatingParameters.TryGetValue($"GasItemId{index}", out var itemId) || !PositiveId(itemId) ||
|
||||
!catalog.Items.ContainsKey((int)itemId) ||
|
||||
!operatingParameters.TryGetValue($"GasSpeedPerSecond{index}", out var gasSpeed) ||
|
||||
!FiniteNonnegative(gasSpeed))
|
||||
@@ -85,14 +85,4 @@ public sealed class GasCollectionAdapter : IProductionProcessAdapter
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -74,7 +75,7 @@ public sealed class LaunchProcessAdapter : IProductionProcessAdapter
|
||||
}
|
||||
|
||||
var nativeStep = Math.Truncate(10000 * (1 + speedBonus) + 0.1) * (boosted ? 10 : 1);
|
||||
if (nativeStep <= 0 || double.IsInfinity(nativeStep) || double.IsNaN(nativeStep))
|
||||
if (!FinitePositive(nativeStep))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The launcher's native speed is outside the supported range.", buildingItemId: building.ItemId);
|
||||
@@ -84,8 +85,7 @@ public sealed class LaunchProcessAdapter : IProductionProcessAdapter
|
||||
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))
|
||||
if (!FinitePositive(launchesPerMinute))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The launcher cycle is outside the supported range.", buildingItemId: building.ItemId);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -25,7 +26,7 @@ public sealed class MiningProcessAdapter : IProductionProcessAdapter
|
||||
|
||||
if (operatingParameters == null ||
|
||||
!operatingParameters.TryGetValue("ResourceItemId", out var outputId) ||
|
||||
!ValidItemId(outputId) || !catalog.Items.ContainsKey((int)outputId) ||
|
||||
!PositiveId(outputId) || !catalog.Items.ContainsKey((int)outputId) ||
|
||||
!operatingParameters.TryGetValue("MiningSpeedMultiplier", out var miningSpeed) ||
|
||||
!FinitePositive(miningSpeed))
|
||||
{
|
||||
@@ -72,8 +73,7 @@ public sealed class MiningProcessAdapter : IProductionProcessAdapter
|
||||
var powerRatio = machineSpeed * machineSpeed;
|
||||
var workingWatts = building.WorkingPowerWatts * powerRatio +
|
||||
building.IdlePowerWatts * (1 - powerRatio);
|
||||
if (!FinitePositive(perMinute) || workingWatts < 0 ||
|
||||
double.IsNaN(workingWatts) || double.IsInfinity(workingWatts))
|
||||
if (!FinitePositive(perMinute) || !FiniteNonnegative(workingWatts))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The mineral output rate or power demand is outside the supported range.",
|
||||
@@ -87,14 +87,4 @@ public sealed class MiningProcessAdapter : IProductionProcessAdapter
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -52,7 +53,9 @@ public sealed class ProcessEvaluator
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!IsOrdinary(recipe.Category))
|
||||
// Recipe types unknown to the catalog, such as ones added by other mods, keep their material flows only
|
||||
// while no building is selected.
|
||||
if (!IsOrdinary(recipe.Category) && (recipe.Category != ProductionRecipeCategory.None || building != null))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
|
||||
"The recipe requires a special-process adapter.", recipeId: recipe.Id,
|
||||
@@ -114,17 +117,6 @@ public sealed class ProcessEvaluator
|
||||
|
||||
private static bool ValidFlows(IReadOnlyDictionary<int, double> 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);
|
||||
return flows.All(flow => flow.Key > 0 && FinitePositive(flow.Value));
|
||||
}
|
||||
}
|
||||
@@ -39,8 +39,10 @@ public static class ProductionCatalogReader
|
||||
var kind = ClassifyBuilding(prefab);
|
||||
if (category == ProductionRecipeCategory.None && kind == ProductionBuildingKind.Ordinary) continue;
|
||||
var speed = prefab.isLab ? prefab.labAssembleSpeed : prefab.assemblerSpeed;
|
||||
// Charging power nodes draw idle power except while charging a mecha, which production power excludes.
|
||||
var workEnergyPerTick = prefab.isPowerCharger ? prefab.idleEnergyPerTick : prefab.workEnergyPerTick;
|
||||
buildings.Add(new ProductionBuilding(item.ID, category, speed / 10000.0,
|
||||
prefab.workEnergyPerTick * 60.0, prefab.idleEnergyPerTick * 60.0, kind,
|
||||
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 :
|
||||
@@ -68,9 +70,12 @@ public static class ProductionCatalogReader
|
||||
|
||||
recipes.Add(new ProductionRecipe(recipe.ID, MapCategory(recipe.Type), recipe.TimeSpend, recipe.productive,
|
||||
PairFlows(recipe.Items, recipe.ItemCounts), PairFlows(recipe.Results, recipe.ResultCounts)));
|
||||
// Follow native maincraft selection (lowest result index, then recipe order), but skip recipes such as
|
||||
// Reforming Refine that consume their own product and so cannot start its production chain.
|
||||
for (var resultIndex = 0; resultIndex < recipe.Results.Length; resultIndex++)
|
||||
{
|
||||
var productId = recipe.Results[resultIndex];
|
||||
if (Array.IndexOf(recipe.Items, productId) >= 0) continue;
|
||||
if (!defaultRecipes.TryGetValue(productId, out var old) || resultIndex < old.resultIndex)
|
||||
defaultRecipes[productId] = (recipe.ID, resultIndex);
|
||||
}
|
||||
@@ -82,8 +87,8 @@ public static class ProductionCatalogReader
|
||||
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 defaultRecipeId = defaultRecipes.TryGetValue(item.ID, out var defaultRecipe)
|
||||
? defaultRecipe.recipeId : 0;
|
||||
var isProliferator = proliferators.Contains(item.ID);
|
||||
items.Add(new ProductionItem(item.ID, defaultRecipeId,
|
||||
naturalItems.Contains(item.ID) || !string.IsNullOrEmpty(item.MiningFrom),
|
||||
@@ -192,7 +197,7 @@ public static class ProductionCatalogReader
|
||||
? ProductionBuildingKind.RenewableGenerator : ProductionBuildingKind.FuelGenerator;
|
||||
if (prefab.isStation || prefab.isDispenser || prefab.isBattleBase)
|
||||
return ProductionBuildingKind.Logistics;
|
||||
if (prefab.isPowerConsumer && !prefab.isStation && !prefab.isDispenser)
|
||||
if (prefab.isPowerConsumer || prefab.isPowerCharger)
|
||||
return ProductionBuildingKind.Auxiliary;
|
||||
return ProductionBuildingKind.Ordinary;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,40 @@ internal static class ProductionUnits
|
||||
internal const double FixedPointScale = 10000;
|
||||
}
|
||||
|
||||
internal static class ProductionMath
|
||||
{
|
||||
internal static bool Finite(double value) => !double.IsNaN(value) && !double.IsInfinity(value);
|
||||
|
||||
internal static bool FinitePositive(double value) => value > 0 && Finite(value);
|
||||
|
||||
internal static bool FiniteNonnegative(double value) => value >= 0 && Finite(value);
|
||||
|
||||
// Item and technology IDs arrive as double operating parameters.
|
||||
internal static bool PositiveId(double value) =>
|
||||
value > 0 && value <= int.MaxValue && value == Math.Truncate(value);
|
||||
|
||||
internal static void AddFlow(IDictionary<int, double> flows, int itemId, double amount)
|
||||
{
|
||||
flows[itemId] = (flows.TryGetValue(itemId, out var previous) ? previous : 0) + amount;
|
||||
}
|
||||
|
||||
internal static Dictionary<int, double> ScaleFlows(IReadOnlyDictionary<int, double> flows, double factor)
|
||||
{
|
||||
return flows.ToDictionary(flow => flow.Key, flow => flow.Value * factor);
|
||||
}
|
||||
|
||||
internal static void AddGroup(IDictionary<int, List<int>> groups, int itemId, int groupIndex)
|
||||
{
|
||||
if (!groups.TryGetValue(itemId, out var indices))
|
||||
{
|
||||
indices = new List<int>();
|
||||
groups[itemId] = indices;
|
||||
}
|
||||
|
||||
indices.Add(groupIndex);
|
||||
}
|
||||
}
|
||||
|
||||
public enum ProliferationMode
|
||||
{
|
||||
None,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -36,8 +37,7 @@ public sealed partial class ProductionPlanner
|
||||
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)
|
||||
if (proliferatorItemId > 0 && SpraysInputs(process))
|
||||
{
|
||||
var sprays = process.SprayedInputsPerCycle * executions;
|
||||
foreach (var itemId in reusableSprayItems)
|
||||
@@ -84,8 +84,7 @@ public sealed partial class ProductionPlanner
|
||||
deploymentCount = Math.Max(1, (int)Math.Ceiling(equivalentBuildings.Value - 1e-9));
|
||||
consumedWatts = equivalentBuildings.Value * process.WorkingPowerWatts;
|
||||
peakWatts = deploymentCount.Value * process.WorkingPowerWatts;
|
||||
if (consumedWatts.Value < 0 || double.IsNaN(consumedWatts.Value) ||
|
||||
double.IsInfinity(consumedWatts.Value)) factoryPowerComplete = false;
|
||||
if (!FiniteNonnegative(consumedWatts.Value)) factoryPowerComplete = false;
|
||||
workingPower += consumedWatts.Value;
|
||||
peakPower += peakWatts.Value;
|
||||
generationWatts += equivalentBuildings.Value * process.GenerationWatts;
|
||||
@@ -137,9 +136,7 @@ public sealed partial class ProductionPlanner
|
||||
|
||||
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))
|
||||
!FiniteNonnegative(building.WorkingPowerWatts * auxiliary.Count))
|
||||
{
|
||||
powerComplete = false;
|
||||
factoryPowerComplete = false;
|
||||
@@ -187,8 +184,8 @@ public sealed partial class ProductionPlanner
|
||||
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<int>(),
|
||||
imported, finalProduct,
|
||||
producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty<int>(),
|
||||
consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty<int>()));
|
||||
}
|
||||
|
||||
@@ -202,20 +199,4 @@ public sealed partial class ProductionPlanner
|
||||
return new ProductionReport(status, true, powerComplete, itemFlows, groups, diagnostics, power,
|
||||
new ProductionPowerBreakdown(workingPower, 0, factoryPowerComplete, true));
|
||||
}
|
||||
|
||||
private static Dictionary<int, double> ScaleFlows(IReadOnlyDictionary<int, double> flows, double multiplier)
|
||||
{
|
||||
return flows.ToDictionary(flow => flow.Key, flow => flow.Value * multiplier);
|
||||
}
|
||||
|
||||
private static void AddGroup(IDictionary<int, List<int>> groups, int itemId, int groupIndex)
|
||||
{
|
||||
if (!groups.TryGetValue(itemId, out var indices))
|
||||
{
|
||||
indices = new List<int>();
|
||||
groups[itemId] = indices;
|
||||
}
|
||||
|
||||
indices.Add(groupIndex);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -29,16 +30,16 @@ public sealed partial class ProductionPlanner
|
||||
var targets = new SortedDictionary<int, double>();
|
||||
foreach (var target in request.Targets)
|
||||
{
|
||||
if (target == null || target.ItemId <= 0 || !ValidNonnegative(target.ItemsPerMinute))
|
||||
if (target == null || target.ItemId <= 0 || !FiniteNonnegative(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]))
|
||||
if (!FiniteNonnegative(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))
|
||||
if (surplus.Key <= 0 || !FiniteNonnegative(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);
|
||||
@@ -49,14 +50,14 @@ public sealed partial class ProductionPlanner
|
||||
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 processes = new SortedDictionary<int, ProductionProcess>();
|
||||
var externalItems = new SortedSet<int>();
|
||||
var pending = new SortedSet<int>(targets.Keys);
|
||||
var visited = new HashSet<int>();
|
||||
var warnings = new List<ProductionDiagnostic>();
|
||||
var hasSprayedInputs = false;
|
||||
var hasSprayedTargets = request.SprayDeliveredItems.Any(id => targets[id] > 0);
|
||||
var explicitModes = request.ProliferationEnabled
|
||||
? ExplicitProliferationModes(request) : new Dictionary<int, ProliferationMode?>();
|
||||
ProductionItem proliferator = null;
|
||||
if (request.ProliferationEnabled)
|
||||
{
|
||||
@@ -79,8 +80,7 @@ public sealed partial class ProductionPlanner
|
||||
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)
|
||||
if (IsExternal(request, item, hasExplicitRecipe))
|
||||
{
|
||||
externalItems.Add(itemId);
|
||||
continue;
|
||||
@@ -92,12 +92,21 @@ public sealed partial class ProductionPlanner
|
||||
if (!recipe.Outputs.ContainsKey(itemId))
|
||||
return Fail(ProductionDiagnosticCode.InvalidRequest, "The selected recipe does not produce the item.",
|
||||
itemId, recipeId);
|
||||
if (processes.ContainsKey(recipeId)) continue;
|
||||
|
||||
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);
|
||||
{
|
||||
if (!explicitModes.TryGetValue(recipeId, out var explicitMode))
|
||||
mode = DefaultProliferationMode(recipe, parameters);
|
||||
else if (explicitMode.HasValue)
|
||||
mode = explicitMode.Value;
|
||||
else
|
||||
return Fail(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The products of one recipe request different proliferation modes.", itemId, recipeId);
|
||||
}
|
||||
|
||||
var level = mode == ProliferationMode.None ? 0 : proliferator.ProliferationLevel;
|
||||
var buildingId = request.BuildingByRecipe.TryGetValue(recipeId, out var recipeBuildingId)
|
||||
? recipeBuildingId
|
||||
@@ -122,14 +131,12 @@ public sealed partial class ProductionPlanner
|
||||
warnings.Add(diagnostic);
|
||||
}
|
||||
|
||||
processes[(recipeId, buildingId, mode, level)] = process;
|
||||
processes[recipeId] = 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);
|
||||
if (SpraysInputs(process)) pending.Add(proliferator.Id);
|
||||
}
|
||||
|
||||
var sprayDemand = hasSprayedInputs || hasSprayedTargets;
|
||||
var sprayDemand = hasSprayedTargets || processes.Values.Any(SpraysInputs);
|
||||
var spraysPerBottle = 0.0;
|
||||
if (sprayDemand)
|
||||
{
|
||||
@@ -185,9 +192,8 @@ public sealed partial class ProductionPlanner
|
||||
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;
|
||||
if (SpraysInputs(process))
|
||||
matrix[rowByItem[proliferator.Id], index] -= process.SprayedInputsPerCycle / spraysPerBottle;
|
||||
}
|
||||
|
||||
for (var index = 0; index < importItems.Length; index++)
|
||||
@@ -257,10 +263,40 @@ public sealed partial class ProductionPlanner
|
||||
reusableSprayItems, sprayCreditStart);
|
||||
}
|
||||
|
||||
// A recipe runs in one mode, so explicit choices for the products it is selected to make must agree;
|
||||
// null marks a conflict, which is reported only if the recipe is used.
|
||||
private Dictionary<int, ProliferationMode?> ExplicitProliferationModes(ProductionPlanRequest request)
|
||||
{
|
||||
var modes = new Dictionary<int, ProliferationMode?>();
|
||||
foreach (var choice in request.ProliferationModeByItem)
|
||||
{
|
||||
if (!_catalog.Items.TryGetValue(choice.Key, out var item)) continue;
|
||||
var hasExplicitRecipe = request.RecipeByItem.TryGetValue(item.Id, out var recipeId);
|
||||
if (IsExternal(request, item, hasExplicitRecipe)) continue;
|
||||
if (!hasExplicitRecipe) recipeId = item.DefaultRecipeId;
|
||||
if (!_catalog.Recipes.TryGetValue(recipeId, out var recipe) || !recipe.Outputs.ContainsKey(item.Id))
|
||||
continue;
|
||||
if (!modes.TryGetValue(recipeId, out var previous)) modes[recipeId] = choice.Value;
|
||||
else if (previous != choice.Value) modes[recipeId] = null;
|
||||
}
|
||||
|
||||
return modes;
|
||||
}
|
||||
|
||||
private static bool IsExternal(ProductionPlanRequest request, ProductionItem item, bool hasExplicitRecipe)
|
||||
{
|
||||
return item.IsDarkFogMaterial || request.ExternalMaterials.Contains(item.Id) ||
|
||||
item.IsNatural && !hasExplicitRecipe;
|
||||
}
|
||||
|
||||
private static bool SpraysInputs(ProductionProcess process)
|
||||
{
|
||||
return process.ProliferationMode != ProliferationMode.None && process.SprayedInputsPerCycle > 0;
|
||||
}
|
||||
|
||||
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 (!SpraysInputs(process) || !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;
|
||||
}
|
||||
@@ -278,16 +314,6 @@ public sealed partial class ProductionPlanner
|
||||
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<int, double> 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)
|
||||
{
|
||||
|
||||
@@ -77,8 +77,6 @@ public sealed class ProductionItemFlow
|
||||
public double? SteadyStateExternalSupply { get; }
|
||||
public bool IsFinalProduct { get; }
|
||||
public bool IsResearchProduct { get; }
|
||||
public bool IsExcessIntermediate { get; }
|
||||
public double SingleBuildingSurplusThreshold { get; }
|
||||
public double IntermediateShortage { get; }
|
||||
public double? OverbuildSurplus { get; }
|
||||
public double? CoproductSurplus { get; }
|
||||
@@ -87,20 +85,9 @@ public sealed class ProductionItemFlow
|
||||
|
||||
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<int> producerGroups, IEnumerable<int> consumerGroups)
|
||||
: this(itemId, grossProduction, grossConsumption, externalImports, knownExternalSupply, delivered, surplus,
|
||||
requiredExternalSupply, isFinalProduct, isExcessIntermediate, singleBuildingSurplusThreshold,
|
||||
producerGroups, consumerGroups, 0, null, null)
|
||||
{
|
||||
}
|
||||
|
||||
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<int> producerGroups, IEnumerable<int> consumerGroups, double intermediateShortage,
|
||||
double? overbuildSurplus, double? coproductSurplus, double? steadyStateExternalSupply = null,
|
||||
bool isResearchProduct = false)
|
||||
bool isFinalProduct, IEnumerable<int> producerGroups, IEnumerable<int> consumerGroups,
|
||||
double intermediateShortage = 0, double? overbuildSurplus = null, double? coproductSurplus = null,
|
||||
double? steadyStateExternalSupply = null, bool isResearchProduct = false)
|
||||
{
|
||||
ItemId = itemId;
|
||||
GrossProduction = grossProduction;
|
||||
@@ -113,8 +100,6 @@ public sealed class ProductionItemFlow
|
||||
SteadyStateExternalSupply = steadyStateExternalSupply;
|
||||
IsFinalProduct = isFinalProduct;
|
||||
IsResearchProduct = isResearchProduct;
|
||||
IsExcessIntermediate = isExcessIntermediate;
|
||||
SingleBuildingSurplusThreshold = singleBuildingSurplusThreshold;
|
||||
IntermediateShortage = intermediateShortage;
|
||||
OverbuildSurplus = overbuildSurplus;
|
||||
CoproductSurplus = coproductSurplus;
|
||||
@@ -181,17 +166,10 @@ public sealed class ProductionReport
|
||||
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<ProductionItemFlow> itemFlows, IEnumerable<ProductionGroupFlow> groups,
|
||||
IEnumerable<ProductionDiagnostic> diagnostics, ProductionPower power)
|
||||
: this(status, materialComplete, powerComplete, itemFlows, groups, diagnostics, power, null)
|
||||
{
|
||||
}
|
||||
|
||||
public ProductionReport(ProductionStatus status, bool materialComplete, bool powerComplete,
|
||||
IEnumerable<ProductionItemFlow> itemFlows, IEnumerable<ProductionGroupFlow> groups,
|
||||
IEnumerable<ProductionDiagnostic> diagnostics, ProductionPower power,
|
||||
ProductionPowerBreakdown powerBreakdown)
|
||||
ProductionPowerBreakdown powerBreakdown = null)
|
||||
{
|
||||
Status = status;
|
||||
MaterialComplete = materialComplete;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -28,7 +29,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
|
||||
return false;
|
||||
}
|
||||
|
||||
if (building.RatedGenerationWatts <= 0 || !Finite(building.RatedGenerationWatts) ||
|
||||
if (!FinitePositive(building.RatedGenerationWatts) ||
|
||||
(recipe != null && (recipe.Category != ProductionRecipeCategory.PhotonStore ||
|
||||
recipe.Inputs.Count != 0 || recipe.Outputs.Count != 1 ||
|
||||
!recipe.Outputs.ContainsKey(building.PowerProductItemId))))
|
||||
@@ -60,8 +61,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
|
||||
|
||||
if (recipe == null && selectedMode > 0) photonMode = true;
|
||||
if (photonMode && (building.PowerProductItemId <= 0 ||
|
||||
building.PowerProductEnergyJoules <= 0 ||
|
||||
!Finite(building.PowerProductEnergyJoules) ||
|
||||
!FinitePositive(building.PowerProductEnergyJoules) ||
|
||||
!catalog.Items.ContainsKey(building.PowerProductItemId)))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
|
||||
@@ -71,7 +71,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
|
||||
}
|
||||
|
||||
if (!operatingParameters.TryGetValue("LensItemId", out var lensId) ||
|
||||
lensId < 0 || lensId > int.MaxValue || lensId != Math.Truncate(lensId))
|
||||
lensId != 0 && !PositiveId(lensId))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
|
||||
"Provide the receiver's lens item ID, or zero for no lens.", buildingItemId: building.ItemId);
|
||||
@@ -81,7 +81,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
|
||||
ProductionItem lens = null;
|
||||
if (lensId > 0 && (!catalog.Items.TryGetValue((int)lensId, out lens) ||
|
||||
(lens.CatalystTypeMask & building.CatalystMask) == 0 ||
|
||||
lens.CatalystAbilityMultiplier <= 0 || !Finite(lens.CatalystAbilityMultiplier)))
|
||||
!FinitePositive(lens.CatalystAbilityMultiplier)))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The selected item is not a compatible ray-receiver lens.",
|
||||
@@ -111,7 +111,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
|
||||
(1 + speedBonus) * (photonMode ? 8 : 1);
|
||||
var cyclesPerMinute = photonMode
|
||||
? energyWatts * 60 / building.PowerProductEnergyJoules : 1;
|
||||
if (cyclesPerMinute <= 0 || !Finite(cyclesPerMinute) || !Finite(energyWatts))
|
||||
if (!FinitePositive(cyclesPerMinute) || !Finite(energyWatts))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The receiver's native output is outside the supported range.", buildingItemId: building.ItemId);
|
||||
@@ -129,7 +129,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
|
||||
if (!lossKnown)
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
|
||||
"The Dyson-sphere power requirement needs the current solar energy loss technology setting.",
|
||||
buildingItemId: building.ItemId);
|
||||
recipeId: recipe?.Id ?? 0, buildingItemId: building.ItemId);
|
||||
|
||||
var lensFlow = lens == null ? Array.Empty<KeyValuePair<int, double>>() :
|
||||
new[] { new KeyValuePair<int, double>(lens.Id, 0.1 / cyclesPerMinute) };
|
||||
@@ -172,9 +172,4 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
|
||||
Array.Empty<KeyValuePair<int, double>>(), recipe.Outputs, 0, 0, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool Finite(double value)
|
||||
{
|
||||
return !double.IsNaN(value) && !double.IsInfinity(value);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -17,8 +18,7 @@ public sealed class RenewableGenerationAdapter : IProductionProcessAdapter
|
||||
process = null;
|
||||
diagnostic = null;
|
||||
if (building.RenewableSource == RenewablePowerSource.None ||
|
||||
building.RatedGenerationWatts < 0 || double.IsNaN(building.RatedGenerationWatts) ||
|
||||
double.IsInfinity(building.RatedGenerationWatts))
|
||||
!FiniteNonnegative(building.RatedGenerationWatts))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
|
||||
"The generator has no renewable power rating.", buildingItemId: building.ItemId);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using static UXAssist.Production.ProductionMath;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
@@ -42,8 +43,7 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!operatingParameters.TryGetValue("TechId", out var techId) || techId <= 0 ||
|
||||
techId > int.MaxValue || techId != Math.Truncate(techId) ||
|
||||
if (!operatingParameters.TryGetValue("TechId", out var techId) || !PositiveId(techId) ||
|
||||
!operatingParameters.TryGetValue("ResearchSpeed", out researchSpeed) ||
|
||||
!FinitePositive(researchSpeed))
|
||||
{
|
||||
@@ -60,7 +60,6 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter
|
||||
buildingItemId: building.ItemId);
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (mode != ProliferationMode.None && mode != ProliferationMode.ExtraProducts)
|
||||
@@ -118,9 +117,4 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter
|
||||
researchHashesPerCycle: hashRate);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool FinitePositive(double value)
|
||||
{
|
||||
return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ internal static class TwoPhaseSimplex
|
||||
{
|
||||
private const double PivotTolerance = 1e-10;
|
||||
private const double ReducedTolerance = 1e-8;
|
||||
private const double RatioTieTolerance = 1e-9;
|
||||
|
||||
internal static LinearSolveResult Solve(double[,] coefficients, double[] rightHandSide,
|
||||
IReadOnlyList<double[]> objectives, int iterationBudget, CancellationToken cancellation)
|
||||
@@ -102,12 +103,19 @@ internal static class TwoPhaseSimplex
|
||||
if (Math.Abs(tableau[row, width]) > ReducedTolerance)
|
||||
return new LinearSolveResult(LinearSolveStatus.Infeasible);
|
||||
|
||||
// The remaining artificial counts as zero. Pivot it out on its largest coefficient at exactly zero so a
|
||||
// tiny residual divided by a tiny coefficient cannot move the other rows.
|
||||
var pivotColumn = -1;
|
||||
for (var column = 0; column < columnCount; column++)
|
||||
{
|
||||
if (isBasic[column] || Math.Abs(tableau[row, column]) <= PivotTolerance) continue;
|
||||
Pivot(tableau, basis, isBasic, row, column);
|
||||
break;
|
||||
if (pivotColumn < 0 || Math.Abs(tableau[row, column]) > Math.Abs(tableau[row, pivotColumn]))
|
||||
pivotColumn = column;
|
||||
}
|
||||
|
||||
if (pivotColumn < 0) continue;
|
||||
tableau[row, width] = 0;
|
||||
Pivot(tableau, basis, isBasic, row, pivotColumn);
|
||||
}
|
||||
|
||||
var optimizedObjectives = new List<double[]>();
|
||||
@@ -170,9 +178,10 @@ internal static class TwoPhaseSimplex
|
||||
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]))
|
||||
// Ties are relative: an absolute tolerance would merge distinct small ratios and leave a row infeasible.
|
||||
var tie = leaving < 0 ? 0 : RatioTieTolerance * Math.Max(ratio, minRatio);
|
||||
if (ratio < minRatio - tie ||
|
||||
Math.Abs(ratio - minRatio) <= tie && (leaving < 0 || basis[row] < basis[leaving]))
|
||||
{
|
||||
minRatio = ratio;
|
||||
leaving = row;
|
||||
|
||||
Reference in new issue
Block a user