mirror of
https://github.com/soarqin/DSP_Mods.git
synced 2026-11-19 17:05:20 +08:00
feat(uxassist): generate blueprint production descriptions
Add native blueprint description generation with proliferation controls, separate power categories, and steady-state material and research reporting. Distinguish necessary coproducts from overbuild and fractional headroom, with regression checks and updated architecture documentation. Validation: 464 ProductionCheck checks and Release builds of UXAssist, CheatEnabler, and UniverseGenTweaks.
This commit is contained in:
1 parent
cada02fbf4
commit
e2b8433252
16 files changed
+2294
-51
No files matched your search
@@ -0,0 +1,247 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
internal sealed class BlackBoxProcessGroup
|
||||
{
|
||||
public ProductionProcess Process { get; }
|
||||
public string StableKey { get; }
|
||||
public int Count { get; }
|
||||
public IReadOnlyDictionary<int, double> NetPerBuilding { get; }
|
||||
public bool HasJointProducts { get; }
|
||||
|
||||
public BlackBoxProcessGroup(ProductionProcess process, ProductionBuildingSnapshot snapshot)
|
||||
{
|
||||
Process = process;
|
||||
Count = snapshot.Count;
|
||||
var net = new Dictionary<int, double>();
|
||||
foreach (var flow in process.OutputsPerCycle)
|
||||
net[flow.Key] = flow.Value * process.CyclesPerBuildingPerMinute;
|
||||
foreach (var flow in process.InputsPerCycle)
|
||||
net[flow.Key] = (net.TryGetValue(flow.Key, out var previous) ? previous : 0) -
|
||||
flow.Value * process.CyclesPerBuildingPerMinute;
|
||||
NetPerBuilding = net;
|
||||
HasJointProducts = net.Values.Count(value => value > BlackBoxMaterialClassifier.Tolerance) > 1;
|
||||
|
||||
var key = new StringBuilder();
|
||||
key.Append(process.RecipeId).Append(':').Append(process.BuildingItemId).Append(':')
|
||||
.Append((int)process.ProliferationMode).Append(':').Append(process.ProliferationLevel)
|
||||
.Append(':').Append(snapshot.SpeedFactor?.ToString("R", CultureInfo.InvariantCulture) ?? "-");
|
||||
foreach (var parameter in snapshot.OperatingParameters.OrderBy(entry => entry.Key, StringComparer.Ordinal))
|
||||
key.Append('|').Append(parameter.Key.Length).Append(':').Append(parameter.Key).Append(':')
|
||||
.Append(parameter.Value.ToString("R", CultureInfo.InvariantCulture));
|
||||
StableKey = key.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
IsFinalProduct = isFinalProduct;
|
||||
IsResearchProduct = isResearchProduct;
|
||||
IsIntermediate = isIntermediate;
|
||||
IntermediateShortage = intermediateShortage;
|
||||
OverbuildSurplus = overbuildSurplus;
|
||||
CoproductSurplus = coproductSurplus;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class BlackBoxMaterialClassifier
|
||||
{
|
||||
internal const double Tolerance = 1e-9;
|
||||
|
||||
private sealed class ReductionGroup
|
||||
{
|
||||
public BlackBoxProcessGroup Source { get; }
|
||||
public int Count { get; }
|
||||
public int Removed { get; set; }
|
||||
|
||||
public ReductionGroup(IGrouping<string, BlackBoxProcessGroup> grouped)
|
||||
{
|
||||
Source = grouped.First();
|
||||
Count = grouped.Sum(entry => entry.Count);
|
||||
}
|
||||
}
|
||||
|
||||
public static IReadOnlyDictionary<int, BlackBoxItemClassification> Classify(
|
||||
IReadOnlyList<BlackBoxProcessGroup> processes, IReadOnlyDictionary<int, double> grossProduction,
|
||||
IReadOnlyDictionary<int, double> grossConsumption, bool materialComplete,
|
||||
IReadOnlyCollection<int> uncertainDemandItems, bool unknownDemand, ISet<int> researchMatrixSinks,
|
||||
out IReadOnlyDictionary<int, double> steadyStateBalance)
|
||||
{
|
||||
var producerItems = new HashSet<int>();
|
||||
var consumerItems = new HashSet<int>();
|
||||
foreach (var process in processes)
|
||||
{
|
||||
foreach (var flow in process.NetPerBuilding)
|
||||
{
|
||||
if (flow.Value > Tolerance) producerItems.Add(flow.Key);
|
||||
if (flow.Value < -Tolerance) consumerItems.Add(flow.Key);
|
||||
}
|
||||
}
|
||||
|
||||
var allItems = new SortedSet<int>(grossProduction.Keys);
|
||||
allItems.UnionWith(grossConsumption.Keys);
|
||||
var originalBalance = allItems.ToDictionary(itemId => itemId, itemId =>
|
||||
(grossProduction.TryGetValue(itemId, out var produced) ? produced : 0) -
|
||||
(grossConsumption.TryGetValue(itemId, out var consumed) ? consumed : 0));
|
||||
var remainingBalance = new Dictionary<int, double>(originalBalance);
|
||||
var finalItems = new HashSet<int>(producerItems.Where(itemId => !consumerItems.Contains(itemId)));
|
||||
var intermediateItems = new HashSet<int>(producerItems.Where(consumerItems.Contains));
|
||||
var protectedItems = new HashSet<int>(finalItems);
|
||||
protectedItems.UnionWith(producerItems.Where(researchMatrixSinks.Contains));
|
||||
if (unknownDemand) protectedItems.UnionWith(producerItems);
|
||||
else protectedItems.UnionWith(uncertainDemandItems);
|
||||
var groups = processes.GroupBy(process => process.StableKey, StringComparer.Ordinal)
|
||||
.Select(grouped => new ReductionGroup(grouped))
|
||||
.OrderBy(group => group.Source.Process.RecipeId)
|
||||
.ThenBy(group => group.Source.Process.BuildingItemId)
|
||||
.ThenBy(group => group.Source.StableKey, StringComparer.Ordinal).ToList();
|
||||
|
||||
if (materialComplete)
|
||||
{
|
||||
bool changed;
|
||||
do
|
||||
{
|
||||
changed = false;
|
||||
foreach (var group in groups)
|
||||
{
|
||||
if (!group.Source.NetPerBuilding.Values.Any(value => value > Tolerance)) continue;
|
||||
while (group.Removed < group.Count && CanRemove(group.Source.NetPerBuilding, originalBalance,
|
||||
remainingBalance, protectedItems, intermediateItems))
|
||||
{
|
||||
foreach (var flow in group.Source.NetPerBuilding)
|
||||
remainingBalance[flow.Key] -= flow.Value;
|
||||
group.Removed++;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
} while (changed);
|
||||
}
|
||||
|
||||
var classification = new Dictionary<int, BlackBoxItemClassification>();
|
||||
foreach (var itemId in allItems)
|
||||
{
|
||||
var originalNet = originalBalance[itemId];
|
||||
var isIntermediate = intermediateItems.Contains(itemId);
|
||||
double? overbuild = null;
|
||||
double? coproduct = null;
|
||||
if (materialComplete)
|
||||
{
|
||||
overbuild = 0;
|
||||
coproduct = 0;
|
||||
if (isIntermediate && !researchMatrixSinks.Contains(itemId))
|
||||
{
|
||||
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));
|
||||
var internalConsumption = groups.Sum(group =>
|
||||
group.Source.NetPerBuilding.TryGetValue(itemId, out var amount) && amount < -Tolerance
|
||||
? -amount * (group.Count - group.Removed) : 0);
|
||||
coproduct = Math.Min(Math.Max(0, remainingBalance[itemId]),
|
||||
Math.Max(0, necessaryJointProduction - internalConsumption));
|
||||
}
|
||||
}
|
||||
|
||||
var finalKnown = !unknownDemand && !uncertainDemandItems.Contains(itemId);
|
||||
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);
|
||||
}
|
||||
|
||||
steadyStateBalance = CalculateSteadyStateBalance(groups, originalBalance, remainingBalance,
|
||||
protectedItems, intermediateItems);
|
||||
return classification;
|
||||
}
|
||||
|
||||
private static double NecessaryJointProduction(ReductionGroup group, int itemId,
|
||||
IReadOnlyDictionary<int, double> originalBalance, IReadOnlyDictionary<int, double> remainingBalance,
|
||||
ISet<int> protectedItems, ISet<int> intermediateItems)
|
||||
{
|
||||
var retained = group.Count - group.Removed;
|
||||
if (retained == 0 || !group.Source.HasJointProducts ||
|
||||
!group.Source.NetPerBuilding.TryGetValue(itemId, out var production) || production <= Tolerance)
|
||||
return 0;
|
||||
|
||||
var removable = (double)retained;
|
||||
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 available = Math.Floor((remainingBalance[flow.Key] - minimum + Tolerance) / flow.Value);
|
||||
removable = Math.Min(removable, Math.Max(0, available));
|
||||
}
|
||||
|
||||
return production * (retained - removable);
|
||||
}
|
||||
|
||||
private static IReadOnlyDictionary<int, double> CalculateSteadyStateBalance(
|
||||
IReadOnlyList<ReductionGroup> groups, IReadOnlyDictionary<int, double> originalBalance,
|
||||
IReadOnlyDictionary<int, double> remainingBalance, ISet<int> protectedItems, ISet<int> intermediateItems)
|
||||
{
|
||||
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
|
||||
{
|
||||
changed = false;
|
||||
foreach (var group in groups)
|
||||
{
|
||||
if (!group.Source.NetPerBuilding.Values.Any(value => value > Tolerance)) continue;
|
||||
var reducible = available[group];
|
||||
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;
|
||||
reducible = Math.Min(reducible, Math.Max(0, (balance[flow.Key] - minimum) / flow.Value));
|
||||
}
|
||||
|
||||
if (reducible <= Tolerance) continue;
|
||||
foreach (var flow in group.Source.NetPerBuilding)
|
||||
balance[flow.Key] -= flow.Value * reducible;
|
||||
available[group] -= reducible;
|
||||
changed = true;
|
||||
}
|
||||
} while (changed);
|
||||
|
||||
return balance;
|
||||
}
|
||||
|
||||
private static bool CanRemove(IReadOnlyDictionary<int, double> netPerBuilding,
|
||||
IReadOnlyDictionary<int, double> originalBalance, IReadOnlyDictionary<int, double> remainingBalance,
|
||||
ISet<int> protectedItems, ISet<int> intermediateItems)
|
||||
{
|
||||
foreach (var flow in netPerBuilding)
|
||||
{
|
||||
var reduced = remainingBalance[flow.Key] - flow.Value;
|
||||
if (protectedItems.Contains(flow.Key) && reduced < originalBalance[flow.Key] - Tolerance)
|
||||
return false;
|
||||
if (intermediateItems.Contains(flow.Key) &&
|
||||
Math.Max(0, -reduced) > Math.Max(0, -originalBalance[flow.Key]) + Tolerance)
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace UXAssist.Production;
|
||||
|
||||
public sealed class BlueprintDescriptionLabels
|
||||
{
|
||||
public string FactoryPower { get; }
|
||||
public string LogisticsPower { get; }
|
||||
public string Missing { get; }
|
||||
public string Excess { get; }
|
||||
public string Unknown { get; }
|
||||
public string KnownPortion { get; }
|
||||
public string InputLine { get; }
|
||||
public string OutputLine { get; }
|
||||
public string ResearchLine { get; }
|
||||
|
||||
public BlueprintDescriptionLabels(string factoryPower, string logisticsPower, string missing, string excess,
|
||||
string unknown, string knownPortion, string inputLine, string outputLine, string researchLine)
|
||||
{
|
||||
FactoryPower = factoryPower;
|
||||
LogisticsPower = logisticsPower;
|
||||
Missing = missing;
|
||||
Excess = excess;
|
||||
Unknown = unknown;
|
||||
KnownPortion = knownPortion;
|
||||
InputLine = inputLine;
|
||||
OutputLine = outputLine;
|
||||
ResearchLine = researchLine;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class BlueprintDescriptionText
|
||||
{
|
||||
public const int MaximumDescriptionLength = 2000;
|
||||
|
||||
public string Power { get; }
|
||||
public string Warnings { get; }
|
||||
public string Input { get; }
|
||||
public string Output { get; }
|
||||
public string Research { get; }
|
||||
public string Description { get; }
|
||||
|
||||
public BlueprintDescriptionText(string power, string warnings, string input, string output, string research,
|
||||
string inputLine, string outputLine, string researchLine)
|
||||
{
|
||||
Power = power;
|
||||
Warnings = warnings;
|
||||
Input = input;
|
||||
Output = output;
|
||||
Research = research;
|
||||
var lines = new List<string>();
|
||||
if (warnings.Length > 0) lines.Add(warnings);
|
||||
if (input.Length > 0) lines.Add(inputLine + input);
|
||||
if (output.Length > 0) lines.Add(outputLine + output);
|
||||
if (research.Length > 0) lines.Add(researchLine + research);
|
||||
Description = string.Join("\n", lines);
|
||||
}
|
||||
}
|
||||
|
||||
public static class BlueprintDescriptionFormatter
|
||||
{
|
||||
private const double Tolerance = 1e-9;
|
||||
|
||||
public static BlueprintDescriptionText Format(ProductionReport report, Func<int, string> itemTag,
|
||||
BlueprintDescriptionLabels labels)
|
||||
{
|
||||
if (report == null || report.Status == ProductionStatus.Failed ||
|
||||
report.Status == ProductionStatus.DataNotReady)
|
||||
throw new InvalidOperationException("A usable blueprint production report is required.");
|
||||
if (itemTag == null) throw new ArgumentNullException(nameof(itemTag));
|
||||
if (labels == null) throw new ArgumentNullException(nameof(labels));
|
||||
|
||||
var breakdown = report.PowerBreakdown ??
|
||||
throw new InvalidOperationException("A blueprint power breakdown is required.");
|
||||
var power = new List<string>();
|
||||
if (breakdown.KnownFactoryConsumptionWatts > 0 || !breakdown.FactoryComplete)
|
||||
power.Add(labels.FactoryPower + " " + FormatPower(breakdown.FactoryConsumptionWatts, labels));
|
||||
if (breakdown.KnownLogisticsConsumptionWatts > 0 || !breakdown.LogisticsComplete)
|
||||
power.Add(labels.LogisticsPower + " " + FormatPower(breakdown.LogisticsConsumptionWatts, labels));
|
||||
var missing = new List<string>();
|
||||
var excess = new List<string>();
|
||||
var input = new List<string>();
|
||||
var output = new SortedDictionary<int, double>();
|
||||
var research = new SortedDictionary<int, double>();
|
||||
foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId))
|
||||
{
|
||||
var shortage = Math.Min(flow.IntermediateShortage,
|
||||
flow.SteadyStateExternalSupply ?? flow.RequiredExternalSupply);
|
||||
if (shortage > Tolerance)
|
||||
missing.Add(FormatItem(flow.ItemId, shortage, itemTag));
|
||||
}
|
||||
|
||||
if (report.MaterialComplete)
|
||||
{
|
||||
foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId))
|
||||
{
|
||||
if (flow.OverbuildSurplus.GetValueOrDefault() > Tolerance)
|
||||
excess.Add(FormatItem(flow.ItemId, flow.OverbuildSurplus.Value, itemTag));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId))
|
||||
{
|
||||
var requiredSupply = flow.SteadyStateExternalSupply ?? flow.RequiredExternalSupply;
|
||||
if (requiredSupply > Tolerance && flow.IntermediateShortage <= Tolerance)
|
||||
input.Add(FormatItem(flow.ItemId, requiredSupply, itemTag));
|
||||
|
||||
var rate = flow.IsFinalProduct ? Math.Max(0, flow.NetFlow) : 0;
|
||||
if (report.MaterialComplete) rate += flow.CoproductSurplus.GetValueOrDefault();
|
||||
if (rate > Tolerance)
|
||||
{
|
||||
if (flow.IsResearchProduct) research[flow.ItemId] = rate;
|
||||
else output[flow.ItemId] = rate;
|
||||
}
|
||||
}
|
||||
|
||||
var formattedOutput = output.Select(flow => FormatItem(flow.Key, flow.Value, itemTag));
|
||||
var formattedResearch = research.Select(flow => FormatItem(flow.Key, flow.Value, itemTag));
|
||||
var warnings = new List<string>();
|
||||
if (missing.Count > 0)
|
||||
warnings.Add(labels.Missing + FormatMaterial(missing, report.MaterialComplete, labels));
|
||||
if (excess.Count > 0)
|
||||
warnings.Add(labels.Excess + FormatMaterial(excess, report.MaterialComplete, labels));
|
||||
return new BlueprintDescriptionText(string.Join(" | ", power),
|
||||
string.Join("\n", warnings),
|
||||
FormatMaterial(input, report.MaterialComplete, labels),
|
||||
FormatMaterial(formattedOutput, report.MaterialComplete, labels),
|
||||
FormatMaterial(formattedResearch, report.MaterialComplete, labels),
|
||||
labels.InputLine, labels.OutputLine, labels.ResearchLine);
|
||||
}
|
||||
|
||||
private static string FormatMaterial(IEnumerable<string> entries, bool complete,
|
||||
BlueprintDescriptionLabels labels)
|
||||
{
|
||||
var text = string.Join(", ", entries);
|
||||
if (text.Length == 0) return "";
|
||||
return complete ? text : text + " " + labels.KnownPortion;
|
||||
}
|
||||
|
||||
private static string FormatItem(int itemId, double rate, Func<int, string> itemTag)
|
||||
{
|
||||
var tag = itemTag(itemId);
|
||||
if (string.IsNullOrEmpty(tag))
|
||||
throw new InvalidOperationException("An item in the blueprint report has no native icon tag.");
|
||||
return tag + " x" + FormatNumber(rate);
|
||||
}
|
||||
|
||||
private static string FormatPower(double? watts, BlueprintDescriptionLabels labels)
|
||||
{
|
||||
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";
|
||||
}
|
||||
|
||||
private static string FormatNumber(double value)
|
||||
{
|
||||
if (double.IsNaN(value) || double.IsInfinity(value) || value < 0)
|
||||
throw new InvalidOperationException("A blueprint report contains an invalid rate or power value.");
|
||||
var rounded = Math.Round(value, value < 1 ? 3 : 2, MidpointRounding.AwayFromZero);
|
||||
if (rounded > 0 || value == 0)
|
||||
return rounded.ToString(value < 1 ? "0.###" : "0.##", CultureInfo.InvariantCulture);
|
||||
var precise = value.ToString("0.######", CultureInfo.InvariantCulture);
|
||||
return precise != "0" ? precise : value.ToString("0.###E+0", CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class BlueprintDescriptionField
|
||||
{
|
||||
public string Title { get; }
|
||||
public string Value { get; }
|
||||
public IReadOnlyList<string> MatchingTitles { get; }
|
||||
|
||||
public BlueprintDescriptionField(string title, string value, params string[] matchingTitles)
|
||||
{
|
||||
Title = title;
|
||||
Value = value;
|
||||
MatchingTitles = Array.AsReadOnly(matchingTitles);
|
||||
}
|
||||
|
||||
public bool Matches(string title)
|
||||
{
|
||||
return string.Equals(Title, title, StringComparison.Ordinal) ||
|
||||
MatchingTitles.Any(candidate => string.Equals(candidate, title, StringComparison.Ordinal));
|
||||
}
|
||||
}
|
||||
|
||||
public enum BlueprintFieldUpdateResult
|
||||
{
|
||||
Updated,
|
||||
CapacityExceeded,
|
||||
InvalidFields
|
||||
}
|
||||
|
||||
public static class BlueprintDescriptionFields
|
||||
{
|
||||
public static bool IsNativeFormatValid(string serialized)
|
||||
{
|
||||
if (string.IsNullOrEmpty(serialized)) return true;
|
||||
if (!serialized.EndsWith(";", StringComparison.Ordinal)) return false;
|
||||
var parts = serialized.Split(';');
|
||||
for (var index = 0; index < parts.Length - 1; index++)
|
||||
{
|
||||
var delimiter = parts[index].IndexOf(':');
|
||||
if (delimiter < 0 || parts[index].IndexOf(':', delimiter + 1) >= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static BlueprintFieldUpdateResult TryUpdate(string existing, IReadOnlyList<BlueprintDescriptionField> fields,
|
||||
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 (maximumFields < 0 || !IsNativeFormatValid(existing))
|
||||
return BlueprintFieldUpdateResult.InvalidFields;
|
||||
|
||||
var parts = (existing ?? "").Split(';');
|
||||
var matches = new int[parts.Length];
|
||||
var found = new bool[fields.Count];
|
||||
var nativeCount = 0;
|
||||
var removedCount = 0;
|
||||
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 (!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;
|
||||
}
|
||||
}
|
||||
|
||||
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++)
|
||||
{
|
||||
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(';');
|
||||
}
|
||||
|
||||
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();
|
||||
return BlueprintFieldUpdateResult.Updated;
|
||||
}
|
||||
}
|
||||
@@ -173,6 +173,8 @@ public static class BlueprintSelectionReader
|
||||
});
|
||||
var operation = new Dictionary<string, double>();
|
||||
AddSettings(parameters, operation);
|
||||
if (operation.ContainsKey("ResearchMode"))
|
||||
operation["ResearchMatrixSink"] = 1;
|
||||
if (building.Kind == ProductionBuildingKind.Logistics)
|
||||
CaptureStoredChargePower(building, parameters, blueprint.parameters, operation);
|
||||
ApplySupplied(context?.OperatingParametersByIndex, blueprint.index, operation);
|
||||
@@ -449,7 +451,9 @@ public static class BlueprintSelectionReader
|
||||
IReadOnlyDictionary<string, double> operation, ICollection<ProductionDiagnostic> diagnostics)
|
||||
{
|
||||
var kind = building.Kind;
|
||||
var requiredKey = parameters.type == BuildingType.Lab && parameters.mode0 == 2 ? "TechId" :
|
||||
var researchNeedsTechnology = parameters.type == BuildingType.Lab && parameters.mode0 == 2 &&
|
||||
(!operation.TryGetValue("ResearchMatrixSink", out var matrixSink) || matrixSink != 1);
|
||||
var requiredKey = researchNeedsTechnology ? "TechId" :
|
||||
kind == ProductionBuildingKind.Miner ? "ResourceItemId" :
|
||||
kind == ProductionBuildingKind.Collector ? "GasCount" :
|
||||
kind == ProductionBuildingKind.FuelGenerator ? "FuelItemId" :
|
||||
@@ -458,8 +462,7 @@ public static class BlueprintSelectionReader
|
||||
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
|
||||
$"The selected building needs the {requiredKey} operating parameter.",
|
||||
buildingItemId: building.ItemId));
|
||||
if (parameters.type == BuildingType.Lab && parameters.mode0 == 2 &&
|
||||
!operation.ContainsKey("ResearchSpeed"))
|
||||
if (researchNeedsTechnology && !operation.ContainsKey("ResearchSpeed"))
|
||||
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
|
||||
"The research lab needs the current research technology speed.",
|
||||
buildingItemId: building.ItemId));
|
||||
|
||||
@@ -59,19 +59,26 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
|
||||
var diagnostics = new List<ProductionDiagnostic>(request.CaptureDiagnostics);
|
||||
var groups = new List<ProductionGroupFlow>();
|
||||
var processGroups = new List<BlackBoxProcessGroup>();
|
||||
var grossProduction = new SortedDictionary<int, double>();
|
||||
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>();
|
||||
var skippedSelection = diagnostics.Any(diagnostic =>
|
||||
diagnostic.Code == ProductionDiagnosticCode.InvalidRequest ||
|
||||
diagnostic.Code == ProductionDiagnosticCode.UnknownItem ||
|
||||
diagnostic.Code == ProductionDiagnosticCode.DataNotReady);
|
||||
var unknownDemand = skippedSelection;
|
||||
var materialComplete = !skippedSelection;
|
||||
var powerComplete = !skippedSelection;
|
||||
var consumptionWatts = 0.0;
|
||||
var factoryPowerComplete = !skippedSelection;
|
||||
var logisticsPowerComplete = !skippedSelection;
|
||||
var totalPowerKnown = !skippedSelection;
|
||||
var factoryConsumptionWatts = 0.0;
|
||||
var logisticsConsumptionWatts = 0.0;
|
||||
var generationWatts = 0.0;
|
||||
var chargingWatts = 0.0;
|
||||
var dischargingWatts = 0.0;
|
||||
@@ -84,7 +91,9 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"A selected building has an invalid count."));
|
||||
materialComplete = false;
|
||||
powerComplete = false;
|
||||
factoryPowerComplete = false;
|
||||
logisticsPowerComplete = false;
|
||||
unknownDemand = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -101,7 +110,9 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
"The selected building is not supported by the catalog.",
|
||||
buildingItemId: snapshot.BuildingItemId));
|
||||
materialComplete = false;
|
||||
powerComplete = false;
|
||||
factoryPowerComplete = false;
|
||||
logisticsPowerComplete = false;
|
||||
unknownDemand = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -113,7 +124,9 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
"A research-mode lab cannot also run a manufacturing recipe.",
|
||||
recipeId: snapshot.RecipeId, buildingItemId: snapshot.BuildingItemId));
|
||||
materialComplete = false;
|
||||
powerComplete = false;
|
||||
factoryPowerComplete = false;
|
||||
logisticsPowerComplete = false;
|
||||
unknownDemand = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -132,8 +145,8 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
else
|
||||
logisticsWatts = chargePowerWatts * snapshot.Count;
|
||||
|
||||
if (logisticsWatts.HasValue) consumptionWatts += logisticsWatts.Value;
|
||||
else powerComplete = false;
|
||||
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>>()));
|
||||
@@ -149,7 +162,7 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
{
|
||||
var idleWatts = (building.Kind == ProductionBuildingKind.Auxiliary
|
||||
? building.WorkingPowerWatts : building.IdlePowerWatts) * snapshot.Count;
|
||||
consumptionWatts += idleWatts;
|
||||
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>>()));
|
||||
@@ -164,25 +177,53 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
"The selected building's recipe is missing.", recipeId: snapshot.RecipeId,
|
||||
buildingItemId: snapshot.BuildingItemId));
|
||||
materialComplete = false;
|
||||
powerComplete = false;
|
||||
factoryPowerComplete = false;
|
||||
unknownDemand = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (snapshot.SpeedFactor.HasValue) building = building.WithSpeedFactor(snapshot.SpeedFactor.Value);
|
||||
var mode = request.ProliferationEnabled
|
||||
? FullProliferationMode(building, snapshot) : ProliferationMode.None;
|
||||
if (IsResearchModeLab(building, snapshot) && _catalog.MaximumProliferationLevel == 0)
|
||||
mode = ProliferationMode.None;
|
||||
var researchMatrixSink = IsResearchModeLab(building, snapshot) &&
|
||||
snapshot.OperatingParameters.TryGetValue("ResearchMatrixSink", out var sinkSetting) &&
|
||||
sinkSetting == 1 && _catalog.ResearchMatrixItemIds.Count > 0;
|
||||
if (researchMatrixSink) hasResearchMatrixSink = true;
|
||||
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;
|
||||
if (building.Kind != ProductionBuildingKind.RenewableGenerator && !researchMatrixSink)
|
||||
materialComplete = false;
|
||||
if (recipe != null) uncertainDemandItems.UnionWith(recipe.Inputs.Keys);
|
||||
else if (building.Kind != ProductionBuildingKind.Miner &&
|
||||
building.Kind != ProductionBuildingKind.Collector &&
|
||||
building.Kind != ProductionBuildingKind.RenewableGenerator && !researchMatrixSink)
|
||||
unknownDemand = true;
|
||||
if (TryGetConsumptionWithoutMaterials(building, snapshot, diagnostic, mode,
|
||||
out var knownWatts))
|
||||
{
|
||||
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>>()));
|
||||
}
|
||||
else
|
||||
{
|
||||
totalPowerKnown = false;
|
||||
factoryPowerComplete = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (diagnostic != null) diagnostics.Add(diagnostic);
|
||||
if (!process.PowerKnown) powerComplete = false;
|
||||
if (!process.PowerKnown) totalPowerKnown = false;
|
||||
if (process.WorkingPowerWatts < 0 || double.IsNaN(process.WorkingPowerWatts) ||
|
||||
double.IsInfinity(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);
|
||||
@@ -205,7 +246,7 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
}
|
||||
|
||||
var watts = process.WorkingPowerWatts * snapshot.Count;
|
||||
consumptionWatts += watts;
|
||||
factoryConsumptionWatts += watts;
|
||||
generationWatts += process.GenerationWatts * snapshot.Count;
|
||||
chargingWatts += process.AccumulatorChargingWatts * snapshot.Count;
|
||||
dischargingWatts += process.AccumulatorDischargingWatts * snapshot.Count;
|
||||
@@ -217,8 +258,13 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
process.DysonSphereRequirementWatts * snapshot.Count,
|
||||
cycleRate * snapshot.Count * process.LaunchesPerCycle,
|
||||
cycleRate * snapshot.Count * process.ResearchHashesPerCycle));
|
||||
processGroups.Add(new BlackBoxProcessGroup(process, snapshot));
|
||||
}
|
||||
|
||||
var matrixSinkItems = hasResearchMatrixSink
|
||||
? new HashSet<int>(_catalog.ResearchMatrixItemIds) : new HashSet<int>();
|
||||
var classifications = BlackBoxMaterialClassifier.Classify(processGroups, grossProduction, grossConsumption,
|
||||
materialComplete, uncertainDemandItems, unknownDemand, matrixSinkItems, out var steadyStateBalance);
|
||||
var flows = new List<ProductionItemFlow>();
|
||||
var allItems = new SortedSet<int>(grossProduction.Keys);
|
||||
allItems.UnionWith(grossConsumption.Keys);
|
||||
@@ -228,22 +274,32 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
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;
|
||||
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,
|
||||
!isFinalProduct && consumed > 1e-9 && net > 1e-9 && threshold > 0 &&
|
||||
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>(),
|
||||
consumers.TryGetValue(itemId, out var usingItem) ? usingItem : 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.IsResearchProduct));
|
||||
}
|
||||
|
||||
var powerComplete = factoryPowerComplete && logisticsPowerComplete && totalPowerKnown;
|
||||
var consumptionWatts = factoryConsumptionWatts + logisticsConsumptionWatts;
|
||||
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);
|
||||
return new ProductionReport(status, materialComplete, powerComplete, flows, groups, diagnostics, power,
|
||||
new ProductionPowerBreakdown(factoryConsumptionWatts, logisticsConsumptionWatts,
|
||||
factoryPowerComplete, logisticsPowerComplete));
|
||||
}
|
||||
|
||||
private static ProliferationMode FullProliferationMode(ProductionBuilding building,
|
||||
@@ -272,6 +328,45 @@ public sealed class FactoryBlackBoxAnalyzer
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryGetConsumptionWithoutMaterials(ProductionBuilding building,
|
||||
ProductionBuildingSnapshot snapshot, ProductionDiagnostic diagnostic, ProliferationMode mode,
|
||||
out double watts)
|
||||
{
|
||||
watts = 0;
|
||||
if (IsResearchModeLab(building, snapshot))
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
watts = building.WorkingPowerWatts * multiplier * snapshot.Count;
|
||||
return watts > 0 && !double.IsNaN(watts) && !double.IsInfinity(watts);
|
||||
}
|
||||
|
||||
if (diagnostic?.Code != ProductionDiagnosticCode.MissingOperatingParameter) return false;
|
||||
if (building.Kind == ProductionBuildingKind.Collector) return true;
|
||||
if (building.Kind != ProductionBuildingKind.Miner) return false;
|
||||
|
||||
var speed = snapshot.OperatingParameters.TryGetValue("MachineSpeedFactor", out var capturedSpeed)
|
||||
? capturedSpeed : 1;
|
||||
if (speed <= 0 || double.IsNaN(speed) || double.IsInfinity(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);
|
||||
}
|
||||
|
||||
private static bool IsResearchModeLab(ProductionBuilding building, ProductionBuildingSnapshot snapshot)
|
||||
{
|
||||
return building.Kind == ProductionBuildingKind.Ordinary &&
|
||||
building.Category == ProductionRecipeCategory.Research && snapshot.RecipeId == 0 &&
|
||||
snapshot.OperatingParameters.TryGetValue("ResearchMode", out var researchMode) && researchMode == 1;
|
||||
}
|
||||
|
||||
private static Dictionary<int, double> Scale(IReadOnlyDictionary<int, double> flows, double factor)
|
||||
{
|
||||
return flows.ToDictionary(entry => entry.Key, entry => entry.Value * factor);
|
||||
|
||||
@@ -114,7 +114,7 @@ public static class ProductionCatalogReader
|
||||
|
||||
return new ProductionCatalog(items, recipes, buildings,
|
||||
(double[])Cargo.accTableMilli.Clone(), (double[])Cargo.incTableMilli.Clone(),
|
||||
(double[])Cargo.powerTableRatio.Clone(), technologies);
|
||||
(double[])Cargo.powerTableRatio.Clone(), technologies, matrixIds);
|
||||
}
|
||||
|
||||
private static void AddSpecialRecipes(IEnumerable<ItemProto> itemProtos,
|
||||
|
||||
@@ -267,17 +267,20 @@ public sealed class ProductionCatalog
|
||||
public IReadOnlyDictionary<int, ProductionRecipe> Recipes { get; }
|
||||
public IReadOnlyDictionary<int, ProductionBuilding> Buildings { get; }
|
||||
public IReadOnlyDictionary<int, ProductionTechnology> Technologies { get; }
|
||||
public IReadOnlyCollection<int> ResearchMatrixItemIds { get; }
|
||||
public int MaximumProliferationLevel { get; }
|
||||
|
||||
public ProductionCatalog(IEnumerable<ProductionItem> items, IEnumerable<ProductionRecipe> recipes,
|
||||
IEnumerable<ProductionBuilding> buildings, double[] speedBonus, double[] extraBonus, double[] powerMultiplier,
|
||||
IEnumerable<ProductionTechnology> technologies = null)
|
||||
IEnumerable<ProductionTechnology> technologies = null, IEnumerable<int> researchMatrixItemIds = null)
|
||||
{
|
||||
Items = new ReadOnlyDictionary<int, ProductionItem>(items.ToDictionary(item => item.Id));
|
||||
Recipes = new ReadOnlyDictionary<int, ProductionRecipe>(recipes.ToDictionary(recipe => recipe.Id));
|
||||
Buildings = new ReadOnlyDictionary<int, ProductionBuilding>(buildings.ToDictionary(building => building.ItemId));
|
||||
Technologies = new ReadOnlyDictionary<int, ProductionTechnology>(
|
||||
(technologies ?? Array.Empty<ProductionTechnology>()).ToDictionary(tech => tech.Id));
|
||||
ResearchMatrixItemIds = Array.AsReadOnly((researchMatrixItemIds ?? Array.Empty<int>())
|
||||
.Where(itemId => Items.ContainsKey(itemId)).Distinct().OrderBy(itemId => itemId).ToArray());
|
||||
_speedBonus = (double[])speedBonus.Clone();
|
||||
_extraBonus = (double[])extraBonus.Clone();
|
||||
_powerMultiplier = (double[])powerMultiplier.Clone();
|
||||
|
||||
@@ -21,6 +21,7 @@ public sealed partial class ProductionPlanner
|
||||
var groups = new List<ProductionGroupFlow>();
|
||||
var activeRecipes = new HashSet<int>();
|
||||
var powerComplete = true;
|
||||
var factoryPowerComplete = true;
|
||||
var workingPower = 0.0;
|
||||
var peakPower = 0.0;
|
||||
var generationWatts = 0.0;
|
||||
@@ -74,6 +75,7 @@ public sealed partial class ProductionPlanner
|
||||
if (equivalentBuildings.Value > int.MaxValue || double.IsInfinity(equivalentBuildings.Value))
|
||||
{
|
||||
powerComplete = false;
|
||||
factoryPowerComplete = false;
|
||||
warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The rounded deployment count exceeds the supported range.", recipeId: process.RecipeId));
|
||||
}
|
||||
@@ -82,6 +84,8 @@ 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;
|
||||
workingPower += consumedWatts.Value;
|
||||
peakPower += peakWatts.Value;
|
||||
generationWatts += equivalentBuildings.Value * process.GenerationWatts;
|
||||
@@ -93,6 +97,7 @@ public sealed partial class ProductionPlanner
|
||||
else
|
||||
{
|
||||
powerComplete = false;
|
||||
factoryPowerComplete = false;
|
||||
if (!warnings.Any(warning => warning.RecipeId == process.RecipeId &&
|
||||
(warning.Code == ProductionDiagnosticCode.MissingBuilding ||
|
||||
warning.Code == ProductionDiagnosticCode.IncompatibleBuilding)))
|
||||
@@ -116,6 +121,7 @@ public sealed partial class ProductionPlanner
|
||||
if (auxiliary == null || auxiliary.Count <= 0 || auxiliary.RecipeId != 0)
|
||||
{
|
||||
powerComplete = false;
|
||||
factoryPowerComplete = false;
|
||||
warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"Auxiliary power requires a positive building count and no production recipe."));
|
||||
continue;
|
||||
@@ -136,6 +142,7 @@ public sealed partial class ProductionPlanner
|
||||
double.IsInfinity(building.WorkingPowerWatts * auxiliary.Count))
|
||||
{
|
||||
powerComplete = false;
|
||||
factoryPowerComplete = false;
|
||||
warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
|
||||
"The auxiliary building has no rated working power.",
|
||||
buildingItemId: auxiliary.BuildingItemId));
|
||||
@@ -192,7 +199,8 @@ public sealed partial class ProductionPlanner
|
||||
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);
|
||||
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)
|
||||
|
||||
@@ -44,6 +44,25 @@ public sealed class ProductionPower
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ProductionPowerBreakdown
|
||||
{
|
||||
public double KnownFactoryConsumptionWatts { get; }
|
||||
public double KnownLogisticsConsumptionWatts { get; }
|
||||
public bool FactoryComplete { get; }
|
||||
public bool LogisticsComplete { get; }
|
||||
public double? FactoryConsumptionWatts => FactoryComplete ? KnownFactoryConsumptionWatts : null;
|
||||
public double? LogisticsConsumptionWatts => LogisticsComplete ? KnownLogisticsConsumptionWatts : null;
|
||||
|
||||
public ProductionPowerBreakdown(double knownFactoryConsumptionWatts, double knownLogisticsConsumptionWatts,
|
||||
bool factoryComplete, bool logisticsComplete)
|
||||
{
|
||||
KnownFactoryConsumptionWatts = knownFactoryConsumptionWatts;
|
||||
KnownLogisticsConsumptionWatts = knownLogisticsConsumptionWatts;
|
||||
FactoryComplete = factoryComplete;
|
||||
LogisticsComplete = logisticsComplete;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ProductionItemFlow
|
||||
{
|
||||
public int ItemId { get; }
|
||||
@@ -55,9 +74,14 @@ public sealed class ProductionItemFlow
|
||||
public double Delivered { get; }
|
||||
public double Surplus { get; }
|
||||
public double RequiredExternalSupply { get; }
|
||||
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; }
|
||||
public IReadOnlyList<int> ProducerGroups { get; }
|
||||
public IReadOnlyList<int> ConsumerGroups { get; }
|
||||
|
||||
@@ -65,6 +89,18 @@ public sealed class ProductionItemFlow
|
||||
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)
|
||||
{
|
||||
ItemId = itemId;
|
||||
GrossProduction = grossProduction;
|
||||
@@ -74,9 +110,14 @@ public sealed class ProductionItemFlow
|
||||
Delivered = delivered;
|
||||
Surplus = surplus;
|
||||
RequiredExternalSupply = requiredExternalSupply;
|
||||
SteadyStateExternalSupply = steadyStateExternalSupply;
|
||||
IsFinalProduct = isFinalProduct;
|
||||
IsResearchProduct = isResearchProduct;
|
||||
IsExcessIntermediate = isExcessIntermediate;
|
||||
SingleBuildingSurplusThreshold = singleBuildingSurplusThreshold;
|
||||
IntermediateShortage = intermediateShortage;
|
||||
OverbuildSurplus = overbuildSurplus;
|
||||
CoproductSurplus = coproductSurplus;
|
||||
ProducerGroups = Array.AsReadOnly(producerGroups.ToArray());
|
||||
ConsumerGroups = Array.AsReadOnly(consumerGroups.ToArray());
|
||||
}
|
||||
@@ -136,12 +177,21 @@ public sealed class ProductionReport
|
||||
public IReadOnlyList<ProductionGroupFlow> Groups { get; }
|
||||
public IReadOnlyList<ProductionDiagnostic> Diagnostics { get; }
|
||||
public ProductionPower Power { get; }
|
||||
public ProductionPowerBreakdown PowerBreakdown { 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<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)
|
||||
{
|
||||
Status = status;
|
||||
MaterialComplete = materialComplete;
|
||||
@@ -150,6 +200,7 @@ public sealed class ProductionReport
|
||||
Groups = Array.AsReadOnly(groups.ToArray());
|
||||
Diagnostics = Array.AsReadOnly(diagnostics.ToArray());
|
||||
Power = power;
|
||||
PowerBreakdown = powerBreakdown;
|
||||
}
|
||||
|
||||
internal static ProductionReport Failure(ProductionDiagnostic diagnostic)
|
||||
|
||||
@@ -18,11 +18,7 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter
|
||||
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))
|
||||
!operatingParameters.TryGetValue("ResearchMode", out var researchMode) || researchMode != 1)
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
|
||||
"Research mode needs a lab technology and current research speed.",
|
||||
@@ -30,12 +26,41 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!catalog.Technologies.TryGetValue((int)techId, out var tech))
|
||||
var matrixSink = operatingParameters.TryGetValue("ResearchMatrixSink", out var sinkSetting) &&
|
||||
sinkSetting == 1;
|
||||
var researchSpeed = 0.0;
|
||||
ProductionTechnology technology = null;
|
||||
if (matrixSink)
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The selected technology is not a lab-research technology.",
|
||||
buildingItemId: building.ItemId);
|
||||
return false;
|
||||
if (catalog.ResearchMatrixItemIds.Count == 0)
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
|
||||
"The catalog has no native research matrix item IDs.",
|
||||
buildingItemId: building.ItemId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!operatingParameters.TryGetValue("TechId", out var techId) || techId <= 0 ||
|
||||
techId > int.MaxValue || techId != Math.Truncate(techId) ||
|
||||
!operatingParameters.TryGetValue("ResearchSpeed", out 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 technology))
|
||||
{
|
||||
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)
|
||||
@@ -60,7 +85,7 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter
|
||||
var baseHashes = 3600.0 * researchSpeed;
|
||||
var hashRate = baseHashes * (1 + extraBonus);
|
||||
var workingWatts = building.WorkingPowerWatts * powerMultiplier;
|
||||
if (!FinitePositive(hashRate) || !FinitePositive(workingWatts))
|
||||
if (!FinitePositive(workingWatts) || !matrixSink && !FinitePositive(hashRate))
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The research hash rate or power demand is outside the supported range.",
|
||||
@@ -69,19 +94,22 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter
|
||||
}
|
||||
|
||||
var inputs = new List<KeyValuePair<int, double>>();
|
||||
foreach (var requirement in tech.MatrixPointsPerHash)
|
||||
if (!matrixSink)
|
||||
{
|
||||
if (!catalog.Items.ContainsKey(requirement.Key) || !FinitePositive(requirement.Value) ||
|
||||
!FinitePositive(researchSpeed * requirement.Value))
|
||||
foreach (var requirement in technology.MatrixPointsPerHash)
|
||||
{
|
||||
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
|
||||
"The technology has an invalid matrix point requirement.",
|
||||
itemId: requirement.Key, buildingItemId: building.ItemId);
|
||||
return false;
|
||||
}
|
||||
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<int, double>(requirement.Key,
|
||||
researchSpeed * requirement.Value));
|
||||
inputs.Add(new KeyValuePair<int, double>(requirement.Key,
|
||||
researchSpeed * requirement.Value));
|
||||
}
|
||||
}
|
||||
|
||||
process = new ProductionProcess(0, building.ItemId, mode,
|
||||
|
||||
Reference in new issue
Block a user