Merge eureka/aetheria-release-roles-backfill: roles backfill command and its tests (catalog blob stays master's; regenerated on the next commit)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-09 03:21:01 +02:00
commit e915f95244
5 changed files with 599 additions and 21 deletions

View file

@ -0,0 +1,185 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
// Aetheria release, cut roles-backfill, rule CB-R1: a crafted design declares roles iff a stat varies with quality,
// every declared role is read by a non-flat stat, and every seller authors one ProductRole per role. These tests read
// the shipped catalog through the real reader.
public sealed class CatalogRoleTests
{
internal static IEnumerable<(string Name, PerformanceStat Stat)> StatsOf(EquippableItemData design) =>
design.Behaviors.Where(b => b != null)
.SelectMany(b => b.GetType().GetFields().Where(f => f.FieldType == typeof(PerformanceStat))
.Select(f => ($"{b.GetType().Name}.{f.Name}", (PerformanceStat)f.GetValue(b))))
.Where(s => s.Item2?.Terms != null);
private static PerformanceStat Stat(EquippableItemData design, string field) =>
Assert.Single(design.Behaviors.SelectMany(b => b.GetType().GetFields().Where(f => f.Name == field && f.FieldType == typeof(PerformanceStat)).Select(f => (PerformanceStat)f.GetValue(b))));
internal static string[] NamedQualityRoles(PerformanceStat stat) =>
stat.Terms.Where(t => t.Source == StatSource.Quality && !string.IsNullOrEmpty(t.Role)).Select(t => t.Role).ToArray();
// CB-R1 for one stat. A non-flat stat carries exactly one Quality term, it names a declared role, and its exponent is
// positive (a role that cannot move the stat is not read). A flat stat carries no Quality term that names a role.
// Returns the fault, or null.
internal static string StatFault(PerformanceStat stat, string[] declared)
{
var quality = stat.Terms.Where(t => t.Source == StatSource.Quality).ToArray();
if (stat.Min == stat.Max)
return quality.Any(t => !string.IsNullOrEmpty(t.Role)) ? $"is flat but a Quality term names [{string.Join(", ", NamedQualityRoles(stat))}]" : null;
if (quality.Length != 1)
return $"is non-flat with {quality.Length} Quality terms, not one";
if (string.IsNullOrEmpty(quality[0].Role) || !declared.Contains(quality[0].Role))
return $"is non-flat and reads [{quality[0].Role}], not one of its declared roles [{string.Join(", ", declared)}]";
return quality[0].Exponent > 0f ? null : $"is non-flat but its role \"{quality[0].Role}\" has exponent {quality[0].Exponent}";
}
// The whole of CB-R1 over every design in the catalog: each non-flat stat reads exactly one declared role, every
// declared role is read, and every seller authors each role once. Weapons, and designs of a kind the tool keeps a role
// map for, must also carry a non-flat stat (a design with no stat at all has nothing for quality to vary).
[Fact]
public void ShippedCatalogRolesAreLive()
{
using var cache = RestoredHullsTests.OpenCatalog();
var products = cache.GetAll<FactionProductData>().ToArray();
var broken = new List<string>();
foreach (var design in cache.GetAll<EquippableItemData>().OrderBy(i => i.Name, StringComparer.Ordinal))
{
var stats = StatsOf(design).ToArray();
var varying = stats.Where(s => s.Stat.Min != s.Stat.Max).ToArray();
var declared = (design.Roles ?? new List<ItemRole>()).Select(r => r.Name).OrderBy(r => r, StringComparer.Ordinal).ToArray();
foreach (var (name, stat) in stats)
{
var fault = StatFault(stat, declared);
if (fault != null) broken.Add($"{design.Name}: {name} {fault}");
}
var read = varying.SelectMany(s => NamedQualityRoles(s.Stat)).Distinct().OrderBy(r => r, StringComparer.Ordinal).ToArray();
if (!read.SequenceEqual(declared))
broken.Add($"{design.Name}: declares [{string.Join(", ", declared)}] but non-flat stats read [{string.Join(", ", read)}]");
if (varying.Length == 0 && stats.Length > 0 && (design is WeaponItemData || Program.HasRoleMap(design)))
broken.Add($"{design.Name}: every stat is flat");
foreach (var product in products.Where(p => p.Design.Key.Equals(cache.RefOf(design).Key)))
{
var authored = (product.Roles ?? new List<ProductRole>()).Select(r => r.Role).OrderBy(r => r, StringComparer.Ordinal).ToArray();
if (!authored.SequenceEqual(declared))
broken.Add($"{design.Name}: product \"{product.Name}\" authors [{string.Join(", ", authored)}], not each of [{string.Join(", ", declared)}] once");
}
}
Assert.True(broken.Count == 0, string.Join("\n", broken));
}
private static PerformanceStat Ranged(params StatTerm[] terms) => new PerformanceStat { Min = 1f, Max = 2f, Terms = terms.ToList() };
private static StatTerm Quality(string role, float exponent = 1f) => new StatTerm { Source = StatSource.Quality, Role = role, Exponent = exponent };
// The stat check refuses what the shipped catalog does not hold but a later content cut could author.
[Fact]
public void TheStatCheckRefusesGenericQualityDeadRolesAndNamedFlatStats()
{
var declared = new[] { "barrel" };
Assert.Null(StatFault(Ranged(Quality("barrel")), declared));
Assert.Null(StatFault(new PerformanceStat { Min = 3f, Max = 3f, Terms = new List<StatTerm>() }, declared));
Assert.NotNull(StatFault(Ranged(Quality("barrel"), Quality(null)), declared));
Assert.NotNull(StatFault(Ranged(Quality("barrel", 0f)), declared));
Assert.NotNull(StatFault(Ranged(Quality(null)), declared));
Assert.NotNull(StatFault(Ranged(Quality("bogus")), declared));
Assert.NotNull(StatFault(new PerformanceStat { Min = 3f, Max = 3f, Terms = new List<StatTerm> { Quality("bogus") } }, declared));
}
// A product with no maker would title as its design and take no maker profile for its roles.
[Fact]
public void EveryShippedProductHasAMaker()
{
using var cache = RestoredHullsTests.OpenCatalog();
var makerless = cache.GetAll<FactionProductData>().Where(p => cache.Get(p.Manufacturer) == null).Select(p => p.Name).OrderBy(n => n, StringComparer.Ordinal).ToArray();
Assert.True(makerless.Length == 0, "products with no maker: " + string.Join(", ", makerless));
}
// A benefit rises with quality across 0.8x to 1.2x of its authored value (Max/Min 1.5), a cost falls across 1.2x to 0.8x
// (Max/Min 2/3). The ratio and the role are pinned, not the value, so an operator retune of a design stays green.
private static void AssertRange(EquippableItemData design, string field, bool cost, string role)
{
var stat = Stat(design, field);
Assert.Equal(cost ? 2f / 3f : 1.5f, stat.Max / stat.Min, 3);
Assert.Equal(new[] { role }, NamedQualityRoles(stat));
}
// Stats that already varied before the backfill keep their range; only their unnamed Quality term gains the role.
private static void AssertNamed(EquippableItemData design, string field, string role) =>
Assert.Equal(new[] { role }, NamedQualityRoles(Stat(design, field)));
[Fact]
public void RolesBackfillIsAuthored()
{
using var cache = RestoredHullsTests.OpenCatalog();
EquippableItemData Design(string name) => Assert.Single(cache.GetAll<EquippableItemData>(), i => i.Name == name);
string[] Roles(EquippableItemData d) => d.Roles.Select(r => r.Name).OrderBy(r => r, StringComparer.Ordinal).ToArray();
var autocannon = Design("Autocannon");
Assert.Equal(new[] { "barrel", "feed mechanism" }, Roles(autocannon));
AssertRange(autocannon, "Damage", false, "barrel");
AssertRange(autocannon, "Range", false, "barrel");
AssertRange(autocannon, "Penetration", false, "barrel");
var lrm = Design("LRMM72");
Assert.Equal(new[] { "guidance system", "thruster", "warhead" }, Roles(lrm));
AssertRange(lrm, "Damage", false, "warhead");
AssertRange(lrm, "Cooldown", true, "guidance system");
AssertRange(lrm, "LockAngle", false, "guidance system");
var srm = Design("SRMM72");
Assert.Equal(new[] { "guidance system", "thruster", "warhead" }, Roles(srm));
AssertRange(srm, "Damage", false, "warhead");
AssertRange(srm, "Cooldown", true, "guidance system");
var mine = Design("Mine Launcher");
Assert.Equal(new[] { "dispenser", "warhead" }, Roles(mine));
AssertRange(mine, "Damage", false, "warhead");
AssertRange(mine, "Range", false, "dispenser");
AssertRange(mine, "Cooldown", true, "dispenser");
AssertRange(mine, "Spread", true, "dispenser");
var layer = Assert.Single(mine.Behaviors.OfType<MineLayerData>());
Assert.Equal(2f, layer.ArmingDelay);
Assert.Equal(2f, layer.FuseDelay);
Assert.Equal(30f, layer.Lifetime);
var drive = Design("Large Drive");
Assert.Equal(new[] { "injector", "nozzle" }, Roles(drive));
AssertRange(drive, "Thrust", false, "nozzle");
AssertRange(drive, "Visibility", true, "nozzle");
AssertRange(drive, "Heat", true, "injector");
AssertRange(Design("Small Drive"), "Thrust", false, "nozzle");
// Designs whose non-flat stats named no role are pointed at the role their kind's map gives them.
AssertNamed(Design("DeathCluster"), "Count", "feed mechanism");
AssertNamed(Design("Flak Gun"), "Count", "feed mechanism");
AssertNamed(Design("GT 3K"), "MinRange", "guidance system");
AssertNamed(Design("plight"), "DamageSpread", "focusing array");
AssertNamed(Design("MoveOnPro"), "Modifier", "core");
AssertNamed(Design("MoveOnPro Station Reactor"), "Modifier", "core");
// Each seller's means come from its maker's profile; the Pirates are middling and inconsistent.
var profiles = new Dictionary<string, (float Mean, float Dev)>
{
["Zhestokost"] = (.50f, .08f), ["R&D"] = (.60f, .15f), ["DME"] = (.55f, .20f), ["Lightsail"] = (.55f, .10f), ["Pirates"] = (.45f, .22f),
};
foreach (var design in new[] { autocannon, lrm, srm, mine, drive })
{
var sellers = cache.GetAll<FactionProductData>().Where(p => p.Design.Key.Equals(cache.RefOf(design).Key)).ToArray();
Assert.NotEmpty(sellers);
foreach (var product in sellers)
{
var maker = cache.Get(product.Manufacturer);
var (mean, dev) = profiles[maker.ShortName];
Assert.Equal(Roles(design), product.Roles.Select(r => r.Role).OrderBy(r => r, StringComparer.Ordinal).ToArray());
Assert.All(product.Roles, r =>
{
Assert.Equal(mean, r.Mean, 3);
Assert.Equal(dev, r.StandardDeviation, 3);
});
}
}
Assert.Contains(cache.GetAll<FactionProductData>(), p => p.Design.Key.Equals(cache.RefOf(autocannon).Key) && cache.Get(p.Manufacturer).ShortName == "Pirates");
}
}

View file

@ -283,7 +283,17 @@ public sealed partial class RunStartTests
[Fact]
public void TheEnvelopeComesFromTheGear()
{
var (_, longinus, _) = EvFleet();
// The Longinus is fitted by name, not generated: what the generator picks follows the item stream, and every role a
// product authors draws from it (roles-backfill), so a generated hull would stop carrying these drives.
Ship longinus = null;
var scenario = new Scripted(false, stage =>
{
stage.Player(stage.Bare("Djinni"), float2(-50000, -50000));
longinus = stage.Place(EvLonginus(stage), float2(-30000, -30000), facing: float2(0, 1)) as Ship;
});
var (_, _, _, failures) = Launch(scenario, Inputs(() => GalaxySeed));
Assert.True(failures.Count == 0, string.Join("; ", failures));
Assert.NotNull(longinus);
EvSettle(longinus);
// A thruster's Thrust property is refreshed only while it fires: turn each way so the flank thrusters hold what
// they push with, then read the envelope at rest.
@ -306,11 +316,18 @@ public sealed partial class RunStartTests
var envelope = longinus.Envelope;
var mass = longinus.Mass;
Assert.InRange(envelope.Forward, 500000f / mass * .99f, 500000f / mass * 1.01f);
// The shipped Large Drive's Thrust is a range its lot's roll moves it through, so each drive pushes within the catalog's
// range and the envelope forward is what the two push together.
var catalogThrust = _cache.GetAll<GearData>().Single(gear => gear.Name == "Large Drive").Behaviors.OfType<ThrusterData>().Single().Thrust;
Assert.All(largeDrives, t => Assert.InRange(t.Thrust, catalogThrust.Min * .99f, catalogThrust.Max * 1.01f));
var forward = largeDrives.Sum(t => t.Thrust) / mass;
Assert.InRange(envelope.Forward, forward * .99f, forward * 1.01f);
Assert.Equal(0f, envelope.Reverse);
var flankAcceleration = flanks.Max(t => t.Thrust) / mass;
Assert.InRange(envelope.Left, flankAcceleration * .99f, flankAcceleration * 1.01f);
Assert.InRange(envelope.Right, flankAcceleration * .99f, flankAcceleration * 1.01f);
// One Talaria pushes each way, and each has its own lot's thrust: the sides are the two flanks' accelerations.
var flankAccelerations = flanks.Select(t => t.Thrust / mass).OrderBy(a => a).ToArray();
var sides = new[] { envelope.Left, envelope.Right }.OrderBy(a => a).ToArray();
Assert.InRange(sides[0], flankAccelerations[0] * .99f, flankAccelerations[0] * 1.01f);
Assert.InRange(sides[1], flankAccelerations[1] * .99f, flankAccelerations[1] * 1.01f);
var clockwise = thrusters.Where(t => t.Torque > settings.TorqueFloor).Sum(t => t.Torque * t.Thrust) * settings.TorqueMultiplier / mass;
var counterClockwise = thrusters.Where(t => t.Torque < -settings.TorqueFloor).Sum(t => -t.Torque * t.Thrust) * settings.TorqueMultiplier / mass;
Assert.InRange(envelope.Clockwise, clockwise * .99f, clockwise * 1.01f);

View file

@ -0,0 +1,228 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using Xunit;
// AetherDb's roles-backfill command (aetheria-release, cut roles-backfill) run on a scratch copy of the shipped catalog,
// with the designs it backfills put back to the state they shipped in before it: flat stats at the middle of their range,
// no roles, no seller quality, and the unnamed Quality terms of the stats that already varied. The shipped catalog is the
// oracle, since the command produced it.
public sealed class RolesBackfillCommandTests : IDisposable
{
private static readonly string[] Flattened = { "Autocannon", "LRMM72", "SRMM72", "Mine Launcher", "Large Drive", "Small Drive" };
// Designs that shipped with non-flat stats whose Quality term named no role; the field is the stat to unname.
private static readonly (string Design, string Field)[] Unnamed =
{
("DeathCluster", "Count"), ("Flak Gun", "Count"), ("GT 3K", "MinRange"), ("plight", "DamageSpread"),
("MoveOnPro", "Modifier"), ("MoveOnPro Station Reactor", "Modifier"),
};
private readonly string _root = Path.Combine(Path.GetTempPath(), "roles-backfill-" + Guid.NewGuid().ToString("N"));
private string CatalogPath => Path.Combine(_root, "GameData", "Aetheria.cc");
private readonly Dictionary<string, string> _shipped = new Dictionary<string, string>();
public RolesBackfillCommandTests()
{
Directory.CreateDirectory(Path.Combine(_root, "GameData"));
File.Copy(Path.Combine(AetherDb.FindRoot(), "GameData", "Aetheria.cc"), CatalogPath);
using var cache = new CultCache(ScopedRegistry());
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
var products = cache.GetAll<FactionProductData>().ToArray();
foreach (var design in cache.GetAll<EquippableItemData>().Where(d => Flattened.Contains(d.Name) || Unnamed.Any(u => u.Design == d.Name)))
_shipped[design.Name] = Describe(cache, design, products);
}
// A registry scoped to the shipped assembly, so this test assembly's own documents never reach the real catalog.
private static CultDocumentRegistry ScopedRegistry() => CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
// Puts the named designs back to the state they shipped in before the backfill, through a registry scoped to the shipped
// assembly (as PiratesFactionCommandTests strips its faction).
private void Reset(bool flattened, bool unnamed)
{
using var cache = new CultCache(ScopedRegistry());
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
var designs = cache.GetAll<EquippableItemData>().ToArray();
var products = cache.GetAll<FactionProductData>().ToArray();
var changed = new List<object>();
if (flattened)
foreach (var design in designs.Where(d => Flattened.Contains(d.Name)))
{
foreach (var (_, stat) in CatalogRoleTests.StatsOf(design))
{
if (stat.Min != stat.Max) stat.Min = stat.Max = (stat.Min + stat.Max) / 2f;
// The drives shipped with unnamed Quality terms on their flat stats (roles-migrate); the command keeps those
// exponents and names them. The other four shipped with no term at all.
if (design.Name.EndsWith(" Drive", StringComparison.Ordinal)) foreach (var term in stat.Terms.Where(t => t.Source == StatSource.Quality)) term.Role = null;
else stat.Terms.RemoveAll(t => t.Source == StatSource.Quality);
}
design.Roles = new List<ItemRole>();
changed.Add(design);
// Small Drive shipped with its sellers' quality already authored (roles-migrate); only its stats were flat.
foreach (var product in products.Where(p => design.Name != "Small Drive" && p.Design.Key.Equals(cache.RefOf(design).Key)))
{
product.Roles = new List<ProductRole>();
changed.Add(product);
}
}
if (unnamed)
foreach (var (name, field) in Unnamed)
{
var design = designs.Single(d => d.Name == name);
foreach (var term in Stat(design, field).Terms.Where(t => t.Source == StatSource.Quality)) term.Role = null;
changed.Add(design);
}
if (changed.Count > 0)
cache.Commit(batch =>
{
foreach (var document in changed) batch.Upsert(document.GetType(), document, cache.RefOf(document).Key);
});
cache.FlushAsync().Wait();
// Then the record AetherDb's process-wide registry demands in this test host (as PiratesFactionCommandTests).
using (var plain = new CultCache())
{
plain.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
plain.Upsert(new TestCatalogGlobal { Name = "Temperament" });
plain.FlushAsync().Wait();
}
}
public void Dispose() => Directory.Delete(_root, true);
private static PerformanceStat Stat(EquippableItemData design, string field) =>
Assert.Single(CatalogRoleTests.StatsOf(design), s => s.Name.EndsWith("." + field)).Stat;
// Everything the command decides about one design: its roles, each stat's range, role and exponent, and its sellers' role quality.
private static string Describe(CultCache cache, EquippableItemData design, FactionProductData[] products)
{
static string F(float v) => float.IsInfinity(v) ? v.ToString() : ((double) v).ToString("G5");
var stats = CatalogRoleTests.StatsOf(design).Select(s =>
$"{s.Name} {F(s.Stat.Min)}..{F(s.Stat.Max)} {string.Join("+", s.Stat.Terms.Where(t => t.Source == StatSource.Quality && !string.IsNullOrEmpty(t.Role)).Select(t => $"{t.Role}^{F(t.Exponent)}"))}");
var sellers = products.Where(p => p.Design.Key.Equals(cache.RefOf(design).Key)).OrderBy(p => p.Name, StringComparer.Ordinal)
.Select(p => $"{p.Name}: " + string.Join(", ", (p.Roles ?? new List<ProductRole>()).OrderBy(r => r.Role, StringComparer.Ordinal)
.Select(r => $"{r.Role} {F(r.Mean)}/{F(r.StandardDeviation)}")));
var roles = "roles " + string.Join(", ", (design.Roles ?? new List<ItemRole>()).Select(r => r.Name).OrderBy(r => r, StringComparer.Ordinal));
return string.Join("\n", new[] { roles }.Concat(stats).Concat(sellers));
}
private Dictionary<string, string> Read()
{
var db = AetherDb.Open(root: _root);
try
{
var products = db.Cache.GetAll<FactionProductData>().ToArray();
return db.Cache.GetAll<EquippableItemData>().Where(d => _shipped.ContainsKey(d.Name))
.ToDictionary(d => d.Name, d => Describe(db.Cache, d, products));
}
finally { db.Cache.Dispose(); }
}
[Fact]
public void A_dry_run_writes_nothing_and_apply_lands_what_the_catalog_ships_and_replays_as_a_no_op()
{
Reset(flattened: true, unnamed: true);
var before = File.ReadAllBytes(CatalogPath);
var start = Read();
Assert.All(_shipped.Keys, name => Assert.NotEqual(_shipped[name], start[name]));
Assert.Equal(0, Program.RolesBackfill(apply: false, root: _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root));
var landed = File.ReadAllBytes(CatalogPath);
Assert.NotEqual(before, landed);
var after = Read();
foreach (var name in _shipped.Keys.OrderBy(n => n, StringComparer.Ordinal))
Assert.Equal(_shipped[name], after[name]);
// A second apply finds every stat ranged and named and every seller authored, and writes nothing.
Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root));
Assert.Equal(landed, File.ReadAllBytes(CatalogPath));
}
// Only unnamed Quality terms to name: no seller and no range changes, and apply must still land the designs.
[Fact]
public void Naming_an_unnamed_term_alone_lands_without_touching_ranges_or_sellers()
{
Reset(flattened: false, unnamed: true);
var before = File.ReadAllBytes(CatalogPath);
var start = Read();
Assert.All(Unnamed.Select(u => u.Design), name => Assert.NotEqual(_shipped[name], start[name]));
Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root));
Assert.NotEqual(before, File.ReadAllBytes(CatalogPath));
var after = Read();
foreach (var (name, _) in Unnamed) Assert.Equal(_shipped[name], after[name]);
}
// The exponents a first apply authors do not depend on which designs it targets: applied to the base-shaped catalog, the
// command reproduces the shipped exponents of Autocannon and LRMM72, which differ across stats (the mode is not one value).
[Fact]
public void Apply_on_the_base_shaped_catalog_reproduces_the_shipped_exponents()
{
static Dictionary<string, float> Exponents(EquippableItemData d) => CatalogRoleTests.StatsOf(d)
.SelectMany(s => s.Stat.Terms.Where(t => t.Source == StatSource.Quality && !string.IsNullOrEmpty(t.Role)).Select(t => (s.Name, t.Exponent)))
.ToDictionary(x => x.Name, x => x.Exponent);
var designs = new[] { "Autocannon", "LRMM72" };
Dictionary<string, Dictionary<string, float>> shipped;
Dictionary<string, Dictionary<string, float>> Read(EquippableItemData[] all) => all.Where(d => designs.Contains(d.Name)).ToDictionary(d => d.Name, Exponents);
using (var catalog = RestoredHullsTests.OpenCatalog()) shipped = Read(catalog.GetAll<EquippableItemData>().ToArray());
Assert.All(designs, name => Assert.True(shipped[name].Values.Distinct().Count() > 1, name + " exponents are one value; the test would not tell a mode from a default"));
Reset(flattened: true, unnamed: true);
Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root));
var db = AetherDb.Open(root: _root);
Dictionary<string, Dictionary<string, float>> after;
try { after = Read(db.Cache.GetAll<EquippableItemData>().ToArray()); }
finally { db.Cache.Dispose(); }
foreach (var name in designs) Assert.Equal(shipped[name].OrderBy(x => x.Key, StringComparer.Ordinal), after[name].OrderBy(x => x.Key, StringComparer.Ordinal));
}
// A seller that authors one of a design's two roles gets only the other one added, and keeps the one it authored.
[Fact]
public void A_seller_with_one_of_two_roles_authored_gains_only_the_missing_role()
{
Reset(flattened: false, unnamed: false);
var db = AetherDb.Open(catalogWritable: true, root: _root);
var autocannon = db.Cache.GetAll<WeaponItemData>().Single(weapon => weapon.Name == "Autocannon");
var seller = db.Cache.GetAll<FactionProductData>().OrderBy(p => p.Name, StringComparer.Ordinal).First(p => p.Design.Key.Equals(db.Cache.RefOf(autocannon).Key) && p.Roles.Count == 2);
var kept = seller.Roles.OrderBy(r => r.Role, StringComparer.Ordinal).First();
kept.Mean = .91f;
seller.Roles = new List<ProductRole> { kept };
var sellerName = seller.Name;
var keptRole = kept.Role;
db.Cache.Commit(batch => batch.Upsert(typeof(FactionProductData), seller, db.Cache.RefOf(seller).Key));
db.Cache.Dispose();
Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root));
db = AetherDb.Open(root: _root);
try
{
var after = db.Cache.GetAll<FactionProductData>().Single(p => p.Name == sellerName);
Assert.Equal(new[] { "barrel", "feed mechanism" }, after.Roles.Select(r => r.Role).OrderBy(r => r, StringComparer.Ordinal).ToArray());
Assert.Equal(.91f, after.Roles.Single(r => r.Role == keptRole).Mean, 3);
}
finally { db.Cache.Dispose(); }
}
[Fact]
public void A_design_the_catalog_does_not_hold_refuses_and_lands_nothing()
{
Reset(flattened: false, unnamed: false);
var db = AetherDb.Open(catalogWritable: true, root: _root);
var autocannon = db.Cache.GetAll<WeaponItemData>().Single(weapon => weapon.Name == "Autocannon");
autocannon.Name = "Autocannon (renamed)";
db.Cache.Commit(batch => batch.Upsert(typeof(WeaponItemData), autocannon, db.Cache.RefOf(autocannon).Key));
db.Cache.Dispose();
var before = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => Program.RolesBackfill(apply: true, root: _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
}
}

