diff --git a/Aetheria.Shared/Aetheria.Shared.csproj b/Aetheria.Shared/Aetheria.Shared.csproj
index a8a4c97bc..591e1f42c 100644
--- a/Aetheria.Shared/Aetheria.Shared.csproj
+++ b/Aetheria.Shared/Aetheria.Shared.csproj
@@ -26,6 +26,8 @@
+
+
diff --git a/Assets/Scripts/ServerShared/EconomyBalance.cs b/Assets/Scripts/ServerShared/EconomyBalance.cs
index 006a91ebf..770806487 100644
--- a/Assets/Scripts/ServerShared/EconomyBalance.cs
+++ b/Assets/Scripts/ServerShared/EconomyBalance.cs
@@ -138,14 +138,16 @@ public static class EconomyBalance
// The price of every made commodity (a commodity whose recipe is not raw) at the going wage: its inputs, upkeep and cheapest
// role fillers at their prices, plus the wage times its labour, over its output count. Raw and recipeless goods keep their
- // authored price; designs are not priced here. Unsettled names the goods still moving when the sweep gave up: a cycle of recipes
+ // authored price; designs are not priced here unless asked. Unsettled names the goods still moving when the sweep gave up: a cycle of recipes
// whose requirements do not shrink has no price, so none of the values are a price.
- public static Dictionary Prices(CultCache catalog, out List unsettled)
+ // With designs, the derived price of every design output that has a recipe is returned too: a reading for the report, never a
+ // price anything writes.
+ public static Dictionary Prices(CultCache catalog, out List unsettled, bool designs = false)
{
var columns = EconomyChecks.Columns(catalog);
var raw = new HashSet(columns.Where(c => Recipes.IsRaw(catalog, c.Recipe)).Select(c => c.Output), StringComparer.Ordinal);
var derived = Sweep(catalog, columns, RawWage(catalog, columns, Links(catalog, columns)), raw, out unsettled);
- return columns.Where(c => c.IsCommodity && !raw.Contains(c.Output)).Select(c => c.Output).Distinct(StringComparer.Ordinal)
+ return columns.Where(c => (c.IsCommodity || designs) && !raw.Contains(c.Output)).Select(c => c.Output).Distinct(StringComparer.Ordinal)
.ToDictionary(key => key, key => derived[key], StringComparer.Ordinal);
}
diff --git a/Assets/Scripts/ServerShared/EconomyChecks.cs b/Assets/Scripts/ServerShared/EconomyChecks.cs
index 0665cd574..cff5de88b 100644
--- a/Assets/Scripts/ServerShared/EconomyChecks.cs
+++ b/Assets/Scripts/ServerShared/EconomyChecks.cs
@@ -96,7 +96,7 @@ public static class EconomyChecks
};
// The designs some faction offers, but a Station or Turret hull, distinct and ordered by key: the designs that need a recipe.
- private static List OfferedDesigns(CultCache catalog)
+ public static List OfferedDesigns(CultCache catalog)
{
var designs = new Dictionary(StringComparer.Ordinal);
foreach (var product in catalog.GetAll().Where(p => LoadoutGenerator.IsOffered(catalog, p)))
diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs
index 7e75f95af..37ada792d 100644
--- a/Assets/Scripts/ServerShared/Settings.cs
+++ b/Assets/Scripts/ServerShared/Settings.cs
@@ -191,6 +191,9 @@ public class GameplaySettings
public int StartingCredits = 150000;
// A tuning tolerance, not a price: `economy balance` flags a chain link whose implied wage falls outside [median / k, median x k].
public float EconomyWageSpread = 2;
+ // Tuning tolerances like it: the band `economy balance --loop` checks the width of an offered gear ladder against (dearest over
+ // cheapest offered design in a category). 0 means unset: the widths are reported and no ladder is a fault.
+ public float EconomyLadderMin = 0, EconomyLadderMax = 0;
public float DurabilityQualityExponent = 2;
public float DurabilityQualityMin = 2;
public float DurabilityQualityMax = .25f;
diff --git a/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs b/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs
new file mode 100644
index 000000000..ca6264501
--- /dev/null
+++ b/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs
@@ -0,0 +1,175 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Xunit;
+
+// The player-loop section of `economy balance --loop` (EconomyLoop): rates from hand samples, minutes to afford, the ladder band and
+// the H faults, on fixture catalogs whose numbers are solved by hand. The sortie itself runs on the shipped catalog.
+public sealed class EconomyLoopTests
+{
+ private static LoopSample Sample(uint seed, int sell, int ammo, int repair, double seconds) =>
+ new LoopSample { Seed = seed, BeltKind = "belt", Weapons = "gun", SimSeconds = seconds, SellValue = sell, AmmoSpent = ammo, Repair = repair };
+
+ private static GameplaySettings Settings(float min = 0, float max = 0, int purse = 100000) =>
+ new GameplaySettings { StartingCredits = purse, EconomyLadderMin = min, EconomyLadderMax = max };
+
+ // A gear in `hardpoint` offered at `price`, with a recipe so it is an offered design.
+ private static void Offer(EconomyFixture f, string id, HardpointType hardpoint, int price)
+ {
+ var key = f.Gear(id, new[] { ("Plate", 1) });
+ f.EditItem(key, g => { g.Hardpoint = hardpoint; g.Price = price; });
+ }
+
+ private static LoopLadder Ladder(LoopReport report, string category) => report.Ladders.Single(l => l.Category == category);
+
+ [Fact]
+ public void MinutesToAffordIsPriceOverRate()
+ {
+ using var f = EconomyFixture.Healthy();
+ Offer(f, "cannon", HardpointType.Tool, 600);
+ // Gross 1000 a minute, and net 150 a minute once ammunition and repair are paid: the rate is net, per sim-minute.
+ var report = EconomyLoop.Report(f.Cache, Settings(), new[] { Sample(1, 1000, 0, 0, 60), Sample(2, 500, 100, 100, 120) });
+ Assert.Equal(575, report.Median, 9);
+ Assert.Equal(1000, report.Best, 9);
+ var cannon = Ladder(report, "Gear/Tool").Designs.Single(d => d.Key == "gear:cannon");
+ Assert.Equal(600 / 575.0, cannon.MinutesAtMedian.Value, 9);
+ Assert.Equal(0.6, cannon.MinutesAtBest.Value, 9);
+ Assert.True(cannon.Covered);
+ }
+
+ [Fact]
+ public void ADesignDearerThanThePurseIsNotCovered()
+ {
+ using var f = EconomyFixture.Healthy();
+ Offer(f, "cannon", HardpointType.Tool, 600);
+ var report = EconomyLoop.Report(f.Cache, Settings(purse: 599), new[] { Sample(1, 1000, 0, 0, 60) });
+ Assert.False(Ladder(report, "Gear/Tool").Designs.Single(d => d.Key == "gear:cannon").Covered);
+ }
+
+ [Fact]
+ public void UnsetLadderBandRaisesNoLadderFault()
+ {
+ using var f = EconomyFixture.Healthy();
+ Offer(f, "cheap", HardpointType.Reactor, 10);
+ Offer(f, "dear", HardpointType.Reactor, 1000);
+ // A settings object nobody tuned: its band is what the field defaults to.
+ var report = EconomyLoop.Report(f.Cache, new GameplaySettings(), new[] { Sample(1, 1000, 0, 0, 60) });
+ Assert.Equal(100, Ladder(report, "Gear/Reactor").WidthAuthored.Value, 9);
+ Assert.DoesNotContain(report.Faults, x => x.Invariant == EconomyLoop.HLadder);
+ }
+
+ [Fact]
+ public void LadderOutsideBandIsAFault()
+ {
+ using var f = EconomyFixture.Healthy();
+ // 2x, 40x, 20x, and the two edges of the band, 10x and 30x; Sensors holds one design alone.
+ foreach (var (hardpoint, low, high) in new[] { (HardpointType.Tool, 100, 200), (HardpointType.Thruster, 50, 2000), (HardpointType.Reactor, 100, 2000),
+ (HardpointType.Radiator, 100, 1000), (HardpointType.Ballistic, 100, 3000) })
+ {
+ Offer(f, hardpoint + "-low", hardpoint, low);
+ Offer(f, hardpoint + "-high", hardpoint, high);
+ }
+ Offer(f, "Sensors-only", HardpointType.Sensors, 5000);
+ // The fixture's own laser is a Tool at price 1: move it into the ladder it should not narrow.
+ f.EditItem("gear:laser", g => { g.Hardpoint = HardpointType.Energy; g.Price = 7; });
+ var report = EconomyLoop.Report(f.Cache, Settings(10, 30), new[] { Sample(1, 1000, 0, 0, 60) });
+ var faulted = report.Faults.Where(x => x.Invariant == EconomyLoop.HLadder).Select(x => x.Record).OrderBy(x => x, StringComparer.Ordinal).ToArray();
+ Assert.Equal(new[] { "Gear/Thruster", "Gear/Tool" }, faulted);
+ Assert.Null(Ladder(report, "Gear/Sensors").WidthAuthored);
+ Assert.Null(Ladder(report, "Gear/Energy").WidthAuthored);
+ }
+
+ [Fact]
+ public void ACategoryIsTheHullTypeTheWeaponTypeTheHardpointOrTheRecordType()
+ {
+ using var f = EconomyFixture.Healthy();
+ Offer(f, "beam", HardpointType.Energy, 100);
+ var gun = f.Cache.Get(new GameCult.Caching.CultRecordKey("gear:beam"));
+ Assert.Equal("Gear/Energy", EconomyLoop.Category(gun));
+ Assert.Equal("Hull/Ship", EconomyLoop.Category(f.Cache.Get(new GameCult.Caching.CultRecordKey("hull:skiff"))));
+ Assert.Equal("Weapon/Laser", EconomyLoop.Category(new WeaponItemData { WeaponType = WeaponType.Laser, Hardpoint = HardpointType.Energy }));
+ Assert.Equal("CargoBayData", EconomyLoop.Category(new CargoBayData()));
+ }
+
+ [Fact]
+ public void NetLossSortieIsHLoop()
+ {
+ using var f = EconomyFixture.Healthy();
+ // Gross positive in all three; net 0, -1 and 1: only the last earns anything.
+ var report = EconomyLoop.Report(f.Cache, Settings(), new[] { Sample(1, 100, 60, 40, 60), Sample(2, 100, 60, 41, 60), Sample(3, 100, 60, 39, 60) });
+ var faults = report.Faults.Where(x => x.Invariant == EconomyLoop.HLoop).Select(x => x.Record).OrderBy(x => x, StringComparer.Ordinal).ToArray();
+ Assert.Equal(new[] { "seed 1", "seed 2" }, faults);
+ }
+
+ [Fact]
+ public void DesignPricesOnlyWhenAsked()
+ {
+ using var f = EconomyFixture.Healthy();
+ var plain = EconomyBalance.Prices(f.Cache, out _);
+ Assert.Equal(new[] { "commodity:plate" }, plain.Keys.OrderBy(k => k, StringComparer.Ordinal).ToArray());
+ var withDesigns = EconomyBalance.Prices(f.Cache, out _, designs: true);
+ Assert.Equal(new[] { "commodity:plate", "gear:laser", "hull:skiff" }, withDesigns.Keys.OrderBy(k => k, StringComparer.Ordinal).ToArray());
+ Assert.Equal(plain["commodity:plate"], withDesigns["commodity:plate"]);
+ // Laser takes two plates and skiff one, with no labour on either recipe.
+ Assert.Equal(2 * plain["commodity:plate"], withDesigns["gear:laser"], 9);
+ Assert.Equal(plain["commodity:plate"], withDesigns["hull:skiff"], 9);
+ }
+
+ [Fact]
+ public void SortieLeavesTheCatalogAndMinesSomething()
+ {
+ var root = RunStartTests.FindRepoRoot();
+ var catalog = Path.Combine(root, "GameData", "Aetheria.cc");
+ var before = System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(catalog));
+ var sample = EconomyLoop.Sortie(root, 1, 60);
+ Assert.True(sample.Units > 0);
+ Assert.True(sample.Rocks > 0);
+ Assert.Equal(60, sample.SimSeconds, 1);
+ Assert.Equal(before, System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(catalog)));
+ }
+
+ [Fact]
+ public void BalanceWithoutLoopIsUnchanged()
+ {
+ using var db = AetherDb.Open();
+ var spread = AuthoredSettings.Load(db.Root).Read("GameplaySettings").EconomyWageSpread;
+ var expected = new StringWriter();
+ var expectedCode = EconomyCommand.Balance(db.Cache, spread, expected);
+ var output = new StringWriter();
+ var code = EconomyCommand.Run(new[] { "balance" }, output);
+ Assert.Equal(expectedCode, code);
+ Assert.Equal(expected.ToString(), output.ToString());
+ Assert.DoesNotContain("Player loop", output.ToString());
+ }
+
+ [Fact]
+ public void BalanceLoopPrintsTheLoopAndTheLaddersAndLetsTheirFaultsFailTheCommand()
+ {
+ using var db = AetherDb.Open();
+ var settings = AuthoredSettings.Load(db.Root).Read("GameplaySettings");
+ var report = EconomyLoop.Report(db.Cache, settings, new[] { Sample(7, 100, 100, 0, 60) });
+ var plain = new StringWriter();
+ EconomyCommand.Balance(db.Cache, settings.EconomyWageSpread, plain);
+ var output = new StringWriter();
+ Assert.Equal(1, EconomyCommand.Balance(db.Cache, settings.EconomyWageSpread, output, report));
+ var text = output.ToString();
+ Assert.StartsWith(plain.ToString().Split('\n')[0], text);
+ Assert.Contains("H-loop (1)", text);
+ Assert.Contains("Player loop (", text);
+ Assert.Contains("Ladders (", text);
+ Assert.Contains(" Gear/Reactor: ", text);
+ }
+
+ [Theory]
+ [InlineData("--cap", "5")]
+ [InlineData("--loop", "x")]
+ [InlineData("--loop", "--cap")]
+ [InlineData("--bogus")]
+ public void BalanceRefusesWhatItCannotRead(params string[] words)
+ {
+ var output = new StringWriter();
+ Assert.Equal(1, EconomyCommand.Run(new[] { "balance" }.Concat(words).ToArray(), output));
+ Assert.Contains("balance [--loop", output.ToString());
+ }
+}
diff --git a/tools/AetherDb/EconomyCommand.cs b/tools/AetherDb/EconomyCommand.cs
index 74f555862..1e3acf087 100644
--- a/tools/AetherDb/EconomyCommand.cs
+++ b/tools/AetherDb/EconomyCommand.cs
@@ -71,7 +71,7 @@ public static class EconomyCommand
{ EconomyChecks.LRecipe, EconomyChecks.LLore, EconomyChecks.LProductive, EconomyChecks.LOneKindList, EconomyChecks.LWeights, EconomyChecks.LShape, EconomyChecks.LPrice };
// A batch is compiled code under tools/AetherDb/Economy/ and runs with the operator's authority: reviewed code, never an input.
- private const string Usage = "economy report | author [...] [apply] | " + EconomyPrices.Usage + " | balance\nbalance reads the chain and changes nothing. A batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor. After the batches, author reprices every made commodity to the price its chain derives; with no batch it reprices alone.";
+ private const string Usage = "economy report | author [...] [apply] | " + EconomyPrices.Usage + " | balance [--loop [...]] [--cap ]\nbalance reads the chain and changes nothing; --loop adds the player loop (a mining sortie per seed, default seeds 1 2 3 69 97 and cap 300 sim seconds) and the offered gear ladders. A batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor. After the batches, author reprices every made commodity to the price its chain derives; with no batch it reprices alone.";
public static int Run(string[] args, TextWriter output)
{
@@ -84,8 +84,33 @@ public static class EconomyCommand
if (args.Length > 0 && args[0] == "balance")
{
using var db = AetherDb.Open();
- var spread = AuthoredSettings.Load(db.Root).Read("GameplaySettings").EconomyWageSpread;
- return Balance(db.Cache, spread, output);
+ var settings = AuthoredSettings.Load(db.Root).Read("GameplaySettings");
+ var rest = args.Skip(1).ToList();
+ var cap = EconomyLoop.DefaultCap;
+ var capAt = rest.IndexOf("--cap");
+ if (capAt >= 0 && (capAt + 1 >= rest.Count || !float.TryParse(rest[capAt + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out cap) || cap <= 0))
+ {
+ output.WriteLine(Usage);
+ return 1;
+ }
+ if (capAt >= 0) rest.RemoveRange(capAt, 2);
+ var loopAt = rest.IndexOf("--loop");
+ var seeds = new List();
+ if (loopAt >= 0)
+ foreach (var word in rest.Skip(loopAt + 1))
+ {
+ if (!uint.TryParse(word, out var seed)) { output.WriteLine(Usage); return 1; }
+ seeds.Add(seed);
+ }
+ if ((loopAt >= 0 ? rest.Count - 1 - seeds.Count : rest.Count) != 0 || (capAt >= 0 && loopAt < 0))
+ {
+ output.WriteLine(Usage);
+ return 1;
+ }
+ LoopReport loop = null;
+ if (loopAt >= 0)
+ loop = EconomyLoop.Report(db.Cache, settings, (seeds.Count == 0 ? EconomyLoop.DefaultSeeds : seeds.ToArray()).Select(seed => EconomyLoop.Sortie(db.Root, seed, cap)).ToList());
+ return Balance(db.Cache, settings.EconomyWageSpread, output, loop);
}
if (args.Length > 0 && args[0] == "author")
{
@@ -108,13 +133,14 @@ public static class EconomyCommand
// The static balance: the median implied wage, the H faults, one line per chain link by wage over the median, then the belts.
// Report-only: nothing here is a Shape invariant. Exit 1 when any fault.
- public static int Balance(CultCache catalog, double wageSpread, TextWriter output)
+ public static int Balance(CultCache catalog, double wageSpread, TextWriter output, LoopReport loop = null)
{
var report = EconomyBalance.Balance(catalog, wageSpread);
+ var faults = report.Faults.Concat(loop?.Faults ?? new List()).ToList();
var inv = System.Globalization.CultureInfo.InvariantCulture;
output.WriteLine($"median implied wage {report.WageReference.ToString("0.#####", inv)} per worker-second, spread {wageSpread.ToString(inv)}, {report.Links.Count} links, {report.Links.Count(l => l.Wage == null)} unpriced");
- output.WriteLine($"{report.Faults.Count} faults");
- foreach (var group in report.Faults.GroupBy(f => f.Invariant).OrderBy(g => g.Key, StringComparer.Ordinal))
+ output.WriteLine($"{faults.Count} faults");
+ foreach (var group in faults.GroupBy(f => f.Invariant).OrderBy(g => g.Key, StringComparer.Ordinal))
{
output.WriteLine($"{group.Key} ({group.Count()})");
foreach (var fault in group) output.WriteLine($" {fault.Record}: {fault.Message}");
@@ -130,7 +156,30 @@ public static class EconomyCommand
foreach (var y in belt.Yields)
output.WriteLine(string.Format(inv, " {0} {1:P0} | wage {2} | price {3:0.##} | cost {4:0.##}", y.Ore, y.Share, y.WageRatio.HasValue ? y.WageRatio.Value.ToString("0.##", inv) + "x" : "-", y.Price, y.Cost));
}
- return report.Faults.Count == 0 ? 0 : 1;
+ if (loop != null) PrintLoop(loop, output);
+ return faults.Count == 0 ? 0 : 1;
+ }
+
+ // The player loop and the ladders, as numbers: a line per sortie, the median and best rate and the purse, then each category's
+ // width and its designs with the minutes of income each takes to afford. No verdict beyond the faults the report raised.
+ private static void PrintLoop(LoopReport loop, TextWriter output)
+ {
+ var inv = System.Globalization.CultureInfo.InvariantCulture;
+ output.WriteLine("\nPlayer loop (seed | belt | weapons | rocks | sim s | hold full at | units | sell | ammo | repair | net per minute)");
+ foreach (var s in loop.Samples)
+ output.WriteLine(string.Format(inv, " {0} | {1} | {2} | {3} | {4:0.#} | {5} | {6} | {7} | {8} | {9} | {10:0.#}", s.Seed, s.BeltKind, s.Weapons, s.Rocks, s.SimSeconds,
+ s.HoldFullAt.HasValue ? s.HoldFullAt.Value.ToString("0.#", inv) + " s" : "never", s.Units, s.SellValue, s.AmmoSpent, s.Repair, s.RatePerMinute));
+ output.WriteLine(string.Format(inv, " median {0:0.#} per minute, best {1:0.#} per minute, purse {2}", loop.Median, loop.Best, loop.Purse));
+ string Minutes(double? m) => m.HasValue ? m.Value.ToString("0.#", inv) : "-";
+ string Width(double? w) => w.HasValue ? w.Value.ToString("0.##", inv) + "x" : "-";
+ output.WriteLine("\nLadders (category: width authored, derived; each design: price | derived | minutes at median | minutes at best | purse covers)");
+ foreach (var ladder in loop.Ladders)
+ {
+ output.WriteLine($" {ladder.Category}: {Width(ladder.WidthAuthored)}, {Width(ladder.WidthDerived)}");
+ foreach (var d in ladder.Designs)
+ output.WriteLine(string.Format(inv, " {0} ({1}) | {2} | {3} | {4} | {5} | {6}", d.Name, d.Key, d.Price, d.Derived.HasValue ? d.Derived.Value.ToString("0.##", inv) : "-",
+ Minutes(d.MinutesAtMedian), Minutes(d.MinutesAtBest), d.Covered ? "yes" : "no"));
+ }
}
// Faults grouped by invariant, then one line per good with its depth, then one line per recipe. Fails on any fault.
diff --git a/tools/AetherDb/EconomyLoop.cs b/tools/AetherDb/EconomyLoop.cs
new file mode 100644
index 000000000..309a34173
--- /dev/null
+++ b/tools/AetherDb/EconomyLoop.cs
@@ -0,0 +1,226 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+using CultMath;
+using GameCult.Caching;
+using UniRx;
+
+// The player loop of `economy balance --loop`: a measured mining sortie per seed, the income it implies, the minutes that income
+// takes to afford each offered design, and the width of each offered gear ladder against a band. It measures and reports; it changes
+// no price, yield or purse (rulings economy-numbers-are-sim-tuned-knobs, economy-tuned-by-systemic-health). Faults are report-only.
+// The sortie driver teleports the ship, so it is a measuring rig that lives here and never in ServerShared.
+public sealed class LoopSample
+{
+ public uint Seed;
+ public string BeltKind;
+ public string Weapons;
+ public int Rocks;
+ public double SimSeconds;
+ public int Units;
+ // The sim second the first unit floated, i.e. the hold was full; null if it never filled.
+ public double? HoldFullAt;
+ public int SellValue;
+ public int AmmoSpent;
+ public int Repair;
+
+ public int Net => SellValue - AmmoSpent - Repair;
+ public double RatePerMinute => SimSeconds > 0 ? Net * 60.0 / SimSeconds : 0;
+}
+
+public sealed class LoopDesign
+{
+ public string Key;
+ public string Name;
+ public int Price;
+ public double? Derived;
+ public double? MinutesAtMedian;
+ public double? MinutesAtBest;
+ public bool Covered;
+}
+
+public sealed class LoopLadder
+{
+ public string Category;
+ public List Designs;
+ // Dearest over cheapest, for a category of two or more priced designs; null otherwise.
+ public double? WidthAuthored;
+ public double? WidthDerived;
+}
+
+public sealed class LoopReport
+{
+ public IReadOnlyList Samples;
+ public double Median;
+ public double Best;
+ public int Purse;
+ public List Ladders;
+ public List Faults;
+}
+
+public static class EconomyLoop
+{
+ public const string HLoop = "H-loop", HLadder = "H-ladder";
+ public static readonly uint[] DefaultSeeds = { 1, 2, 3, 69, 97 };
+ public const float DefaultCap = 300f;
+
+ private const float Step = .02f;
+ private const float RockSeconds = 60f;
+
+ // One sortie in the demo run of this seed: the staged ship is held forty units off each rock of the arena's belt in index order,
+ // fires every weapon at it, and stops when the first unit floats (the hold is full) or at the cap. Everything it touches is its
+ // own: a scratch copy of the catalog, its own run store and its own ItemManager (a shared one advances its Random and gave the
+ // same seed different results).
+ public static LoopSample Sortie(string root, uint seed, float capSeconds)
+ {
+ var scratch = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-loop-" + Guid.NewGuid().ToString("N"))).FullName;
+ try
+ {
+ var catalog = Path.Combine(scratch, "Aetheria.cc");
+ File.Copy(Path.Combine(root, "GameData", "Aetheria.cc"), catalog);
+ new FileInfo(catalog).IsReadOnly = false;
+ using var cache = AetheriaStores.Open(catalog, runPath: Path.Combine(scratch, "run.cc"));
+ var authored = AuthoredSettings.Load(root);
+ var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { });
+ var zoneSettings = authored.Read("ZoneSettings");
+ var planetSettings = authored.Read("PlanetSettings");
+ var startingHull = File.ReadLines(Path.Combine(root, "Assets", "Resources", "Settings.asset"))
+ .Select(line => Regex.Match(line, @"^ StartingHullName: (.+)$")).First(match => match.Success).Groups[1].Value.Trim();
+
+ var scenario = new DemoTerminus();
+ var stage = new GalaxyStage(authored.Read("SectorGenerationSettings"),
+ authored.Read("SectorBackgroundSettings"), authored.Read("CastBackgroundSettings"),
+ cache, _ => { }, null, () => seed);
+ var galaxy = RunStart.Generate(scenario, stage);
+ var arena = new Zone(items, planetSettings, RunStart.GenerateArena(items, zoneSettings, planetSettings, galaxy, scenario), galaxy.Entrance, galaxy);
+ var failures = new List();
+ var player = RunStart.Stage(items, arena, scenario, startingHull, failures).Player;
+ if (failures.Count > 0) throw new InvalidOperationException($"seed {seed}: staging failed: {string.Join("; ", failures)}");
+
+ var belt = arena.Planets.First(body => body.Value is AsteroidBeltData);
+ var rocks = ((AsteroidBeltData) belt.Value).Asteroids.Length;
+ var weapons = player.Equipment.SelectMany(item => item.Behaviors.OfType()).ToArray();
+ var ammoBefore = Ammunition(items, player);
+ var units = 0;
+ arena.CargoGained.Subscribe(gain => units += gain.Stored);
+
+ for (var tick = 0; tick < 50; tick++) arena.Update(Step);
+ var ticks = 0;
+ var capTicks = (int) Math.Round(capSeconds / Step);
+ var broken = 0;
+ int? fullTick = null;
+ bool Stopped() => fullTick != null || ticks >= capTicks;
+ void Tick(Action hold) { hold(); arena.Update(Step); ticks++; if (fullTick == null && arena.FloatingItems.Count > 0) fullTick = ticks; }
+
+ for (var index = 0; index < rocks && !Stopped(); index++)
+ {
+ var rock = new ChunkId(belt.Key, index);
+ if (!arena.ChunkExists(rock)) continue;
+ void Hold()
+ {
+ var at = arena.ChunkPose(rock.Field, rock.Index).xy;
+ player.Position = new float3(at.x, player.Position.y, at.y - 40f);
+ player.Velocity = float2.zero;
+ player.Direction = new float2(0, 1);
+ player.Aim = new float3(0, 0, 1);
+ }
+ Tick(Hold);
+ Tick(Hold);
+ if (!player.SetTarget(rock)) continue;
+ foreach (var weapon in weapons) weapon.Activate();
+ for (var spent = 0; spent < (int) Math.Round(RockSeconds / Step) && arena.ChunkExists(rock) && !Stopped(); spent++) Tick(Hold);
+ if (!arena.ChunkExists(rock)) broken++;
+ }
+ foreach (var weapon in weapons) weapon.Deactivate();
+
+ var ammoAfter = Ammunition(items, player);
+ var spentOnAmmo = 0L;
+ foreach (var (data, (quantity, sample)) in ammoBefore)
+ {
+ var left = ammoAfter.TryGetValue(data, out var held) ? held.Quantity : 0;
+ if (quantity > left) spentOnAmmo += StationServices.BuyPrice(items, sample, quantity - left);
+ }
+ return new LoopSample
+ {
+ Seed = seed,
+ BeltKind = cache.Get(((AsteroidBeltData) belt.Value).Kind)?.Name ?? ((AsteroidBeltData) belt.Value).Kind.Key.Value,
+ Weapons = string.Join(", ", weapons.Select(w => items.GetData(w.Item.EquippableItem).Name).GroupBy(n => n).Select(g => g.Count() + "x " + g.Key)),
+ Rocks = broken,
+ SimSeconds = ticks * (double) Step,
+ Units = units,
+ HoldFullAt = fullTick == null ? null : fullTick * (double) Step,
+ SellValue = StationServices.OreValue(items, player.CargoBays),
+ AmmoSpent = (int) Math.Min(spentOnAmmo, int.MaxValue),
+ Repair = StationServices.RepairCost(items, player)
+ };
+ }
+ finally
+ {
+ try { Directory.Delete(scratch, true); } catch (IOException) { }
+ }
+ }
+
+ // The simple commodities the hold carries that were not mined (a mined stack names an Extracted lot), summed per commodity: ammunition
+ // and consumables. The sampled stack carries the item the price is read from.
+ private static Dictionary Ammunition(ItemManager items, Entity player)
+ {
+ var stacks = player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType())
+ .Where(stack => stack.Lot == 0 || !(items.GetLot(stack).Origin is Extracted));
+ return stacks.GroupBy(stack => items.GetData(stack)).ToDictionary(g => g.Key, g => (g.Sum(stack => stack.Quantity), g.First()));
+ }
+
+ // The category an offered design belongs to, for the width of its ladder: the one owner of this rule.
+ public static string Category(ItemData design) => design switch
+ {
+ HullData hull => "Hull/" + hull.HullType,
+ WeaponItemData weapon => "Weapon/" + weapon.WeaponType,
+ GearData gear => "Gear/" + gear.Hardpoint,
+ _ => design.GetType().Name
+ };
+
+ // Rates, minutes to afford and ladder widths from the samples and the catalog: pure, recomputed every run, nothing stored.
+ public static LoopReport Report(CultCache catalog, GameplaySettings settings, IReadOnlyList samples)
+ {
+ var rates = samples.Select(s => s.RatePerMinute).OrderBy(r => r).ToList();
+ var median = rates.Count == 0 ? 0 : rates.Count % 2 == 1 ? rates[rates.Count / 2] : (rates[rates.Count / 2 - 1] + rates[rates.Count / 2]) / 2;
+ var best = rates.Count == 0 ? 0 : rates[rates.Count - 1];
+ var derived = EconomyBalance.Prices(catalog, out _, designs: true);
+ double? Minutes(int price, double rate) => rate > 0 ? price / rate : (double?) null;
+ double? Width(IEnumerable prices)
+ {
+ var list = prices.Where(p => p > 0).ToList();
+ return list.Count >= 2 ? list.Max() / list.Min() : (double?) null;
+ }
+
+ var ladders = EconomyChecks.OfferedDesigns(catalog).GroupBy(Category).OrderBy(g => g.Key, StringComparer.Ordinal).Select(g =>
+ {
+ var designs = g.Select(design =>
+ {
+ var key = catalog.RefOf(design).Key.Value;
+ return new LoopDesign
+ {
+ Key = key, Name = design.Name, Price = design.Price, Derived = derived.TryGetValue(key, out var d) ? d : (double?) null,
+ MinutesAtMedian = Minutes(design.Price, median), MinutesAtBest = Minutes(design.Price, best), Covered = design.Price <= settings.StartingCredits
+ };
+ }).OrderBy(d => d.Price).ThenBy(d => d.Key, StringComparer.Ordinal).ToList();
+ return new LoopLadder
+ {
+ Category = g.Key, Designs = designs,
+ WidthAuthored = Width(designs.Select(d => (double) d.Price)),
+ WidthDerived = Width(designs.Where(d => d.Derived.HasValue).Select(d => d.Derived.Value))
+ };
+ }).ToList();
+
+ var faults = new List();
+ foreach (var sample in samples.Where(s => s.Net <= 0))
+ faults.Add(new EconomyFault(HLoop, "seed " + sample.Seed, $"the sortie nets {sample.Net} (sell {sample.SellValue}, ammunition {sample.AmmoSpent}, repair {sample.Repair}): no income."));
+ var (min, max) = (settings.EconomyLadderMin, settings.EconomyLadderMax);
+ if (min > 0 || max > 0)
+ foreach (var ladder in ladders)
+ foreach (var (width, which) in new[] { (ladder.WidthAuthored, "authored"), (ladder.WidthDerived, "derived") })
+ if (width.HasValue && ((min > 0 && width.Value < min) || (max > 0 && width.Value > max)))
+ faults.Add(new EconomyFault(HLadder, ladder.Category, $"the {which} ladder is {width.Value:0.##}x wide, outside the band {min:0.##} to {max:0.##}."));
+ return new LoopReport { Samples = samples, Median = median, Best = best, Purse = settings.StartingCredits, Ladders = ladders, Faults = faults };
+ }
+}