Merge origin/master (2403a5f3, gear-without-presence) into eureka/aetheria-release-retire-longinusx

Lands retire-longinusx on master after gear-without-presence. The catalog
is regenerated from master's catalog with retire-longinusx apply (next commit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	GameData/Aetheria.cc
This commit is contained in:
Meta Vens 2026-10-08 18:59:38 +02:00
commit 284231f4c1
49 changed files with 2770 additions and 180 deletions

View file

@ -0,0 +1,241 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using CultMath;
using Xunit;
// The demo scenario (aetheria-release, cut demo-galaxy): a prelude galaxy of a fixed cast whose antagonist's home is the
// boss zone and the exit. The shipped catalog holds no Pirates faction yet, so each test that needs one adds it to its
// scratch copy of the catalog.
public sealed partial class RunStartTests
{
private static readonly uint[] DemoSeeds = { 1, 2, 3, 4, 5 };
// The catalog record the demo's protagonist needs, until the shipped catalog has one. Zone names need a name file,
// and the entrance's station needs a faction whose allegiance reaches some manufacturer, so it reaches every one.
private void AddPirates()
{
var pirates = new Faction
{
Name = "Pirates", ShortName = "Pirates", GeonameFile = _cache.RefOf(_cache.GetAll<NameFile>().First())
};
foreach (var faction in _cache.GetAll<Faction>().ToArray()) pirates.Allegiance[_cache.RefOf(faction)] = 1;
_cache.Upsert(pirates);
}
private Galaxy DemoGalaxy(uint seed) => RunStart.Generate(new DemoTerminus(), Inputs(() => seed));
[Fact]
public void DemoTerminus_fixed_cast()
{
AddPirates();
foreach (var seed in DemoSeeds)
Assert.Equal(new[] { "Pirates", "Zhestokost", "Lucent Media", "Aeronautics Unlimited" },
DemoGalaxy(seed).Factions.Select(faction => faction.Name));
}
[Fact]
public void DemoTerminus_gate_at_antagonist_home()
{
AddPirates();
foreach (var seed in DemoSeeds)
{
var galaxy = DemoGalaxy(seed);
// Zones are compared by index: xunit formats a failing zone into its message, and a zone drags the galaxy
// graph in with it until the test host dies.
int At(GalaxyZone zone) => Array.IndexOf(galaxy.Zones, zone);
var zhestokost = galaxy.Factions.Single(faction => faction.Name == "Zhestokost");
Assert.Equal(new[] { "Zhestokost" }, galaxy.BossZones.Keys.Select(faction => faction.Name));
Assert.Equal(At(galaxy.HomeZones[zhestokost]), At(galaxy.BossZones[zhestokost]));
Assert.Equal(At(galaxy.HomeZones[zhestokost]), At(galaxy.Exit));
Assert.NotEqual(At(galaxy.Entrance), At(galaxy.Exit));
}
}
// The player's standing is part of the run: Continue restores it, and the gate, through the saved game.
[Fact]
public void DemoTerminus_standing_survives_continue()
{
AddPirates();
var (galaxy, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1));
Assert.True(failures.Count == 0, string.Join("; ", failures));
galaxy.Entrance.Contents = arena;
var (game, zones) = RunSave.Capture(_cache, galaxy, arena, staged.Player, new SavedActionBarBinding[0], 0);
RunSave.Commit(_cache, game, zones, _items.Lots);
var restored = new Galaxy(_cache, _cache.GetGlobal<SavedGame>(), _ => { });
Dictionary<string, FactionRelationship> Standing(Galaxy g) => g.Factions.ToDictionary(faction => faction.Name, faction => g.FactionRelationships[faction]);
Assert.Equal(new Dictionary<string, FactionRelationship>
{
["Pirates"] = FactionRelationship.Friendly,
["Zhestokost"] = FactionRelationship.Hated,
["Lucent Media"] = FactionRelationship.Neutral,
["Aeronautics Unlimited"] = FactionRelationship.Neutral
}, Standing(restored));
Assert.Equal(Standing(galaxy), Standing(restored));
Assert.Equal(Array.IndexOf(galaxy.Zones, galaxy.Exit), Array.IndexOf(restored.Zones, restored.Exit));
Assert.Equal(
galaxy.BossZones.Select(boss => (boss.Key.Name, Array.IndexOf(galaxy.Zones, boss.Value))),
restored.BossZones.Select(boss => (boss.Key.Name, Array.IndexOf(restored.Zones, boss.Value))));
}
// On the shipped catalog, which has no Pirates, the run does not start: the galaxy refuses, naming the cast field,
// and the scenario never reaches staging.
[Fact]
public void DemoTerminus_missing_cast_refused()
{
Assert.DoesNotContain(_cache.GetAll<Faction>(), faction => faction.Name.StartsWith("Pirates", StringComparison.Ordinal));
var refusal = Assert.Throws<InvalidOperationException>(() => DemoGalaxy(1));
Assert.Contains("Pirates", refusal.Message);
Assert.Contains(nameof(TutorialGenerationSettings.ProtagonistFaction), refusal.Message);
}
// The operator's ruling is that the first release is a demo: the one scenario a release build lists says so by name.
[Fact]
public void DemoTerminus_is_named_a_demo()
{
var listed = Assert.Single(Scenarios.Modes);
Assert.IsType<DemoTerminus>(listed);
Assert.Equal("Terminus (Demo)", listed.Name);
}
// The run start as New Game runs it: the player is not a Pirate, so the hull is the base Longinus, made by Alakrita,
// not by the Pirates or any cast faction, with no faction on the ship, at the entrance zone's origin.
[Fact]
public void DemoTerminus_player_flies_a_non_pirates_brand_hull_the_longinus()
{
AddPirates();
foreach (var seed in DemoSeeds)
{
var (galaxy, _, staged, failures) = Launch(new DemoTerminus(), Inputs(() => seed));
Assert.True(failures.Count == 0, string.Join("; ", failures));
Assert.Equal("Longinus", staged.Player.HullData.Name);
var design = _cache.RefOf(staged.Player.HullData).Key;
var product = Assert.Single(_cache.GetAll<FactionProductData>(), p => p.Design.Key.Equals(design));
var maker = _cache.Get(product.Manufacturer);
Assert.Equal("Alakrita", maker.Name);
Assert.DoesNotContain(galaxy.Factions, faction => faction.Name == maker.Name);
Assert.Null(staged.Player.Faction);
Assert.Equal(float3.zero, staged.Player.Position);
}
}
// The ruling says the Longinus with its default fit: the fit the game generates for that hull from the run's item
// draws, which Stage seeds from the galaxy's seed. The expected fit is that same generation replayed from the same
// seed, so no item list is spelled here; a bare hull, a preset, or one item swapped for another differs from it.
[Fact]
public void DemoTerminus_player_carries_the_longinus_default_fit()
{
AddPirates();
string Fit(Entity ship) => string.Join(";", ship.Equipment
.Select(item => $"{item.Data.Name}@{item.Position}/{item.EquippableItem.Rotation}")
.OrderBy(entry => entry, StringComparer.Ordinal));
foreach (var seed in DemoSeeds)
{
var (galaxy, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => seed));
Assert.True(failures.Count == 0, string.Join("; ", failures));
_items.Random = new CultMath.Random(galaxy.Seed * 0x9E3779B1u + 2);
var generator = new LoadoutGenerator(ref _items.Random, _items, galaxy, arena.GalaxyZone, null, 2);
var expected = EntitySerializer.Unpack(_items, null, generator.GenerateShipLoadout(hull => hull.Name == "Longinus"));
Assert.NotEmpty(expected.Equipment);
Assert.Equal(Fit(expected), Fit(staged.Player));
}
}
// The demo region's size and connectivity are authored: 64 zones, links thinned to half. The reference galaxy is the
// same cast with the thinning written out here, generated at the same seed, so any other density is a different graph.
[Fact]
public void DemoTerminus_region_is_sixty_four_zones_linked_at_half_density()
{
AddPirates();
string Links(Galaxy g) => string.Join(";", g.Zones.Select(zone =>
string.Join(",", zone.AdjacentZones.Select(adjacent => Array.IndexOf(g.Zones, adjacent)).OrderBy(index => index))));
Galaxy Reference(uint seed, float density)
{
var cast = new TutorialGenerationSettings
{
ProtagonistFaction = "Pirates", AntagonistFaction = "Zhe", BufferFaction = "Luc",
NeutralFactions = new[] { "Aero" }, QuestFaction = null, ZoneCount = 64, LinkDensity = density
};
return RunStart.Generate(new Scripted(false, _ => { }, seed, galaxy => galaxy.Prelude(cast)), Inputs());
}
foreach (var seed in DemoSeeds)
{
var galaxy = DemoGalaxy(seed);
Assert.Equal(64, galaxy.Zones.Length);
Assert.Equal(Links(Reference(seed, .5f)), Links(galaxy));
Assert.NotEqual(Links(Reference(seed, 1f)), Links(galaxy));
}
}
// A cast that names no quest faction places no quest zone: one home for each of its four factions.
[Fact]
public void ACastNamingNoQuestFactionPlacesNoQuestZone()
{
AddPirates();
var galaxy = DemoGalaxy(1);
Assert.Equal(4, galaxy.HomeZones.Count);
Assert.Equal(4, galaxy.Factions.Length);
}
// A name that resolves to nothing refuses the galaxy whichever cast field names it, and the refusal names the field.
[Theory]
[InlineData(nameof(TutorialGenerationSettings.ProtagonistFaction))]
[InlineData(nameof(TutorialGenerationSettings.AntagonistFaction))]
[InlineData(nameof(TutorialGenerationSettings.BufferFaction))]
[InlineData(nameof(TutorialGenerationSettings.QuestFaction))]
[InlineData(nameof(TutorialGenerationSettings.NeutralFactions))]
public void AnUnresolvedCastNameRefusesTheGalaxyNamingItsField(string field)
{
var cast = new TutorialGenerationSettings
{
ProtagonistFaction = _tutorialSettings.ProtagonistFaction,
AntagonistFaction = _tutorialSettings.AntagonistFaction,
BufferFaction = _tutorialSettings.BufferFaction,
QuestFaction = _tutorialSettings.QuestFaction,
NeutralFactions = _tutorialSettings.NeutralFactions,
ZoneCount = _tutorialSettings.ZoneCount,
LinkDensity = _tutorialSettings.LinkDensity
};
typeof(TutorialGenerationSettings).GetField(field).SetValue(cast, field == nameof(cast.NeutralFactions) ? new[] { "Nonesuch" } : "Nonesuch");
var scenario = new Scripted(false, _ => { }, generate: galaxy => galaxy.Prelude(cast));
var refusal = Assert.Throws<InvalidOperationException>(() => RunStart.Generate(scenario, Inputs()));
Assert.Contains(field, refusal.Message);
}
// What a release build lists under New Game is the demo alone; the tutorial and the main galaxy are listed only in
// editor and development builds (MainMenu.ShowScenarios), beside the test arenas.
[Fact]
public void ReleaseBuildsListOnlyTheDemo()
{
Assert.Equal(new[] { typeof(DemoTerminus) }, Scenarios.Modes.Select(scenario => scenario.GetType()));
Assert.Equal(new[] { typeof(TutorialGalaxy), typeof(MainGalaxy) }, Scenarios.Development.Select(scenario => scenario.GetType()));
}
// The tutorial is the galaxy it was before the demo: its cast, homes, entrance and ownership at a fixed seed, with
// no exit and no boss zone.
[Fact]
public void TutorialGalaxy_unchanged()
{
var galaxy = RunStart.Generate(new TutorialGalaxy(), Inputs(() => GalaxySeed));
Assert.Equal(TutorialSeed1, TutorialShape(galaxy));
Assert.True(galaxy.Exit == null, "the tutorial has no exit");
Assert.True(galaxy.BossZones.Count == 0, $"the tutorial has {galaxy.BossZones.Count} boss zones");
}
private static string TutorialShape(Galaxy g) =>
string.Join(",", g.Factions.Select(f => f.Name)) +
" | homes " + string.Join(",", g.Factions.Select(f => g.HomeZones.TryGetValue(f, out var z) ? Array.IndexOf(g.Zones, z) : -2)) +
" | entrance " + Array.IndexOf(g.Zones, g.Entrance) +
" | zones " + g.Zones.Length +
" | owners " + string.Join(",", g.Zones.Select(z => z.Owner == null ? "-" : z.Owner.ShortName));
// Measured on 228f241e, before the demo cut, at seed 1.
private const string TutorialSeed1 =
"Miss Terri’s Sugariffic Snack Company,Zhestokost,Lucent Media,Adrasteia,Aeronautics Unlimited,Finch Cybernetics | homes 47,10,17,49,35,1 | entrance 25 | zones 64 | owners Zhestokost,Finch,Lucent,Zhestokost,Finch,Adrasteia,Zhestokost,Adrasteia,Zhestokost,Zhestokost,Zhestokost,Zhestokost,Finch,Lucent,Adrasteia,Adrasteia,Zhestokost,Lucent,Finch,Finch,Lucent,Lucent,Finch,AU,Adrasteia,-,-,Adrasteia,Lucent,-,AU,Lucent,Zhestokost,Lucent,Lucent,AU,Adrasteia,AU,Lucent,AU,Finch,Finch,-,Lucent,Zhestokost,Zhestokost,Miss Terri's,Miss Terri's,Miss Terri's,Adrasteia,Finch,-,-,Miss Terri's,Lucent,AU,Miss Terri's,Zhestokost,Lucent,Lucent,Lucent,Finch,-,-";
}