View file

@ -2,7 +2,7 @@ using System.Linq;
using Xunit;
// A weapon is thermally online only while its performance exceeds the shutdown threshold (Entity.UpdatePerformance
// compares against EntitySettings.ShutdownPerformance), and wear runs at full rate below it. Hull cells
// compares against the catalog settings' DefaultEntitySettings.ShutdownPerformance, which production clones), and wear runs at full rate below it. Hull cells
// start at Entity.StartingCellTemperature, so every shipped weapon must perform there, or a ship fitted with it
// can never fire it. The catalog comes from the shipped GameData/Aetheria.cc and the temperature from the
// constant Entity builds its cells with, so a unit slip in authoring (celsius for kelvin) fails here.
@ -15,7 +15,7 @@ public sealed class ShippedWeaponOperabilityTests
var weapons = cache.GetAll<GearData>().OfType<WeaponItemData>().ToArray();
Assert.NotEmpty(weapons);
var threshold = new EntitySettings().ShutdownPerformance;
var threshold = RestoredHullsTests.Settings().DefaultEntitySettings.ShutdownPerformance;
Assert.True(threshold > 0f);
var dead = weapons.Where(weapon => weapon.Performance(Entity.StartingCellTemperature) <= threshold)

View file

@ -42,11 +42,12 @@ public static class Program
case "field-kinds": return FieldKindsCatalog(args.Contains("apply"));
case "pd-gear": return PdGearCatalog(args.Contains("apply"));
case "mine-launcher": return MineLauncherCatalog(args.Contains("apply"));
case "roles-backfill": return RolesBackfill(args.Contains("apply"));
case "pirates-faction":
Console.OutputEncoding = new System.Text.UTF8Encoding(false);
return PiratesFaction(args.Contains("apply"));
default:
Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear <Type.Member>]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply], ship-authoring create|inspect|validate|compose, field-kinds [apply], mine-launcher [apply], pd-gear [apply], pirates-faction [apply]");
Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear <Type.Member>]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply], ship-authoring create|inspect|validate|compose, field-kinds [apply], mine-launcher [apply], roles-backfill [apply], pd-gear [apply], pirates-faction [apply]");
return 1;
}
}
@ -144,13 +145,13 @@ public static class Program
{
["Damage"] = "barrel", ["Range"] = "barrel", ["Velocity"] = "barrel", ["Penetration"] = "barrel",
["Cooldown"] = "feed mechanism", ["Spread"] = "feed mechanism", ["Heat"] = "feed mechanism",
["Visibility"] = "feed mechanism", ["Energy"] = "feed mechanism",
["Visibility"] = "feed mechanism", ["Energy"] = "feed mechanism", ["Count"] = "feed mechanism",
};
private static readonly Dictionary<string, string> EnergyWeaponRoles = new Dictionary<string, string>
{
["Damage"] = "focusing array", ["Range"] = "focusing array", ["Velocity"] = "focusing array",
["Penetration"] = "focusing array",
["Penetration"] = "focusing array", ["DamageSpread"] = "focusing array",
["Energy"] = "power coupling", ["Heat"] = "power coupling", ["ChargeTime"] = "power coupling",
["ChargeEnergy"] = "power coupling", ["ChargeHeat"] = "power coupling", ["Cooldown"] = "power coupling",
["Spread"] = "power coupling", ["Visibility"] = "power coupling",
@ -161,11 +162,21 @@ public static class Program
["Damage"] = "warhead", ["Penetration"] = "warhead", ["DamageSpread"] = "warhead",
["LockSpeed"] = "guidance system", ["SensorImpact"] = "guidance system", ["LockAngle"] = "guidance system",
["DirectionImpact"] = "guidance system", ["Decay"] = "guidance system", ["Range"] = "guidance system",
["MinRange"] = "guidance system",
["Cooldown"] = "guidance system", ["Spread"] = "guidance system", ["Visibility"] = "guidance system",
["Energy"] = "guidance system", ["Heat"] = "guidance system",
["Thrust"] = "thruster", ["MissileVelocity"] = "thruster", ["Velocity"] = "thruster",
};
// Warhead and dispenser: a mine layer is a launcher without guidance or thrust, so its stats split between the
// charge it lays and the mechanism that lays it. ArmingDelay, FuseDelay and Lifetime are timings, not stats.
private static readonly Dictionary<string, string> MineLayerRoles = new Dictionary<string, string>
{
["Damage"] = "warhead", ["Penetration"] = "warhead", ["DamageSpread"] = "warhead",
["Range"] = "dispenser", ["Cooldown"] = "dispenser", ["Spread"] = "dispenser", ["Velocity"] = "dispenser",
["Energy"] = "dispenser", ["Heat"] = "dispenser", ["Visibility"] = "dispenser",
};
private static readonly Dictionary<string, string> RadiatorRoles = new Dictionary<string, string>
{
["Emissivity"] = "fins", ["WasteHeat"] = "fins",
@ -175,7 +186,7 @@ public static class Program
private static readonly Dictionary<string, string> ReactorRoles = new Dictionary<string, string>
{
["Charge"] = "core", ["Efficiency"] = "core",
["Charge"] = "core", ["Efficiency"] = "core", ["Modifier"] = "core",
["OverloadEfficiency"] = "regulator", ["ThrottlingFactor"] = "regulator",
};
@ -215,6 +226,17 @@ public static class Program
},
};
// One Mean / StandardDeviation per maker, applied to every role of a design the maker sells (catalog-growth
// addenda, "Maker profiles"); the Pirates are middling and inconsistent (pirates-record).
private static readonly Dictionary<string, (float Mean, float Dev)> MakerProfiles = new Dictionary<string, (float Mean, float Dev)>
{
["Zhestokost"] = (.50f, .08f), ["AU"] = (.50f, .12f), ["Lightsail"] = (.55f, .10f), ["R&D"] = (.60f, .15f),
["Lucent"] = (.60f, .15f), ["NiteLife"] = (.55f, .12f), ["Finch"] = (.65f, .20f), ["Alakrita"] = (.60f, .14f),
["DME"] = (.55f, .20f), ["Adrasteia"] = (.60f, .10f),
};
private static readonly (float Mean, float Dev) PirateProfile = (.45f, .22f);
private static string KindOf(EquippableItemData item) =>
item is HullData hull ? $"Hull/{hull.HullType}"
: item is DockingBayData ? "DockingBay"
@ -225,7 +247,8 @@ public static class Program
// The field->role map for one design, or null when its kind carries no per-part behaviour stat at all
// (CargoBay, DockingBay, ControlModule, Hull/Station, Hull/Turret -- none of their behaviours read
// StatSource.Quality today, so there is no natural role to author and the report says so per design).
private static Dictionary<string, string> RoleMapFor(EquippableItemData item, string kind) => kind switch
private static Dictionary<string, string> RoleMapFor(EquippableItemData item, string kind) =>
item.Behaviors != null && item.Behaviors.OfType<MineLayerData>().Any() ? MineLayerRoles : kind switch
{
"Weapon/Ballistic" => BallisticWeaponRoles,
"Weapon/Energy" => EnergyWeaponRoles,
@ -239,6 +262,9 @@ public static class Program
_ => null,
};
// Whether CB-R1 maps this design's stats to roles; the catalog test asks the tool, so it keeps no copy of the kinds.
public static bool HasRoleMap(EquippableItemData item) => RoleMapFor(item, KindOf(item)) != null;
private sealed record RoleAuthoring(
EquippableItemData Item, string Kind, List<(string Behavior, string Field, string Role)> StatsAssigned,
List<string> RolesDeclared, string SkipReason);
@ -1511,12 +1537,6 @@ public static class Program
flakData.AmmoType = db.Cache.RefOf(ammunition); flakData.MagazineSize = 40; flakData.ReloadTime = 4f;
Track(flakData, 20f);
var makers = new Dictionary<string, (float Mean, float Dev)>
{
["Zhestokost"] = (.50f, .08f), ["AU"] = (.50f, .12f), ["Lightsail"] = (.55f, .10f), ["R&D"] = (.60f, .15f),
["Lucent"] = (.60f, .15f), ["NiteLife"] = (.55f, .12f), ["Finch"] = (.65f, .20f), ["Alakrita"] = (.60f, .14f),
["DME"] = (.55f, .20f), ["Adrasteia"] = (.60f, .10f),
};
var products = new (WeaponItemData Design, string Name, string Maker, string Description)[]
{
(gun, "Waykeeper", "Lightsail", "Freight first, questions later. Keeps a hauler's paint unscratched through a full salvo."),
@ -1547,7 +1567,7 @@ public static class Program
Console.WriteLine("\nNew products:");
foreach (var (design, name, maker, description) in products)
{
var (mean, dev) = makers[maker];
var (mean, dev) = MakerProfiles[maker];
Console.WriteLine($" {design.Name} -> \"{name}\" by {maker}, every role mean {mean:0.##} dev {dev:0.##}: {description}");
}
@ -1564,7 +1584,7 @@ public static class Program
foreach (var design in new[] { gun, laser, flak }) keys[design] = batch.Upsert(typeof(WeaponItemData), design);
foreach (var (design, name, maker, description) in products)
{
var (mean, dev) = makers[maker];
var (mean, dev) = MakerProfiles[maker];
batch.Upsert(typeof(FactionProductData), new FactionProductData
{
Name = name,
@ -1690,6 +1710,134 @@ public static class Program
return 0;
}
// Aetheria release, cut roles-backfill (rule CB-R1): designs that shipped with flat stats and no roles get the
// roles their kind's map names, and every seller authors a ProductRole per role. Each mapped stat becomes a range
// of value x (0.8, 1.2) that rises with quality for a benefit and falls for a cost, read through one Quality term
// naming its role (exponent: the mode of the kind's existing designs on that field, 1 when there is none; an
// existing Quality term keeps its exponent). Zero stats stay flat. A mapped stat that already varies keeps its range
// and only has its unnamed Quality term pointed at the role. Small Drive joined the set because it declares roles that
// no non-flat stat reads; DeathCluster, Flak Gun, GT 3K, plight and the two MoveOnPros because each had a non-flat stat
// whose Quality term named no role (CB-R1: each non-flat stat reads exactly one declared role). Idempotent: a design with
// no flat mapped stat and no unnamed one is left alone, a product with a role is left alone. Dry run unless passed "apply".
private static readonly string[] BackfillDesigns = { "Autocannon", "LRMM72", "SRMM72", "Mine Launcher", "Large Drive", "Small Drive",
"DeathCluster", "Flak Gun", "GT 3K", "plight", "MoveOnPro", "MoveOnPro Station Reactor" };
// Stats the backfill names but never ranges: a shot count is whole, and which way a launcher's MinRange should fall is
// each design's own call (GT 3K authors it as a cost already).
private static readonly HashSet<string> RoleOnlyStats = new HashSet<string>(StringComparer.Ordinal) { "Count", "MinRange" };
private static readonly HashSet<string> CostStats = new HashSet<string>(StringComparer.Ordinal)
{
"Cooldown", "Spread", "Heat", "Visibility", "Energy", "EnergyUsage", "ChargeTime", "ChargeEnergy", "ChargeHeat",
"SensorImpact", "DirectionImpact", "Decay",
};
private static IEnumerable<PerformanceStat> StatsOf(EquippableItemData item) =>
(item.Behaviors ?? new List<BehaviorData>()).Where(b => b != null)
.SelectMany(b => b.GetType().GetFields().Where(f => f.FieldType == typeof(PerformanceStat)).Select(f => f.GetValue(b) as PerformanceStat))
.Where(s => s?.Terms != null);
public static int RolesBackfill(bool apply, string root = null)
{
var db = AetherDb.Open(catalogWritable: apply, root: root);
var items = db.Cache.GetAll<EquippableItemData>().ToArray();
var products = db.Cache.GetAll<FactionProductData>().ToArray();
var targets = BackfillDesigns.Select(name => items.Where(i => i.Name == name).ToArray())
.Select((found, i) => found.Length == 1 ? found[0] : throw new InvalidOperationException(
$"Expected exactly one design named \"{BackfillDesigns[i]}\", found {found.Length}.")).ToArray();
// The precedent is read once, before any target changes: the named Quality exponents of every design that declares
// roles, so a design the command names later never leaves the pool another target draws from, and a design that
// starts with no named term contributes nothing.
var precedent = items.Where(i => i.Roles != null && i.Roles.Count > 0)
.SelectMany(i => (i.Behaviors ?? new List<BehaviorData>()).Where(b => b != null)
.SelectMany(b => b.GetType().GetFields().Where(f => f.FieldType == typeof(PerformanceStat)).Select(f => (Kind: KindOf(i), Field: f.Name, Stat: f.GetValue(b) as PerformanceStat))))
.Where(x => x.Stat?.Terms != null && x.Stat.Min != x.Stat.Max)
.SelectMany(x => x.Stat.Terms.Where(t => t.Source == StatSource.Quality && !string.IsNullOrEmpty(t.Role)).Select(t => (x.Kind, x.Field, t.Exponent)))
.ToArray();
float ExponentFor(string kind, string field)
{
var modes = precedent.Where(p => p.Kind == kind && p.Field == field).Select(p => p.Exponent)
.GroupBy(e => e).OrderByDescending(g => g.Count()).ThenBy(g => g.Key).Select(g => g.Key).ToArray();
return modes.Length > 0 ? modes[0] : 1f;
}
var changedDesigns = new List<(EquippableItemData Document, CultRecordKey Key)>();
foreach (var design in targets)
{
var kind = KindOf(design);
var map = RoleMapFor(design, kind) ?? throw new InvalidOperationException($"\"{design.Name}\" has no role map.");
var lines = new List<string>();
foreach (var behavior in design.Behaviors.Where(b => b != null))
foreach (var field in behavior.GetType().GetFields().Where(f => f.FieldType == typeof(PerformanceStat)))
{
var stat = field.GetValue(behavior) as PerformanceStat;
if (stat == null) continue;
if (!map.TryGetValue(field.Name, out var role)) continue;
stat.Terms ??= new List<StatTerm>();
var quality = stat.Terms.FirstOrDefault(t => t.Source == StatSource.Quality);
var value = stat.Min;
if (stat.Min == stat.Max)
{
if (RoleOnlyStats.Contains(field.Name)) continue; // a count or a per-design bound: never ranged
if (stat.Min == 0f || float.IsInfinity(stat.Min)) continue;
(stat.Min, stat.Max) = CostStats.Contains(field.Name) ? (value * 1.2f, value * .8f) : (value * .8f, value * 1.2f);
quality ??= new StatTerm { Source = StatSource.Quality, Exponent = ExponentFor(kind, field.Name) };
if (!stat.Terms.Contains(quality)) stat.Terms.Add(quality);
}
else if (quality == null || !string.IsNullOrEmpty(quality.Role)) continue; // already named, or not quality-driven
quality.Role = role;
lines.Add($" {behavior.GetType().Name}.{field.Name,-16} {value:0.####} -> {stat.Min:0.####}..{stat.Max:0.####} {role} ^{quality.Exponent:0.##}");
}
if (lines.Count == 0) continue;
design.Roles = StatsOf(design).Where(s => s.Min != s.Max)
.SelectMany(s => s.Terms.Where(t => t.Source == StatSource.Quality && !string.IsNullOrEmpty(t.Role)).Select(t => t.Role))
.Distinct().OrderBy(r => r, StringComparer.Ordinal).Select(r => new ItemRole { Name = r }).ToList();
Console.WriteLine($" {design.Name} ({kind}) roles [{string.Join(", ", design.Roles.Select(r => r.Name))}]");
foreach (var line in lines) Console.WriteLine(line);
changedDesigns.Add((design, db.Cache.RefOf(design).Key));
}
var changedProducts = new List<(FactionProductData Document, CultRecordKey Key)>();
foreach (var design in targets)
foreach (var product in products.Where(p => p.Design.Key.Equals(db.Cache.RefOf(design).Key)).OrderBy(p => p.Name, StringComparer.Ordinal))
{
var maker = db.Cache.Get(product.Manufacturer);
var profile = maker?.Name == "Pirates" ? PirateProfile
: maker != null && MakerProfiles.TryGetValue(maker.ShortName, out var found) ? found
: throw new InvalidOperationException($"No maker profile for the seller of \"{design.Name}\" ({maker?.ShortName ?? "no maker"}).");
product.Roles ??= new List<ProductRole>();
var missing = design.Roles.Select(r => r.Name).Where(r => product.Roles.All(p => p.Role != r)).ToArray();
if (missing.Length == 0) continue;
foreach (var role in missing)
product.Roles.Add(new ProductRole { Role = role, Mean = profile.Mean, StandardDeviation = profile.Dev });
Console.WriteLine($" {product.Name,-28} ({design.Name}, {maker.ShortName}) {string.Join(", ", missing)} at {profile.Mean:0.00}/{profile.Dev:0.00}");
changedProducts.Add((product, db.Cache.RefOf(product).Key));
}
if (changedDesigns.Count == 0 && changedProducts.Count == 0)
{
Console.WriteLine("Roles backfill is already authored; nothing to do.");
return 0;
}
Console.WriteLine($"\n{changedDesigns.Count} design(s) and {changedProducts.Count} product(s) to author.");
if (!apply)
{
Console.WriteLine("Dry run. Pass \"apply\" to land them.");
return 0;
}
foreach (var (document, _) in changedDesigns) CultRecordRefs.Validate(document);
foreach (var (document, _) in changedProducts) CultRecordRefs.Validate(document);
db.Cache.Commit(batch =>
{
foreach (var (document, key) in changedDesigns) batch.Upsert(document is WeaponItemData ? typeof(WeaponItemData) : typeof(GearData), document, key);
foreach (var (document, key) in changedProducts) batch.Upsert(typeof(FactionProductData), document, key);
});
Console.WriteLine($"Landed {changedDesigns.Count} design(s) and {changedProducts.Count} product(s) in Aetheria.cc");
return 0;
}
// Aetheria release, cut pirates-record (rulings pirates-record-content, catalog-grows-generic-designs-branded-products):
// the Pirates faction and eight rebrands of other makers' designs, named in emoji. The Pirates own no design: their range
// is what they took, so every product points at a design someone else also makes. Each product carries one ProductRole per
@ -1749,7 +1897,7 @@ public static class Program
{
var design = DesignByName(r.Design);
return (Design: design, r.Name, r.Description,
Roles: (design.Roles ?? new List<ItemRole>()).Select(role => new ProductRole { Role = role.Name, Mean = .45f, StandardDeviation = .22f }).ToList());
Roles: (design.Roles ?? new List<ItemRole>()).Select(role => new ProductRole { Role = role.Name, Mean = PirateProfile.Mean, StandardDeviation = PirateProfile.Dev }).ToList());
}).ToArray();
Console.WriteLine($"New faction \"{pirates.Name}\": influence {pirates.InfluenceDistance}, names \"{nameFile.Name}\", allegiance 1.0 to {pirates.Allegiance.Count} factions.");