Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Maintenance changes/updates #345

Merged
merged 15 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,5 @@ dotnet_diagnostic.IDE0052.severity = none

# Disable "IDE0130: Namespace does not match folder structure" because VS Code Cleanup applies it automatically and breaks things.
dotnet_style_namespace_match_folder = false

spelling_exclusion_path = exclusion.dic
1 change: 1 addition & 0 deletions FactorioCalc.sln
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
ProjectSection(SolutionItems) = preProject
changelog.txt = changelog.txt
Directory.Build.props = Directory.Build.props
exclusion.dic = exclusion.dic
EndProjectSection
EndProject
Global
Expand Down
6 changes: 2 additions & 4 deletions Yafc.Model.Tests/Data/DataUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
namespace Yafc.Model.Data.Tests;

public class DataUtilsTests {
public DataUtilsTests() {
Project.current = new();
}
public DataUtilsTests() => Project.current = new();

[Fact]
public void TryParseAmount_IsInverseOfFormatValue() {
Expand Down Expand Up @@ -49,7 +47,7 @@ public void TryParseAmount_IsInverseOfFormatValue() {
[Fact]
public void TryParseAmount_IsInverseOfFormatValue_WithBeltsAndPipes() {
// Hammer the formatter and parser with lots of random but repeatable values, making sure TryParseAmount can correctly read anything FormatAmount generates.
// This time, include b and p suffixes. These suffixes noticably reduce precision, so do them separately.
// This time, include b and p suffixes. These suffixes noticeably reduce precision, so do them separately.
Random r = new Random(0);
byte[] bytes = new byte[4];
for (int i = 0; i < 1000; i++) {
Expand Down
38 changes: 18 additions & 20 deletions Yafc.Model.Tests/Data/LocalisedStringParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,63 +4,61 @@
namespace Yafc.Model.Data.Tests;

public class LocalisedStringParserTests {
public LocalisedStringParserTests() {
FactorioLocalization.Initialize(new System.Collections.Generic.Dictionary<string, string>() {
["hours"] = "__1__ __plural_for_parameter__1__{1=hour|rest=hours}__",
["si-unit-kilometer-per-hour"] = "__1__ km/h",
["not-enough-ingredients"] = "Not enough ingredients.",
["item-name.iron-plate"] = "Iron plate",
["item-name.big-iron-plate"] = "Big __ITEM__iron-plate__",
["connecting"] = "__plural_for_parameter__1__{1=__1__ player is|rest=__1__ players are}__ connecting",
["ends.in"] = "__plural_for_parameter__1__{ends in 12=option 1|ends in 2=option 2|rest=option 3}__"
});
}
public LocalisedStringParserTests() => FactorioLocalization.Initialize(new System.Collections.Generic.Dictionary<string, string>() {
["hours"] = "__1__ __plural_for_parameter__1__{1=hour|rest=hours}__",
["si-unit-kilometer-per-hour"] = "__1__ km/h",
["not-enough-ingredients"] = "Not enough ingredients.",
["item-name.iron-plate"] = "Iron plate",
["item-name.big-iron-plate"] = "Big __ITEM__iron-plate__",
["connecting"] = "__plural_for_parameter__1__{1=__1__ player is|rest=__1__ players are}__ connecting",
["ends.in"] = "__plural_for_parameter__1__{ends in 12=option 1|ends in 2=option 2|rest=option 3}__"
});

[Fact]
public void Parse_JustString() {
var localised = LocalisedStringParser.Parse("test");
string localised = LocalisedStringParser.Parse("test");
Assert.Equal("test", localised);
}

[Fact]
public void Parse_RemoveRichText() {
var localised = LocalisedStringParser.Parse("[color=#ffffff]iron[/color] [color=1,0,0]plate[.color] [item=iron-plate]");
string localised = LocalisedStringParser.Parse("[color=#ffffff]iron[/color] [color=1,0,0]plate[.color] [item=iron-plate]");
Assert.Equal("iron plate ", localised);
}

[Fact]
public void Parse_NoParameters() {
var localised = LocalisedStringParser.Parse("not-enough-ingredients", []);
string localised = LocalisedStringParser.Parse("not-enough-ingredients", []);
Assert.Equal("Not enough ingredients.", localised);
}

[Fact]
public void Parse_Parameter() {
var localised = LocalisedStringParser.Parse("si-unit-kilometer-per-hour", ["100"]);
string localised = LocalisedStringParser.Parse("si-unit-kilometer-per-hour", ["100"]);
Assert.Equal("100 km/h", localised);
}

[Fact]
public void Parse_LinkItem() {
var localised = LocalisedStringParser.Parse("item-name.big-iron-plate", []);
string localised = LocalisedStringParser.Parse("item-name.big-iron-plate", []);
Assert.Equal("Big Iron plate", localised);
}

[Fact]
public void Parse_PluralSpecial() {
var localised = LocalisedStringParser.Parse("hours", ["1"]);
string localised = LocalisedStringParser.Parse("hours", ["1"]);
Assert.Equal("1 hour", localised);
}

[Fact]
public void Parse_PluralRest() {
var localised = LocalisedStringParser.Parse("hours", ["2"]);
string localised = LocalisedStringParser.Parse("hours", ["2"]);
Assert.Equal("2 hours", localised);
}

[Fact]
public void Parse_PluralWithParameter() {
var localised = LocalisedStringParser.Parse("connecting", ["1"]);
string localised = LocalisedStringParser.Parse("connecting", ["1"]);
Assert.Equal("1 player is connecting", localised);
}

Expand All @@ -69,7 +67,7 @@ public void Parse_PluralWithParameter() {
[InlineData(22, "option 2")]
[InlineData(5, "option 3")]
public void Parse_PluralEndsIn(int n, string expectedResult) {
var localised = LocalisedStringParser.Parse("ends.in", [n.ToString()]);
string localised = LocalisedStringParser.Parse("ends.in", [n.ToString()]);
Assert.Equal(expectedResult, localised);
}
}
2 changes: 1 addition & 1 deletion Yafc.Model.Tests/LuaDependentTestHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ static LuaDependentTestHelper() {
/// Do not use <c>require</c> in the embedded files.</remarks>
/// <param name="targetStreamName">The name of the embedded resource to load, if the default name selection does not work for you.</param>
internal static Project GetProjectForLua(string targetStreamName = null) {
// Verify correct non-parallel declaration for tests, to accomodate the singleton analyses.
// Verify correct non-parallel declaration for tests, to accommodate the singleton analyses.
StackTrace stack = new();

for (int i = 1; i < stack.FrameCount; i++) {
Expand Down
4 changes: 2 additions & 2 deletions Yafc.Model.Tests/Model/ProductionTableContentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ void testCombinations(RecipeRow row, ProductionTable table, Action assert) {
for (int beaconCount = 0; beaconCount < 13; beaconCount++) {
for (float payback = 1; payback < float.MaxValue; payback *= 16) {
if (table.GetType().GetProperty("modules").SetMethod is MethodInfo method) {
// Pre-emptive code for if ProductionTable.modules is made writable.
// Preemptive code for if ProductionTable.modules is made writable.
// The ProductionTable.modules setter must notify all relevant recipes if it is added.
_ = method.Invoke(table, [new ModuleFillerParameters(table) {
beacon = new(beacon, Quality.Normal),
Expand All @@ -103,7 +103,7 @@ void testCombinations(RecipeRow row, ProductionTable table, Action assert) {
}

/// <summary>
/// Run the preceeding tests for fixed buildings, fuel, ingredients, and products.
/// Run the preceding tests for fixed buildings, fuel, ingredients, and products.
/// </summary>
/// <param name="row">The row containing the recipe to test with fixed amounts.</param>
/// <param name="testCombinations">An action that loops through the various combinations of entities, beacons, etc, and calls its third parameter for each combination.</param>
Expand Down
7 changes: 4 additions & 3 deletions Yafc.Model.Tests/Model/RecipeParametersTests.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace Yafc.Model.Tests.Model;

[Collection("LuaDependentTests")]
public class RecipeParametersTests {
[Fact]
public void FluidBoilingRecipes_HaveCorrectConsumption() {
public async Task FluidBoilingRecipes_HaveCorrectConsumption() {
Project project = LuaDependentTestHelper.GetProjectForLua();

ProjectPage page = new(project, typeof(ProductionTable));
Expand All @@ -22,7 +23,7 @@ public void FluidBoilingRecipes_HaveCorrectConsumption() {
RecipeRow heatExchanger = table.recipes[1];
boiler.fixedBuildings = 1;
heatExchanger.fixedBuildings = 1;
table.Solve((ProjectPage)table.owner).Wait(); // Initial Solve to set RecipeRow.Ingredients
await table.Solve((ProjectPage)table.owner); // Initial Solve to set RecipeRow.Ingredients

for (int i = 0; i < 3; i++) {
if (i != 0) {
Expand All @@ -32,7 +33,7 @@ public void FluidBoilingRecipes_HaveCorrectConsumption() {
boiler.ChangeVariant(boiler.Ingredients.Single().Goods, water[i]);
heatExchanger.ChangeVariant(boiler.Ingredients.Single().Goods, water[i]);

table.Solve((ProjectPage)table.owner).Wait();
await table.Solve((ProjectPage)table.owner);

// boil 60, 78.26, 120 water per second from 15, 50, 90° to 165°
float expectedBoilerAmount = 1800 / .2f / (165 - water[i].temperature);
Expand Down
19 changes: 10 additions & 9 deletions Yafc.Model.Tests/Model/SelectableVariantsTests.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace Yafc.Model.Tests.Model;

[Collection("LuaDependentTests")]
public class SelectableVariantsTests {
[Fact]
public void CanSelectVariantFuel_VariantFuelChanges() {
public async Task CanSelectVariantFuel_VariantFuelChanges() {
Project project = LuaDependentTestHelper.GetProjectForLua();

ProjectPage page = new ProjectPage(project, typeof(ProductionTable));
Expand All @@ -15,16 +16,16 @@ public void CanSelectVariantFuel_VariantFuelChanges() {
RecipeRow row = table.GetAllRecipes().Single();

// Solve is not necessary in this test, but I'm calling it in case we decide to hide the fuel on disabled recipes.
table.Solve((ProjectPage)table.owner).Wait();
await table.Solve((ProjectPage)table.owner);
Assert.Equal("steam@165", row.FuelInformation.Goods.name);

row.fuel = row.FuelInformation.Variants[1];
table.Solve((ProjectPage)table.owner).Wait();
await table.Solve((ProjectPage)table.owner);
Assert.Equal("steam@500", row.FuelInformation.Goods.name);
}

[Fact]
public void CanSelectVariantFuelWithFavorites_VariantFuelChanges() {
public async Task CanSelectVariantFuelWithFavorites_VariantFuelChanges() {
Project project = LuaDependentTestHelper.GetProjectForLua();
project.preferences.ToggleFavorite(Database.fluids.all.Single(c => c.name == "steam@500"));

Expand All @@ -34,16 +35,16 @@ public void CanSelectVariantFuelWithFavorites_VariantFuelChanges() {
RecipeRow row = table.GetAllRecipes().Single();

// Solve is not necessary in this test, but I'm calling it in case we decide to hide the fuel on disabled recipes.
table.Solve((ProjectPage)table.owner).Wait();
await table.Solve((ProjectPage)table.owner);
Assert.Equal("steam@500", row.FuelInformation.Goods.name);

row.fuel = row.FuelInformation.Variants[0];
table.Solve((ProjectPage)table.owner).Wait();
await table.Solve((ProjectPage)table.owner);
Assert.Equal("steam@165", row.FuelInformation.Goods.name);
}

[Fact]
public void CanSelectVariantIngredient_VariantIngredientChanges() {
public async Task CanSelectVariantIngredient_VariantIngredientChanges() {
Project project = LuaDependentTestHelper.GetProjectForLua();

ProjectPage page = new ProjectPage(project, typeof(ProductionTable));
Expand All @@ -52,11 +53,11 @@ public void CanSelectVariantIngredient_VariantIngredientChanges() {
RecipeRow row = table.GetAllRecipes().Single();

// Solve is necessary here: Disabled recipes have null ingredients (and products), and Solve is the call that updates hierarchyEnabled.
table.Solve((ProjectPage)table.owner).Wait();
await table.Solve((ProjectPage)table.owner);
Assert.Equal("steam@165", row.Ingredients.Single().Goods.name);

row.ChangeVariant(row.Ingredients.Single().Goods, row.Ingredients.Single().Variants[1]);
table.Solve((ProjectPage)table.owner).Wait();
await table.Solve((ProjectPage)table.owner);
Assert.Equal("steam@500", row.Ingredients.Single().Goods.name);
}

Expand Down
4 changes: 1 addition & 3 deletions Yafc.Model.Tests/PrepareForTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,5 @@
namespace Yafc.Model.Tests;
public class PrepareForTests : XunitTestFramework {
public PrepareForTests(IMessageSink messageSink)
: base(messageSink) {
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
}
: base(messageSink) => Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
}
6 changes: 3 additions & 3 deletions Yafc.Model.Tests/Yafc.Model.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
4 changes: 2 additions & 2 deletions Yafc.Model/Analysis/Dependencies.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ public enum Flags {
}

public static class Dependencies {
public static Mapping<FactorioObject, DependencyList[]> dependencyList;
public static Mapping<FactorioObject, List<FactorioId>> reverseDependencies;
public static Mapping<FactorioObject, DependencyList[]> dependencyList { get; private set; }
public static Mapping<FactorioObject, List<FactorioId>> reverseDependencies { get; private set; }

public static void Calculate() {
dependencyList = Database.objects.CreateMapping<DependencyList[]>();
Expand Down
2 changes: 1 addition & 1 deletion Yafc.Model/Data/DataUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ public static string FormatAmountRaw(float amount, float unitMultiplier, string?
/// <returns>True if the string could be parsed as the specified unit, false otherwise.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="unit"/> is <see cref="UnitOfMeasure.Celsius"/>.</exception>
public static bool TryParseAmount(string str, out float amount, UnitOfMeasure unit) {
if (unit is UnitOfMeasure.Celsius) { throw new ArgumentException("Parsing to UnitOfMeasure.Celcius is not supported.", nameof(unit)); }
if (unit is UnitOfMeasure.Celsius) { throw new ArgumentException("Parsing to UnitOfMeasure.Celsius is not supported.", nameof(unit)); }

var (mul, _) = Project.current.ResolveUnitOfMeasure(unit);
float multiplier = unit is UnitOfMeasure.Megawatt or UnitOfMeasure.Megajoule ? 1e6f : 1f;
Expand Down
16 changes: 8 additions & 8 deletions Yafc.Model/Model/ProductionTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ private void CalculateFlow(RecipeRow? include) {
/// Add/update the variable value for the constraint with the given amount, and store the recipe to the production link.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void AddLinkCoef(Constraint cst, Variable var, ProductionLink link, RecipeRow recipe, float amount) {
private static void AddLinkCoefficient(Constraint cst, Variable var, ProductionLink link, RecipeRow recipe, float amount) {
// GetCoefficient will return 0 when the variable is not available in the constraint
amount += (float)cst.GetCoefficient(var);
_ = link.capturedRecipes.Add(recipe);
Expand All @@ -331,7 +331,7 @@ private static void AddLinkCoef(Constraint cst, Variable var, ProductionLink lin
List<ProductionLink> allLinks = [];
Setup(allRecipes, allLinks);
Variable[] vars = new Variable[allRecipes.Count];
float[] objCoefs = new float[allRecipes.Count];
float[] objCoefficients = new float[allRecipes.Count];

for (int i = 0; i < allRecipes.Count; i++) {
var recipe = allRecipes[i];
Expand Down Expand Up @@ -372,11 +372,11 @@ private static void AddLinkCoef(Constraint cst, Variable var, ProductionLink lin
if (recipe.FindLink(product.goods, out var link)) {
link.flags |= ProductionLink.Flags.HasProduction;
float added = product.GetAmountPerRecipe(recipe.parameters.productivity);
AddLinkCoef(constraints[link.solverIndex], recipeVar, link, recipe, added);
AddLinkCoefficient(constraints[link.solverIndex], recipeVar, link, recipe, added);
float cost = product.goods.Cost();

if (cost > 0f) {
objCoefs[i] += added * cost;
objCoefficients[i] += added * cost;
}
}

Expand All @@ -389,7 +389,7 @@ private static void AddLinkCoef(Constraint cst, Variable var, ProductionLink lin

if (recipe.FindLink(option, out var link)) {
link.flags |= ProductionLink.Flags.HasConsumption;
AddLinkCoef(constraints[link.solverIndex], recipeVar, link, recipe, -ingredient.amount);
AddLinkCoefficient(constraints[link.solverIndex], recipeVar, link, recipe, -ingredient.amount);
}

links.ingredients[j] = link;
Expand All @@ -404,16 +404,16 @@ private static void AddLinkCoef(Constraint cst, Variable var, ProductionLink lin
if (recipe.FindLink(recipe.fuel, out var link)) {
links.fuel = link;
link.flags |= ProductionLink.Flags.HasConsumption;
AddLinkCoef(constraints[link.solverIndex], recipeVar, link, recipe, -fuelAmount);
AddLinkCoefficient(constraints[link.solverIndex], recipeVar, link, recipe, -fuelAmount);
}

if (recipe.fuel.HasSpentFuel(out var spentFuel) && recipe.FindLink(spentFuel, out link)) {
links.spentFuel = link;
link.flags |= ProductionLink.Flags.HasProduction;
AddLinkCoef(constraints[link.solverIndex], recipeVar, link, recipe, fuelAmount);
AddLinkCoefficient(constraints[link.solverIndex], recipeVar, link, recipe, fuelAmount);

if (spentFuel.Cost() > 0f) {
objCoefs[i] += fuelAmount * spentFuel.Cost();
objCoefficients[i] += fuelAmount * spentFuel.Cost();
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Yafc.Model/Model/ProductionTableContent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -612,7 +612,7 @@ public ChangeModulesOrEntity(RecipeRow row) {
oldFuel = row.fuel;
row.fuel = Database.voidEnergy; // step 1
}
// Store the current state of the target RecipeRow for the calcualations in Dispose
// Store the current state of the target RecipeRow for the calculations in Dispose
oldParameters = RecipeParameters.CalculateParameters(row);
}

Expand Down
Loading