View file

@ -285,8 +285,9 @@ public sealed partial class RunStartTests
Assert.True(price > limited * 2f, $"the mount limit priced the limited gun down: {limited} against {price}");
}
// The shipped catalog's weapon behaviours: launchers and guided weapons never mount-track, every other gun is a mount.
private static bool EvMountless(WeaponData data) => data is LauncherData || data is GuidedWeaponData;
// The shipped catalog's weapon behaviours: launchers, guided weapons and mine layers (which lay at no bearing)
// never mount-track, every other gun is a mount.
private static bool EvMountless(WeaponData data) => data is LauncherData || data is GuidedWeaponData || data is MineLayerData;
private IEnumerable<(WeaponItemData item, WeaponData data)> EvCatalogGuns() =>
_cache.GetAll<WeaponItemData>().SelectMany(item => item.Behaviors.OfType<WeaponData>().Select(data => (item, data)));

View file

@ -23,7 +23,7 @@ using int2 = CultMath.int2;
// follows, with the rules this cut's own tests must obey: SchematicCellSize 2 throughout (the 12.3 fixture's
// cell size of 1 would hide a missing `/ SchematicCellSize`), the target off the origin, and a hull whose
// centre of mass is not an integer cell.
public sealed class FireControlCut124Tests : IDisposable
public sealed partial class FireControlCut124Tests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-firecontrolcut124-" + Guid.NewGuid().ToString("N"));
private string Catalog => Path.Combine(_root, "Aetheria.cc");
@ -1396,7 +1396,7 @@ public sealed class FireControlCut124Tests : IDisposable
var e = Build(TestSettings(), SolidShape(5, 4), velocity: 0, fuse: fuse, blastRadius: 4f, damage: 100f,
weaponRange: NoLockRange, targetRange: 40f);
e.Shooter.Direction = float2(0, -1);
Aim(e, float2(0, -1));
Aim(e, float2(0, 1)); // outside the flipped mount's arc too: no solution, and the aim is not free
Assert.Equal(fires, e.Weapon.ArcAllowsFire);
var committed = 0;
using var c = e.Zone.ShotCommitted.Subscribe(_ => committed++);
@ -2594,7 +2594,8 @@ public sealed class FireControlCut124Tests : IDisposable
{
var weapons = cache.GetAll<WeaponItemData>().ToList();
Assert.NotEmpty(weapons);
foreach (var w in weapons)
// A mine layer is the one shipped weapon that carries a blast: its radius is the mine's (MineLauncherCatalogTests).
foreach (var w in weapons.Where(w => !w.Behaviors.OfType<MineLayerData>().Any()))
{
Assert.Null(w.BlastRadius);
Assert.Null(w.Fuse);

View file

@ -364,6 +364,7 @@ public sealed class FireControlCut5Tests : IDisposable
var settings = TestSettings();
settings.FiringArc = 60; // narrow -- an abeam target is well outside it
var e = BuildBeam(settings, float3(100, 0, 0)); // directly abeam
e.Shooter.Aim = float3(0, 0, -1); // astern, outside the arc: nothing bears and the aim is not free
e.Weapon.Activate();
Assert.True(e.Weapon.Firing); // Activate() sets _firing unconditionally, same as InstantWeapon.Trigger
@ -466,11 +467,13 @@ public sealed class FireControlCut5Tests : IDisposable
shooter.Position = float3.zero;
target.Position = float3(100, 0, 0); // directly abeam
shooter.SetTarget(target);
shooter.Aim = float3(0, 0, -1); // astern, outside the arc: only a solution can fire the gun
var weapon = (Weapon) weaponItem.Behaviors.Single(b => b is Weapon);
Assert.False(weapon.ArcAllowsFire);
target.Position = float3(0, 0, 100); // dead ahead
shooter.Aim = float3(0, 0, 1); // the free aim fires, as a gun with no target would
Assert.True(weapon.ArcAllowsFire);
}
@ -489,6 +492,7 @@ public sealed class FireControlCut5Tests : IDisposable
e.Shooter.Position = float3.zero;
e.Target.Position = float3(100, 0, 0); // abeam -- outside the narrow 60-degree arc
e.Shooter.SetTarget(e.Target);
e.Shooter.Aim = float3(0, 0, -1); // astern, outside the arc: nothing bears and the aim is not free
var resolvedCount = 0;
e.Zone.ShotResolved.Subscribe(_ => resolvedCount++);

View file

@ -231,9 +231,9 @@ public sealed class FireControlCut6cTests : IDisposable
var cache = AetheriaStores.Open(Catalog, Run(), Player());
_openCaches.Add(cache);
// A minimal one-zone galaxy whose faction roster excludes Targeting Maker entirely, the same
// SavedGame/Galaxy round trip RunSaveTests uses to build a real Galaxy without standing up full
// procedural generation.
// A minimal one-zone galaxy the same SavedGame/Galaxy round trip RunSaveTests uses builds, without standing
// up full procedural generation. Its generator's faction is Maker, whose allegiance does not name
// Targeting Maker, so IsAvailable rejects Targeting Maker's products by allegiance.
var game = new SavedGame
{
Factions = new[] { maker },
@ -250,13 +250,14 @@ public sealed class FireControlCut6cTests : IDisposable
};
RunSave.Commit(cache, game, zones, new ProvenanceLedger());
var galaxy = new Galaxy(cache, cache.GetGlobal<SavedGame>(), _ => { });
Assert.False(galaxy.ContainsFaction(targetingMaker));
var makerFaction = cache.Get(maker);
Assert.False(makerFaction.Allegiance.ContainsKey(targetingMaker));
var random = new Random(1u);
var settings = TestSettings();
var log = new List<string>();
var items = new ItemManager(cache, new ProvenanceLedger(), settings, log.Add);
var generator = new LoadoutGenerator(ref random, items, galaxy, null, null, .5f);
var generator = new LoadoutGenerator(ref random, items, galaxy, null, makerFaction, .5f);
var pack = generator.GenerateShipLoadout(candidate => candidate.Name == "Armed");

View file

@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.IO;
using CultMath;
using GameCult.Caching;
using Xunit;
// Items are titled by their product (ruling catalog-grows-generic-designs-branded-products): ItemManager.Title reads
// Brand, so the lot's maker picks which of a design's products names the unit, and nothing else carries a name.
public sealed class ItemTitleTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-itemtitle-" + Guid.NewGuid().ToString("N"));
private readonly CultCache _cache;
private readonly ItemManager _items;
private readonly FactionProductData _panopticon, _clapBack, _spiceBlend;
private readonly CultRecordRef<Faction> _stranger;
private readonly CompoundCommodityData _spice;
private readonly GearData _array;
public ItemTitleTests()
{
Directory.CreateDirectory(_root);
_cache = AetheriaStores.Open(Path.Combine(_root, "Aetheria.cc"), catalogWritable: true);
_cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
_array = new GearData { Name = "Array", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10, Durability = 5 };
_cache.Upsert(_array);
_cache.Upsert(new SimpleCommodityData { Name = "Ore", Shape = new Shape(), Price = 7, MaxStack = 100 });
var finch = _cache.Upsert(new Faction { Name = "Finch", ShortName = "FIN" });
var lucent = _cache.Upsert(new Faction { Name = "Lucent", ShortName = "LUC" });
_stranger = _cache.Upsert(new Faction { Name = "Stranger", ShortName = "STR" });
_spice = new CompoundCommodityData { Name = "Spice", Shape = new Shape(), Price = 3 };
_cache.Upsert(_spice);
var design = _cache.RefOf<CraftedItemData>(_cache.GetByName<GearData>("Array"));
_panopticon = new FactionProductData { Name = "Panopticon Prime", Design = design, Manufacturer = finch };
_clapBack = new FactionProductData { Name = "ClapBack Ultra", Design = design, Manufacturer = lucent };
_cache.Commit(batch => batch.Upsert(typeof(FactionProductData), _panopticon, new CultRecordKey("array-finch")));
_cache.Commit(batch => batch.Upsert(typeof(FactionProductData), _clapBack, new CultRecordKey("array-lucent")));
_spiceBlend = new FactionProductData { Name = "Finch Reserve", Design = _cache.RefOf<CraftedItemData>(_spice), Manufacturer = finch };
_cache.Commit(batch => batch.Upsert(typeof(FactionProductData), _spiceBlend, new CultRecordKey("spice-finch")));
_items = new ItemManager(_cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { });
}
public void Dispose()
{
_cache.Dispose();
Directory.Delete(_root, true);
}
[Fact]
public void A_product_unit_is_titled_by_its_product()
{
var unit = _items.CreateInstance(_items.CreateLot(_panopticon));
Assert.Equal("Panopticon Prime", _items.Title(unit));
Assert.NotEqual("Panopticon Prime", _items.GetData(unit).Name);
}
[Fact]
public void Two_makers_title_their_own_units()
{
var finch = _items.CreateInstance(_items.CreateLot(_panopticon));
var lucent = _items.CreateInstance(_items.CreateLot(_clapBack));
Assert.Equal(_items.GetData(finch).Name, _items.GetData(lucent).Name);
Assert.Equal("Panopticon Prime", _items.Title(finch));
Assert.Equal("ClapBack Ultra", _items.Title(lucent));
}
[Fact]
public void Unbranded_units_are_titled_by_design()
{
var given = _items.CreateInstance(_items.CreateLot(_array, default, .5f));
Assert.Equal("Array", _items.Title(given));
var extractedLot = _items.Lots.Add(new Lot
{
Design = _cache.RefOf<ItemData>(_array), Origin = new Extracted(), Quality = .5f, Roles = new List<RoleFill>()
});
Assert.Equal("Array", _items.Title(_items.CreateInstance(extractedLot)));
var ore = new SimpleCommodity { Data = _cache.RefOf<ItemData>(_cache.GetByName<SimpleCommodityData>("Ore")), Quantity = 3 };
Assert.Equal("Ore", _items.Title(ore));
}
[Fact]
public void A_maker_without_a_product_of_the_design_is_titled_by_design()
{
var unit = _items.CreateInstance(_items.CreateLot(_array, _stranger, .5f));
Assert.Equal("Stranger", _items.Brand(unit).Maker.Name);
Assert.Equal("Array", _items.Title(unit));
}
[Fact]
public void A_crafted_commodity_with_a_product_is_titled_by_its_product()
{
var unit = _items.CreateInstance(_items.CreateLot(_spiceBlend));
Assert.IsType<CompoundCommodity>(unit);
Assert.Equal("Finch Reserve", _items.Title(unit));
}
}

