Merge eureka/aetheria-release-product-lines-weapons (cut-product-lines-weapons r5, h4) into master

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-17 04:48:14 +02:00
commit 6179846249
28 changed files with 1032 additions and 216 deletions

View file

@ -172,7 +172,8 @@ public sealed class CatalogRoleTests
Assert.Equal(generic, design.Name);
Assert.Equal(Program.Renames.Single(r => r.Generic == generic).Functional, design.Description);
var products = cache.GetAll<FactionProductData>().Where(p => p.Design.Key.Equals(cache.RefOf(design).Key)).ToArray();
Assert.Equal(sold.Select(p => p.Key).OrderBy(k => k, StringComparer.Ordinal), products.Select(p => cache.RefOf(p).Key.Value).OrderBy(k => k, StringComparer.Ordinal));
// Later product lines add sellers to these designs; the renamed designs keep the products they were renamed with.
Assert.All(sold, product => Assert.Contains(products, p => cache.RefOf(p).Key.Value == product.Key));
foreach (var (key, name, maker) in sold)
{
var product = products.Single(p => cache.RefOf(p).Key.Value == key);
@ -190,7 +191,7 @@ public sealed class CatalogRoleTests
var mine = Assert.Single(cache.GetAll<EquippableItemData>(), d => cache.RefOf(d).Key.Value == "1b4a2bb358eb432eb1cfc0ccf3317303");
Assert.Equal("Mine Launcher", mine.Name);
Assert.Equal("Lays a drifting proximity mine that arms after two seconds.", mine.Description);
var brand = Assert.Single(cache.GetAll<FactionProductData>(), p => p.Design.Key.Equals(cache.RefOf(mine).Key));
var brand = Assert.Single(cache.GetAll<FactionProductData>(), p => p.Design.Key.Equals(cache.RefOf(mine).Key) && p.Name == "parting gift");
Assert.Equal("parting gift", brand.Name);
Assert.Equal("DME", cache.Get(brand.Manufacturer).ShortName);
}
@ -260,10 +261,7 @@ public sealed class CatalogRoleTests
AssertNamed(Design("Muon Fusion 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),
};
var profiles = new Dictionary<string, (float Mean, float Dev)>(Program.MakerProfiles) { ["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();

View file

@ -67,11 +67,6 @@ public sealed class LaunchSuppressorCatalogTests
}
// Exactly these six products and these makers, each authoring both roles at its maker's own mean and deviation.
var profiles = new Dictionary<string, (float Mean, float Dev)>
{
["NiteLife"] = (.55f, .12f), ["Finch"] = (.65f, .20f), ["DME"] = (.55f, .20f), ["R&D"] = (.60f, .15f),
["Lightsail"] = (.55f, .10f), ["Alakrita"] = (.60f, .14f),
};
foreach (var (name, makers) in new[]
{
(StrongName, new[] { "DME", "Finch", "NiteLife", "R&D" }),
@ -84,7 +79,7 @@ public sealed class LaunchSuppressorCatalogTests
Assert.Equal(products.Length, products.Select(p => p.Name).Distinct().Count());
Assert.All(products, product =>
{
var (mean, dev) = profiles[cache.Get(product.Manufacturer).ShortName];
var (mean, dev) = Program.MakerProfiles[cache.Get(product.Manufacturer).ShortName];
Assert.Equal(new[] { "baffles", "heat sink" }, product.Roles.Select(r => r.Role).OrderBy(r => r, StringComparer.Ordinal).ToArray());
Assert.All(product.Roles, r =>
{

View file

@ -252,7 +252,8 @@ public sealed class LoadoutTests : IDisposable
Assert.DoesNotContain(forbidden, bad => bad.IsAssignableFrom(type));
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(CultRecordRef<>))
{
Assert.True(typeof(EquippableItemData).IsAssignableFrom(type.GetGenericArguments()[0]), $"{type} names a non-design record");
var named = type.GetGenericArguments()[0];
Assert.True(typeof(EquippableItemData).IsAssignableFrom(named) || named == typeof(FactionProductData), $"{type} names a record that is neither a design nor a product");
continue;
}
if (type.IsArray) pending.Enqueue(type.GetElementType());
@ -312,38 +313,6 @@ public sealed class LoadoutTests : IDisposable
Assert.Contains("slot 0,0: Crate does not fit", failure);
}
// Two new makers, each with one Lamp product, upserted into the live cache so its enumeration order (z before a)
// disagrees with record-key order; a reopened snapshot could already hand them back sorted. Each gets its own
// maker rather than sharing "Maker".
[Fact]
public void FirstAvailableProductInKeyOrderBuildsTheSlot()
{
using var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
var lamp = new CultRecordRef<CraftedItemData>(cache.RefOf(cache.GetByName<GearData>("Lamp")).Key);
var zMaker = cache.Upsert(new Faction { Name = "Zeta", ShortName = "ZET" });
var aMaker = cache.Upsert(new Faction { Name = "Alpha", ShortName = "ALP" });
cache.Commit(batch => batch.Upsert(typeof(FactionProductData), new FactionProductData { Name = "lamp-z", Design = lamp, Manufacturer = zMaker }, new CultRecordKey("lamp-z")));
cache.Commit(batch => batch.Upsert(typeof(FactionProductData), new FactionProductData { Name = "lamp-a", Design = lamp, Manufacturer = aMaker }, new CultRecordKey("lamp-a")));
Assert.Equal(new[] { "lamp-z", "lamp-a" }, cache.GetAll<FactionProductData>().Select(p => p.Name).Where(name => name.StartsWith("lamp-")));
var items = new ItemManager(cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { });
var hand = HandBuilt(cache);
string LampProduct(Predicate<FactionProductData> available, List<string> failures)
{
var ship = Loadouts.Materialize(items, null, hand, available, failures);
if (ship == null) return null;
var unit = ship.Equipment.Single(item => item.EquippableItem != ship.Hull && item.Position.Equals(HardpointCell)).EquippableItem;
return items.Brand(unit).Product.Name;
}
var failures = new List<string>();
Assert.Equal("lamp-a", LampProduct(p => p.Name != "Lamp by Maker", failures));
Assert.Equal("lamp-z", LampProduct(p => p.Name != "Lamp by Maker" && p.Name != "lamp-a", failures));
Assert.Empty(failures);
Assert.Null(LampProduct(p => !p.Name.StartsWith("Lamp") && !p.Name.StartsWith("lamp"), failures));
Assert.Contains("slot 0,0: no available product of Lamp", Assert.Single(failures));
}
// Scenarios Q3 (docs/scenarios-cut.md): a design no product makes is outside the economy, and a preset builds it
// unbranded -- no maker -- at the one named quality. "Orphan" has no product in this catalog.
[Fact]
@ -368,7 +337,8 @@ public sealed class LoadoutTests : IDisposable
using var cache = Open();
var items = new ItemManager(cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { });
var failures = new List<string>();
Assert.Null(Loadouts.Materialize(items, null, HandBuilt(cache), p => p.Name != "Lamp by Maker", failures));
var soleProduct = SoleProduct(cache);
Assert.Null(Loadouts.Materialize(items, null, HandBuilt(cache), design => design.Name == "Lamp" ? null : soleProduct(design), failures));
Assert.Equal("slot 0,0: no available product of Lamp", Assert.Single(failures));
}
@ -918,9 +888,17 @@ public sealed class LoadoutTests : IDisposable
Assert.Equal(originalThreshold, template.ShutdownPerformance);
}
// Everything available: for tests about placement and failure lists.
// The deterministic chooser for tests about placement and failure lists: the design's only product, and nothing (so a
// failure) when it has several.
internal static Func<CraftedItemData, FactionProductData> SoleProduct(CultCache cache) => design =>
{
var key = cache.RefOf(design).Key;
var made = cache.GetAll<FactionProductData>().Where(p => p.Design.Key.Equals(key)).Take(2).ToArray();
return made.Length == 1 ? made[0] : null;
};
private static Entity Build(ItemManager items, Loadout loadout, List<string> failures) =>
Loadouts.Materialize(items, null, loadout, _ => true, failures);
Loadouts.Materialize(items, null, loadout, SoleProduct(items.ItemData), failures);
private static (int2, ItemRotation, CultRecordKey) Describe(LoadoutSlot slot) => (slot.Position, slot.Rotation, slot.Design.Key);

View file

@ -53,18 +53,6 @@ public sealed partial class RunStartTests
}
}
// Brand finds a lot's product by (maker, design), so a maker may sell one product per design.
[Fact]
public void NoMakerSellsTwoProductsOfOneDesign()
{
var twice = _cache.GetAll<FactionProductData>()
.GroupBy(product => (Maker: product.Manufacturer.Key.Value, Design: product.Design.Key.Value))
.Where(group => group.Count() > 1)
.Select(group => string.Join(", ", group.Select(product => product.Name)))
.ToArray();
Assert.Empty(twice);
}
// A unit minted from a Pirates rebrand titles and brands as that rebrand: the lot records its product, so the
// emoji name shows although the same design is also sold by its original maker.
[Fact]

View file

@ -0,0 +1,278 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using CultMath;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using MessagePack;
using Xunit;
using Random = CultMath.Random;
// Ruling loadout-product-optional-context-chooses: a slot or fit may name a product; a design-only slot is chosen by
// the outfitter (LoadoutGenerator.ChooseProduct), never by record-key order.
public sealed class ProductChoiceTests : IDisposable
{
private static readonly int2 HardpointCell = new int2(0, 0);
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-productchoice-" + Guid.NewGuid().ToString("N"));
private readonly List<CultCache> _caches = new List<CultCache>();
private int _catalogs;
public ProductChoiceTests() => Directory.CreateDirectory(_root);
public void Dispose()
{
foreach (var cache in _caches) cache.Dispose();
Directory.Delete(_root, true);
}
// One Skiff (made by Alpha only) and one Lamp with a product from each of Alpha and Zeta. Two outfitting factions:
// OutA's allegiance names only Alpha, OutZ's only Zeta. lampKeys are the Lamp products' record keys in insertion
// order [lamp-z, lamp-a], so a permutation shuffles both keys and enumeration.
private sealed class Rig
{
public CultCache Cache;
public ItemManager Items;
public Galaxy Galaxy;
public Faction OutA, OutZ, OutBoth, OutEven, OutNone;
// zone is the index of the zone the outfitter stands in; -1 stands in none, so distance does not weigh.
public LoadoutGenerator Outfitter(Faction faction, uint seed, int zone = -1)
{
var random = new Random(seed);
return new LoadoutGenerator(ref random, Items, faction == null ? null : Galaxy, faction == null || zone < 0 ? null : Galaxy.Zones[zone], faction, .5f);
}
public FactionProductData Product(string name) => Cache.GetAll<FactionProductData>().Single(p => p.Name == name);
public CultRecordRef<FactionProductData> ProductRef(string name) => Cache.RefOf(Product(name));
public Loadout Fit(CultRecordRef<FactionProductData> lamp = default) => new Loadout
{
Name = "Lamp skiff",
Hull = Cache.RefOf(Cache.GetByName<HullData>("Skiff")),
HullProduct = ProductRef("Skiff by Alpha"),
Slots = { new LoadoutSlot { Position = HardpointCell, Design = Cache.RefOf<EquippableItemData>(Cache.GetByName<GearData>("Lamp")), Product = lamp } },
WeaponGroups = new int[0][]
};
public string LampBrand(Entity ship)
{
var unit = ship.Equipment.Single(item => item.EquippableItem != ship.Hull && item.Position.Equals(HardpointCell)).EquippableItem;
return Items.Brand(unit).Product.Name;
}
}
private Rig Build(params string[] lampOrder)
{
var root = Path.Combine(_root, "rig" + _catalogs++);
Directory.CreateDirectory(root);
var catalog = Path.Combine(root, "Aetheria.cc");
using (var seed = AetheriaStores.Open(catalog, catalogWritable: true))
{
seed.Upsert(new VerseGrammar { Revision = 1 });
var alpha = seed.Upsert(new Faction { Name = "Alpha", ShortName = "ALP" });
var zeta = seed.Upsert(new Faction { Name = "Zeta", ShortName = "ZET" });
var mu = seed.Upsert(new Faction { Name = "Mu", ShortName = "MU" });
seed.Upsert(new Faction { Name = "OutA", ShortName = "OTA", Allegiance = { { alpha, 1f } } });
seed.Upsert(new Faction { Name = "OutZ", ShortName = "OTZ", Allegiance = { { zeta, 1f } } });
seed.Upsert(new Faction { Name = "OutBoth", ShortName = "OTB", Allegiance = { { alpha, 1f }, { zeta, .1f } } });
seed.Upsert(new Faction { Name = "OutEven", ShortName = "OTE", Allegiance = { { alpha, 1f }, { zeta, 1f } } });
seed.Upsert(new Faction { Name = "OutLoose", ShortName = "OTL", Allegiance = { { alpha, 1f }, { zeta, .25f } } });
seed.Upsert(new Faction { Name = "OutZero", ShortName = "OTO", Allegiance = { { alpha, 0f }, { zeta, 0f } } });
seed.Upsert(new Faction { Name = "OutNone", ShortName = "OTN" });
var shape = new Shape(3, 3);
foreach (var cell in shape.AllCoordinates) shape[cell] = true;
var skiff = seed.Upsert(new HullData
{
Name = "Skiff", HullType = HullType.Ship, Shape = shape, Price = 100,
Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = HardpointCell, Shape = new Shape() } }
});
var lamp = seed.Upsert(new GearData { Name = "Lamp", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10 });
void Sell(string name, CultRecordKey design, CultRecordRef<Faction> maker, string key) =>
seed.Commit(batch => batch.Upsert(typeof(FactionProductData), new FactionProductData
{ Name = name, Design = new CultRecordRef<CraftedItemData>(design), Manufacturer = maker }, new CultRecordKey(key)));
Sell("Skiff by Alpha", skiff.Key, alpha, "skiff-a");
var makers = new Dictionary<string, CultRecordRef<Faction>> { ["lamp-a"] = alpha, ["lamp-z"] = zeta, ["lamp-m"] = mu };
// lampOrder holds product names; the record key of the i-th inserted is "k" + i, so keys and insertion order
// both follow the permutation.
for (var i = 0; i < lampOrder.Length; i++) Sell(lampOrder[i], lamp.Key, makers[lampOrder[i]], "k" + i);
seed.FlushAsync().Wait();
}
var cache = AetheriaStores.Open(catalog, Path.Combine(root, "run.cc"), Path.Combine(root, "player.cc"));
_caches.Add(cache);
var outA = cache.GetByName<Faction>("OutA");
var outZ = cache.GetByName<Faction>("OutZ");
var game = new SavedGame
{
// Alpha's headquarters are in zone 0 and Zeta's in zone 1.
Factions = new[] { cache.RefOf(outA), cache.RefOf(outZ), cache.RefOf(cache.GetByName<Faction>("Alpha")), cache.RefOf(cache.GetByName<Faction>("Zeta")) },
Relationships = new[] { FactionRelationship.Neutral, FactionRelationship.Neutral, FactionRelationship.Neutral, FactionRelationship.Neutral },
HomeZones = new Dictionary<int, int> { { 0, 0 }, { 1, 0 }, { 2, 0 }, { 3, 1 } },
BossZones = new Dictionary<int, int>(),
DiscoveredZones = new[] { 0 },
ActionBarBindings = new SavedActionBarBinding[0],
Exit = -1
};
var zones = new[]
{
new SavedZone { Name = "Zone 0", Position = new float2(0, 0), AdjacentZones = new[] { 1 }, Factions = new[] { 0, 1 }, Owner = 0, Contents = null },
new SavedZone { Name = "Zone 1", Position = new float2(1, 0), AdjacentZones = new[] { 0 }, Factions = new[] { 0, 1 }, Owner = 0, Contents = null }
};
RunSave.Commit(cache, game, zones, new ProvenanceLedger());
return new Rig
{
Cache = cache, OutA = outA, OutZ = outZ, OutBoth = cache.GetByName<Faction>("OutBoth"), OutEven = cache.GetByName<Faction>("OutEven"), OutNone = cache.GetByName<Faction>("OutNone"),
Items = new ItemManager(cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }),
Galaxy = new Galaxy(cache, cache.GetGlobal<SavedGame>(), _ => { })
};
}
// Small seeds give correlated first draws, so the seeds a distribution test runs over are spread across the range.
private static uint Seed(int i) => unchecked((uint) (i * 2654435761L));
private static Entity Materialize(Rig rig, Loadout loadout, Func<CraftedItemData, FactionProductData> choose, List<string> failures) =>
Loadouts.Materialize(rig.Items, null, loadout, choose, failures);
[Fact]
public void ADifferentOutfitterChoosesADifferentProduct()
{
var rig = Build("lamp-z", "lamp-a");
var failures = new List<string>();
Assert.Equal("lamp-a", rig.LampBrand(Materialize(rig, rig.Fit(), rig.Outfitter(rig.OutA, 1).ChooseProduct, failures)));
Assert.Equal("lamp-z", rig.LampBrand(Materialize(rig, rig.Fit(), rig.Outfitter(rig.OutZ, 1).ChooseProduct, failures)));
Assert.Empty(failures);
}
// An outfitter that reaches both makers favors the one its allegiance weighs ten times heavier: the draw follows
// ManufacturerPreference rather than splitting evenly.
[Fact]
public void TheDrawFollowsTheOutfittersPreference()
{
var rig = Build("lamp-z", "lamp-a");
var lamp = rig.Cache.GetByName<GearData>("Lamp");
var drawn = Enumerable.Range(1, 200).Select(i => rig.Outfitter(rig.OutBoth, Seed(i)).ChooseProduct(lamp).Name).ToArray();
var alpha = drawn.Count(name => name == "lamp-a");
Assert.InRange(alpha, 160, 199);
Assert.Contains("lamp-z", drawn);
}
// An outfitter that reaches no maker of the design gets nothing, however the weights fall: the slot fails.
[Fact]
public void AnOutfitterThatReachesNoMakerGetsNoProduct()
{
var rig = Build("lamp-z", "lamp-a");
var generator = rig.Outfitter(rig.OutNone, 1);
Assert.Null(generator.ChooseProduct(rig.Cache.GetByName<GearData>("Lamp")));
var failures = new List<string>();
Assert.Null(Materialize(rig, rig.Fit(), generator.ChooseProduct, failures));
Assert.Equal("slot 0,0: no available product of Lamp", Assert.Single(failures));
}
[Fact]
public void ANullFactionDrawIsSeededAndReachesEveryMaker()
{
var rig = Build("lamp-z", "lamp-a");
var lamp = rig.Cache.GetByName<GearData>("Lamp");
Assert.Equal(rig.Outfitter(null, 7).ChooseProduct(lamp).Name, rig.Outfitter(null, 7).ChooseProduct(lamp).Name);
var seen = Enumerable.Range(1, 64).Select(i => rig.Outfitter(null, Seed(i)).ChooseProduct(lamp).Name).Distinct().OrderBy(name => name).ToArray();
Assert.Equal(new[] { "lamp-a", "lamp-z" }, seen);
}
[Fact]
public void APinnedProductIsBuiltInEveryContext()
{
var rig = Build("lamp-z", "lamp-a");
var failures = new List<string>();
var pinned = rig.Fit(rig.ProductRef("lamp-z"));
Assert.Equal("lamp-z", rig.LampBrand(Materialize(rig, pinned, rig.Outfitter(rig.OutA, 1).ChooseProduct, failures)));
Assert.Equal("lamp-z", rig.LampBrand(Materialize(rig, pinned, _ => null, failures)));
Assert.Empty(failures);
var foreign = rig.Fit(rig.ProductRef("Skiff by Alpha"));
Assert.Null(Materialize(rig, foreign, rig.Outfitter(null, 1).ChooseProduct, failures));
Assert.Equal("slot 0,0: product Skiff by Alpha is not a product of Lamp", Assert.Single(failures));
}
[Fact]
public void ShuffledKeysDoNotChangeTheChoice()
{
var orders = new[] { new[] { "lamp-a", "lamp-m", "lamp-z" }, new[] { "lamp-z", "lamp-a", "lamp-m" }, new[] { "lamp-m", "lamp-z", "lamp-a" } };
var rigs = orders.Select(order => Build(order)).ToArray();
foreach (var faction in new Func<Rig, Faction>[] { _ => null, rig => rig.OutA })
for (uint seed = 1; seed <= 16; seed++)
{
var chosen = rigs.Select(rig => rig.Outfitter(faction(rig), seed).ChooseProduct(rig.Cache.GetByName<GearData>("Lamp"))?.Name).Distinct().ToArray();
Assert.Single(chosen);
}
}
[Fact]
public void CaptureKeepsTheLotsProduct()
{
var rig = Build("lamp-z", "lamp-a");
var failures = new List<string>();
var ship = Materialize(rig, rig.Fit(rig.ProductRef("lamp-z")), rig.Outfitter(rig.OutA, 1).ChooseProduct, failures);
var captured = Loadouts.Capture(rig.Items, ship, "captured");
Assert.Equal(rig.ProductRef("lamp-z").Key, captured.Slots.Single().Product.Key);
Assert.Equal(rig.ProductRef("Skiff by Alpha").Key, captured.HullProduct.Key);
var rebuilt = Materialize(rig, captured, _ => null, failures);
Assert.Empty(failures);
Assert.Equal("lamp-z", rig.LampBrand(rebuilt));
Assert.Equal("Skiff by Alpha", rig.Items.Brand(rebuilt.Hull).Product.Name);
}
[Fact]
public void AChooserOfAnotherDesignIsRefused()
{
var rig = Build("lamp-z", "lamp-a");
var failures = new List<string>();
Assert.Null(Materialize(rig, rig.Fit(), _ => rig.Product("Skiff by Alpha"), failures));
Assert.Equal("slot 0,0: product Skiff by Alpha is not a product of Lamp", Assert.Single(failures));
}
private static int MakerDraws(Rig rig, Faction faction, int zone, string maker, int n)
{
var lamp = rig.Cache.GetByName<GearData>("Lamp");
return Enumerable.Range(1, n).Count(i => rig.Outfitter(faction, Seed(i), zone).ChooseProduct(lamp).Name == maker);
}
// Two makers an even allegiance weighs the same differ only by distance: standing in a zone, the maker whose
// headquarters is nearer comes up about twice as often (1 against 1/2).
[Fact]
public void ANearerMakerIsFavored()
{
var rig = Build("lamp-z", "lamp-a");
Assert.InRange(MakerDraws(rig, rig.OutEven, 0, "lamp-a", 300), 180, 220);
Assert.InRange(MakerDraws(rig, rig.OutEven, 1, "lamp-a", 300), 80, 120);
}
// A weight that read the allegiance alone would give 1 : .25 here, an 80% draw; the zone and allegiance together
// give 1 : .125 for alpha at its own zone, 89%.
[Fact]
public void AnAlliedMakerWeighsByItsAllegiance()
{
var rig = Build("lamp-z", "lamp-a");
Assert.InRange(MakerDraws(rig, rig.Cache.GetByName<Faction>("OutLoose"), 0, "lamp-a", 300), 245, 290);
}
// When every reachable maker weighs 0 the draw is uniform over them, not a pick of the first or last.
[Fact]
public void WhenEveryWeightIsZeroTheDrawIsUniform()
{
var rig = Build("lamp-z", "lamp-a");
var zero = rig.Cache.GetByName<Faction>("OutZero");
Assert.InRange(MakerDraws(rig, zero, 0, "lamp-a", 300), 100, 200);
Assert.InRange(MakerDraws(rig, zero, 0, "lamp-z", 300), 100, 200);
}
// The wire positions of the new fields: a preset written by one build is read by the next.
[Fact]
public void TheProductRefsSitAtTheirWirePositions()
{
Assert.Equal(4, typeof(Loadout).GetField(nameof(Loadout.HullProduct)).GetCustomAttribute<KeyAttribute>().IntKey);
Assert.Equal(3, typeof(LoadoutSlot).GetField(nameof(LoadoutSlot.Product)).GetCustomAttribute<KeyAttribute>().IntKey);
}
}

