From c39a73ca12af2a31a06694790157ccbc1d6240f0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 09:00:21 +0200 Subject: [PATCH] Tests: belts fill their slots, five placement rules pinned by forced fixtures BeltsFillTheirSlots (midpoint, slot bound, no zero-width belt, width distribution printed), ANarrowAuthoredBeltKeepsItsWidth, ASoleRootRingSitsAtThreeEighthsOfItsRadius, ARingMembersChildrenStayWithinAFifthOfTheChord, ATurretTailStopsAtItsBaseBody and ATutorialEntranceWithNoCandidateOrbitsItsBodyRootOutsideItsExtent. Not yet run. Co-Authored-By: Claude Opus 5.5 --- .../ChildrenWithinReachTests.cs | 137 +++++++++++++++++- .../StationPlacementTests.cs | 103 ++++++++++++- 2 files changed, 232 insertions(+), 8 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs index bc675821b..96ffb8b82 100644 --- a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs +++ b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs @@ -18,10 +18,14 @@ public sealed class ChildrenWithinReachTests : IClassFixture All = new List<(uint, Zone)>(); + public ZoneGenerationSettings Settings; - public Zones() + public Zones() : this(1, 6, null) { } + + // Not public: xunit builds the fixture through its one public constructor; a test that wants a tuned sample builds its own. + internal Zones(uint first, uint last, Action tune) { - for (uint seed = 1; seed <= 6; seed++) + for (uint seed = first; seed <= last; seed++) { var dir = Path.Combine(_worlds.Root, $"galaxy{seed}"); Directory.CreateDirectory(dir); @@ -40,7 +44,9 @@ public sealed class ChildrenWithinReachTests : IClassFixture("PlanetSettings"); foreach (var galaxyZone in galaxy.Zones) { - var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), planetSettings, galaxy, galaxyZone, + Settings = authored.Read("ZoneSettings"); + tune?.Invoke(Settings); + var pack = ZoneGenerator.GenerateZone(items, Settings, planetSettings, galaxy, galaxyZone, galaxyZone == galaxy.Entrance && galaxy.IsPrelude, false); All.Add((seed, new Zone(items, planetSettings, pack, galaxyZone, galaxy))); } @@ -349,6 +355,131 @@ public sealed class ChildrenWithinReachTests : IClassFixture 20, $"only {belts} belts checked"); } + private static float Percentile(List sorted, float fraction) => sorted[Math.Min(sorted.Count - 1, (int) (fraction * sorted.Count))]; + + // A belt fills the slot between its neighbours' spacing, its parent's Roche margin and the parent's window, up to the + // authored width (ruling belt-fills-its-slot): it sits at the slot's midpoint where the test can spell both edges, and + // none collapses to a line (finding belts-collapse-to-a-line). Rocks are scattered inside the belt's half width, so their + // spread is at most the belt's width; a belt beside another belt has an edge only the generator knows, and is checked + // against the weaker bound. + [Fact] + public void BeltsFillTheirSlots() + { + var q = 1 / (1 - GravityField.Reach / 2); + var ratios = new List(); + int belts = 0, bounded = 0, midpoints = 0, lines = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + var beltAt = zone.AsteroidBelts.ToDictionary(b => zone.Planets[b.Key].Orbit.Key, b => b.Value.Data.Asteroids); + foreach (var (orbit, rocks) in beltAt) + { + var parent = zone.Orbits[orbit].Data.Parent.Key; + if (rocks.Length == 0 || !mass.TryGetValue(parent, out var parentMass)) continue; + belts++; + var sibling = ChildrenOf(zone, parent, placed); + var at = sibling.IndexOf(orbit); + var d = DistanceOf(zone, orbit); + var spread = rocks.Max(a => a.Distance) - rocks.Min(a => a.Distance); + var width = _zones.Settings.AsteroidBeltWidth.Evaluate(d); + ratios.Add(spread / width); + if (spread < 1e-3f) lines++; + + var prevIsBelt = at > 0 && beltAt.ContainsKey(sibling[at - 1]); + var nextIsBelt = at < sibling.Count - 1 && beltAt.ContainsKey(sibling[at + 1]); + var prevEdge = at == 0 ? 0f : prevIsBelt && beltAt[sibling[at - 1]].Length > 0 ? beltAt[sibling[at - 1]].Max(a => a.Distance) : DistanceOf(zone, sibling[at - 1]); + var inner = Math.Max(RocheMargin * Roche(zone, parentMass), prevEdge * q); + var grand = zone.Orbits[parent].Data.Parent; + var window = grand.IsSet() ? GravityField.Gamma * GravityField.Reach * DistanceOf(zone, parent) / Math.Max(GravityField.Beta, 1 + GravityField.Reach) : float.PositiveInfinity; + var next = at < sibling.Count - 1 && !nextIsBelt ? DistanceOf(zone, sibling[at + 1]) / q : float.PositiveInfinity; + var outerLimit = Math.Min(window, next); + if (!nextIsBelt) bounded++; + Assert.True(spread <= Math.Min(width, outerLimit - inner) * (1 + Tolerance), + $"seed {seed}: a belt spreads {spread} in a slot of {outerLimit - inner} and an authored width of {width}"); + // Past the last sibling a root's window is its own to spell, and a ring member's child is held by a chord as well. + var upperKnown = at < sibling.Count - 1 || (grand.IsSet() && mass.ContainsKey(grand.Key)); + if (prevIsBelt || nextIsBelt || !upperKnown) continue; + midpoints++; + Assert.True(Math.Abs(d - (inner + outerLimit) / 2) <= Tolerance * d, + $"seed {seed}: a belt at {d} is not the midpoint {(inner + outerLimit) / 2} of its slot [{inner}, {outerLimit}]"); + } + } + ratios.Sort(); + _out.WriteLine($"belts {belts}, with a slot bound {bounded}, midpoints checked {midpoints}, rock spread under 0.001: {lines}; " + + $"spread / authored width at p10/25/50/75/90/max: {string.Join(" / ", new[] { .1f, .25f, .5f, .75f, .9f }.Select(f => Percentile(ratios, f).ToString("F3")))} / {ratios[ratios.Count - 1]:F3}"); + Assert.True(belts > 20 && bounded > 0 && midpoints > 0, $"{belts} belts, {bounded} bounded, {midpoints} midpoints: the seeds do not exercise the rule"); + Assert.True(lines == 0, $"{lines} of {belts} belts have no radial width"); + } + + // With the authored width narrower than the slot the width is the ceiling and the belt keeps it: neither wider (W/2 -> W, a + // deleted cap) nor reduced to the slot. + [Fact] + public void ANarrowAuthoredBeltKeepsItsWidth() + { + var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()).Read("ZoneSettings").AsteroidBeltWidth; + using var narrow = new Zones(1, 3, z => z.AsteroidBeltWidth = new ExponentialCurve + { Exponent = authored.Exponent, Multiplier = authored.Multiplier * .02f, Constant = authored.Constant * .02f }); + int belts = 0, filled = 0; + foreach (var (seed, zone) in narrow.All) + foreach (var (key, belt) in zone.AsteroidBelts) + { + var rocks = belt.Data.Asteroids; + if (rocks.Length < 2) continue; + var width = narrow.Settings.AsteroidBeltWidth.Evaluate(DistanceOf(zone, zone.Planets[key].Orbit.Key)); + var spread = rocks.Max(a => a.Distance) - rocks.Min(a => a.Distance); + belts++; + Assert.True(spread <= width * (1 + Tolerance), $"seed {seed}: a belt spreads {spread}, past its authored width {width}"); + if (spread >= .5f * width) filled++; + } + _out.WriteLine($"narrow belts {belts}, spreading at least half the authored width {filled}"); + Assert.True(filled >= 10, $"only {filled} of {belts} belts fill the authored width"); + } + + private static GeneratorPlanet Body(GeneratorPlanet parent, float mass, float phase = 0, bool ring = false) + { + var node = new GeneratorPlanet { Parent = parent, Mass = mass, Phase = phase, Ring = ring }; + parent.Children.Add(node); + return node; + } + + private static PlanetSettings AuthoredPlanetSettings() => AuthoredSettings.Load(RunStartTests.FindRepoRoot()).Read("PlanetSettings"); + + // A rosette's ring round a root with no reach limit of its own sits at half the root's 0.75 x radius window, 3/8 of the radius. + [Fact] + public void ASoleRootRingSitsAtThreeEighthsOfItsRadius() + { + const float radius = 1e6f; + var root = new GeneratorPlanet { Empty = true }; + var members = new[] { Body(root, 100f, 0, true), Body(root, 100f, .5f, true) }; + ZoneGenerator.Place(root, AuthoredPlanetSettings(), radius, float.PositiveInfinity); + Assert.True(root.Empty && root.Children.Count == 2, "the ring folded into its node"); + foreach (var member in members) + Assert.True(Math.Abs(member.Distance - .375f * radius) <= 1e-4f * radius, $"a ring member sits at {member.Distance}, not {.375f * radius}"); + } + + // A ring member's children end within a fifth of the chord to the member's nearest partner, where the chord, not the member's + // fade, is what holds them. + [Fact] + public void ARingMembersChildrenStayWithinAFifthOfTheChord() + { + const float radius = 1e6f; + const int count = 12; + var root = new GeneratorPlanet { Empty = true }; + var members = Enumerable.Range(0, count).Select(i => Body(root, 100f, (float) i / count, true)).ToList(); + foreach (var member in members) { Body(member, 10f); Body(member, 10f); } + ZoneGenerator.Place(root, AuthoredPlanetSettings(), radius, float.PositiveInfinity); + foreach (var member in members) + { + Assert.True(root.Children.Count == count && member.Children.Count == 2, "a ring member or its children folded"); + var chord = .2f * 2 * member.Distance * (float) Math.Sin(Math.PI / count); + var fade = GravityField.Gamma * GravityField.Reach * member.Distance / Math.Max(GravityField.Beta, 1 + GravityField.Reach); + Assert.True(chord < fade, "the fade, not the chord, would hold these children"); + var outermost = member.Children.Max(c => c.Distance); + Assert.True(Math.Abs(outermost - chord) <= 1e-4f * chord, $"a ring member's outermost child sits at {outermost}, not at the chord's fifth {chord}"); + } + } + [Fact] public void NoStrengthlessOrbitRidesARing() { diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index 2c5a2149d..ccc2d309a 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -5,6 +5,7 @@ using System.Linq; using CultMath; using GameCult.Caching; using Xunit; +using Xunit.Abstractions; using static CultMath.math; using float2 = CultMath.float2; @@ -18,7 +19,13 @@ public sealed class StationPlacementTests : IDisposable private readonly List _caches = new List(); private int _generation; - public StationPlacementTests() => Directory.CreateDirectory(_root); + private readonly ITestOutputHelper _output; + + public StationPlacementTests(ITestOutputHelper output) + { + _output = output; + Directory.CreateDirectory(_root); + } public void Dispose() { @@ -31,7 +38,7 @@ public sealed class StationPlacementTests : IDisposable // stock may rearrange the catalog before a galaxy is generated; storyTurrets > 0 gives every zone a story station that // authors that many turrets (the '#turrets' tag), the way a narrative does. private IEnumerable GeneratedZones(Action stock = null, int storyTurrets = 0, uint seeds = 6, int zonesPerSeed = int.MaxValue, - Action tune = null) + Action tune = null, bool entranceOnly = false) { for (uint seed = 1; seed <= seeds; seed++) { @@ -51,7 +58,7 @@ public sealed class StationPlacementTests : IDisposable Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); var items = new ItemManager(cache, new ProvenanceLedger(), settings, _ => { }); stock?.Invoke(items); - foreach (var galaxyZone in galaxy.Zones.Take(zonesPerSeed)) + foreach (var galaxyZone in entranceOnly ? new[] { galaxy.Entrance } : galaxy.Zones.Take(zonesPerSeed)) { if (storyTurrets > 0) galaxyZone.Locations.Add(new LocationStory { Zone = galaxyZone, Name = "Test station", Faction = galaxy.Factions[0], Type = LocationType.Station, Turrets = storyTurrets }); @@ -327,6 +334,74 @@ public sealed class StationPlacementTests : IDisposable Assert.True(stations > 0, "the seeds generated no station"); } + + // A side of a station grows outward until its next turret would sit within the base body's extent plus that turret's reach of + // the base (story-turret-tail-clearance). With a single wide turret hull on offer and forty story turrets every station + // reaches the base: a side that placed fewer than its half stopped, and its would-be next turret, spelled from the zone, is + // inside that distance. Ambient stations carry at most two turrets, so only a station with three or more is a story one. + [Fact] + public void ATurretTailStopsAtItsBaseBody() + { + const int turrets = 40; + int stations = 0, sides = 0, stops = 0, nearBase = 0; + foreach (var built in GeneratedZones(WithOnlyAWiderTurretHull, turrets, 6)) + { + var zone = built.Zone; + var orbitals = Orbitals(built); + var ridden = orbitals.Select(e => e.OrbitData).ToHashSet(); + foreach (var station in orbitals.Where(e => TypeOf(built.Items, e) == HullType.Station)) + { + var orbit = zone.Orbits[station.OrbitData]; + var mine = orbitals.Where(e => TypeOf(built.Items, e) == HullType.Turret && SameRing(zone.Orbits[e.OrbitData], orbit)).ToList(); + var source = zone.Orbits.Where(o => !ridden.Contains(o.Key) && SameRing(o.Value, orbit)).Select(o => o.Key).ToList(); + if (mine.Count < 3 || source.Count != 1) continue; + stations++; + var extent = BaseExtent(zone, source[0]); + var reach = Contacts.Radius(mine[0]); + var circumference = 2 * PI * orbit.Data.Distance; + var arcs = mine.Select(t => { var turn = Turns(zone.Orbits[t.OrbitData].Data.Phase - orbit.Data.Phase); return (turn > .5f ? turn - 1 : turn) * circumference; }).ToList(); + foreach (var sign in new[] { -1f, 1f }) + { + var side = arcs.Where(a => a * sign > 0).OrderBy(a => a * sign).ToList(); + sides++; + var wouldBe = (side.Count == 0 ? 0f : side[side.Count - 1]) + sign * ((side.Count == 0 ? Contacts.Radius(station) : reach) + 2 * reach); + var phase = orbit.Data.Phase + wouldBe / circumference; + var chord = 2 * orbit.Data.Distance * Math.Abs((float) Math.Sin(PI * (phase - zone.Orbits[source[0]].Data.Phase))); + if (side.Count >= turrets / 2) continue; + stops++; + Assert.True(chord < (extent + reach) * (1 + 1e-3f), $"seed {built.Seed}: a side stopped at {side.Count} turrets with its next turret still {chord} from the base, outside {extent + reach}"); + if (chord >= .8f * (extent + reach)) nearBase++; + } + } + } + _output.WriteLine($"story stations {stations}, sides {sides}, sides that stopped {stops}, of them with the next turret within a fifth of the stop distance {nearBase}"); + Assert.True(stops > 0 && nearBase > 0, $"{stops} stops, {nearBase} in the 0.8 band: the seeds do not exercise the rule"); + } + + // The entrance always gets a station. With no candidate orbit (a station hull so large that no rail clears a massive sibling + // by its reach) it orbits a body root outside that root's extent, not at a Lagrange point. + [Fact] + public void ATutorialEntranceWithNoCandidateOrbitsItsBodyRootOutsideItsExtent() + { + var fired = 0; + foreach (var built in GeneratedZones(WithAnUnofferedHugeStationHull, 0, 20, 1, + z => { z.RosetteProbability = 0; z.BinaryCreationProbability = 0; z.SatelliteCreationProbability = 0; }, true)) + { + var zone = built.Zone; + var station = Orbitals(built).FirstOrDefault(e => TypeOf(built.Items, e) == HullType.Station); + if (station == null) continue; + var orbit = zone.Orbits[station.OrbitData]; + var root = orbit.Data.Parent.IsSet() ? orbit.Data.Parent.Key : default; + if (!orbit.Data.Parent.IsSet() || zone.Orbits[root].Data.Parent.IsSet() || !zone.Planets.Values.Any(b => !(b is AsteroidBeltData) && b.Orbit.Key.Equals(root))) continue; + if (zone.Planets.Values.Any(b => SameRing(zone.Orbits[b.Orbit.Key], orbit))) continue; + fired++; + var extent = BaseExtent(zone, root); + Assert.True(Math.Abs(orbit.Data.Distance - extent) <= 1e-4f * extent, $"seed {built.Seed}: the entrance station orbits its root at {orbit.Data.Distance}, not at its extent {extent}"); + } + _output.WriteLine($"entrance zones where the fallback seated a station at a body root: {fired}"); + Assert.True(fired > 0, "no entrance zone of seeds 1-20 took the fallback for a body root"); + } + private static List TurretProducts(ItemManager items) => items.ItemData.GetAll().Where(p => items.ItemData.Get(p.Design) is HullData { HullType: HullType.Turret }).ToList(); @@ -338,7 +413,24 @@ public sealed class StationPlacementTests : IDisposable // The shipped catalog has one turret hull. A copy with a bigger solid shape (a larger reach) and its own product // gives the generator two turret hulls to choose between. - private static void WithALargerTurretHull(ItemManager items) + private static void WithALargerTurretHull(ItemManager items) => AddATurretHull(items, 2, false); + + // Only the wider hull is on offer: the shipped turret is priced at zero once the wider copy has its price. + private static void WithOnlyAWiderTurretHull(ItemManager items) => AddATurretHull(items, 6, true); + + // A station hull with no product, so nothing builds it, but wide enough that its reach is the largest in the catalog. + private static void WithAnUnofferedHugeStationHull(ItemManager items) + { + var copyOf = typeof(object).GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + var hull = items.ItemData.GetAll().First(h => h.HullType == HullType.Station); + var huge = (HullData) copyOf.Invoke(hull, null); + huge.Name = hull.Name + " (huge)"; + huge.Shape = new Shape(20000, 1); + foreach (var cell in huge.Shape.AllCoordinates) huge.Shape[cell] = true; + items.ItemData.Upsert(huge); + } + + private static void AddATurretHull(ItemManager items, int extraCells, bool only) { var copyOf = typeof(object).GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); foreach (var product in TurretProducts(items)) @@ -346,12 +438,13 @@ public sealed class StationPlacementTests : IDisposable var hull = (HullData) items.ItemData.Get(product.Design); var larger = (HullData) copyOf.Invoke(hull, null); larger.Name = hull.Name + " (large)"; - larger.Shape = new Shape(hull.Shape.Width + 2, hull.Shape.Height + 2); + larger.Shape = new Shape(hull.Shape.Width + extraCells, hull.Shape.Height + extraCells); foreach (var cell in larger.Shape.AllCoordinates) larger.Shape[cell] = true; var largerProduct = (FactionProductData) copyOf.Invoke(product, null); largerProduct.Name = product.Name + " (large)"; largerProduct.Design = new CultRecordRef(items.ItemData.Upsert(larger).Key); items.ItemData.Upsert(largerProduct); + if (only) hull.Price = 0; } }