View file

@ -0,0 +1,30 @@
using System.Linq;
using Xunit;
// sim-mines-presenter: the shipped catalog carries the Mine Launcher a ship can be fitted with, and what it
// carries is what the sim's mine layer reads (MineLayerData for the mine's own timings, the item's WeaponType,
// Fuse and BlastRadius for the layer and the blast).
public sealed class MineLauncherCatalogTests
{
[Fact]
public void TheShippedCatalogHasAMineLauncherThatLaysMines()
{
var cache = RestoredHullsTests.OpenCatalog();
var launcher = Assert.Single(cache.GetAll<GearData>().OfType<WeaponItemData>(), item => item.Name == "Mine Launcher");
Assert.Equal(HardpointType.Launcher, launcher.HardpointType);
Assert.NotNull(launcher.Shape);
Assert.Contains(cache.GetAll<FactionProductData>(), product => cache.RefOf(launcher).Key.Equals(product.Design.Key));
Assert.Equal(WeaponType.Mine, launcher.WeaponType);
Assert.Equal(WeaponFuse.Proximity, launcher.Fuse);
Assert.Equal(25f, launcher.BlastRadius);
var layer = Assert.IsType<MineLayerData>(Assert.Single(launcher.Behaviors));
Assert.Equal(2f, layer.ArmingDelay);
Assert.Equal(2f, layer.FuseDelay);
Assert.Equal(30f, layer.Lifetime);
Assert.True(layer.Damage.Max > 0f);
Assert.True(layer.Velocity.Max > 0f);
Assert.True(layer.Cooldown.Max > 0f);
}
}