View file

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Caching;
using Xunit;
// The weapon product lines the shipped catalog holds (campaign aetheria-release, cut product-lines-weapons; rulings
// catalog-grows-generic-designs-branded-products, maker-design-tiers-allowed): a sold weapon design has several brands, a
// brand name is one product's, and every row of the command's table is in the catalog with the quality its maker's profile gives.
// The rows come from the command's own table and the profiles from its own maker-profile table, so a row edited in one place
// and not shipped fails here.
public sealed class ProductLinesCatalogTests
{
// A design with any product is sold; the Smoke test designs have none and stay exempt.
[Fact]
public void EveryWeaponDesignWithAProductHasTwoMakers()
{
using var cache = RestoredHullsTests.OpenCatalog();
var products = cache.GetAll<FactionProductData>().ToArray();
var unsold = new List<string>();
foreach (var design in cache.GetAll<WeaponItemData>())
{
var key = cache.RefOf(design).Key;
var makers = products.Where(p => p.Design.Key.Equals(key)).Select(p => p.Manufacturer.Key).Distinct().Count();
if (makers == 0)
{
unsold.Add(design.Name);
continue;
}
Assert.True(makers >= 2, $"the weapon design \"{design.Name}\" is sold by {makers} maker");
}
// The designs no product sells are the Smoke test designs and no others: a design that lost all its products is a failure.
Assert.All(unsold, name => Assert.StartsWith("Smoke ", name));
}
[Fact]
public void NoTwoProductsShareAName()
{
using var cache = RestoredHullsTests.OpenCatalog();
var shared = cache.GetAll<FactionProductData>()
.GroupBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
.Where(group => group.Count() > 1)
.Select(group => group.Key)
.ToArray();
Assert.Empty(shared);
}
[Fact]
public void WeaponLineRowsAreShipped()
{
using var cache = RestoredHullsTests.OpenCatalog();
var table = ProductLinesCommand.Table("weapons");
Assert.Equal(20, table.Count);
foreach (var row in table)
{
var product = Assert.Single(cache.GetAll<FactionProductData>(), p => p.Name == row.Name);
var design = cache.Get(product.Design);
Assert.Equal(row.Design, design.Name);
Assert.Equal(row.Maker, cache.Get(product.Manufacturer).ShortName);
Assert.Equal(row.Description, product.Description);
var (mean, dev) = Program.MakerProfiles[row.Maker];
Assert.Equal(
design.Roles.Select(r => r.Name).OrderBy(n => n, StringComparer.Ordinal),
product.Roles.Select(r => r.Role).OrderBy(n => n, StringComparer.Ordinal));
foreach (var role in product.Roles)
{
Assert.Equal(mean, role.Mean, 4);
Assert.Equal(dev, role.StandardDeviation, 4);
}
}
}
}