View file

@ -446,6 +446,24 @@ public sealed class MineTests : IDisposable
Assert.True(shipsA[4].Hull.Durability < 1000000f);
}
// The trigger gate never arcs a mine layer (FireControl.ArcPermitsFire; IsMineLayer is its own half of the
// exemption). The layer is unfused, so the fused half cannot pass it: only the mine-layer exemption can. An unfused
// layer lays nothing (Lay), so the gate is the layer this is decided at. The fixture checks the aim is outside
// the arc, with no target designated, so the gate has no other way to pass.
[Fact]
public void AMineLayerPassesTheTriggerGateWithTheAimOutsideItsArc()
{
var lab = Build(fuseKind: null);
Assert.Null(FireControl.FuseOf(lab.WeaponItem, out _));
Assert.True(FireControl.IsMineLayer(lab.Weapon));
lab.Layer.Aim = -FireControl.MountDirection(lab.WeaponItem);
Assert.False(FireControl.InArc(lab.WeaponItem, lab.Layer.Aim), "fixture: the aim must be outside the arc");
Assert.False(FireControl.Solution(lab.Weapon, lab.Layer, lab.Layer.Target.Value).Free);
Assert.False(FireControl.Solution(lab.Weapon, lab.Layer, lab.Layer.Target.Value).Bears);
Assert.True(FireControl.ArcPermitsFire(lab.Weapon, lab.Layer));
}
[Fact]
public void LayingFiresNoShot()
{

View file

@ -719,6 +719,7 @@ public sealed partial class MiningCut3Tests : IDisposable
Tick((shooter, eyeAt));
var gun = shooter.Weapons.Single();
shooter.Aim = float3(0, 0, -1); // astern: only a solution can fire the gun
Assert.True(shooter.SetTarget(ahead));
Assert.True(gun.ArcAllowsFire);
Assert.True(gun.StanceAllowsFire);
@ -728,6 +729,33 @@ public sealed partial class MiningCut3Tests : IDisposable
Assert.True(gun.StanceAllowsFire);
}
// The same bearing through the solution: a chunk ahead is a solution, one to the side is not, and a chunk is a
// solution without a subject entity (its round flies the aim, as an untargeted one).
[Fact]
public void AChunkTargetBearsByItsPose()
{
var kind = Kind("Asteroid", 4f);
var s = BuildScene(new[] { kind }, Belt(kind, Rock(150f, .25f), Rock(150f)));
var eyeAt = float2(-10, 50);
var shooter = SpawnShip(s, eyeAt, sensor: true, weaponRanges: 300f);
Tick((shooter, eyeAt));
var gun = shooter.Weapons.Single();
var ahead = FireControl.Solution(gun, shooter, new ChunkId(s.Belts[0], 0));
var aside = FireControl.Solution(gun, shooter, new ChunkId(s.Belts[0], 1));
Assert.True(ahead.Bears);
Assert.Null(ahead.Subject);
Assert.False(aside.Bears);
// The bearing is the chunk's pose minus the shooter's position: from (100, -100) the side chunk at (150, 0)
// is 26 degrees off the nose, though its pose sum with the shooter's position would be far abeam.
var nearAt = float2(100, -100);
var near = SpawnShip(s, nearAt, sensor: true, weaponRanges: 300f);
Tick((shooter, eyeAt), (near, nearAt));
Assert.True(FireControl.Solution(near.Weapons.Single(), near, new ChunkId(s.Belts[0], 1)).Bears);
}
// A writable copy of the shipped catalog plus a scratch run store, through a registry scoped to the shipped
// assembly's own document types (RestoredHullsTests' composition): this test assembly's own catalog global
// would otherwise be demanded of a catalog that was never authored with it.

View file

@ -0,0 +1,278 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using CultMath;
using UniRx;
using Xunit;
// The demo's goal (aetheria-release, cut boss-gate): the boss zone spawns its faction's boss, and the exit gate opens
// only when that boss is dead. Every input is the production one: the demo galaxy, GenerateZone, the Zone death path,
// and the run save.
public sealed partial class RunStartTests
{
private ZonePack BossZonePack(Galaxy galaxy, ItemManager items, GalaxyZone zone, bool ambient = true)
{
items.Random = new CultMath.Random(7);
return ZoneGenerator.GenerateZone(items, _zoneSettings, galaxy, zone, galaxy.IsPrelude, ambient);
}
private Zone ZoneOf(Galaxy galaxy, GalaxyZone zone) =>
new Zone(_items, _planetSettings, BossZonePack(galaxy, _items, zone), zone, galaxy);
private static Faction Zhestokost(Galaxy galaxy) => galaxy.Factions.Single(faction => faction.Name == "Zhestokost");
private ItemManager LoggingItems(List<string> log) =>
new ItemManager(_cache, new ProvenanceLedger(), AuthoredSettings.Load(FindRepoRoot()).Read<GameplaySettings>("GameplaySettings"), log.Add);
private static string HullName(ItemManager items, EntityPack pack) => items.GetData(pack.Hull).Name;
private HullData[] SoldShipHulls() => _cache.GetAll<FactionProductData>()
.Where(product => product.Manufacturer.IsSet())
.Select(product => _cache.Get(product.Design) as HullData)
.Where(hull => hull != null && hull.HullType == HullType.Ship && hull.Price > 0)
.Distinct().ToArray();
[Fact]
public void Boss_spawns_once_in_boss_zone()
{
AddPirates();
foreach (var seed in DemoSeeds.Take(3))
{
var galaxy = DemoGalaxy(seed);
var antagonist = Zhestokost(galaxy);
foreach (var zone in galaxy.Zones)
{
var bosses = BossZonePack(galaxy, _items, zone).Entities.Where(entity => entity.Boss).ToArray();
if (zone != galaxy.Exit) { Assert.Empty(bosses); continue; }
var boss = Assert.Single(bosses);
Assert.IsType<ShipPack>(boss);
Assert.Same(antagonist, _cache.Get(boss.Faction));
// Generation is repeatable per zone: the same zone yields the same boss hull.
var again = Assert.Single(BossZonePack(galaxy, _items, zone).Entities, entity => entity.Boss);
Assert.Equal(HullName(_items, boss), HullName(_items, again));
}
}
}
// A zone that is not ambient still has its boss: the boss is the goal, not traffic.
[Fact]
public void Boss_spawns_in_a_zone_that_is_not_ambient()
{
AddPirates();
var galaxy = DemoGalaxy(1);
var pack = BossZonePack(galaxy, _items, galaxy.Exit, ambient: false);
Assert.Single(pack.Entities, entity => entity.Boss);
Assert.DoesNotContain(pack.Entities, entity => !entity.Boss && entity is ShipPack);
}
[Fact]
public void Boss_hull_from_BossHull_else_fallback()
{
AddPirates();
var galaxy = DemoGalaxy(1);
var antagonist = Zhestokost(galaxy);
var hulls = SoldShipHulls().OrderByDescending(hull => hull.Price).ThenBy(hull => hull.Name, StringComparer.Ordinal).ToArray();
var priciest = hulls.First();
var cheaper = hulls.Last();
Assert.True(cheaper.Price < priciest.Price, "the catalog needs two ship hulls of different price for this test to tell them apart");
// Set and sold: the boss flies it, and nothing is logged about a gap.
antagonist.BossHull = _cache.RefOf(cheaper);
var log = new List<string>();
var items = LoggingItems(log);
var boss = Assert.Single(BossZonePack(galaxy, items, galaxy.Exit).Entities, entity => entity.Boss);
Assert.Equal(cheaper.Name, HullName(items, boss));
Assert.DoesNotContain(log, line => line.Contains("BossHull"));
// Unset: the most expensive ship hull on offer, and the log names the missing BossHull.
antagonist.BossHull = default;
log.Clear();
boss = Assert.Single(BossZonePack(galaxy, items, galaxy.Exit).Entities, entity => entity.Boss);
Assert.Equal(priciest.Name, HullName(items, boss));
Assert.Contains(log, line => line.Contains("Zhestokost") && line.Contains("no BossHull"));
}
// Set but sold by no product: the boss falls back the same way, and the log says which hull has no seller.
[Fact]
public void Boss_hull_nobody_sells_falls_back()
{
AddPirates();
var galaxy = DemoGalaxy(1);
var antagonist = Zhestokost(galaxy);
var sold = SoldShipHulls();
// A ship hull no product sells, dearer than any that is sold: the fallback must not pick it.
var unsold = new HullData { Name = "Unsold Test Hull", HullType = HullType.Ship, Price = sold.Max(hull => hull.Price) + 1 };
_cache.Upsert(unsold);
antagonist.BossHull = _cache.RefOf(unsold);
var log = new List<string>();
var items = LoggingItems(log);
var boss = Assert.Single(BossZonePack(galaxy, items, galaxy.Exit).Entities, entity => entity.Boss);
Assert.Equal(sold.OrderByDescending(hull => hull.Price).ThenBy(hull => hull.Name, StringComparer.Ordinal).First().Name, HullName(items, boss));
Assert.Contains(log, line => line.Contains(unsold.Name) && line.Contains("BossHull"));
}
[Fact]
public void Exit_sealed_until_boss_dies()
{
AddPirates();
var galaxy = DemoGalaxy(1);
var exit = ZoneOf(galaxy, galaxy.Exit);
var boss = Assert.Single(exit.Entities, entity => entity.IsBoss);
Assert.True(RunGoal.BossAlive(exit));
Assert.False(RunGoal.ExitOpen(exit));
// Death removes the boss from the zone (the one death path), and that alone opens the gate.
boss.HeatstrokeDeath.OnNext(Unit.Default);
Assert.DoesNotContain(boss, exit.Entities);
Assert.False(RunGoal.BossAlive(exit));
Assert.True(RunGoal.ExitOpen(exit));
// No other zone is ever an exit, boss or no boss.
foreach (var zone in galaxy.Zones.Where(zone => zone != galaxy.Exit))
Assert.False(RunGoal.ExitOpen(ZoneOf(galaxy, zone)));
}
// Continue: the mark is saved with the zone and restored, so a boss alive when the run was saved is alive after.
[Fact]
public void Boss_mark_survives_continue()
{
AddPirates();
var (galaxy, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1));
Assert.True(failures.Count == 0, string.Join("; ", failures));
galaxy.Entrance.Contents = arena;
galaxy.Exit.Contents = ZoneOf(galaxy, galaxy.Exit);
var before = Assert.Single(galaxy.Exit.Contents.Entities, entity => entity.IsBoss);
Assert.False(RunGoal.ExitOpen(galaxy.Exit.Contents));
var (game, zones) = RunSave.Capture(_cache, galaxy, arena, staged.Player, new SavedActionBarBinding[0], 0);
RunSave.Commit(_cache, game, zones, _items.Lots);
var restored = new Galaxy(_cache, _cache.GetGlobal<SavedGame>(), _ => { });
var exit = new Zone(_items, _planetSettings, restored.Exit.PackedContents, restored.Exit, restored);
var after = Assert.Single(exit.Entities, entity => entity.IsBoss);
Assert.Equal(before.Name, after.Name);
Assert.Equal(before.Faction.Name, after.Faction.Name);
Assert.False(RunGoal.ExitOpen(exit));
after.HeatstrokeDeath.OnNext(Unit.Default);
Assert.True(RunGoal.ExitOpen(exit));
}
// The gate fails closed. The main galaxy puts its bosses on choke points, not at its exit, so its exit zone never gets
// one: the gate stays sealed on arrival and when every boss in the galaxy dies, because a boss that never existed is
// not a dead one.
[Fact]
public void Exit_sealed_where_no_boss_was_spawned_main_galaxy()
{
foreach (var seed in new uint[] { 1, 2, 3, 4, 5, 6, 7, 8 })
{
var galaxy = RunStart.Generate(new MainGalaxy(), Inputs(() => seed));
var exit = ZoneOf(galaxy, galaxy.Exit);
Assert.False(RunGoal.ExitOpen(exit), $"seed {seed}: the gate is open on arrival");
foreach (var boss in exit.Entities.Where(entity => entity.IsBoss).ToArray())
boss.HeatstrokeDeath.OnNext(Unit.Default);
Assert.False(RunGoal.ExitOpen(exit), $"seed {seed}: the gate is open with no boss spawned");
}
}
// The same for a demo exit whose boss could not be generated: the zone logs the gap by name and the gate stays sealed.
[Fact]
public void Exit_sealed_and_logged_when_the_boss_cannot_be_generated()
{
AddPirates();
var galaxy = DemoGalaxy(1);
galaxy.BossZones.Clear();
var log = new List<string>();
var items = LoggingItems(log);
var pack = BossZonePack(galaxy, items, galaxy.Exit);
Assert.False(pack.BossSpawned);
Assert.Contains(log, line => line.Contains("Galaxy.Exit") && line.Contains("exit-without-boss"));
var exit = new Zone(items, _planetSettings, pack, galaxy.Exit, galaxy);
Assert.False(RunGoal.ExitOpen(exit));
}
// A boss killed before the save stays dead after it, and the gate stays open: the spawn fact travels with the zone.
[Fact]
public void Exit_open_after_save_of_a_slain_boss()
{
AddPirates();
var galaxy = DemoGalaxy(1);
var exit = ZoneOf(galaxy, galaxy.Exit);
Assert.Single(exit.Entities, entity => entity.IsBoss).HeatstrokeDeath.OnNext(Unit.Default);
var repacked = exit.PackZone();
Assert.True(repacked.BossSpawned);
Assert.DoesNotContain(repacked.Entities, entity => entity.Boss);
Assert.True(RunGoal.ExitOpen(new Zone(_items, _planetSettings, repacked, galaxy.Exit, galaxy)));
}
// The gate shares no point with an adjacency wormhole: every one is farther from it than a ship's wormhole reach.
[Fact]
public void Exit_gate_shares_no_point_with_a_wormhole()
{
AddPirates();
var ratio = float.Parse(File.ReadLines(Path.Combine(FindRepoRoot(), "Assets", "Resources", "Settings.asset"))
.Select(line => Regex.Match(line, @"^ WormholeDistanceRatio: (.+)$")).First(match => match.Success).Groups[1].Value.Trim(),
System.Globalization.CultureInfo.InvariantCulture);
var reach = AuthoredSettings.Load(FindRepoRoot()).Read<GameplaySettings>("GameplaySettings").WormholeExitRadius;
foreach (var seed in DemoSeeds)
{
var galaxy = DemoGalaxy(seed);
var zone = ZoneOf(galaxy, galaxy.Exit);
var gate = RunGoal.ExitGatePosition(zone, ratio);
foreach (var adjacent in galaxy.Exit.AdjacentZones)
{
var wormhole = math.normalize(adjacent.Position - galaxy.Exit.Position) * zone.Pack.Radius * ratio;
Assert.True(math.length(gate - wormhole) > 2 * reach, $"seed {seed}: the exit gate sits {math.length(gate - wormhole)} from a wormhole");
}
}
}
// The gate sits on the wormholes' radius, in the middle of the widest gap between neighbours, whatever the
// neighbours' number and order: an empty ring, one, two straddling the +-pi seam, and eight spread evenly (every gap
// under one radian). Checked against a brute-force sweep of every direction.
[Theory]
[InlineData(new double[0])]
[InlineData(new[] { 40.0 })]
[InlineData(new[] { 170.0, -170.0 })]
[InlineData(new[] { 100.0, 10.0, 20.0, 350.0, -90.0 })]
[InlineData(new[] { 0.0, 45.0, 90.0, 135.0, 180.0, -135.0, -90.0, -45.0 })]
public void Exit_gate_sits_in_the_widest_gap_at_the_wormhole_radius(double[] neighbourDegrees)
{
AddPirates();
var galaxy = DemoGalaxy(1);
var zone = ZoneOf(galaxy, galaxy.Exit);
const float ratio = 0.75f;
var radius = zone.Pack.Radius * ratio;
// Away from the origin and with close neighbours, so a direction taken from raw positions instead of the
// offset from the zone cannot pass.
var originalPosition = galaxy.Exit.Position;
var origin = galaxy.Exit.Position = math.float2(500, -300);
var original = galaxy.Exit.AdjacentZones;
galaxy.Exit.AdjacentZones = neighbourDegrees
.Select(degrees => new GalaxyZone
{
Position = origin + math.float2((float) Math.Cos(degrees * Math.PI / 180), (float) Math.Sin(degrees * Math.PI / 180)) * 10
}).ToList();
float2 gate;
try { gate = RunGoal.ExitGatePosition(zone, ratio); }
finally { galaxy.Exit.AdjacentZones = original; galaxy.Exit.Position = originalPosition; }
Assert.Equal(radius, math.length(gate), 2);
if (neighbourDegrees.Length == 0) { Assert.Equal(radius, gate.x, 2); Assert.Equal(0, gate.y, 2); return; }
double Separation(double angle) => neighbourDegrees.Min(degrees =>
{
var difference = Math.Abs(angle - degrees * Math.PI / 180) % (2 * Math.PI);
return difference > Math.PI ? 2 * Math.PI - difference : difference;
});
var best = Enumerable.Range(0, 7200).Max(step => Separation(step * Math.PI / 3600));
Assert.True(Separation(Math.Atan2(gate.y, gate.x)) >= best - 0.002,
$"the gate's nearest wormhole is {Separation(Math.Atan2(gate.y, gate.x))} rad away; the widest gap's middle is {best}");
}
}