View file

@ -0,0 +1,262 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using Xunit;
// AetherDb's product-lines command (cut product-lines-weapons), run on a scratch copy of the shipped catalog with the weapon
// line's twenty products removed from it. Apply must write what the shipped catalog holds, only its own records, finish a
// catalog that holds part of the line, refuse a name that is another product's, and accept a maker that already sells the design.
public sealed class ProductLinesCommandTests : IDisposable
{
private static readonly string[] Names = ProductLinesCommand.Table("weapons").Select(r => r.Name).ToArray();
private static readonly string[] Line = { "weapons" };
private static readonly string[] LineApply = { "weapons", "apply" };
private readonly string _root = Path.Combine(Path.GetTempPath(), "product-lines-command-" + Guid.NewGuid().ToString("N"));
private string CatalogPath => Path.Combine(_root, "GameData", "Aetheria.cc");
// The rows as the shipped catalog holds them, taken before they are removed from the scratch copy.
private readonly string[] _shipped;
private readonly string[] _shippedKeys;
private static string Describe(CultCache cache, FactionProductData product) =>
$"{cache.Get(product.Design).Name} | {product.Name} | {cache.Get(product.Manufacturer).ShortName} | {product.Description} | " +
string.Join(",", product.Roles.OrderBy(r => r.Role, StringComparer.Ordinal).Select(r => $"{r.Role}:{r.Mean}:{r.StandardDeviation}"));
public ProductLinesCommandTests()
{
Directory.CreateDirectory(Path.Combine(_root, "GameData"));
Directory.CreateDirectory(Path.Combine(_root, "Assets", "Resources"));
var shipped = AetherDb.FindRoot();
File.Copy(Path.Combine(shipped, "GameData", "Aetheria.cc"), CatalogPath);
File.Copy(Path.Combine(shipped, "Assets", "Resources", "Settings.asset"), Path.Combine(_root, "Assets", "Resources", "Settings.asset"));
using var cache = Open();
var products = cache.GetAll<FactionProductData>().Where(p => Names.Contains(p.Name)).ToArray();
Assert.Equal(Names.Length, products.Length);
_shipped = products.Select(p => Describe(cache, p)).OrderBy(x => x, StringComparer.Ordinal).ToArray();
_shippedKeys = products.Select(p => cache.RefOf(p).Key.Value).OrderBy(x => x, StringComparer.Ordinal).ToArray();
foreach (var product in products) Assert.True(cache.Remove(cache.RefOf(product).Key));
cache.FlushAsync().Wait();
}
public void Dispose() => Directory.Delete(_root, true);
private CultCache Open()
{
var cache = new CultCache(TestCatalog.Registry());
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
return cache;
}
private string[] Line20()
{
using var cache = Open();
return cache.GetAll<FactionProductData>().Where(p => Names.Contains(p.Name)).Select(p => Describe(cache, p)).OrderBy(x => x, StringComparer.Ordinal).ToArray();
}
private string[] Line20Keys()
{
using var cache = Open();
return cache.GetAll<FactionProductData>().Where(p => Names.Contains(p.Name)).Select(p => cache.RefOf(p).Key.Value).OrderBy(x => x, StringComparer.Ordinal).ToArray();
}
[Fact]
public void A_dry_run_writes_nothing_and_apply_lands_the_shipped_rows_once()
{
var before = File.ReadAllBytes(CatalogPath);
Assert.Empty(Line20());
Assert.Equal(0, ProductLinesCommand.Run(Line, _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
Assert.Empty(Line20());
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
var landed = File.ReadAllBytes(CatalogPath);
Assert.NotEqual(before, landed);
// The command derives each record's key from the product's name, so applying the table again lands the keys the
// shipped catalog holds.
Assert.Equal(_shipped, Line20());
Assert.Equal(_shippedKeys, Line20Keys());
// A second apply finds everything authored and writes nothing; so does a dry run.
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(landed, File.ReadAllBytes(CatalogPath));
Assert.Equal(0, ProductLinesCommand.Run(Line, _root));
Assert.Equal(landed, File.ReadAllBytes(CatalogPath));
}
// Re-spell every record's payload in a longer, equally valid MessagePack form (an array16 header for the fixarray one). A
// write that re-encodes records it did not author shows as changed bytes; one that lands onto the file as it is leaves them.
private int WidenEveryPayload()
{
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(CatalogPath));
var widened = 0;
foreach (var record in snapshot.Records)
{
var payload = record.Payload;
if (payload.Length == 0 || (payload[0] & 0xF0) != 0x90) continue;
record.Payload = new byte[] { 0xDC, 0x00, (byte)(payload[0] & 0x0F) }.Concat(payload.Skip(1)).ToArray();
widened++;
}
File.WriteAllBytes(CatalogPath, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
return widened;
}
private Dictionary<string, CultPersistedRecord> Records() =>
CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(CatalogPath)).Records.ToDictionary(r => r.Key, StringComparer.Ordinal);
[Fact]
public void Apply_writes_only_the_records_it_authors()
{
Assert.True(WidenEveryPayload() > 100, "the scratch catalog should hold many records in the widened spelling");
var before = Records();
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
var after = Records();
Assert.Equal(before.Count + Names.Length, after.Count);
foreach (var (key, record) in before)
{
Assert.True(after.TryGetValue(key, out var kept), "a record the command did not author is gone");
Assert.Equal(record.SchemaId, kept.SchemaId);
Assert.Equal(record.StoredAt, kept.StoredAt);
Assert.True(record.Payload.AsSpan().SequenceEqual(kept.Payload), "a record the command did not author has changed bytes");
}
}
[Fact]
public void Apply_finishes_a_catalog_that_holds_part_of_the_line()
{
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
using (var cache = Open())
{
foreach (var product in cache.GetAll<FactionProductData>().Where(p => p.Name == "Merlin" || p.Name == "Tripwire").ToArray())
Assert.True(cache.Remove(cache.RefOf(product).Key));
cache.FlushAsync().Wait();
}
Assert.Equal(Names.Length - 2, Line20().Length);
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(_shipped, Line20());
}
[Fact]
public void Apply_refuses_a_row_name_that_is_another_products_and_writes_nothing()
{
using (var cache = Open())
{
var other = cache.GetAll<WeaponItemData>().First(w => w.Name == "Light Machine Gun");
var maker = cache.GetAll<Faction>().First(f => f.ShortName == "Zhestokost");
cache.Upsert(new FactionProductData { Name = "Sparrow", Design = new CultRecordRef<CraftedItemData>(cache.RefOf(other).Key), Manufacturer = cache.RefOf(maker) });
cache.FlushAsync().Wait();
}
var conflicted = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(conflicted, File.ReadAllBytes(CatalogPath));
}
// Ruling maker-design-tiers-allowed: a maker that already sells a design may sell another product of it.
[Fact]
public void Apply_accepts_a_maker_that_already_sells_the_design()
{
using (var cache = Open())
{
var laser = cache.GetAll<WeaponItemData>().First(w => w.Name == "Light Laser");
var lucent = cache.GetAll<Faction>().First(f => f.ShortName == "Lucent");
cache.Upsert(new FactionProductData { Name = "Scratch tier", Design = new CultRecordRef<CraftedItemData>(cache.RefOf(laser).Key), Manufacturer = cache.RefOf(lucent) });
cache.FlushAsync().Wait();
}
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(_shipped, Line20());
using var after = Open();
Assert.Contains(after.GetAll<FactionProductData>(), p => p.Name == "Scratch tier");
}
// Master's committed catalog holds records written on a schema older than today's (HullData lost a member after the last
// catalog write). The scratch copy gets that shape: the hull records point at an earlier schema id the loader resolves to
// the current type.
private string MakeHullsStale()
{
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(CatalogPath));
var current = snapshot.SchemaCatalog.Single(e => e.SchemaName == "aetheria.hulldata");
var stale = new CultSchemaCatalogEntry
{
SchemaId = "sha256:earlier-hulldata", SchemaName = current.SchemaName, SchemaVersion = current.SchemaVersion,
ContentHash = "sha256:earlier-hulldata", CanonicalSchemaJson = current.CanonicalSchemaJson, Members = current.Members,
};
snapshot.SchemaCatalog = snapshot.SchemaCatalog.Append(stale).ToArray();
var hulls = snapshot.Records.Where(r => r.SchemaId == current.SchemaId).ToArray();
Assert.NotEmpty(hulls);
foreach (var hull in hulls) hull.SchemaId = stale.SchemaId;
File.WriteAllBytes(CatalogPath, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
return stale.SchemaId;
}
[Fact]
public void Apply_lands_on_a_catalog_that_holds_records_of_an_older_schema_and_replays_to_the_same_bytes()
{
var stale = MakeHullsStale();
var before = Records();
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
var landed = File.ReadAllBytes(CatalogPath);
Assert.Equal(_shipped, Line20());
var after = Records();
foreach (var (key, record) in before)
Assert.True(record.Payload.AsSpan().SequenceEqual(after[key].Payload) && record.SchemaId == after[key].SchemaId, "a record the command did not author changed");
Assert.Contains(after.Values, r => r.SchemaId == stale);
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(landed, File.ReadAllBytes(CatalogPath));
}
private void AddProduct(string name, string design, string maker)
{
using var cache = Open();
var designRecord = cache.GetAll<WeaponItemData>().First(w => w.Name == design);
var makerRecord = cache.GetAll<Faction>().First(f => f.ShortName == maker);
cache.Upsert(new FactionProductData { Name = name, Design = new CultRecordRef<CraftedItemData>(cache.RefOf(designRecord).Key), Manufacturer = cache.RefOf(makerRecord) });
cache.FlushAsync().Wait();
}
// Sparrow is the Light Laser by Finch. A product of that name is the row only when design and maker both match.
[Theory]
[InlineData("Sparrow", "Light Machine Gun", "Finch")]
[InlineData("Sparrow", "Light Laser", "Zhestokost")]
[InlineData("sparrow", "Light Laser", "Finch")]
public void Apply_refuses_a_name_unless_design_and_maker_both_match_it_ignoring_case(string name, string design, string maker)
{
AddProduct(name, design, maker);
var conflicted = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(conflicted, File.ReadAllBytes(CatalogPath));
}
[Fact]
public void Apply_refuses_a_row_name_that_is_a_designs_and_writes_nothing()
{
using (var cache = Open())
{
cache.Upsert(new WeaponItemData { Name = "Tripwire" });
cache.FlushAsync().Wait();
}
var conflicted = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(conflicted, File.ReadAllBytes(CatalogPath));
}
// The command is reached as AetherDb's product-lines word, with the line after it; the shipped catalog holds the line.
[Fact]
public void The_product_lines_word_runs_the_named_line_and_refuses_an_unknown_one()
{
Assert.Equal(0, Program.Main(new[] { "product-lines", "weapons" }));
Assert.Equal(1, Program.Main(new[] { "product-lines", "nonesuch" }));
}
}

View file

@ -0,0 +1,64 @@
using System.Collections.Generic;
using System.Linq;
using Xunit;
// Ruling loadout-product-optional-context-chooses: a rig whose test reads stats names the brand it was measured on, and
// staging builds exactly that brand whatever the stage's seed draws for open designs. The fixture is RunStartTests'.
public sealed partial class RunStartTests
{
private string ProductOf(EquippableItem item) => _items.Brand(item).Product.Name;
private IEnumerable<string> FittedBrands(Entity entity, string design) =>
entity.Equipment.Concat(entity.CargoBays).Where(item => _items.GetData(item.EquippableItem).Name == design).Select(item => ProductOf(item.EquippableItem));
// Every product a scenario's fits name. A rig whose fits name a design where a brand stood would draw its brand from
// the stage's seed; so each scenario is staged under eight seeds, and the design of every pinned product must come out
// as exactly that product on every ship the scenario fits. A hull that is not a fit's (a generated or bare ship)
// is left out: its gear is not pinned.
public static IEnumerable<object[]> PinnedRigs() => new[]
{
Rig(new AiFusedDiscipline(), "not if i see you first", "Panopticon Prime"),
Rig(new Arcs(), "GT 3K", "FastBlast+-", "🫳🔫", "ChargeBlast SG", "ClearPath", "not if i see you first", "Panopticon Prime"),
Rig(new Belt(), "GT 3K", "DragOnBreath", "FastBlast+-", "not if i see you first", "Panopticon Prime"),
Rig(new Crossing(), "GT 3K", "DragOnBreath", "FastBlast+-", "not if i see you first", "Panopticon Prime"),
Rig(new Duel(), "GT 3K", "FastBlast+-", "Store-All Plus", "not if i see you first", "Panopticon Prime"),
Rig(new FusedRounds(), "DeathCluster", "not if i see you first", "Panopticon Prime"),
Rig(new LauncherAngles(), "GT 3K", "Leonid", "FastBlast+-", "not if i see you first", "Panopticon Prime"),
Rig(new LockOn(), "GT 3K", "FastBlast+-", "Store-All Plus", "not if i see you first", "Panopticon Prime"),
Rig(new Pursuit(), "parting gift", "Leonid", "GT 3K", "FastBlast+-", "Store-All Plus", "not if i see you first", "Panopticon Prime"),
Rig(new RefusedRounds(), "🫳🔫", "not if i see you first", "Panopticon Prime"),
Rig(new StarvedReactor(), "Spectra", "not if i see you first", "Panopticon Prime"),
Rig(new WeaponFeel(), "ChargeBlast SG", "🫳🔫", "FastBlast+-", "not if i see you first", "Panopticon Prime"),
};
private static object[] Rig(Scenario scenario, params string[] brands) => new object[] { scenario, brands };
[Theory]
[MemberData(nameof(PinnedRigs))]
public void TheRigsKeepTheirBrands(Scenario scenario, string[] brands)
{
for (uint seed = 1; seed <= 8; seed++)
{
var (_, _, staged, failures) = Launch(new Scripted(false, scenario.Stage, seed * 7919, scenario.Generate));
Assert.Empty(failures);
var ships = staged.Entities.Append(staged.Player).Where(ship => _items.GetData(ship.Hull).Name is "Longinus" or "Smoke Test Hull" or "Turret");
foreach (var brand in brands)
{
var product = _items.ItemData.GetAll<FactionProductData>().Single(candidate => candidate.Name == brand);
var design = _items.ItemData.Get(product.Design).Name;
var built = ships.SelectMany(ship => FittedBrands(ship, design)).Distinct().ToArray();
Assert.True(built.SequenceEqual(new[] { brand }), $"{scenario.Name} seed {seed}: {design} is built as [{string.Join(", ", built)}], not {brand}");
}
}
}
// Duel's rival holds Spectra in its cargo.
[Fact]
public void TheDuelRivalHoldsItsBrand()
{
var duel = Launch(new Scripted(false, new Duel().Stage, 7919));
Assert.Empty(duel.failures);
var rival = Assert.Single(duel.staged.Entities);
Assert.Equal(new[] { "Spectra" }, Held(rival).Select(item => _items.Brand(item).Product.Name));
}
}

View file

@ -662,7 +662,7 @@ public sealed partial class RunStartTests : IDisposable
foreach (var hull in new[] { Hull("Djinni"), Hull("Longinus"), TurretHull() })
{
var failures = new List<string>();
var entity = Loadouts.Materialize(_items, null, BareLoadout(hull), available.IsAvailable, failures);
var entity = Loadouts.Materialize(_items, null, BareLoadout(hull), available.ChooseProduct, failures);
Assert.Empty(failures);
Assert.NotNull(_items.Brand(entity.Hull).Maker);
}
@ -681,7 +681,7 @@ public sealed partial class RunStartTests : IDisposable
Assert.True(ships.Count > 1);
foreach (var ship in ships) Assert.Equal(ship.IsPlayerShip ? 0 : 1, AgentsOf(zone, ship));
var arriving = (Ship) Loadouts.Materialize(_items, zone, BareLoadout(Hull("Djinni")), _ => true, new List<string>());
var arriving = (Ship) Loadouts.Materialize(_items, zone, BareLoadout(Hull("Djinni")), new LoadoutGenerator(ref _items.Random, _items, _galaxy, _galaxy.Entrance, null, 2).ChooseProduct, new List<string>());
var agents = zone.Agents.Count;
zone.Admit(arriving, piloted: false);
SafeAssert.In(zone, arriving, "the arrival is admitted");