View file

@ -0,0 +1,134 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.Collections.Generic;
using System.Linq;
using GameCult.Caching;
using Xunit;
// Gear does not need its maker present: LoadoutGenerator.IsAvailable reaches by allegiance alone, and an absent
// maker only weighs less (operator, 2026-10-06: a faction need not be present in the galaxy for its gear to be
// available). Every galaxy reaches the same way, the prelude included.
public sealed partial class RunStartTests
{
// A maker the galaxy does not carry, with one product made from a real design, and a generator for a fresh
// faction whose allegiance names exactly the makers given (the absent one among them, or not).
private (FactionProductData product, Faction absent) AbsentMaker(string name)
{
var absent = new Faction { Name = name, ShortName = name };
_cache.Upsert(absent);
var design = _cache.GetAll<FactionProductData>().First(p => p.Manufacturer.IsSet()).Design;
var product = new FactionProductData { Name = name + " Product", Design = design, Manufacturer = _cache.RefOf(absent) };
_cache.Upsert(product);
return (product, absent);
}
private LoadoutGenerator GeneratorFor(Galaxy galaxy, string name, params Faction[] allies)
{
var faction = new Faction { Name = name, ShortName = name };
_cache.Upsert(faction);
foreach (var ally in allies) faction.Allegiance[_cache.RefOf(ally)] = 1;
return new LoadoutGenerator(ref _items.Random, _items, galaxy, galaxy.Entrance, faction, .5f);
}
[Fact]
public void AnAbsentMakersGearIsAvailableThroughAllegiance()
{
var galaxy = MainSectorGalaxy();
var (product, absent) = AbsentMaker("AbsentAlly");
Assert.DoesNotContain(galaxy.Factions, f => f == absent);
Assert.True(GeneratorFor(galaxy, "Friend", absent).IsAvailable(product));
}
[Fact]
public void AnAbsentMakerOutsideAllegianceIsNot()
{
var galaxy = MainSectorGalaxy();
var (product, _) = AbsentMaker("AbsentStranger");
Assert.False(GeneratorFor(galaxy, "Loner").IsAvailable(product));
}
[Fact]
public void AFactionlessGeneratorReachesEveryMaker()
{
var galaxy = MainSectorGalaxy();
AbsentMaker("AbsentToAll");
var generator = new LoadoutGenerator(ref _items.Random, _items, galaxy, galaxy.Entrance, null, .5f);
var products = _cache.GetAll<FactionProductData>().Where(p => p.Manufacturer.IsSet()).ToArray();
Assert.NotEmpty(products);
Assert.All(products, product => Assert.True(generator.IsAvailable(product), product.Name));
}
[Fact]
public void AnAbsentMakerWeighsAsTheFarthest()
{
var galaxy = MainSectorGalaxy();
var (product, absent) = AbsentMaker("AbsentFar");
var zone = galaxy.Entrance;
var farthest = galaxy.Factions
.Where(f => galaxy.HomeZones.TryGetValue(f, out var home) && zone.Distance.ContainsKey(home))
.OrderByDescending(f => zone.Distance[galaxy.HomeZones[f]]).First();
var generator = GeneratorFor(galaxy, "Trader", absent, farthest);
var absentWeight = generator.ManufacturerPreference(product.Manufacturer);
var farthestWeight = generator.ManufacturerPreference(_cache.RefOf(farthest));
Assert.True(absentWeight > 0, "an absent ally is reachable");
Assert.True(absentWeight < farthestWeight, $"absent {absentWeight} must weigh below the farthest present maker {farthestWeight}");
Assert.Equal(1f / (2 + zone.Distance.Values.Max()), absentWeight);
}
[Fact]
public void APreludeNoLongerOffersEverything()
{
Assert.True(_galaxy.IsPrelude);
var (absentProduct, _) = AbsentMaker("AbsentToPrelude");
var generator = GeneratorFor(_galaxy, "PreludeLoner");
Assert.False(generator.IsAvailable(absentProduct));
var present = _cache.GetAll<FactionProductData>().Where(p => p.Manufacturer.IsSet() &&
_galaxy.Factions.Any(f => _cache.RefOf(f).Key.Equals(p.Manufacturer.Key))).ToArray();
Assert.NotEmpty(present);
Assert.All(present, product => Assert.False(generator.IsAvailable(product), product.Name));
}
// Preference only weighs by distance when there is a galaxy and a faction to weigh for.
[Fact]
public void PreferenceIsNeutralWithoutAGalaxyOrAFaction()
{
var galaxy = MainSectorGalaxy();
var (product, absent) = AbsentMaker("AbsentNeutral");
var faction = galaxy.Factions.First();
var noGalaxy = new LoadoutGenerator(ref _items.Random, _items, null, null, faction, .5f);
var noFaction = new LoadoutGenerator(ref _items.Random, _items, galaxy, galaxy.Entrance, null, .5f);
Assert.Equal(1f, noGalaxy.ManufacturerPreference(product.Manufacturer));
Assert.Equal(1f, noFaction.ManufacturerPreference(product.Manufacturer));
}
// A maker the generator's faction does not name weighs nothing, present or not.
[Fact]
public void AMakerOutsideAllegianceWeighsNothing()
{
var galaxy = MainSectorGalaxy();
var (product, _) = AbsentMaker("AbsentUnnamed");
var generator = GeneratorFor(galaxy, "Hermit");
var stranger = galaxy.Factions.First();
Assert.Equal(0f, generator.ManufacturerPreference(product.Manufacturer));
Assert.Equal(0f, generator.ManufacturerPreference(_cache.RefOf(stranger)));
}
// The distance table decides: a present maker whose home the table does not reach adds no distance, an absent
// maker is one jump past the table's farthest zone, and an empty table adds none either way.
[Fact]
public void ADistanceTableOnlyDistancesTheMakersItNames()
{
var galaxy = MainSectorGalaxy();
var (product, absent) = AbsentMaker("AbsentOffTable");
var present = galaxy.Factions.First(f => galaxy.HomeZones.TryGetValue(f, out var home) && home != galaxy.Entrance);
var friend = GeneratorFor(galaxy, "Ally", absent, present);
var table = new GalaxyZone { Distance = new Dictionary<GalaxyZone, int> { { galaxy.Entrance, 0 } } };
var generator = new LoadoutGenerator(ref _items.Random, _items, galaxy, table, friend.Faction, .5f);
Assert.Equal(1f, generator.ManufacturerPreference(_cache.RefOf(present))); // home not in the table: distance 0
Assert.Equal(.5f, generator.ManufacturerPreference(product.Manufacturer)); // absent: 0 + 1
var empty = new LoadoutGenerator(ref _items.Random, _items, galaxy, new GalaxyZone { Distance = new Dictionary<GalaxyZone, int>() }, friend.Faction, .5f);
Assert.Equal(1f, empty.ManufacturerPreference(product.Manufacturer));
}
}

View file

@ -119,8 +119,8 @@ public sealed partial class RunStartTests : IDisposable
private const float Freezing = 273.15f;
// A main-sector galaxy (not the prelude, which offers every product): each station's gear must come from
// manufacturers its faction can reach, the galaxy's factions its allegiance names.
// A main-sector galaxy: each station's gear must come from manufacturers its faction can reach, the makers its
// allegiance names, present in the galaxy or not.
private Galaxy MainSectorGalaxy()
{
var authored = AuthoredSettings.Load(FindRepoRoot());

View file

@ -44,7 +44,7 @@ public sealed partial class RunStartTests
public override void Stage(ScenarioStage stage) => _stage(stage);
}
private static IEnumerable<Scenario> EveryScenario => Scenarios.Modes.Concat(Scenarios.Tests);
private static IEnumerable<Scenario> EveryScenario => Scenarios.Modes.Concat(Scenarios.Development).Concat(Scenarios.Tests);
// The galaxy inputs the menu hands to RunStart, read from the authored settings.
private GalaxyStage Inputs(Func<uint> clock = null)
@ -96,6 +96,7 @@ public sealed partial class RunStartTests
[Fact]
public void EveryScenarioStages()
{
AddPirates();
Assert.Equal(EveryScenario.Count(), EveryScenario.Select(scenario => scenario.Name).Distinct().Count());
foreach (var scenario in EveryScenario)
{
@ -522,6 +523,7 @@ public sealed partial class RunStartTests
[Fact]
public void EveryUnsoldDesignIsAScenarioTestDesign()
{
AddPirates();
var runs = EveryScenario.Select(scenario => Launch(scenario, Inputs(() => GalaxySeed)).staged).ToList();
Assert.Empty(UnsoldAndUnplaced(runs));

View file

@ -0,0 +1,26 @@
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
// 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.
public sealed class ShippedWeaponOperabilityTests
{
[Fact]
public void EveryShippedWeaponPerformsAtAHullsStartingTemperature()
{
using var cache = RestoredHullsTests.OpenCatalog();
var weapons = cache.GetAll<GearData>().OfType<WeaponItemData>().ToArray();
Assert.NotEmpty(weapons);
var threshold = new EntitySettings().ShutdownPerformance;
Assert.True(threshold > 0f);
var dead = weapons.Where(weapon => weapon.Performance(Entity.StartingCellTemperature) <= threshold)
.Select(weapon => $"{weapon.Name} ({weapon.MinimumTemperature}..{weapon.MaximumTemperature} K)").ToArray();
Assert.Empty(dead);
}
}

View file

@ -0,0 +1,210 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using CultMath;
using Xunit;
using static CultMath.math;
using float2 = CultMath.float2;
using float3 = CultMath.float3;
// Controls 2 (rulings fire-on-solutions, controls-solution-subject, controls-solution-trigger): FireControl.Solution is
// each gun's one solution against the designated target, and ArcPermitsFire is the one trigger gate over it. The
// fixture is FireControlCut124Tests': a forward mount at the origin facing +z, the designated target 100 ahead.
public sealed partial class FireControlCut124Tests
{
private const float SolutionArc = 120f;
private static GunSolution SolutionOf(Engagement e) => FireControl.Solution(e.Weapon, e.Shooter, e.Shooter.Target.Value);
// A designated target in the arc is fired on whatever the aim says; the round goes to its intercept, not the aim.
// Kills an aim-only gate (the astern aim holds) and a direction that ignores the subject.
[Fact]
public void ASolutionFiresWithoutTheAim()
{
var e = Build(TestSettings(), SolidShape(5, 4), hardpointArc: SolutionArc);
Aim(e, float2(0, -1));
var solution = SolutionOf(e);
Assert.True(FireControl.ArcPermitsFire(e.Weapon, e.Shooter));
Assert.True(solution.Bears);
Assert.False(solution.Free);
Assert.Same(e.Target, solution.Subject);
Near(FireControl.TravelDirection(e.Weapon, e.Shooter, e.Target), solution.Direction);
Near(float2(0, 1), solution.Direction);
}
[Fact]
public void FreeFireNeedsTheAimInArc()
{
var e = Build(TestSettings(), SolidShape(5, 4), hardpointArc: SolutionArc);
e.Shooter.SetTarget(TargetRef.None);
Aim(e, float2(0, 1));
Assert.True(FireControl.ArcPermitsFire(e.Weapon, e.Shooter));
var free = SolutionOf(e);
Assert.True(free.Free);
Assert.False(free.Bears);
Near(float2(0, 1), free.Direction);
Aim(e, float2(0, -1));
Assert.False(FireControl.ArcPermitsFire(e.Weapon, e.Shooter));
Assert.False(SolutionOf(e).Free);
}
// A designated target 90 degrees off a 120 degree forward mount gives no solution. With the aim astern the gun
// holds; with the aim ahead it fires free along the aim, and the price of that shot is zero.
[Fact]
public void ATargetOutOfArcGivesNoSolution()
{
var e = Build(TestSettings(), SolidShape(5, 4), hardpointArc: SolutionArc, weaponRange: 200f);
e.Target.Position = e.Shooter.Position + float3(100, 0, 0);
Aim(e, float2(0, -1));
Assert.False(SolutionOf(e).Bears);
Assert.False(FireControl.ArcPermitsFire(e.Weapon, e.Shooter));
Aim(e, float2(0, 1));
var solution = SolutionOf(e);
Assert.False(solution.Bears);
Assert.True(solution.Free);
Assert.True(FireControl.ArcPermitsFire(e.Weapon, e.Shooter));
Near(float2(0, 1), solution.Direction);
Assert.True(ReferenceEquals(e.Target, solution.Subject), "a designated target out of arc is still the solution's subject");
Assert.Equal(0f, FireControl.HitProbability(e.Weapon, e.Shooter, e.Target));
}
[Fact]
public void AFusedWeaponIgnoresTheGate()
{
var e = Build(TestSettings(), SolidShape(5, 4), fuse: WeaponFuse.Proximity, blastRadius: 4f, weaponRange: NoLockRange, hardpointArc: SolutionArc);
e.Shooter.SetTarget(TargetRef.None);
Aim(e, float2(0, -1));
var solution = SolutionOf(e);
Assert.False(solution.Bears);
Assert.False(solution.Free);
Assert.True(FireControl.ArcPermitsFire(e.Weapon, e.Shooter));
}
// HitProbability above zero implies Bears and no Bears means no price, over bearings, ranges and visibility around
// a weapon of range 100: the price's gate and the solution's are the one Bears. The grid is checked to price
// something, so a gate that closed everything could not pass it.
[Fact]
public void BearsIsThePricesGate()
{
var e = Build(TestSettings(), SolidShape(5, 4), hardpointArc: SolutionArc, weaponRange: 100f);
var priced = 0;
foreach (var degrees in new[] { 0f, 30f, 59f, 61f, 90f, 135f, 180f })
foreach (var range in new[] { 20f, 99f, 101f, 150f })
foreach (var visible in new[] { true, false })
{
var at = radians(degrees);
e.Target.Position = e.Shooter.Position + float3(sin(at), 0, cos(at)) * range;
if (visible && !e.Shooter.VisibleEntities.Contains(e.Target)) e.Shooter.VisibleEntities.Add(e.Target);
if (!visible) e.Shooter.VisibleEntities.Remove(e.Target);
var bears = FireControl.Bears(e.Weapon, e.Shooter, e.Target, out _);
var price = FireControl.HitProbability(e.Weapon, e.Shooter, e.Target);
Assert.Equal(bears, SolutionOf(e).Bears);
if (price > 0f) Assert.True(bears, $"priced {price} at {degrees} degrees, {range} out, visible {visible}, without bearing");
if (!bears) Assert.Equal(0f, price);
if (price > 0f) priced++;
}
Assert.True(priced > 0, "fixture: nothing on the grid was priced");
}
// Each branch of what a round does flies along Solution.Direction as it stood at fire time: a target that bears
// (aim ignored), an unfused round at a designated target out of arc (the clamped aim), a fused round with no lock.
[Fact]
public void SolveFliesAlongTheSolution()
{
var bearing = Build(TestSettings(), SolidShape(5, 4), hardpointArc: SolutionArc);
Aim(bearing, float2(0, -1));
Assert.True(SolutionOf(bearing).Bears);
AssertFlies(bearing);
var outOfArc = Build(TestSettings(), SolidShape(5, 4), hardpointArc: SolutionArc, weaponRange: 200f);
outOfArc.Target.Position = outOfArc.Shooter.Position + float3(100, 0, 0);
Aim(outOfArc, float2(1, 4));
Assert.False(SolutionOf(outOfArc).Bears);
AssertFlies(outOfArc);
var fused = Build(TestSettings(), SolidShape(5, 4), fuse: WeaponFuse.Proximity, blastRadius: 4f, weaponRange: NoLockRange, hardpointArc: SolutionArc);
fused.Shooter.SetTarget(TargetRef.None);
Aim(fused, float2(0, -1));
AssertFlies(fused);
}
private static void AssertFlies(Engagement e)
{
var direction = SolutionOf(e).Direction;
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
Near(direction, SafeAssert.OnlyShot(e.Zone).TravelDirection);
}
[Fact]
public void AFullArcTracksTheAimAllRound()
{
var settings = TestSettings();
settings.FiringArc = 360;
var e = Build(settings, SolidShape(5, 4));
e.Shooter.SetTarget(TargetRef.None);
for (var degrees = 0; degrees < 360; degrees += 30)
{
var aim = float2(sin(radians(degrees)), cos(radians(degrees)));
Aim(e, aim);
Assert.True(FireControl.ArcPermitsFire(e.Weapon, e.Shooter));
Near(aim, SolutionOf(e).Direction);
}
}
// An agent's aim is its intercept (Combat sets it), so an in-arc target is a solution and the free aim both: its
// fire is the same with or without the aim.
[Fact]
public void TheAgentStillFiresAtItsIntercept()
{
var e = Build(TestSettings(), SolidShape(5, 4), hardpointArc: SolutionArc);
var intercept = FireControl.TravelDirection(e.Weapon, e.Shooter, e.Target);
Aim(e, intercept);
var solution = SolutionOf(e);
Assert.True(solution.Bears && solution.Free);
Assert.True(FireControl.ArcPermitsFire(e.Weapon, e.Shooter));
Assert.True(FireControl.AgentFires(e.Weapon, e.Shooter, e.Target));
Near(intercept, solution.Direction);
}
// Solve flies along the solution against the target it is given, not the shooter's designated one (the HUD forecast
// and an agent's burst ask about other entities). A decoy 40 degrees off, in the same zone, is passed while the
// designated target sits dead ahead; the round goes to the decoy's intercept. Kills a Solve that reads the shooter's
// target, a constant, or a swapped argument; the fixture checks the two intercepts differ.
[Fact]
public void SolveFliesToTheTargetItIsGiven()
{
var e = Build(TestSettings(), SolidShape(5, 4), hardpointArc: SolutionArc, weaponRange: 200f);
var hull = e.Items.ItemData.RefOf<ItemData>(e.HullData);
var decoy = new Ship(e.Items, e.Zone, new EquippableItem { Data = hull, Durability = 1000000, Lot = 400 }, new EntitySettings());
e.Zone.Entities.Add(decoy);
decoy.Activate();
var at = radians(40f);
decoy.Position = e.Shooter.Position + float3(sin(at), 0, cos(at)) * 100f;
e.Shooter.VisibleEntities.Add(decoy);
e.Shooter.EntityInfoGathered[decoy] = 1f;
e.Shooter.SetIff(decoy, true);
Aim(e, float2(0, -1));
var designated = FireControl.Solution(e.Weapon, e.Shooter, e.Target).Direction;
var other = FireControl.Solution(e.Weapon, e.Shooter, decoy).Direction;
Assert.True(FireControl.Bears(e.Weapon, e.Shooter, decoy, out _));
Assert.True(length(designated - other) > .3f, "fixture: the two intercepts must differ");
Assert.Same(e.Target, e.Shooter.Target.Value.Entity);
Near(other, FireControl.Solve(e.Weapon, e.WeaponItem, e.Shooter, decoy).TravelDirection);
Near(designated, FireControl.Solve(e.Weapon, e.WeaponItem, e.Shooter, e.Target).TravelDirection);
}
}