From 781607763e857fa95919d8af4a009d0b7381407e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 04:55:48 +0200 Subject: [PATCH 01/22] WellTree: SubzoneReach is one public static; the strengthless-orbit mean rule is deleted The nearest-anchor rule (Reach x distance to the nearest other root) moves to WellTree.SubzoneReach(anchors, root) so the generator spells it once; the instance method returns max(it, floor). PullAround no longer gives a strengthless orbit on a ring a period of its own (binaries-orbited-from-afar); its test goes with it. Builds. Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/ServerShared/WellTree.cs | 40 ++++++++++--------- .../OrbitsFromFieldTests.cs | 37 +---------------- 2 files changed, 23 insertions(+), 54 deletions(-) diff --git a/Assets/Scripts/ServerShared/WellTree.cs b/Assets/Scripts/ServerShared/WellTree.cs index bacf474de..5f9f408e6 100644 --- a/Assets/Scripts/ServerShared/WellTree.cs +++ b/Assets/Scripts/ServerShared/WellTree.cs @@ -257,19 +257,29 @@ public sealed class WellTree } } - // A root's reach. The one place the subzone shape is decided (question multi-root-zone-shape): a sole massive root is the - // whole zone (+inf, so its global term is the far field); with several, isolated-subzones bounds each root to Reach x the - // distance to the nearest other massive root, or its floor (Beta x support) if more. The superposed-inside option - // (Beta x max(pack radius, max over massive roots of |anchor - Centre| + support)) is not a change to this return: it needs - // every massive root's support, and roots are processed one at a time here, so it would take a second pass over the roots - // once their supports exist. + // A root's reach: the floor (Beta x support) or the subzone reach, whichever is more. The subzone shape is decided in the + // public static SubzoneReach (multi-root-isolated-subzones): the generator calls the same function, so Reach x the nearest + // root's distance is spelled once and the roots' windows are fitted to it (root-window-floor). private float SubzoneReach(int root, float floor) { - if (_massiveRoots.Length < 2) return float.PositiveInfinity; + var anchors = new List(); + foreach (var other in _massiveRoots) anchors.Add(_anchor[other]); + return Math.Max(SubzoneReach(anchors, Array.IndexOf(_massiveRoots, root)), floor); + } + + /// + /// A subzone root's reach among the zone's massive roots' anchors: a sole massive root is the whole zone (+inf, so its + /// global term is the far field); with several, each root is bounded to GravityField.Reach x the distance to the nearest + /// other root (multi-root-isolated-subzones). The superposed-inside option is not a change to this return: it needs every + /// root's support, and roots are processed one at a time. + /// + public static float SubzoneReach(IReadOnlyList anchors, int root) + { + if (anchors.Count < 2) return float.PositiveInfinity; var nearest = float.PositiveInfinity; - foreach (var other in _massiveRoots) - if (other != root) nearest = Math.Min(nearest, length(_anchor[other] - _anchor[root])); - return Math.Max(GravityField.Reach * nearest, floor); + for (var other = 0; other < anchors.Count; other++) + if (other != root) nearest = Math.Min(nearest, length(anchors[other] - anchors[root])); + return GravityField.Reach * nearest; } private void EmitTerms(int[] parent, float[] body, float[] family, int[][] ring, float[] lower, RingGroup[] group, @@ -395,8 +405,7 @@ public sealed class WellTree /// /// The pull (toward the node, u/s^2) a rail at `distance` round `parentOrbit` is given: the node's own terms at that /// distance. A ring member of a bodyless node adds each other member's own terms at their chord (positions at t = 0), - /// projected toward the node; a strengthless orbit on that ring (a station, a turret) takes the mean of what the ring's - /// members feel, so it keeps their period. Infinite period for a pull of 0 is the caller's. + /// projected toward the node. Infinite period for a pull of 0 is the caller's. /// public float PullAround(CultRecordKey parentOrbit, float distance, CultRecordKey self) { @@ -405,12 +414,7 @@ public sealed class WellTree var members = _ring[node]; if (members == null || members.Length < 2) return pull; if (_index.TryGetValue(self, out var me) && Array.IndexOf(members, me) >= 0) return pull + PartnersPull(members, me); - var inner = float.PositiveInfinity; - foreach (var m in members) inner = Math.Min(inner, _distance[m]); - if (Math.Abs(distance - inner) > RingWindow) return pull; - var mean = 0f; - foreach (var m in members) mean += PartnersPull(members, m) / members.Length; - return pull + mean; + return pull; } // What the other members of a ring pull member m with, along the direction from m to the node. diff --git a/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs b/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs index fea0d84c6..6a3b1c618 100644 --- a/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs +++ b/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs @@ -150,41 +150,6 @@ public sealed class OrbitsFromFieldTests : IDisposable Assert.Equal(zone.Orbits[planet2].Period, zone.Orbits[companion2].Period); } - // A station on a binary's ring, with nothing inside, feels what the pair's members feel (the mean of what each does), - // and so does one a hair off the ring's distance but within its window. - [Theory] - [InlineData(0f)] - [InlineData(.05f)] - [InlineData(-.05f)] - public void ACompanionOnABinarysRingTakesTheMembersPeriod(float offset) - { - var w = NewWorld(); - var node = w.Orbit(default, 0f); - var light = w.Orbit(node, 400f, 0f); - var heavy = w.Orbit(node, 400f, .5f); - var lightBody = w.Body(light, 100f); - var heavyBody = w.Body(heavy, 2000f); - var companion = w.Orbit(node, 400f + offset, .25f); - var zone = w.Build(); - - Assert.True(C(zone, heavyBody) > 1.5f * C(zone, lightBody), "fixture: unequal members"); - AssertPeriod(PeriodUnder((Pull(zone, lightBody, 800f) + Pull(zone, heavyBody, 800f)) / 2, 400f + offset), zone.Orbits[companion].Period, - "the companion, between its two members"); - - // An equal pair: the companion has the members' period. - w = NewWorld(); - node = w.Orbit(default, 0f); - var a = w.Orbit(node, 400f, 0f); - var b = w.Orbit(node, 400f, .5f); - w.Body(a, 300f); - w.Body(b, 300f); - companion = w.Orbit(node, 400f, .25f); - zone = w.Build(); - Assert.True(float.IsFinite(zone.Orbits[a].Period)); - AssertPeriod(zone.Orbits[a].Period, zone.Orbits[companion].Period, "the companion, against the first member"); - AssertPeriod(zone.Orbits[b].Period, zone.Orbits[companion].Period, "the companion, against the second member"); - } - // The ring is the 0.1 u window about the innermost massive distance: a member just inside it is a ring partner (felt at // the chord), one just outside it is not a partner and the rail has the node's own terms alone, which give a // ring's own member next to no pull. @@ -291,7 +256,7 @@ public sealed class OrbitsFromFieldTests : IDisposable authored.Read("NameGeneratorSettings"), cache, new PlayerSettings(), Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); var items = new ItemManager(cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), galaxy, galaxy.Entrance, + var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, galaxy.IsPrelude, false); var zone = new Zone(items, authored.Read("PlanetSettings"), pack, galaxy.Entrance, galaxy); From 84337de5693cadbb093d906521d29da7dff39d70 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 04:55:57 +0200 Subject: [PATCH 02/22] ZoneGenerator.Place owns every generated distance, fold and belt width PlanetSafetyRadius, ChildDistanceMinimum/Maximum, ExpandSolar's distance series and the window filters are deleted. Place (ported from replace.py, root window from rootReach per root-window-floor) lays children inside-out, folds the lightest family while the outermost overflows, stretches to the window, merges rings that cannot keep their heavy member outside its Roche margin and sets belt half widths. Stations pick well-bearing, sibling-clear off-ring bodies; the tutorial entrance falls back to an orbit round a root node; turrets stop a side when within the base body's extent. GenerateZone/GenerateArena take PlanetSettings. Not yet built. Co-Authored-By: Claude Opus 5.5 --- Assets/Resources/Settings.asset | 4 +- Assets/Scripts/Gameplay/ActionGameManager.cs | 3 +- Assets/Scripts/ServerShared/RunStart.cs | 4 +- Assets/Scripts/ServerShared/Settings.cs | 1 - Assets/Scripts/ServerShared/ZoneGenerator.cs | 321 ++++++++++++------ .../Aetheria.Shared.Tests/MiningCut3Tests.cs | 2 +- .../RestoredHullsTests.cs | 23 +- tests/Aetheria.Shared.Tests/RunGoalTests.cs | 2 +- tests/Aetheria.Shared.Tests/RunStartTests.cs | 4 +- tests/Aetheria.Shared.Tests/ScenarioTests.cs | 6 +- .../StationPlacementTests.cs | 2 +- .../SunsNeverGreenTests.cs | 2 +- tools/AetherDb/Program.cs | 1 - 13 files changed, 240 insertions(+), 135 deletions(-) diff --git a/Assets/Resources/Settings.asset b/Assets/Resources/Settings.asset index 4536e99f1..f92142d6b 100644 --- a/Assets/Resources/Settings.asset +++ b/Assets/Resources/Settings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:2c67fcecfea500365c54e5c80e59b6f26d0526e877c266d9fa75a43053df225d -size 12647 +oid sha256:ab2cdc0732716dcbfa4875e90e598b0dff3f0c8d4f871cc180649a3db2e4cf0c +size 12562 diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index ecb4af6d2..503d2836f 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -723,6 +723,7 @@ public class ActionGameManager : MonoBehaviour galaxyZone.PackedContents ??= ZoneGenerator.GenerateZone( ItemManager, Settings.ZoneSettings, + Settings.PlanetSettings, CurrentGalaxy, galaxyZone, CurrentGalaxy.IsPrelude @@ -846,7 +847,7 @@ public class ActionGameManager : MonoBehaviour { staged = RunSave.Replace(CultCache, () => { - RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, CurrentGalaxy, scenario); + RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, scenario); PopulateLevel(CurrentGalaxy.Entrance); return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, Settings.TutorialGenerationSettings, failures); }); diff --git a/Assets/Scripts/ServerShared/RunStart.cs b/Assets/Scripts/ServerShared/RunStart.cs index a8e0f6134..b330ad944 100644 --- a/Assets/Scripts/ServerShared/RunStart.cs +++ b/Assets/Scripts/ServerShared/RunStart.cs @@ -23,11 +23,11 @@ public static class RunStart return scenario.Generate(stage) ?? throw new InvalidOperationException($"Scenario {scenario.Name} generated no galaxy."); } - public static ZonePack GenerateArena(ItemManager itemManager, ZoneGenerationSettings zoneSettings, Galaxy galaxy, Scenario scenario) + public static ZonePack GenerateArena(ItemManager itemManager, ZoneGenerationSettings zoneSettings, PlanetSettings planetSettings, Galaxy galaxy, Scenario scenario) { SeedItems(itemManager, galaxy, 1); return galaxy.Entrance.PackedContents = ZoneGenerator.GenerateZone( - itemManager, zoneSettings, galaxy, galaxy.Entrance, galaxy.IsPrelude, scenario.Ambient); + itemManager, zoneSettings, planetSettings, galaxy, galaxy.Entrance, galaxy.IsPrelude, scenario.Ambient); } // Runs the scenario's Stage, then admits its player and everything it placed: each entity's stance set both ways diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 235092f90..85d1f3d96 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -111,7 +111,6 @@ public class TutorialGenerationSettings [Serializable, MessagePackObject(keyAsPropertyName:true), JsonObject] public class ZoneGenerationSettings { - public ExponentialCurve PlanetSafetyRadius; public float MassFloor = 1; public float SunMass = 10000; diff --git a/Assets/Scripts/ServerShared/ZoneGenerator.cs b/Assets/Scripts/ServerShared/ZoneGenerator.cs index c6ec75375..149e63db4 100644 --- a/Assets/Scripts/ServerShared/ZoneGenerator.cs +++ b/Assets/Scripts/ServerShared/ZoneGenerator.cs @@ -40,6 +40,7 @@ public static class ZoneGenerator public static ZonePack GenerateZone( ItemManager itemManager, ZoneGenerationSettings zoneSettings, + PlanetSettings planetSettings, Galaxy galaxy, GalaxyZone galaxyZone, bool isTutorial = false, @@ -88,13 +89,17 @@ public static class ZoneGenerator } var totalArea = occupiedAreas.Sum(c => c.Area); - foreach (var c in occupiedAreas) + // Every area root is massive, so a root's reach is Reach x its nearest area's centre (WellTree.SubzoneReach) + var centres = occupiedAreas.Select(c => c.Center).ToList(); + for (var k = 0; k < occupiedAreas.Count; k++) { - planets.AddRange(GenerateEntities(zoneSettings, ref random, c.Area / totalArea * pack.Mass, c.Radius, c.Center)); + var c = occupiedAreas[k]; + planets.AddRange(GenerateEntities(zoneSettings, planetSettings, ref random, c.Area / totalArea * pack.Mass, c.Radius, c.Center, + WellTree.SubzoneReach(centres, k))); } } else - planets.AddRange(GenerateEntities(zoneSettings, ref random, pack.Mass, pack.Radius, float2.zero)); + planets.AddRange(GenerateEntities(zoneSettings, planetSettings, ref random, pack.Mass, pack.Radius, float2.zero, float.PositiveInfinity)); // Every orbit is a record; parents link to records, so each orbit holds its key before any child names it var orbitMap = new Dictionary(); @@ -147,7 +152,7 @@ public static class ZoneGenerator Enumerable.Range(0, (int) zoneSettings.AsteroidCount.Evaluate(beltData.Mass * orbitMap[planet].Distance)) .Select(_ => new Asteroid { - Distance = orbitMap[planet].Distance + random.NextFloat()*(random.NextFloat()-.5f)*zoneSettings.AsteroidBeltWidth.Evaluate(orbitMap[planet].Distance), + Distance = orbitMap[planet].Distance + random.NextFloat()*(random.NextFloat()-.5f)*2*planet.BeltHalfWidth, Phase = random.NextFloat(), Size = random.NextFloat(), RotationSpeed = zoneSettings.AsteroidRotationSpeed.Evaluate(random.NextFloat()) @@ -209,6 +214,20 @@ public static class ZoneGenerator return cache.Upsert(planetData); }).ToList(); + // The generator's own well tree, for clearance only (the Zone builds its own): what a rail must stay out of is the body's + // support, or its Roche margin if more. + var wellNodes = planets.Select(p => new WellNode(cache.RefOf(orbitMap[p]).Key, p.Parent == null ? default : cache.RefOf(orbitMap[p.Parent]).Key, + p.Distance, p.Phase, p.Empty || p.Belt ? 0f : p.Mass, + p.Belt ? p.Distance + p.BeltHalfWidth : p.Distance, p.FixedPosition)).ToList(); + var wells = WellTree.Build(wellNodes, planetSettings, pack.Radius); + float Extent(GeneratorPlanet p) + { + var key = cache.RefOf(orbitMap[p]).Key; + var roche = p.Empty || p.Belt ? 0f : WellTree.Curves(planetSettings, p.Mass).Softening * RocheMargin; + return Math.Max(wells.Support(key), roche); + } + bool Massive(GeneratorPlanet p) => wells.Reach(cache.RefOf(orbitMap[p]).Key) > 0f; + var nearestFaction = galaxy.Factions.MinBy(f => galaxy.HomeZones[f].Distance[galaxyZone]); var nearestFactionHomeZone = galaxy.HomeZones[nearestFaction]; var factionPresence = galaxy.InfluenceOf(nearestFaction) - nearestFactionHomeZone.Distance[galaxyZone] + 1; @@ -224,30 +243,35 @@ public static class ZoneGenerator // seed. galaxy.Entrance is reference-identity, not a name comparison. var isTutorialEntrance = isTutorial && galaxyZone == galaxy.Entrance; if (isTutorialEntrance && stationCount < 1) stationCount = 1; - var potentialLagrangePoints = planets - .Where(p => p.Parent != null && p.Parent.Children - .TrueForAll(c => !(c != p && abs(c.Distance - p.Distance) < .1f))) // Filter Rosettes + // A station's source is a well-bearing body alone on its ring whose rail clears every massive sibling's extent (the + // sibling's support, or its Roche margin if more): its Lagrange orbit then sits clear of any other body. + var candidates = planets + .Where(p => p.Parent != null && !p.Empty && !p.Belt + && p.Parent.Children.TrueForAll(c => c == p || (abs(c.Distance - p.Distance) >= WellTree.RingWindow + && (!Massive(c) || abs(c.Distance - p.Distance) > Extent(c))))) .OrderBy(p => p.Distance) .ToArray(); - // The entrance's own station count is the floor above; its orbit always comes from this same selection. - // Ordinarily that selection is potentialLagrangePoints (non-rosette planet orbits). If the entrance zone - // has none of those (a boring single-body system, or a system that is entirely one rosette), widen to - // every planet orbit ordinary placement's own candidate pool is drawn from before the rosette filter -- - // still a real, parented planet orbit with a positive Distance -- rather than inventing an unparented, - // zero-distance orbit (that gave PlaceTurret's phase = 20*multiplier/orbit.Distance a division by zero, - // and left an orbit record with no planet behind it). - var lagrangeCandidates = potentialLagrangePoints; - if (isTutorialEntrance && lagrangeCandidates.Length == 0) - lagrangeCandidates = planets.Where(p => p.Parent != null).OrderBy(p => p.Distance).ToArray(); - // Pick a selection from the middle of the distribution - var selectedStationOrbits = lagrangeCandidates - .Skip(lagrangeCandidates.Length / 2) - .Take(stationCount) - .Select(p=>orbitMap[p]) - .ToArray(); - if (isTutorialEntrance && lagrangeCandidates.Length == 0) - throw new InvalidOperationException( - "The tutorial entrance zone must always get a station, but it has no candidate orbit at all -- every planet in the zone is a parentless root."); + // (the rail, how far a body on it keeps others out, whether it is a station's own orbit rather than a base's) + var sources = candidates.Skip(candidates.Length / 2).Take(stationCount) + .Select(p => (orbit: orbitMap[p], extent: Extent(p), direct: false)).ToArray(); + if (isTutorialEntrance && candidates.Length == 0) + { + // The entrance gets a station whatever its bodies: it orbits a root node beyond its ring group (or, for a body, its + // whole family), never at a ring member's distance, and sits there, not at a Lagrange point. + var rootNode = planets.FirstOrDefault(p => p.Parent == null && p.Children.Count > 0); + if (rootNode == null) + throw new InvalidOperationException( + "The tutorial entrance zone must always get a station, but it has no candidate orbit at all -- every planet in the zone is a parentless root."); + var rootKey = cache.RefOf(orbitMap[rootNode]).Key; + var distance = rootNode.Empty + ? (1 + GravityField.RingReach) * GravityField.Beta * rootNode.Children.Where(Massive).Min(c => c.Distance) + : wells.Support(rootKey); + var direct = new OrbitData { Parent = cache.RefOf(orbitMap[rootNode]), Distance = distance, Phase = random.NextFloat() }; + pack.Orbits.Add(cache.Upsert(direct)); + sources = new[] { (orbit: direct, extent: float.NegativeInfinity, direct: true) }; + } + var selectedStationOrbits = sources.Select(x => x.orbit).ToArray(); + var extentOf = sources.ToDictionary(x => x.orbit, x => x.extent); var loadoutGenerators = new Dictionary(); @@ -261,6 +285,7 @@ public static class ZoneGenerator // L4 or L5: 60 degrees (one sixth of a turn) ahead of or behind the planet on its orbit. Phase is in turns. OrbitData CreateLagrangeOrbit(OrbitData baseOrbit) { + if (sources.First(x => x.orbit == baseOrbit).direct) return baseOrbit; var lagrangeOrbit = new OrbitData { Parent = baseOrbit.Parent, @@ -276,36 +301,48 @@ public static class ZoneGenerator // body's. Every body's reach counts, so turrets of differing reach clear each other. Phase is in turns, so the // arc length divides by the orbit's circumference. Returns where the turret sits (signed arc from the station) // and its reach, or null when there is no turret hull to generate, before any orbit is created. - (float arc, float reach)? PlaceTurret(OrbitData orbit, LoadoutGenerator loadoutGenerator, float side, float innerArc, float innerReach) + (float arc, float reach, bool placed)? PlaceTurret(OrbitData orbit, LoadoutGenerator loadoutGenerator, float side, float innerArc, float innerReach, + OrbitData baseOrbit) { var turret = loadoutGenerator.GenerateTurretLoadout(); if (turret == null) return null; var turretReach = (itemManager.GetData(turret.Hull) as HullData).Reach(itemManager.GameplaySettings.SchematicCellSize); var arc = innerArc + side * (innerReach + 2 * turretReach); + // A turret whose centre is within the base body's extent plus its own reach of the base is not placed: its side stops. + var phase = orbit.Phase + arc / (2 * PI * orbit.Distance); + if (2 * orbit.Distance * abs(sin(PI * (phase - baseOrbit.Phase))) < extentOf[baseOrbit] + turretReach) + { + itemManager.Log("A turret was not placed: its station's base body is within its reach (story-turret-tail-clearance)."); + return (arc, turretReach, false); + } var turretOrbit = new OrbitData { Parent = orbit.Parent, Distance = orbit.Distance, - Phase = orbit.Phase + arc / (2 * PI * orbit.Distance) + Phase = phase + }; pack.Orbits.Add(cache.Upsert(turretOrbit)); turret.Orbit = cache.RefOf(turretOrbit); pack.Entities.Add(turret); - return (arc, turretReach); + return (arc, turretReach, true); } // Turrets flank the station alternately, behind then ahead, each side growing outward from the station. - void PlaceTurrets(OrbitData orbit, LoadoutGenerator loadoutGenerator, int count, float stationReach) + void PlaceTurrets(OrbitData orbit, LoadoutGenerator loadoutGenerator, int count, float stationReach, OrbitData baseOrbit) { var arcs = new float[2]; + var stopped = new bool[2]; var reaches = new[] { stationReach, stationReach }; for(int t=0; t= selectedStationOrbits.Length) { itemManager.Log($"Story station for {story.Faction?.Name} has no rail clear of the bodies; its story has nowhere to live!"); continue; } var orbit = selectedStationOrbits[i]; var lagrangeOrbit = CreateLagrangeOrbit(orbit); var station = GetLoadoutGenerator(story.Faction).GenerateStationLoadout(); @@ -329,7 +367,7 @@ public static class ZoneGenerator station.Story = i; pack.Entities.Add(station); - if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(story.Faction), story.Turrets, StationReach(station)); + if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(story.Faction), story.Turrets, StationReach(station), orbit); } for (var i = storyStations.Length; i < selectedStationOrbits.Length; i++) @@ -351,7 +389,7 @@ public static class ZoneGenerator station.SecurityRadius = pack.Radius; pack.Entities.Add(station); - if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(nearestFaction), 2, StationReach(station)); + if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(nearestFaction), 2, StationReach(station), orbit); } // A boss zone gets its faction's boss whether or not the zone is ambient: the boss is the run's goal, not @@ -413,16 +451,15 @@ public static class ZoneGenerator // 1 / lerp(settings.ResourceDensityMinimum, settings.ResourceDensityMaximum, density)); // } - public static GeneratorPlanet[] GenerateEntities(ZoneGenerationSettings settings, ref Random random, float mass, float radius, float2 fixedPosition) + public static GeneratorPlanet[] GenerateEntities(ZoneGenerationSettings settings, PlanetSettings planetSettings, ref Random random, float mass, float radius, float2 fixedPosition, + float rootReach) { var root = new GeneratorPlanet { FixedPosition = fixedPosition, Settings = settings, - Mass = mass, - ChildDistanceMaximum = radius * .75f, - ChildDistanceMinimum = settings.PlanetSafetyRadius.Evaluate(mass) - }; + Mass = mass + }; // There is some chance of generating a rosette or binary system // Probabilities which are fixed for the entire galaxy are in GlobalData, contained in the GameContext @@ -439,8 +476,6 @@ public static class ZoneGenerator count: (int)(random.NextFloat(1, 3) * random.NextFloat(1, 2)), massMulMin: .6f, massMulMax: .8f, - distMulMin: 1.25f, - distMulMax: 1.75f, jupiterJump: 1, massFraction: .1f); @@ -454,8 +489,6 @@ public static class ZoneGenerator count: (int) (random.NextFloat(1, 3 * m) + random.NextFloat(1, 3 * m)), massMulMin: 0.75f, massMulMax: 2.5f, - distMulMin: 1 + m * .25f, - distMulMax: 1.05f + m * .5f, jupiterJump: random.NextFloat() * random.NextFloat() * 10 + 1, massFraction: .5f ); @@ -469,8 +502,6 @@ public static class ZoneGenerator count: random.NextInt(5, 15), massMulMin: 0.75f, massMulMax: 2.5f, - distMulMin: 1.1f, - distMulMax: 1.25f, jupiterJump: random.NextFloat() * random.NextFloat() * 10 + 1, massFraction: .25f ); @@ -511,8 +542,6 @@ public static class ZoneGenerator count: planet.Mass < settings.GasGiantMass ? random.NextInt(1, 3) : random.NextInt(2, 6), massMulMin: .75f, massMulMax: 1.5f, - distMulMin: 1.05f, - distMulMax: 1.25f, jupiterJump: 1, massFraction: .15f); // Planetary satellites are not nearly as massive as planets themselves } @@ -535,8 +564,126 @@ public static class ZoneGenerator foreach (var planet in root.AllPlanets()) planet.Mass = (planet.Mass / totalMass) * rootMass; + Place(root, planetSettings, radius, rootReach); + return root.AllPlanets().ToArray(); } + + // Placement (tail-taming-law-r3-band-loose-cusp, c4-proceed-and-fly): a child sits at least RocheMargin of its parent's Roche + // limits out; a massive child of a body also far enough that its own pull peak beats CuspMargin times its parent's pull there; + // siblings sit SiblingSpacing of a reach apart. Every other number is a GravityField constant. + public const float RocheMargin = 1.5f; + public const float CuspMargin = 1.5f; + public const float SiblingSpacing = .5f; + + /// + /// The one placement pass: gives every generated node its distance and every belt its half width, top-down. A body's children + /// are laid inside-out at the nearest the rules allow, the lightest family is folded into the parent (its mass kept) while the + /// outermost overflows the window, and the rest are stretched geometrically so the outermost sits at the window's edge. A + /// non-root's window ends before its own fade (Gamma x Reach x its distance); a root's, in a zone of several, ends under + /// rootReach / Beta so its support never meets another root's (root-window-floor), and is 0.75 x the area radius at most. + /// A rosette's ring is one orbit; it folds into its node, which becomes a body, if it cannot keep the heavy member outside + /// its Roche margin. Ported from docs/research/gravity-well-law/replace.py. + /// + public static void Place(GeneratorPlanet root, PlanetSettings planetSettings, float radius, float rootReach) + { + var q = 1 / (1 - SiblingSpacing * GravityField.Reach); + float Roche(float mass) => WellTree.Curves(planetSettings, mass).Softening; + float Strength(float mass) => WellTree.Curves(planetSettings, mass).Strength; + float WellMass(GeneratorPlanet p) => p.Empty || p.Belt ? 0f : p.Mass; + float Family(GeneratorPlanet p) => (p.Empty ? 0f : p.Mass) + p.Children.Sum(c => Family(c)); + void Fold(GeneratorPlanet node, GeneratorPlanet into) + { + into.Mass += Family(node); + node.Parent.Children.Remove(node); + } + + void PlaceChildren(List children, Func lower, float upper, GeneratorPlanet into) + { + upper *= 1 - 1e-6f; + float AtLeast(GeneratorPlanet child, float edge) + { + var m = WellMass(child); + var mInto = WellMass(into); + return m <= 0 || mInto <= 0 ? edge : Math.Max(edge, 2 * CuspMargin * Roche(m) * Strength(mInto) / Strength(m)); + } + + var lo = 0f; + var positions = new List(); + while (children.Count > 0) + { + lo = lower(); + positions.Clear(); + for (var k = 0; k < children.Count; k++) + positions.Add(AtLeast(children[k], k == 0 ? lo : Math.Max(lo, positions[k - 1] * q))); + if (positions[positions.Count - 1] <= upper) break; + var lightest = children.OrderBy(c => Family(c)).First(); + Fold(lightest, into); + children.Remove(lightest); + } + if (children.Count == 0) return; + + var g = children.Count > 1 ? pow(upper / positions[positions.Count - 1], 1f / (children.Count - 1)) : 1f; + for (var k = 0; k < children.Count; k++) + children[k].Distance = positions[k] * pow(g, k); + for (var k = 0; k < children.Count; k++) + { + if (!children[k].Belt) continue; + var d = children[k].Distance; + var half = Math.Min(children[k].Settings.AsteroidBeltWidth.Evaluate(d) / 2, d - Math.Max(lo, k > 0 ? children[k - 1].Distance * q : 0f)); + half = Math.Min(half, upper - d); + if (k + 1 < children.Count) half = Math.Min(half, children[k + 1].Distance / q - d); + children[k].BeltHalfWidth = Math.Max(half, 0f); + } + } + + var chordCap = new Dictionary(); // a ring member's children stay within .2 of the nearest partner's chord + void Settle(GeneratorPlanet node) + { + var isRoot = node.Parent == null; + var reach = isRoot ? rootReach : GravityField.Reach * node.Distance; + var share = isRoot ? 1 / GravityField.Beta : GravityField.Gamma; + var cap = isRoot ? .75f * radius : float.PositiveInfinity; + var upper = Math.Min(cap, share * reach / Math.Max(GravityField.Beta, 1 + GravityField.Reach)); + if (chordCap.TryGetValue(node, out var chord)) upper = Math.Min(upper, chord); + if (WellMass(node) > 0) + { + PlaceChildren(node.Children.ToList(), () => RocheMargin * Roche(WellMass(node)), upper, node); + return; + } + + var ring = node.Children.Where(c => c.Ring && WellMass(c) > 0).ToList(); + if (ring.Count == 0) return; + var heavy = ring.OrderByDescending(c => c.Mass).First(); + var soleRoot = isRoot && float.IsInfinity(reach); + var ringDistance = soleRoot ? .5f * cap + : Math.Min(.5f * cap, share * reach / (GravityField.Beta * GravityField.Beta * (1 + GravityField.RingReach))); + if (!soleRoot && ringDistance < RocheMargin * Roche(heavy.Mass)) + { + // The pair cannot keep its heavy member outside its Roche margin inside its node's reach: the node is one body. + node.Empty = false; + node.Mass = 0; + foreach (var child in node.Children.ToList()) Fold(child, node); + return; + } + foreach (var member in ring) + { + member.Distance = ringDistance; + chordCap[member] = .2f * 2 * ringDistance * sin(PI / ring.Count); + } + PlaceChildren(node.Children.Where(c => !ring.Contains(c)).ToList(), + () => (1 + GravityField.RingReach) * ringDistance * GravityField.Beta, upper, heavy); + } + + var queue = new Queue(); + queue.Enqueue(root); + while (queue.Count > 0) + { + var node = queue.Dequeue(); + Settle(node); + foreach (var child in node.Children) queue.Enqueue(child); + } + } } // All orbiting bodies are referred to here as "Planets" @@ -548,10 +695,13 @@ public class GeneratorPlanet public float Distance; public float Phase; public float Mass; - public float ChildDistanceMinimum; - public float ChildDistanceMaximum; + // A belt's half width, written by ZoneGenerator.Place: its inner edge sits outside the parent's Roche margin and its outer + // edge inside the parent's window. + public float BeltHalfWidth; public bool Empty = false; public bool Belt = false; + // A member of a rosette's ring, which Place puts on one orbit round its bodyless parent. + public bool Ring = false; public List Children = new List(); // Planets orbiting this one are referred to as children public GeneratorPlanet Parent; public float2 FixedPosition; @@ -562,12 +712,10 @@ public class GeneratorPlanet return new[]{this}.Concat(Children.SelectMany(c=>c.AllPlanets())); } - // Create children that fill a single orbit, equally spaced + // Create children that fill a single orbit, equally spaced; Place sets the orbit's radius // https://en.wikipedia.org/wiki/Klemperer_rosette public void ExpandRosette(ref Random random, int vertices) { - //Debug.Log("Expanding Rosette"); - // Rosette children replace the parent, parent orbital node is left empty Empty = true; @@ -577,60 +725,37 @@ public class GeneratorPlanet // Proportion of the masses of sequential pairs is random, but only for even vertex counts var proportion = vertices % 2 == 0 ? random.NextFloat(.5f,.95f) : .5f; - // Place children at a fixed distance in the center of the range - var dist = (ChildDistanceMinimum + ChildDistanceMaximum) / 2; - - // Position of first child - var p0 = new float2(0, dist); - - // Position of second child - var p1 = OrbitData.Evaluate(1.0f / vertices) * dist; - - // Maximum child distance is half the distance to the neighbor minus the neighbor's radius - var p0ChildDist = (distance(p0, p1) * proportion - Settings.PlanetSafetyRadius.Evaluate(sharedMass * (1 - proportion))) * .75f; - var p1ChildDist = (distance(p0, p1) * (1 - proportion) - Settings.PlanetSafetyRadius.Evaluate(sharedMass * proportion)) * .75f; - for (int i = 0; i < vertices; i++) { - var child = new GeneratorPlanet + Children.Add(new GeneratorPlanet { Settings = Settings, Parent = this, Mass = sharedMass * (i % 2 == 0 ? proportion : 1 - proportion), // Masses alternate - Distance = dist, Phase = (float) i / vertices, - ChildDistanceMaximum = (i % 2 == 0 ? p0ChildDist : p1ChildDist) - }; - child.ChildDistanceMinimum = Settings.PlanetSafetyRadius.Evaluate(child.Mass) * 2; - Children.Add(child); + Ring = true + }); } - - ChildDistanceMinimum = dist + p0ChildDist; } - // Create children that mimic the distribution of planetary masses in the solar system - public void ExpandSolar(ref Random random, int count, float massMulMin, float massMulMax, float distMulMin, float distMulMax, float jupiterJump, float massFraction) + // Create children that mimic the distribution of planetary masses in the solar system, inside-out in list order; + // Place gives them their distances + public void ExpandSolar(ref Random random, int count, float massMulMin, float massMulMax, float jupiterJump, float massFraction) { - //Debug.Log("Expanding Solar"); - // Expansion is impossible when child space is full - if (count == 0 || ChildDistanceMaximum < ChildDistanceMinimum) + if (count == 0) return; var masses = new float[count]; - var distances = new float[count]; // Accumulate total mass - // Initialize first mass and distance, actual number doesn't matter since total mass will be divided proportionally - float massTotal = distances[0] = masses[0] = 1; + // Initialize first mass, actual number doesn't matter since total mass will be divided proportionally + float massTotal = masses[0] = 1; - // Masses and distances multiply from one planet to the next + // Masses multiply from one planet to the next // Mass typically increases exponentially as you go further out // jupiterJump is an additional mass multiplier applied after half of the planets for (var i = 1; i < count; i++) - { massTotal += masses[i] = masses[i - 1] * random.NextFloat(massMulMin, massMulMax) * (count/2==i ? jupiterJump : 1); - distances[i] = distances[i - 1] * random.NextFloat(distMulMin, distMulMax); - } // Add some randomness to child masses for (var i = 0; i < masses.Length; i++) @@ -640,37 +765,17 @@ public class GeneratorPlanet for (var i = 0; i < count; i++) masses[i] = masses[i] / massTotal * Mass * massFraction; - // Map child distances to range between minimum and maximum - if (count > 1) - { - var oldDistances = (float[]) distances.Clone(); - for (var i = 0; i < count; i++) - distances[i] = lerp(ChildDistanceMinimum, ChildDistanceMaximum, - (oldDistances[i] - oldDistances[0]) / (oldDistances[count - 1] - oldDistances[0])) + Settings.PlanetSafetyRadius.Evaluate(masses[i]); - } - for (var i = 0; i < count; i++) { // Only instantiate children above the mass floor if (masses[i] > Settings.MassFloor) - { - var child = new GeneratorPlanet + Children.Add(new GeneratorPlanet { Settings = Settings, Parent = this, Mass = masses[i], - Distance = distances[i], Phase = random.NextFloat() - }; - child.ChildDistanceMinimum = Settings.PlanetSafetyRadius.Evaluate(child.Mass) * 2; - // Maximum child distance of child is the smallest distance to either of its neighbors - child.ChildDistanceMaximum = min(i == 0 ? child.Distance - ChildDistanceMinimum : child.Distance - distances[i - 1], - i < count - 1 ? distances[i + 1] - child.Distance : float.PositiveInfinity); - if (float.IsNaN(child.Distance)) - throw new NotFiniteNumberException($"Planet created with NaN distance, something went very wrong!"); - if (child.ChildDistanceMaximum > child.ChildDistanceMinimum) - Children.Add(child); - } + }); } } } diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index fd522e357..e77d6c89b 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -820,7 +820,7 @@ public sealed partial class MiningCut3Tests : IDisposable var items = new ItemManager(cache, new ProvenanceLedger(), GameSettings(), _ => { }); foreach (var zone in galaxy.Zones.Take(4)) { - var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance); + var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance); foreach (var body in pack.Planets) { if (!(cache.Get(body) is AsteroidBeltData belt)) continue; diff --git a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs index 217be696a..5c8bae4ce 100644 --- a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs +++ b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs @@ -57,9 +57,10 @@ public sealed class RestoredHullsTests // Shared tutorial-galaxy construction settings (Assets/Resources/Settings.asset's own values), factored out // so every test that needs a real tutorial Galaxy -- not just EntranceZoneAlwaysGetsADockedStationAcrossSeeds // -- builds it the same way instead of re-inlining the same ~20 fields. + internal static PlanetSettings AuthoredPlanetSettings() => AuthoredSettings.Load(RunStartTests.FindRepoRoot()).Read("PlanetSettings"); + internal static ZoneGenerationSettings TutorialZoneSettings() => new ZoneGenerationSettings { - PlanetSafetyRadius = new ExponentialCurve { Exponent = .25f, Multiplier = 2.5f, Constant = 0 }, MassFloor = 1, SunMass = 5000, GasGiantMass = 1000, PlanetMass = 100, SatellitePasses = 5, SatelliteCreationMassFloor = 100, SatelliteCreationProbability = .25f, BinaryCreationProbability = .1f, RosetteProbability = .1f, @@ -156,7 +157,7 @@ public sealed class RestoredHullsTests cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); foreach (var zone in galaxy.Zones.Where(z => !ReferenceEquals(z, galaxy.Entrance))) { - var orbits = ParentedPlanetOrbits(cache, ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, zone, isTutorial: false, ambient: false)); + var orbits = ParentedPlanetOrbits(cache, ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial: false, ambient: false)); if (orbits.Length > 0 && !HasGenuineLagrangeCandidate(orbits)) return (seed, zone.Name); } } @@ -377,7 +378,7 @@ public sealed class RestoredHullsTests var galaxy = new Galaxy(tutorialSettings, background, names, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); var dockedStation = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -418,7 +419,7 @@ public sealed class RestoredHullsTests var galaxy = new Galaxy(tutorialSettings, background, names, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); var planetOrbits = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Where(o => o.Parent.IsSet()).ToArray(); var hasGenuineCandidate = planetOrbits.Any(o => planetOrbits.Count(c => c.Parent.Key.Equals(o.Parent.Key) && abs(c.Distance - o.Distance) < .1f) == 1); @@ -462,7 +463,7 @@ public sealed class RestoredHullsTests zoneSettings.MassFloor = 1e9f; Assert.Throws(() => - ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, galaxy.Entrance, isTutorial: true)); + ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true)); } finally { @@ -497,7 +498,7 @@ public sealed class RestoredHullsTests zoneSettings.SatelliteCreationProbability = 0; zoneSettings.BinaryCreationProbability = 0; - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); var roots = pack.Planets.Select(p => cache.Get(p).Orbit) .Select(cache.Get) @@ -545,7 +546,7 @@ public sealed class RestoredHullsTests var galaxy = new Galaxy(tutorialSettings, background, names, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); var dockedStation = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -740,7 +741,7 @@ public sealed class RestoredHullsTests var galaxy = BuildGalaxyWithForcedEntrance(cache, seed, zoneName); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); var station = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -790,7 +791,7 @@ public sealed class RestoredHullsTests var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); int StationCount(GalaxyZone zone, bool isTutorial) => - ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, zone, isTutorial) + ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial) .Entities.OfType() .Count(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station); @@ -830,7 +831,7 @@ public sealed class RestoredHullsTests cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); var stationCount = pack.Entities.OfType().Count(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station); // Soul's finding (this cut's fix batch 3): pack.Entities.OfType().Count() also counts the // zone's neutral wanderers (ZoneGenerator.cs's own EligibleWandererFactions spawn, keyed to @@ -914,7 +915,7 @@ public sealed class RestoredHullsTests Assert.NotSame(galaxy.Entrance, zone); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, zone, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial: true); // Confirms this fixture still has no genuine (non-rosette) Lagrange candidate -- a regression here // would mean the fixture no longer probes what this test claims to probe. diff --git a/tests/Aetheria.Shared.Tests/RunGoalTests.cs b/tests/Aetheria.Shared.Tests/RunGoalTests.cs index ed96732c9..25b46fdd3 100644 --- a/tests/Aetheria.Shared.Tests/RunGoalTests.cs +++ b/tests/Aetheria.Shared.Tests/RunGoalTests.cs @@ -19,7 +19,7 @@ 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); + return ZoneGenerator.GenerateZone(items, _zoneSettings, _planetSettings, galaxy, zone, galaxy.IsPrelude, ambient); } private Zone ZoneOf(Galaxy galaxy, GalaxyZone zone) => diff --git a/tests/Aetheria.Shared.Tests/RunStartTests.cs b/tests/Aetheria.Shared.Tests/RunStartTests.cs index 5ad89c639..ce853d07c 100644 --- a/tests/Aetheria.Shared.Tests/RunStartTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartTests.cs @@ -78,7 +78,7 @@ public sealed partial class RunStartTests : IDisposable // The fixture galaxy's arena, with or without its generated ships and turrets. private Zone Arena(bool ambient) => - new Zone(_items, _planetSettings, RunStart.GenerateArena(_items, _zoneSettings, _galaxy, new Scripted(ambient, _ => { })), _galaxy.Entrance, _galaxy); + new Zone(_items, _planetSettings, RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new Scripted(ambient, _ => { })), _galaxy.Entrance, _galaxy); private HullData Hull(string name) => _cache.GetAll().Single(hull => hull.Name == name); @@ -673,7 +673,7 @@ public sealed partial class RunStartTests : IDisposable [Fact] public void AdmitIsTheOnlyAgentCreator() { - var pack = RunStart.GenerateArena(_items, _zoneSettings, _galaxy, new Scripted(true, _ => { })); + var pack = RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new Scripted(true, _ => { })); var packedPlayer = pack.Entities.OfType().First(); packedPlayer.IsPlayerShip = true; var zone = new Zone(_items, _planetSettings, pack, _galaxy.Entrance, _galaxy); diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index 11ce2ddf2..da1d08e9a 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -64,7 +64,7 @@ public sealed partial class RunStartTests private (Galaxy galaxy, Zone arena, RunStart.Staged staged, List failures) Launch(Scenario scenario, GalaxyStage inputs = null, Action beforeStaging = null) { var galaxy = RunStart.Generate(scenario, inputs ?? Inputs()); - var arena = new Zone(_items, _planetSettings, RunStart.GenerateArena(_items, _zoneSettings, galaxy, scenario), galaxy.Entrance, galaxy); + var arena = new Zone(_items, _planetSettings, RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, galaxy, scenario), galaxy.Entrance, galaxy); beforeStaging?.Invoke(); var failures = new List(); var staged = RunStart.Stage(_items, arena, scenario, _startingHull, _tutorialSettings, failures); @@ -392,8 +392,8 @@ public sealed partial class RunStartTests { Zone = _galaxy.Entrance, Name = "story", Type = LocationType.Station, Faction = _protagonist, Turrets = 2 }); - var ambient = Census(RunStart.GenerateArena(_items, _zoneSettings, _galaxy, new Scripted(true, _ => { }))); - var quietPack = RunStart.GenerateArena(_items, _zoneSettings, _galaxy, new Scripted(false, _ => { })); + var ambient = Census(RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new Scripted(true, _ => { }))); + var quietPack = RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new Scripted(false, _ => { })); var quiet = Census(quietPack); Assert.Same(quietPack, _galaxy.Entrance.PackedContents); diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index 52bd650f7..4603b5b1b 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -53,7 +53,7 @@ public sealed class StationPlacementTests : IDisposable { if (storyTurrets > 0) galaxyZone.Locations.Add(new LocationStory { Zone = galaxyZone, Name = "Test station", Faction = galaxy.Factions[0], Type = LocationType.Station, Turrets = storyTurrets }); - var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), galaxy, galaxyZone, + var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), authored.Read("PlanetSettings"), galaxy, galaxyZone, galaxyZone == galaxy.Entrance && galaxy.IsPrelude, true); var zone = new Zone(items, authored.Read("PlanetSettings"), pack, galaxyZone, galaxy); zone.Update(.02f); diff --git a/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs b/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs index e6f5314ef..85cbe7ec8 100644 --- a/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs +++ b/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs @@ -191,7 +191,7 @@ public sealed class SunsNeverGreenTests : IDisposable foreach (var zone in galaxy.Zones) { zones++; - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, zone, false, false); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, false, false); suns.AddRange(pack.Planets.Select(p => cache.Get(p)).OfType()); } } diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index a99c7526c..fd1fe941c 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -561,7 +561,6 @@ public static class Program var missing = new List(); if (zones.ZoneRadius == null || zones.ZoneRadius.Maximum <= 0) missing.Add("ZoneSettings.ZoneRadius"); if (zones.SubZoneCount == null || zones.SubZoneCount.Maximum <= 0) missing.Add("ZoneSettings.SubZoneCount"); - if (zones.PlanetSafetyRadius == null || zones.PlanetSafetyRadius.Multiplier <= 0) missing.Add("ZoneSettings.PlanetSafetyRadius"); if (gameplay.Tiers == null || gameplay.Tiers.Length != 5) missing.Add($"GameplaySettings.Tiers (expected 5, got {gameplay.Tiers?.Length ?? 0})"); else if (gameplay.Tiers.Any(t => string.IsNullOrEmpty(t.Name) || t.Quality <= 0)) missing.Add("GameplaySettings.Tiers (a tier parsed without a name or quality)"); if (gameplay.DefaultEntitySettings == null) missing.Add("GameplaySettings.DefaultEntitySettings"); From 2409eed0dcd1a7b2a670426965da228fe77e1a14 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 05:12:17 +0200 Subject: [PATCH 03/22] Tests: children within reach, subzone isolation, station and turret clearance ChildrenWithinReachTests reads the production generator's zones (seeds 1-6) through the Zone and checks each Place rule; SubzonesAreIsolated prints its pair and orbit counts. StationPlacementTests: a station's source is a body (the tutorial root-node fallback excepted), turrets clear their base's extent, no station or turret sits on an unrelated body over 64 instants. Not yet run. Co-Authored-By: Claude Opus 5.5 --- .../ChildrenWithinReachTests.cs | 319 ++++++++++++++++++ .../StationPlacementTests.cs | 66 ++++ 2 files changed, 385 insertions(+) create mode 100644 tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs diff --git a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs new file mode 100644 index 000000000..d87089f48 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs @@ -0,0 +1,319 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; +using Xunit.Abstractions; +using float2 = CultMath.float2; + +// Aetheria gravity, children within reach: the production generator's zones (every zone of seeds 1-6, ambient off) read back +// through the Zone's own tree, orbits and bodies. Each expectation is spelled from the rule it names and the law's constants +// (GravityField), never from ZoneGenerator.Place's helpers. +public sealed class ChildrenWithinReachTests : IClassFixture +{ + public sealed class Zones : IDisposable + { + private readonly ZoneWorlds _worlds = new ZoneWorlds(); + public readonly List<(uint Seed, Zone Zone)> All = new List<(uint, Zone)>(); + + public Zones() + { + for (uint seed = 1; seed <= 6; seed++) + { + var dir = Path.Combine(_worlds.Root, $"galaxy{seed}"); + Directory.CreateDirectory(dir); + var catalog = Path.Combine(dir, "Aetheria.cc"); + File.Copy(TestCatalog.Repo, catalog); + var cache = new CultCache(TestCatalog.Registry()); + _worlds.Caches.Add(cache); + cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(catalog), AetheriaStores.CatalogTypes); + cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); + var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); + var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), + authored.Read("TutorialBackgroundSettings"), + authored.Read("NameGeneratorSettings"), cache, new PlayerSettings(), + Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var items = new ItemManager(cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); + var planetSettings = authored.Read("PlanetSettings"); + foreach (var galaxyZone in galaxy.Zones) + { + var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), planetSettings, galaxy, galaxyZone, + galaxyZone == galaxy.Entrance && galaxy.IsPrelude, false); + All.Add((seed, new Zone(items, planetSettings, pack, galaxyZone, galaxy))); + } + } + } + + public void Dispose() => _worlds.Dispose(); + } + + private readonly Zones _zones; + private readonly ITestOutputHelper _out; + + public ChildrenWithinReachTests(Zones zones, ITestOutputHelper output) + { + _zones = zones; + _out = output; + } + + private const float Tolerance = 1e-3f; + private const float RocheMargin = 1.5f, CuspMargin = 1.5f; // the rulings tail-taming-law-r3-band-loose-cusp and c4-proceed-and-fly + + private static float Roche(Zone zone, float mass) => zone.Settings.RocheLimit.Evaluate(mass); + private static float Strength(Zone zone, float mass) => zone.Settings.WellStrength.Evaluate(mass); + + // Orbits that carry a well-bearing body, with its mass; belts and bodyless nodes carry none. + private static Dictionary BodyMass(Zone zone) => + zone.Planets.Values.Where(b => !(b is AsteroidBeltData)).GroupBy(b => b.Orbit.Key).ToDictionary(g => g.Key, g => g.First().Mass); + + // The generated orbits: every body's and its ancestors', which leaves out stations, turrets and Lagrange copies. + private static HashSet Placed(Zone zone) + { + var placed = new HashSet(); + foreach (var body in zone.Planets.Values) + for (var key = body.Orbit.Key; placed.Add(key) && zone.Orbits[key].Data.Parent.IsSet();) key = zone.Orbits[key].Data.Parent.Key; + return placed; + } + + private static List ChildrenOf(Zone zone, CultRecordKey parent, HashSet placed) => + placed.Where(k => zone.Orbits[k].Data.Parent.IsSet() && zone.Orbits[k].Data.Parent.Key.Equals(parent)) + .OrderBy(k => zone.Orbits[k].Data.Distance).ToList(); + + private static float DistanceOf(Zone zone, CultRecordKey orbit) => zone.Orbits[orbit].Data.Distance; + + private static List MassiveRoots(Zone zone) => + zone.Orbits.Keys.Where(k => !zone.Orbits[k].Data.Parent.IsSet() && zone.Wells.Reach(k) > 0f).ToList(); + + private static float2 Anchor(Zone zone, CultRecordKey root) => zone.Orbits[root].Data.FixedPosition; + + private static IEnumerable Descendants(Zone zone, CultRecordKey root, HashSet placed) + { + foreach (var child in ChildrenOf(zone, root, placed)) + { + yield return child; + foreach (var below in Descendants(zone, child, placed)) yield return below; + } + } + + [Fact] + public void SubzonesAreIsolated() + { + var zonesChecked = 0; + var pairs = 0; + var violatingPairs = 0; + var orbits = 0; + var violatingOrbits = 0; + foreach (var (seed, zone) in _zones.All) + { + var roots = MassiveRoots(zone); + if (roots.Count < 2) continue; + zonesChecked++; + var placed = Placed(zone); + foreach (var i in roots) + { + var nearest = roots.Where(j => !j.Equals(i)).Min(j => length(Anchor(zone, i) - Anchor(zone, j))); + Assert.True(Math.Abs(zone.Wells.Reach(i) - GravityField.Reach * nearest) <= Tolerance * nearest, + $"seed {seed}: a root's reach {zone.Wells.Reach(i)} is not Reach x the nearest root's distance {nearest} (its floor binds)"); + foreach (var j in roots.Where(j => !j.Equals(i))) + { + pairs++; + if (zone.Wells.Reach(i) + zone.Wells.Support(j) > length(Anchor(zone, i) - Anchor(zone, j)) * (1 + Tolerance)) violatingPairs++; + foreach (var orbit in Descendants(zone, i, placed)) + { + orbits++; + if (length(zone.OrbitPositionAt(orbit, 0) - Anchor(zone, j)) < zone.Wells.Reach(j) * (1 - Tolerance)) violatingOrbits++; + } + } + } + } + _out.WriteLine($"subzones isolated: {zonesChecked} multi-root zones, {pairs} ordered root pairs ({violatingPairs} with reach_i + support_j > d), " + + $"{orbits} orbit-vs-root checks ({violatingOrbits} inside another root's reach)"); + Assert.True(zonesChecked > 0 && pairs > 0 && orbits > 0, "the seeds generated no zone with two massive roots"); + Assert.True(violatingPairs == 0, $"{violatingPairs} of {pairs} ordered root pairs overlap"); + Assert.True(violatingOrbits == 0, $"{violatingOrbits} of {orbits} orbits sit inside another root's reach"); + } + + [Fact] + public void NoChildSitsInsideItsParentsRocheMargin() + { + var children = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + foreach (var parent in placed.Where(mass.ContainsKey)) + foreach (var child in ChildrenOf(zone, parent, placed)) + { + children++; + var margin = RocheMargin * Roche(zone, mass[parent]); + Assert.True(DistanceOf(zone, child) >= margin * (1 - Tolerance), $"seed {seed}: a child sits at {DistanceOf(zone, child)}, inside {margin}"); + } + } + Assert.True(children > 100, $"only {children} children checked"); + } + + [Fact] + public void EveryMassiveChildKeepsACusp() + { + var checkedChildren = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + foreach (var parent in placed.Where(mass.ContainsKey)) + foreach (var child in ChildrenOf(zone, parent, placed).Where(mass.ContainsKey)) + { + checkedChildren++; + var cusp = 2 * CuspMargin * Roche(zone, mass[child]) * Strength(zone, mass[parent]) / Strength(zone, mass[child]); + Assert.True(DistanceOf(zone, child) >= cusp * (1 - Tolerance), $"seed {seed}: a massive child sits at {DistanceOf(zone, child)}, inside its cusp bound {cusp}"); + } + } + Assert.True(checkedChildren > 50, $"only {checkedChildren} massive children checked"); + } + + [Fact] + public void AFamilyEndsBeforeItsParentsFade() + { + var families = 0; + foreach (var (seed, zone) in _zones.All) + { + var placed = Placed(zone); + var mass = BodyMass(zone); + foreach (var node in placed.Where(k => zone.Orbits[k].Data.Parent.IsSet() && zone.Wells.Reach(k) > 0f)) + { + var kids = ChildrenOf(zone, node, placed); + if (!kids.Any(k => zone.Wells.Reach(k) > 0f)) continue; + families++; + Assert.True(zone.Wells.Support(node) <= GravityField.Gamma * zone.Wells.Reach(node) * (1 + Tolerance), + $"seed {seed}: a family's support {zone.Wells.Support(node)} runs past Gamma x its reach {zone.Wells.Reach(node)}"); + var parent = zone.Orbits[node].Data.Parent.Key; + if (mass.ContainsKey(parent)) // a ring member's reach is RingReach x D; a body's child's is Reach x D + Assert.True(Math.Abs(zone.Wells.Reach(node) - GravityField.Reach * DistanceOf(zone, node)) <= Tolerance * DistanceOf(zone, node), + $"seed {seed}: a family's reach {zone.Wells.Reach(node)} is not Reach x its distance {DistanceOf(zone, node)}"); + } + } + Assert.True(families > 20, $"only {families} families checked"); + } + + [Fact] + public void SiblingsSitHalfAReachApart() + { + var q = 1 / (1 - GravityField.Reach / 2); + var pairs = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + foreach (var parent in placed.Where(mass.ContainsKey)) + { + var kids = ChildrenOf(zone, parent, placed); + for (var k = 1; k < kids.Count; k++) + { + pairs++; + Assert.True(DistanceOf(zone, kids[k]) >= DistanceOf(zone, kids[k - 1]) * q * (1 - Tolerance), + $"seed {seed}: siblings at {DistanceOf(zone, kids[k - 1])} and {DistanceOf(zone, kids[k])} are closer than a factor {q}"); + } + } + } + Assert.True(pairs > 100, $"only {pairs} sibling pairs checked"); + } + + [Fact] + public void FoldingConservesMass() + { + var zones = 0; + foreach (var (seed, zone) in _zones.All) + { + var placed = Placed(zone); + // A zone with a rosette or binary holds bodyless nodes, whose own (renormalised) mass is not a body's. + if (placed.Any(k => !zone.Planets.Values.Any(b => b.Orbit.Key.Equals(k)))) continue; + zones++; + var sum = zone.Planets.Values.Sum(b => b.Mass); + Assert.True(Math.Abs(sum - zone.Pack.Mass) <= 1e-3f * zone.Pack.Mass, $"seed {seed}: the bodies sum to {sum}, not the pack's {zone.Pack.Mass}"); + } + Assert.True(zones > 10, $"only {zones} zones without a bodyless node"); + } + + [Fact] + public void RingsKeepTheirMembersApartAndCircumbinaryChildrenFar() + { + var rings = 0; + var outer = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + foreach (var node in placed.Where(k => !mass.ContainsKey(k) && !zone.Planets.Values.Any(b => b.Orbit.Key.Equals(k)))) + { + var kids = ChildrenOf(zone, node, placed); + var members = kids.Where(mass.ContainsKey).ToList(); + if (members.Count < 2) continue; + var ring = members.Where(k => DistanceOf(zone, k) - DistanceOf(zone, members[0]) <= WellTree.RingWindow).ToList(); + if (ring.Count < 2) continue; + rings++; + var radius = DistanceOf(zone, ring[0]); + var heavy = ring.Max(k => mass[k]); + Assert.True(radius >= RocheMargin * Roche(zone, heavy) * (1 - Tolerance), + $"seed {seed}: a ring of radius {radius} sits inside its heavy member's Roche margin"); + foreach (var far in kids.Where(k => !ring.Contains(k))) + { + outer++; + Assert.True(DistanceOf(zone, far) >= (1 + GravityField.RingReach) * GravityField.Beta * radius * (1 - Tolerance), + $"seed {seed}: a circumbinary child at {DistanceOf(zone, far)} is inside the ring group of radius {radius}"); + } + } + } + Assert.True(rings > 3, $"only {rings} rings checked"); + _out.WriteLine($"rings {rings}, circumbinary children {outer}"); + } + + [Fact] + public void BeltsKeepTheirEdges() + { + var belts = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + foreach (var (beltKey, belt) in zone.AsteroidBelts) + { + belts++; + var orbit = zone.Planets[beltKey].Orbit.Key; + var parent = zone.Orbits[orbit].Data.Parent.Key; + var inner = belt.Data.Asteroids.Min(a => a.Distance); + var outermost = belt.Data.Asteroids.Max(a => a.Distance); + Assert.True(inner > 0f, $"seed {seed}: an asteroid sits at {inner}"); + if (mass.TryGetValue(parent, out var m)) + Assert.True(inner >= RocheMargin * Roche(zone, m) * (1 - Tolerance), $"seed {seed}: a belt's inner edge {inner} is inside its parent's Roche margin"); + if (zone.Orbits[parent].Data.Parent.IsSet()) + Assert.True(outermost <= GravityField.Gamma * GravityField.Reach * DistanceOf(zone, parent) / Math.Max(GravityField.Beta, 1 + GravityField.Reach) * (1 + Tolerance), + $"seed {seed}: a belt reaches {outermost}, past its parent's window"); + } + } + Assert.True(belts > 20, $"only {belts} belts checked"); + } + + [Fact] + public void NoStrengthlessOrbitRidesARing() + { + var rings = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + foreach (var node in placed.Where(k => !mass.ContainsKey(k) && !zone.Planets.Values.Any(b => b.Orbit.Key.Equals(k)))) + { + var members = ChildrenOf(zone, node, placed).Where(mass.ContainsKey).ToList(); + if (members.Count < 2) continue; + rings++; + var radius = DistanceOf(zone, members[0]); + // Every orbit of the zone, stations and turrets included, that hangs on the node and carries no body. + foreach (var orbit in zone.Orbits.Keys.Where(k => zone.Orbits[k].Data.Parent.IsSet() && zone.Orbits[k].Data.Parent.Key.Equals(node) && !mass.ContainsKey(k))) + Assert.True(DistanceOf(zone, orbit) >= (1 + GravityField.RingReach) * radius * (1 - Tolerance), + $"seed {seed}: a strengthless orbit at {DistanceOf(zone, orbit)} rides the ring group of radius {radius}"); + } + } + Assert.True(rings > 3, $"only {rings} rings checked"); + } +} diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index 4603b5b1b..bb85b3c2f 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -74,6 +74,7 @@ public sealed class StationPlacementTests : IDisposable public void AStationSitsAtItsPlanetsL4OrL5() { var checkedStations = 0; + var rootStations = 0; var ahead = 0; var behind = 0; foreach (var built in GeneratedZones()) @@ -85,7 +86,21 @@ public sealed class StationPlacementTests : IDisposable { var orbit = zone.Orbits[station.OrbitData]; var sources = zone.Orbits.Where(o => !ridden.Contains(o.Key) && SameRing(o.Value, orbit)).ToList(); + if (sources.Count == 0) + { + // The tutorial entrance's one exception: a station on its own orbit round a root node, beyond the node's ring + // group (or, for a body, its whole family), at no Lagrange point. + var rootKey = orbit.Data.Parent.Key; + Assert.False(zone.Orbits[rootKey].Data.Parent.IsSet(), $"seed {built.Seed}: a station with no source orbit does not orbit a root node"); + var innermost = zone.Orbits.Where(o => o.Value.Data.Parent.IsSet() && o.Value.Data.Parent.Key.Equals(rootKey) && zone.Wells.Reach(o.Key) > 0f && o.Key != station.OrbitData) + .Min(o => o.Value.Data.Distance); + Assert.True(orbit.Data.Distance >= zone.Wells.Support(rootKey) * .999f || orbit.Data.Distance >= (1 + GravityField.RingReach) * GravityField.Beta * innermost * .999f, + $"seed {built.Seed}: a root-node station at {orbit.Data.Distance} sits inside its node's family"); + rootStations++; + continue; + } Assert.True(sources.Count == 1, $"seed {built.Seed}: a station shares its ring with {sources.Count} unridden orbits, not one"); + Assert.Contains(zone.Planets.Values, b => b.Orbit.Key.Equals(sources[0].Key) && !(b is AsteroidBeltData)); var planet = sources[0].Value; var offset = Turns(orbit.Data.Phase - planet.Data.Phase); @@ -103,9 +118,49 @@ public sealed class StationPlacementTests : IDisposable } } Assert.True(checkedStations > 0, "the seeds generated no station"); + Assert.True(rootStations == 0 || rootStations < checkedStations, "every station is a root-node fallback"); Assert.True(ahead > 0 && behind > 0, $"the seeds put stations on one side only (ahead {ahead}, behind {behind})"); } + // How far a body keeps others out: its family's support, or 1.5 Roche limits (tail-taming-law-r3-band-loose-cusp) if more. + private static float BaseExtent(Zone zone, CultRecordKey orbit) + { + var body = zone.Planets.Values.FirstOrDefault(b => b.Orbit.Key.Equals(orbit) && !(b is AsteroidBeltData)); + return Math.Max(zone.Wells.Support(orbit), body == null ? 0f : 1.5f * zone.Settings.RocheLimit.Evaluate(body.Mass)); + } + + // Over 64 instants of the longest period in the zone, no station or turret centre is within 1.5 Roche limits plus its + // reach of any body other than its base (station-orbit-choice-residuals item 1). + [Fact] + public void NoStationOrTurretSitsOnAnUnrelatedBody() + { + var checkedEntities = 0; + foreach (var built in GeneratedZones()) + { + var zone = built.Zone; + var longest = zone.Orbits.Values.Select(o => o.Period).Where(float.IsFinite).DefaultIfEmpty(1f).Max(); + var bodies = zone.Planets.Values.Where(b => !(b is AsteroidBeltData)).ToList(); + foreach (var entity in Orbitals(built).Where(e => TypeOf(built.Items, e) is HullType.Station or HullType.Turret)) + { + var orbit = zone.Orbits[entity.OrbitData]; + checkedEntities++; + foreach (var body in bodies) + { + var bodyOrbit = zone.Orbits[body.Orbit.Key]; + if (SameRing(bodyOrbit, orbit)) continue; // its base + var margin = 1.5f * zone.Settings.RocheLimit.Evaluate(body.Mass) + Contacts.Radius(entity); + for (var k = 0; k < 64; k++) + { + var t = k / 64.0 * longest; + Assert.True(length(zone.OrbitPositionAt(entity.OrbitData, t) - zone.OrbitPositionAt(body.Orbit.Key, t)) >= margin * .999f, + $"seed {built.Seed}: an entity passes within {margin} of an unrelated body at instant {k}"); + } + } + } + } + Assert.True(checkedEntities > 0, "the seeds generated no station"); + } + private static List Orbitals(Built built) => built.Zone.Entities.OfType().ToList(); // Every turret belongs to one station on its ring. Each side of a station grows outward from it: a turret's centre sits @@ -157,6 +212,17 @@ public sealed class StationPlacementTests : IDisposable } } + // No turret reaches its base body: the planet whose Lagrange orbit the station rides (the ring's one unridden orbit). + var ridden = built.Zone.Entities.OfType().Select(e => e.OrbitData).ToHashSet(); + var source = built.Zone.Orbits.Where(o => !ridden.Contains(o.Key) && SameRing(o.Value, orbit)).Select(o => o.Key).ToList(); + if (source.Count == 1) + { + var extent = BaseExtent(built.Zone, source[0]); + foreach (var turret in mine) + Assert.True(length(turret.Position.xz - built.Zone.Orbits[source[0]].Position) >= (extent + Contacts.Radius(turret)) * .999f, + $"seed {built.Seed}: a turret sits within the base body's extent {extent} and its reach of the base"); + } + var bodies = new List { station }; bodies.AddRange(mine); for (var a = 0; a < bodies.Count; a++) From 0dc7e4bae384cb9ad4ab46fd72e3fc85c137ed8f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 05:13:03 +0200 Subject: [PATCH 04/22] Tests: compile fixes (does not isolate a build until this commit) Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs | 1 + tests/Aetheria.Shared.Tests/StationPlacementTests.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs index d87089f48..9be8997a4 100644 --- a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs +++ b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs @@ -6,6 +6,7 @@ using CultMath; using GameCult.Caching; using Xunit; using Xunit.Abstractions; +using static CultMath.math; using float2 = CultMath.float2; // Aetheria gravity, children within reach: the production generator's zones (every zone of seeds 1-6, ambient off) read back diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index bb85b3c2f..f231e4a03 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -92,7 +92,7 @@ public sealed class StationPlacementTests : IDisposable // group (or, for a body, its whole family), at no Lagrange point. var rootKey = orbit.Data.Parent.Key; Assert.False(zone.Orbits[rootKey].Data.Parent.IsSet(), $"seed {built.Seed}: a station with no source orbit does not orbit a root node"); - var innermost = zone.Orbits.Where(o => o.Value.Data.Parent.IsSet() && o.Value.Data.Parent.Key.Equals(rootKey) && zone.Wells.Reach(o.Key) > 0f && o.Key != station.OrbitData) + var innermost = zone.Orbits.Where(o => o.Value.Data.Parent.IsSet() && o.Value.Data.Parent.Key.Equals(rootKey) && zone.Wells.Reach(o.Key) > 0f && !o.Key.Equals(station.OrbitData)) .Min(o => o.Value.Data.Distance); Assert.True(orbit.Data.Distance >= zone.Wells.Support(rootKey) * .999f || orbit.Data.Distance >= (1 + GravityField.RingReach) * GravityField.Beta * innermost * .999f, $"seed {built.Seed}: a root-node station at {orbit.Data.Distance} sits inside its node's family"); From ed9f9930ddcf97244877702572e867d208d585da Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 05:21:11 +0200 Subject: [PATCH 05/22] Place: a sole root's ring also folds when it cannot keep its heavy member outside the Roche margin; the entrance station falls back to the heaviest root of childless roots; tests follow Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/ServerShared/ZoneGenerator.cs | 12 +++---- .../ChildrenWithinReachTests.cs | 35 +++++++++++++------ .../RestoredHullsTests.cs | 6 +++- .../StationPlacementTests.cs | 10 +++++- 4 files changed, 43 insertions(+), 20 deletions(-) diff --git a/Assets/Scripts/ServerShared/ZoneGenerator.cs b/Assets/Scripts/ServerShared/ZoneGenerator.cs index 149e63db4..4a4cfcf9a 100644 --- a/Assets/Scripts/ServerShared/ZoneGenerator.cs +++ b/Assets/Scripts/ServerShared/ZoneGenerator.cs @@ -258,14 +258,14 @@ public static class ZoneGenerator { // The entrance gets a station whatever its bodies: it orbits a root node beyond its ring group (or, for a body, its // whole family), never at a ring member's distance, and sits there, not at a Lagrange point. - var rootNode = planets.FirstOrDefault(p => p.Parent == null && p.Children.Count > 0); + var roots = planets.Where(p => p.Parent == null).ToList(); + var rootNode = roots.FirstOrDefault(p => p.Children.Count > 0) ?? (roots.Count > 1 ? roots.OrderByDescending(p => p.Mass).First() : null); if (rootNode == null) throw new InvalidOperationException( "The tutorial entrance zone must always get a station, but it has no candidate orbit at all -- every planet in the zone is a parentless root."); - var rootKey = cache.RefOf(orbitMap[rootNode]).Key; var distance = rootNode.Empty ? (1 + GravityField.RingReach) * GravityField.Beta * rootNode.Children.Where(Massive).Min(c => c.Distance) - : wells.Support(rootKey); + : Extent(rootNode); var direct = new OrbitData { Parent = cache.RefOf(orbitMap[rootNode]), Distance = distance, Phase = random.NextFloat() }; pack.Orbits.Add(cache.Upsert(direct)); sources = new[] { (orbit: direct, extent: float.NegativeInfinity, direct: true) }; @@ -655,10 +655,8 @@ public static class ZoneGenerator var ring = node.Children.Where(c => c.Ring && WellMass(c) > 0).ToList(); if (ring.Count == 0) return; var heavy = ring.OrderByDescending(c => c.Mass).First(); - var soleRoot = isRoot && float.IsInfinity(reach); - var ringDistance = soleRoot ? .5f * cap - : Math.Min(.5f * cap, share * reach / (GravityField.Beta * GravityField.Beta * (1 + GravityField.RingReach))); - if (!soleRoot && ringDistance < RocheMargin * Roche(heavy.Mass)) + var ringDistance = Math.Min(.5f * cap, share * reach / (GravityField.Beta * GravityField.Beta * (1 + GravityField.RingReach))); + if (ringDistance < RocheMargin * Roche(heavy.Mass)) { // The pair cannot keep its heavy member outside its Roche margin inside its node's reach: the node is one body. node.Empty = false; diff --git a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs index 9be8997a4..a0d2b1408 100644 --- a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs +++ b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs @@ -59,7 +59,9 @@ public sealed class ChildrenWithinReachTests : IClassFixture zone.Settings.RocheLimit.Evaluate(mass); @@ -168,7 +170,7 @@ public sealed class ChildrenWithinReachTests : IClassFixture= cusp * (1 - Tolerance), $"seed {seed}: a massive child sits at {DistanceOf(zone, child)}, inside its cusp bound {cusp}"); + Assert.True(DistanceOf(zone, child) >= cusp * (1 - CuspTolerance), $"seed {seed}: a massive child sits at {DistanceOf(zone, child)}, inside its cusp bound {cusp}"); } } Assert.True(checkedChildren > 50, $"only {checkedChildren} massive children checked"); @@ -221,20 +223,31 @@ public sealed class ChildrenWithinReachTests : IClassFixture 100, $"only {pairs} sibling pairs checked"); } + // The mass split is renormalised so a family's masses sum to its root's; folding moves a family's mass into its parent body. + // A tree with a rosette or binary holds a bodyless node whose own mass is renormalised with the rest, so it is left out. [Fact] public void FoldingConservesMass() { - var zones = 0; - foreach (var (seed, zone) in _zones.All) + var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); + var zoneSettings = authored.Read("ZoneSettings"); + var planetSettings = authored.Read("PlanetSettings"); + const float mass = 300000f; + var trees = 0; + var folded = 0; + for (uint seed = 1; seed <= 200; seed++) { - var placed = Placed(zone); - // A zone with a rosette or binary holds bodyless nodes, whose own (renormalised) mass is not a body's. - if (placed.Any(k => !zone.Planets.Values.Any(b => b.Orbit.Key.Equals(k)))) continue; - zones++; - var sum = zone.Planets.Values.Sum(b => b.Mass); - Assert.True(Math.Abs(sum - zone.Pack.Mass) <= 1e-3f * zone.Pack.Mass, $"seed {seed}: the bodies sum to {sum}, not the pack's {zone.Pack.Mass}"); + // The same random stream makes the same tree; only the window differs, so a smaller one folds more of it. + var tight = new CultMath.Random(seed); + var tightTree = ZoneGenerator.GenerateEntities(zoneSettings, planetSettings, ref tight, mass, 1500f, float2.zero, float.PositiveInfinity); + var wide = new CultMath.Random(seed); + var wideTree = ZoneGenerator.GenerateEntities(zoneSettings, planetSettings, ref wide, mass, 1e7f, float2.zero, float.PositiveInfinity); + if (tightTree.Any(p => p.Empty || p.Ring) || wideTree.Any(p => p.Empty || p.Ring)) continue; + trees++; + if (tightTree.Length < wideTree.Length) folded++; + Assert.True(Math.Abs(tightTree.Sum(p => p.Mass) - mass) <= 1e-3f * mass, $"seed {seed}: a folded tree's bodies sum to {tightTree.Sum(p => p.Mass)}, not {mass}"); } - Assert.True(zones > 10, $"only {zones} zones without a bodyless node"); + _out.WriteLine($"folding: {trees} trees, {folded} with a fold"); + Assert.True(trees > 20 && folded > 10, $"{trees} trees, {folded} with a fold"); } [Fact] diff --git a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs index 5c8bae4ce..d21051f0f 100644 --- a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs +++ b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs @@ -750,7 +750,11 @@ public sealed class RestoredHullsTests // Confirms this fixture still exercises the widened path (a regression here would mean the fixture no // longer probes what this test claims to probe). - Assert.True(IsRosetteMember(cache, pack, stationOrbit), "the entrance station no longer sits on a rosette-only orbit -- this fixture no longer tests the widened candidate path."); + // The zone has no body alone on its ring, so the station orbits the root node beyond its ring group. + var rootOrbit = cache.Get(stationOrbit.Parent); + Assert.False(rootOrbit.Parent.IsSet(), "the entrance station no longer orbits a root node -- this fixture no longer tests the no-candidate path."); + var ring = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Where(o => o.Parent.IsSet() && o.Parent.Key.Equals(stationOrbit.Parent.Key)).Select(o => o.Distance).DefaultIfEmpty(0f).Min(); + Assert.True(stationOrbit.Distance >= (1 + GravityField.RingReach) * GravityField.Beta * ring * .999f, $"the entrance station at {stationOrbit.Distance} sits inside its node's ring group of radius {ring}."); var turrets = pack.Entities.OfType() .Where(e => (cache.Get(e.Hull.Data) as HullData)?.HullType != HullType.Station).ToArray(); diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index f231e4a03..913ce8f33 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -93,7 +93,7 @@ public sealed class StationPlacementTests : IDisposable var rootKey = orbit.Data.Parent.Key; Assert.False(zone.Orbits[rootKey].Data.Parent.IsSet(), $"seed {built.Seed}: a station with no source orbit does not orbit a root node"); var innermost = zone.Orbits.Where(o => o.Value.Data.Parent.IsSet() && o.Value.Data.Parent.Key.Equals(rootKey) && zone.Wells.Reach(o.Key) > 0f && !o.Key.Equals(station.OrbitData)) - .Min(o => o.Value.Data.Distance); + .DefaultIfEmpty(0f).Min(o => o.Value.Data.Distance); Assert.True(orbit.Data.Distance >= zone.Wells.Support(rootKey) * .999f || orbit.Data.Distance >= (1 + GravityField.RingReach) * GravityField.Beta * innermost * .999f, $"seed {built.Seed}: a root-node station at {orbit.Data.Distance} sits inside its node's family"); rootStations++; @@ -148,6 +148,7 @@ public sealed class StationPlacementTests : IDisposable { var bodyOrbit = zone.Orbits[body.Orbit.Key]; if (SameRing(bodyOrbit, orbit)) continue; // its base + if (IsAncestorBody(zone, orbit, body.Orbit.Key)) continue; // the body it orbits round: it keeps its distance by its own Roche margin var margin = 1.5f * zone.Settings.RocheLimit.Evaluate(body.Mass) + Contacts.Radius(entity); for (var k = 0; k < 64; k++) { @@ -161,6 +162,13 @@ public sealed class StationPlacementTests : IDisposable Assert.True(checkedEntities > 0, "the seeds generated no station"); } + private static bool IsAncestorBody(Zone zone, Orbit orbit, CultRecordKey bodyOrbit) + { + for (var parent = orbit.Data.Parent; parent.IsSet(); parent = zone.Orbits[parent.Key].Data.Parent) + if (parent.Key.Equals(bodyOrbit)) return true; + return false; + } + private static List Orbitals(Built built) => built.Zone.Entities.OfType().ToList(); // Every turret belongs to one station on its ring. Each side of a station grows outward from it: a turret's centre sits From c3d7d077e6eb47929669866295ad03a8f6c76c43 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 05:22:57 +0200 Subject: [PATCH 06/22] Tests: compile fix Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/StationPlacementTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index 913ce8f33..e3333c1be 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -93,7 +93,7 @@ public sealed class StationPlacementTests : IDisposable var rootKey = orbit.Data.Parent.Key; Assert.False(zone.Orbits[rootKey].Data.Parent.IsSet(), $"seed {built.Seed}: a station with no source orbit does not orbit a root node"); var innermost = zone.Orbits.Where(o => o.Value.Data.Parent.IsSet() && o.Value.Data.Parent.Key.Equals(rootKey) && zone.Wells.Reach(o.Key) > 0f && !o.Key.Equals(station.OrbitData)) - .DefaultIfEmpty(0f).Min(o => o.Value.Data.Distance); + .Select(o => o.Value.Data.Distance).DefaultIfEmpty(0f).Min(); Assert.True(orbit.Data.Distance >= zone.Wells.Support(rootKey) * .999f || orbit.Data.Distance >= (1 + GravityField.RingReach) * GravityField.Beta * innermost * .999f, $"seed {built.Seed}: a root-node station at {orbit.Data.Distance} sits inside its node's family"); rootStations++; From 513d0c43939aaa07193e77231c7eddc1365ab49a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 05:25:26 +0200 Subject: [PATCH 07/22] Place: ring merge decided on the heavy member's final mass; a bodyless node keeps a cusp as the one body it would become; tests follow Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/ServerShared/ZoneGenerator.cs | 8 +++++--- tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs | 4 +++- tests/Aetheria.Shared.Tests/RestoredHullsTests.cs | 7 ++----- tests/Aetheria.Shared.Tests/StationPlacementTests.cs | 2 +- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Assets/Scripts/ServerShared/ZoneGenerator.cs b/Assets/Scripts/ServerShared/ZoneGenerator.cs index 4a4cfcf9a..6597f8541 100644 --- a/Assets/Scripts/ServerShared/ZoneGenerator.cs +++ b/Assets/Scripts/ServerShared/ZoneGenerator.cs @@ -603,7 +603,8 @@ public static class ZoneGenerator upper *= 1 - 1e-6f; float AtLeast(GeneratorPlanet child, float edge) { - var m = WellMass(child); + // A bodyless node stands in for one body of its family's mass, which it becomes if its ring cannot stand + var m = child.Empty ? Family(child) : WellMass(child); var mInto = WellMass(into); return m <= 0 || mInto <= 0 ? edge : Math.Max(edge, 2 * CuspMargin * Roche(m) * Strength(mInto) / Strength(m)); } @@ -656,6 +657,9 @@ public static class ZoneGenerator if (ring.Count == 0) return; var heavy = ring.OrderByDescending(c => c.Mass).First(); var ringDistance = Math.Min(.5f * cap, share * reach / (GravityField.Beta * GravityField.Beta * (1 + GravityField.RingReach))); + PlaceChildren(node.Children.Where(c => !ring.Contains(c)).ToList(), + () => (1 + GravityField.RingReach) * ringDistance * GravityField.Beta, upper, heavy); + // The heavy member's mass is final only now (the outer children fold into it). if (ringDistance < RocheMargin * Roche(heavy.Mass)) { // The pair cannot keep its heavy member outside its Roche margin inside its node's reach: the node is one body. @@ -669,8 +673,6 @@ public static class ZoneGenerator member.Distance = ringDistance; chordCap[member] = .2f * 2 * ringDistance * sin(PI / ring.Count); } - PlaceChildren(node.Children.Where(c => !ring.Contains(c)).ToList(), - () => (1 + GravityField.RingReach) * ringDistance * GravityField.Beta, upper, heavy); } var queue = new Queue(); diff --git a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs index a0d2b1408..9b40f5a44 100644 --- a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs +++ b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs @@ -231,6 +231,8 @@ public sealed class ChildrenWithinReachTests : IClassFixture("ZoneSettings"); var planetSettings = authored.Read("PlanetSettings"); + zoneSettings.RosetteProbability = 0; // a rosette or binary holds a bodyless node + zoneSettings.BinaryCreationProbability = 0; const float mass = 300000f; var trees = 0; var folded = 0; @@ -241,7 +243,7 @@ public sealed class ChildrenWithinReachTests : IClassFixture p.Empty || p.Ring) || wideTree.Any(p => p.Empty || p.Ring)) continue; + trees++; if (tightTree.Length < wideTree.Length) folded++; Assert.True(Math.Abs(tightTree.Sum(p => p.Mass) - mass) <= 1e-3f * mass, $"seed {seed}: a folded tree's bodies sum to {tightTree.Sum(p => p.Mass)}, not {mass}"); diff --git a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs index d21051f0f..641c0d54a 100644 --- a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs +++ b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs @@ -500,11 +500,8 @@ public sealed class RestoredHullsTests var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); - var roots = pack.Planets.Select(p => cache.Get(p).Orbit) - .Select(cache.Get) - .Select(o => o.Parent.IsSet() ? o.Parent.Key.Value : "(root)") - .Distinct().Count(); - Assert.True(roots > 1, $"this fixture no longer produces a multi-root entrance (only {roots} distinct parent); it no longer tests the fragmented-topology case."); + var roots = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Count(o => !o.Parent.IsSet()); + Assert.True(roots > 1, $"this fixture no longer produces a multi-root entrance (only {roots} root); it no longer tests the fragmented-topology case."); var stations = pack.Entities.OfType() .Where(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station).ToArray(); diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index e3333c1be..82f16e4ed 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -154,7 +154,7 @@ public sealed class StationPlacementTests : IDisposable { var t = k / 64.0 * longest; Assert.True(length(zone.OrbitPositionAt(entity.OrbitData, t) - zone.OrbitPositionAt(body.Orbit.Key, t)) >= margin * .999f, - $"seed {built.Seed}: an entity passes within {margin} of an unrelated body at instant {k}"); + $"seed {built.Seed}: a {TypeOf(built.Items, entity)} on a ring of {orbit.Data.Distance} passes within {margin} of an unrelated body (mass {body.Mass}, ring {bodyOrbit.Data.Distance}, same parent {bodyOrbit.Data.Parent.Key.Equals(orbit.Data.Parent.Key)}) at instant {k}"); } } } From 2111174adf850531e5e4b8b4b7858717d3874b68 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 05:27:47 +0200 Subject: [PATCH 08/22] Stations: a candidate rail clears each massive sibling's extent by the largest station or turret reach Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/ServerShared/ZoneGenerator.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Assets/Scripts/ServerShared/ZoneGenerator.cs b/Assets/Scripts/ServerShared/ZoneGenerator.cs index 6597f8541..5248a22bb 100644 --- a/Assets/Scripts/ServerShared/ZoneGenerator.cs +++ b/Assets/Scripts/ServerShared/ZoneGenerator.cs @@ -244,11 +244,15 @@ public static class ZoneGenerator var isTutorialEntrance = isTutorial && galaxyZone == galaxy.Entrance; if (isTutorialEntrance && stationCount < 1) stationCount = 1; // A station's source is a well-bearing body alone on its ring whose rail clears every massive sibling's extent (the - // sibling's support, or its Roche margin if more): its Lagrange orbit then sits clear of any other body. + // sibling's support, or its Roche margin if more) and the largest reach of any station or turret hull: whatever hull + // is built there, its Lagrange orbit then sits clear of any other body. + var cellSize = itemManager.GameplaySettings.SchematicCellSize; + var largestReach = cache.GetAll().Where(h => h.HullType == HullType.Station || h.HullType == HullType.Turret) + .Select(h => h.Reach(cellSize)).DefaultIfEmpty(0f).Max(); var candidates = planets .Where(p => p.Parent != null && !p.Empty && !p.Belt && p.Parent.Children.TrueForAll(c => c == p || (abs(c.Distance - p.Distance) >= WellTree.RingWindow - && (!Massive(c) || abs(c.Distance - p.Distance) > Extent(c))))) + && (!Massive(c) || abs(c.Distance - p.Distance) > Extent(c) + largestReach)))) .OrderBy(p => p.Distance) .ToArray(); // (the rail, how far a body on it keeps others out, whether it is a station's own orbit rather than a base's) From 3ef0ac21ebe02c4e890cf878c2aeb87d8386ad89 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 05:31:08 +0200 Subject: [PATCH 09/22] RunStartTests: the belt race takes the first arena that has a belt Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/RunStartTests.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/RunStartTests.cs b/tests/Aetheria.Shared.Tests/RunStartTests.cs index ce853d07c..62ce0f7ba 100644 --- a/tests/Aetheria.Shared.Tests/RunStartTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartTests.cs @@ -311,8 +311,14 @@ public sealed partial class RunStartTests : IDisposable [Fact] public void NoOrbitStandsStillAgainstItsParent() { - var zone = Arena(false); // no ships: nothing but the zone runs - Assert.True(zone.AsteroidBelts.Count > 0, "the arena has an asteroid belt to race against"); + // No ships: nothing but the zone runs. Belts are rarer than they were, so the first galaxy seed whose entrance holds one. + Zone zone = null; + for (uint seed = GalaxySeed; zone == null && seed < GalaxySeed + 60; seed++) + { + var (_, arena, _, _) = Launch(new Scripted(false, _ => { }, seed), Inputs()); + if (arena.AsteroidBelts.Count > 0) zone = arena; + } + Assert.True(zone != null, "no arena of the first 60 seeds has an asteroid belt to race against"); float2 Relative(Orbit orbit, bool previous) => (previous ? orbit.PreviousPosition : orbit.Position) - (zone.Orbits.TryGetValue(orbit.Data.Parent.Key, out var parent) ? previous ? parent.PreviousPosition : parent.Position : orbit.Data.FixedPosition); From c727141a2f890b4faa43293e5b4337f42f66c3d5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 05:40:34 +0200 Subject: [PATCH 10/22] Scenarios: Belt and Lock On take the seeds that hold their conditions under the new placement Belt: seed 86 (484 rocks, scanned over seeds 1-90). Lock On: seed 1 (the staged hostile settles below the detection threshold). Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/ServerShared/Scenarios/Belt.cs | 7 ++++--- Assets/Scripts/ServerShared/Scenarios/LockOn.cs | 2 +- .../Fonts & Materials/LiberationSans SDF - Fallback.asset | 4 ++-- tests/Aetheria.Shared.Tests/BeltScenarioTests.cs | 6 +++--- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/Assets/Scripts/ServerShared/Scenarios/Belt.cs b/Assets/Scripts/ServerShared/Scenarios/Belt.cs index efab34db7..bc261ddda 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Belt.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Belt.cs @@ -10,9 +10,10 @@ public sealed class Belt : Scenario "across the belt without a hitch; Previous with nothing targeted takes the farthest rock; the target indicator " + "sits on the rock it names."; - // Seeds 1-256 scanned for the arena whose entrance zone holds the belt with the most asteroids: seed 24, a belt of - // 615 rocks. The next four: 179 (553), 251 (548), 221 (532), 29 (515). - public override uint Seed => 24; + // Seeds 1-90 scanned for the arena whose entrance zone holds the belt with the most asteroids once the generator + // placed belts by their parent's window (children-within-reach): seed 86, a belt of 484 rocks. The next four: + // 55 (478), 83 (402), 64 (383), 63 (323). 37 of the 90 arenas hold no belt. + public override uint Seed => 86; public override bool Ambient => false; public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); diff --git a/Assets/Scripts/ServerShared/Scenarios/LockOn.cs b/Assets/Scripts/ServerShared/Scenarios/LockOn.cs index 7dc850497..87cef4a51 100644 --- a/Assets/Scripts/ServerShared/Scenarios/LockOn.cs +++ b/Assets/Scripts/ServerShared/Scenarios/LockOn.cs @@ -7,7 +7,7 @@ public sealed class LockOn : Scenario public override string Brief => "A hostile closes from out of sight, finds you and locks. Verify: no warning at first; once it locks, one " + "indicator appears toward it and tightens as the lock grows; break line of sight or range and it vanishes; " + "your own ping shows no incoming paint on its side, only the lock does."; - public override uint Seed => 113; + public override uint Seed => 1; public override bool Ambient => false; // The hostile starts about 4000 m off, ahead and to port of the player, facing the player. At that range its passive diff --git a/Assets/TextMesh Pro/Resources/Fonts & Materials/LiberationSans SDF - Fallback.asset b/Assets/TextMesh Pro/Resources/Fonts & Materials/LiberationSans SDF - Fallback.asset index 4d9191d4c..4787be7c3 100644 --- a/Assets/TextMesh Pro/Resources/Fonts & Materials/LiberationSans SDF - Fallback.asset +++ b/Assets/TextMesh Pro/Resources/Fonts & Materials/LiberationSans SDF - Fallback.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f1eead45000fe0fe0a6fce50b4d21ab2ff1ea25f5b390452116e0b04f28540a7 -size 536050 +oid sha256:f53586850a70c4f308e7e71b99b63881a49f38de4bd40f4edb7fe7ae6ecf8a52 +size 9748 diff --git a/tests/Aetheria.Shared.Tests/BeltScenarioTests.cs b/tests/Aetheria.Shared.Tests/BeltScenarioTests.cs index 0222ca035..2c352b6e8 100644 --- a/tests/Aetheria.Shared.Tests/BeltScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/BeltScenarioTests.cs @@ -7,9 +7,9 @@ using static CultMath.math; // mining-merge-on-agent-proof). The test launches the scenario the way New Game does and reads what it staged. public sealed partial class RunStartTests { - // The scan behind Belt's seed: seeds 1-256 of the demo cast's arena, no ambient traffic, the most asteroids in one belt - // per seed. Seed 24 holds 615; seed 1 holds 299. - private const int ScannedBeltAsteroids = 615; + // The scan behind Belt's seed: seeds 1-90 of the demo cast's arena, no ambient traffic, the most asteroids in one belt + // per seed. Seed 86 holds 484. + private const int ScannedBeltAsteroids = 484; // Belt: the arena carries a belt of at least the scanned asteroid count, nothing else flies in it, the player stands // 100 m outside the ring on the side nearest the origin and faces along it, and the player's sensors see rocks within From f5329e50a230bcb0c38aa8dad3a0e29e30496e37 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 05:55:53 +0200 Subject: [PATCH 11/22] RestoredHullsTests: the entrance throw is reached by a single-root zone (several roots give the station a root to orbit) Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/RestoredHullsTests.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs index 641c0d54a..6711f894a 100644 --- a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs +++ b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs @@ -461,6 +461,8 @@ public sealed class RestoredHullsTests var zoneSettings = TutorialZoneSettings(); zoneSettings.RosetteProbability = 0; zoneSettings.MassFloor = 1e9f; + // One subzone: the zone's only body is a parentless root. (Several roots give the station a root to orbit.) + zoneSettings.SubZoneCount = new ExponentialLerp { Exponent = 1, Minimum = 0, Maximum = 0 }; Assert.Throws(() => ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true)); From b305c66c6c02e57f32065c0471eda0f3eac485a7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 05:56:58 +0200 Subject: [PATCH 12/22] Tests: belts keep a spacing from their neighbours; story turrets at 3, 5 and 9; a station never sits on a binary's bodyless node Co-Authored-By: Claude Opus 5.5 --- .../ChildrenWithinReachTests.cs | 7 +++ .../StationPlacementTests.cs | 50 +++++++++++++++---- 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs index 9b40f5a44..71fa4e922 100644 --- a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs +++ b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs @@ -302,6 +302,13 @@ public sealed class ChildrenWithinReachTests : IClassFixture 0f, $"seed {seed}: an asteroid sits at {inner}"); if (mass.TryGetValue(parent, out var m)) Assert.True(inner >= RocheMargin * Roche(zone, m) * (1 - Tolerance), $"seed {seed}: a belt's inner edge {inner} is inside its parent's Roche margin"); + // The belt keeps clear of its neighbours' rails by a sibling spacing (rule 3), inner and outer. + var sibling = ChildrenOf(zone, parent, Placed(zone)); + var at = sibling.IndexOf(orbit); + if (at > 0) + Assert.True(inner >= DistanceOf(zone, sibling[at - 1]) * (1 / (1 - GravityField.Reach / 2)) * (1 - Tolerance), $"seed {seed}: a belt reaches in to {inner}, within a spacing of its inner neighbour"); + if (at < sibling.Count - 1) + Assert.True(outermost <= DistanceOf(zone, sibling[at + 1]) * (1 - GravityField.Reach / 2) * (1 + Tolerance), $"seed {seed}: a belt reaches out to {outermost}, within a spacing of its outer neighbour"); if (zone.Orbits[parent].Data.Parent.IsSet()) Assert.True(outermost <= GravityField.Gamma * GravityField.Reach * DistanceOf(zone, parent) / Math.Max(GravityField.Beta, 1 + GravityField.Reach) * (1 + Tolerance), $"seed {seed}: a belt reaches {outermost}, past its parent's window"); diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index 82f16e4ed..b1f10751f 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -29,7 +29,8 @@ 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) + private IEnumerable GeneratedZones(Action stock = null, int storyTurrets = 0, uint seeds = 6, int zonesPerSeed = int.MaxValue, + Action tune = null) { for (uint seed = 1; seed <= seeds; seed++) { @@ -53,7 +54,9 @@ public sealed class StationPlacementTests : IDisposable { if (storyTurrets > 0) galaxyZone.Locations.Add(new LocationStory { Zone = galaxyZone, Name = "Test station", Faction = galaxy.Factions[0], Type = LocationType.Station, Turrets = storyTurrets }); - var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), authored.Read("PlanetSettings"), galaxy, galaxyZone, + var zoneSettings = authored.Read("ZoneSettings"); + tune?.Invoke(zoneSettings); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, authored.Read("PlanetSettings"), galaxy, galaxyZone, galaxyZone == galaxy.Entrance && galaxy.IsPrelude, true); var zone = new Zone(items, authored.Read("PlanetSettings"), pack, galaxyZone, galaxy); zone.Update(.02f); @@ -122,7 +125,31 @@ public sealed class StationPlacementTests : IDisposable Assert.True(ahead > 0 && behind > 0, $"the seeds put stations on one side only (ahead {ahead}, behind {behind})"); } - // How far a body keeps others out: its family's support, or 1.5 Roche limits (tail-taming-law-r3-band-loose-cusp) if more. + // A binary is a bodyless node under its parent; the station's source is never such a node, however many binaries there are. + [Fact] + public void AStationNeverSitsOnABinarysBodylessNode() + { + var binaries = 0; + var stations = 0; + foreach (var built in GeneratedZones(null, 0, 4, int.MaxValue, z => { z.SatelliteCreationProbability = 1; z.BinaryCreationProbability = 1; })) + { + var zone = built.Zone; + var bodyOrbits = zone.Planets.Values.Select(b => b.Orbit.Key).ToHashSet(); + binaries += zone.Orbits.Count(o => o.Value.Data.Parent.IsSet() && !bodyOrbits.Contains(o.Key) && zone.Wells.Reach(o.Key) > 0f); + var ridden = zone.Entities.OfType().Select(e => e.OrbitData).ToHashSet(); + foreach (var station in Orbitals(built).Where(e => TypeOf(built.Items, e) == HullType.Station)) + { + var orbit = zone.Orbits[station.OrbitData]; + var sources = zone.Orbits.Where(o => !ridden.Contains(o.Key) && SameRing(o.Value, orbit)).ToList(); + if (sources.Count == 0) continue; // the tutorial entrance's own orbit round a root + stations++; + Assert.Contains(bodyOrbits, key => key.Equals(sources[0].Key)); + } + } + Assert.True(binaries > 5 && stations > 5, $"{binaries} bodyless nodes and {stations} stations: the seeds do not exercise the rule"); + } + + // How far a body keeps others out: its family's support, or 1.5 Roche limits (tail-taming-law-r3-band-loose-cusp) if more. private static float BaseExtent(Zone zone, CultRecordKey orbit) { var body = zone.Planets.Values.FirstOrDefault(b => b.Orbit.Key.Equals(orbit) && !(b is AsteroidBeltData)); @@ -202,8 +229,7 @@ public sealed class StationPlacementTests : IDisposable var behind = arcs.Where(a => a.arc < 0).OrderByDescending(a => a.arc).ToList(); var ahead = arcs.Where(a => a.arc > 0).OrderBy(a => a.arc).ToList(); // Turrets alternate behind then ahead, so behind holds the extra one when the count is odd. - Assert.Equal((mine.Count + 1) / 2, behind.Count); - Assert.Equal(mine.Count / 2, ahead.Count); + // (A side whose next turret would reach the base body stops, so the sides need not stay level.) if (mine.Select(Contacts.Radius).Distinct().Count() > 1) mixedReach++; foreach (var (side, sign) in new[] { (behind, -1f), (ahead, 1f) }) @@ -267,13 +293,15 @@ public sealed class StationPlacementTests : IDisposable [Fact] public void ANarrativeStationsTurretsKeepFlankingAndClearEachOtherWhateverTheirReach() { - const int authored = 5; - var flanked = 0; + var flanked = 0; var mixed = 0; - var most = 0; - foreach (var built in GeneratedZones(WithALargerTurretHull, authored, 3, 3)) - most = Math.Max(most, AssertFlanks(built, ref flanked, ref mixed)); - Assert.True(most == authored, $"no story station carried its {authored} authored turrets (most {most})"); + foreach (var authored in new[] { 3, 5, 9 }) + { + var most = 0; + foreach (var built in GeneratedZones(WithALargerTurretHull, authored, 6, 6)) + most = Math.Max(most, AssertFlanks(built, ref flanked, ref mixed)); + Assert.True(most > 0 && most <= authored, $"the most turrets a station carried is {most} of {authored} authored"); + } Assert.True(mixed > 0, "no station carried turrets of differing reach"); } From 4d6c307d0cdc6d8c8d9ce99a1d8b04644b88d7af Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 06:07:09 +0200 Subject: [PATCH 13/22] StationPlacementTests: each generated galaxy has its own directory Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/StationPlacementTests.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index b1f10751f..2c5a2149d 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -16,6 +16,7 @@ public sealed class StationPlacementTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-stationplacement-" + Guid.NewGuid().ToString("N")); private readonly List _caches = new List(); + private int _generation; public StationPlacementTests() => Directory.CreateDirectory(_root); @@ -34,7 +35,7 @@ public sealed class StationPlacementTests : IDisposable { for (uint seed = 1; seed <= seeds; seed++) { - var dir = Path.Combine(_root, $"galaxy{seed}"); + var dir = Path.Combine(_root, $"galaxy{seed}-{_generation++}"); Directory.CreateDirectory(dir); var catalog = Path.Combine(dir, "Aetheria.cc"); File.Copy(TestCatalog.Repo, catalog); From 1f83d0743bbdc21f9d82d58a377061ecc851a5d1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 06:08:02 +0200 Subject: [PATCH 14/22] Tests: folding takes the lightest family Co-Authored-By: Claude Opus 5.5 --- .../ChildrenWithinReachTests.cs | 62 ++++++++++++++----- 1 file changed, 47 insertions(+), 15 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs index 71fa4e922..bc675821b 100644 --- a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs +++ b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs @@ -223,33 +223,65 @@ public sealed class ChildrenWithinReachTests : IClassFixture 100, $"only {pairs} sibling pairs checked"); } - // The mass split is renormalised so a family's masses sum to its root's; folding moves a family's mass into its parent body. - // A tree with a rosette or binary holds a bodyless node whose own mass is renormalised with the rest, so it is left out. - [Fact] - public void FoldingConservesMass() + // The same random stream makes the same tree; only the window differs, so a small one (tight) folds some of what a huge one + // (wide) keeps whole. No rosette or binary: a bodyless node's own mass is renormalised with the rest. + private static IEnumerable<(uint Seed, GeneratorPlanet[] Tight, GeneratorPlanet[] Wide)> TightAndWideTrees(float mass) { var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); var zoneSettings = authored.Read("ZoneSettings"); var planetSettings = authored.Read("PlanetSettings"); - zoneSettings.RosetteProbability = 0; // a rosette or binary holds a bodyless node + zoneSettings.RosetteProbability = 0; zoneSettings.BinaryCreationProbability = 0; - const float mass = 300000f; - var trees = 0; - var folded = 0; for (uint seed = 1; seed <= 200; seed++) { - // The same random stream makes the same tree; only the window differs, so a smaller one folds more of it. var tight = new CultMath.Random(seed); var tightTree = ZoneGenerator.GenerateEntities(zoneSettings, planetSettings, ref tight, mass, 1500f, float2.zero, float.PositiveInfinity); var wide = new CultMath.Random(seed); var wideTree = ZoneGenerator.GenerateEntities(zoneSettings, planetSettings, ref wide, mass, 1e7f, float2.zero, float.PositiveInfinity); - - trees++; - if (tightTree.Length < wideTree.Length) folded++; - Assert.True(Math.Abs(tightTree.Sum(p => p.Mass) - mass) <= 1e-3f * mass, $"seed {seed}: a folded tree's bodies sum to {tightTree.Sum(p => p.Mass)}, not {mass}"); + yield return (seed, tightTree, wideTree); } - _out.WriteLine($"folding: {trees} trees, {folded} with a fold"); - Assert.True(trees > 20 && folded > 10, $"{trees} trees, {folded} with a fold"); + } + + // Folding moves a family's mass into its parent body, so a tree's masses still sum to its root's. + [Fact] + public void FoldingConservesMass() + { + const float mass = 300000f; + var folded = 0; + foreach (var (seed, tight, wide) in TightAndWideTrees(mass)) + { + if (tight.Length < wide.Length) folded++; + Assert.True(Math.Abs(tight.Sum(p => p.Mass) - mass) <= 1e-3f * mass, $"seed {seed}: a folded tree's bodies sum to {tight.Sum(p => p.Mass)}, not {mass}"); + } + _out.WriteLine($"folding: {folded} of 200 trees with a fold"); + Assert.True(folded > 10, $"only {folded} trees folded"); + } + + // Under one parent the families folded away are never heavier than the ones kept (rule 4: the lightest goes first). + [Fact] + public void FoldingTakesTheLightestFamily() + { + float Family(GeneratorPlanet p) => p.Mass + p.Children.Sum(Family); + var parentsThatFolded = 0; + foreach (var (seed, tight, wide) in TightAndWideTrees(300000f)) + { + var tightByPhase = tight.ToDictionary(p => p.Phase); + void Compare(GeneratorPlanet w) + { + if (w.Children.Count == 0 || !tightByPhase.TryGetValue(w.Phase, out var t)) return; + var keptPhases = t.Children.Select(c => c.Phase).ToHashSet(); + var kept = w.Children.Where(c => keptPhases.Contains(c.Phase)).ToList(); + var gone = w.Children.Where(c => !keptPhases.Contains(c.Phase)).ToList(); + if (gone.Count > 0 && kept.Count > 0) + { + parentsThatFolded++; + Assert.True(gone.Max(Family) <= kept.Min(Family) * (1 + 1e-4f), $"seed {seed}: a folded family outweighs one that was kept"); + } + foreach (var child in kept) Compare(child); + } + Compare(wide[0]); + } + Assert.True(parentsThatFolded > 10, $"only {parentsThatFolded} parents folded part of their children"); } [Fact] From 6214741ab5d628790d522862dfefb37bc680a870 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 08:45:41 +0200 Subject: [PATCH 15/22] Restore LiberationSans SDF - Fallback.asset to its 09a7f189 LFS pointer Unity re-serialised the generated atlas into the working tree and it was committed in c727141a; the file is back to the pointer (oid f1eead45, size 536050). Builds. Co-Authored-By: Claude Opus 5.5 --- .../Fonts & Materials/LiberationSans SDF - Fallback.asset | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Assets/TextMesh Pro/Resources/Fonts & Materials/LiberationSans SDF - Fallback.asset b/Assets/TextMesh Pro/Resources/Fonts & Materials/LiberationSans SDF - Fallback.asset index 4787be7c3..4d9191d4c 100644 --- a/Assets/TextMesh Pro/Resources/Fonts & Materials/LiberationSans SDF - Fallback.asset +++ b/Assets/TextMesh Pro/Resources/Fonts & Materials/LiberationSans SDF - Fallback.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f53586850a70c4f308e7e71b99b63881a49f38de4bd40f4edb7fe7ae6ecf8a52 -size 9748 +oid sha256:f1eead45000fe0fe0a6fce50b4d21ab2ff1ea25f5b390452116e0b04f28540a7 +size 536050 From b13aa67efd6a82c248d50b321b75d7865112b670 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 09:00:04 +0200 Subject: [PATCH 16/22] Place: a belt fills its slot between its neighbours' spacing, the Roche margin and the window Replaces the symmetric half-width about the chain position (which collapsed a belt at the end of its slot to a line, finding belts-collapse-to-a-line) with the slot interval: the belt sits at the slot's midpoint and its half width is min(authored width, slot) / 2 (ruling belt-fills-its-slot). The chain still places belts as massless points, so no fold count moves. Builds; tests follow. Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/ServerShared/ZoneGenerator.cs | 21 ++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/Assets/Scripts/ServerShared/ZoneGenerator.cs b/Assets/Scripts/ServerShared/ZoneGenerator.cs index 5248a22bb..30d9d52ae 100644 --- a/Assets/Scripts/ServerShared/ZoneGenerator.cs +++ b/Assets/Scripts/ServerShared/ZoneGenerator.cs @@ -631,14 +631,19 @@ public static class ZoneGenerator var g = children.Count > 1 ? pow(upper / positions[positions.Count - 1], 1f / (children.Count - 1)) : 1f; for (var k = 0; k < children.Count; k++) children[k].Distance = positions[k] * pow(g, k); + // A belt is an interval inside its slot: inner edge outside the lower bound and the previous sibling's spacing, outer edge + // inside the next sibling's spacing and the window; the authored width is the widest it may be. + var outer = 0f; for (var k = 0; k < children.Count; k++) { - if (!children[k].Belt) continue; - var d = children[k].Distance; - var half = Math.Min(children[k].Settings.AsteroidBeltWidth.Evaluate(d) / 2, d - Math.Max(lo, k > 0 ? children[k - 1].Distance * q : 0f)); - half = Math.Min(half, upper - d); - if (k + 1 < children.Count) half = Math.Min(half, children[k + 1].Distance / q - d); - children[k].BeltHalfWidth = Math.Max(half, 0f); + var c = children[k]; + if (!c.Belt) { outer = c.Distance; continue; } + var inner = Math.Max(lo, outer * q); + var outerLimit = k + 1 < children.Count ? Math.Min(upper, children[k + 1].Distance / q) : upper; + c.Distance = (inner + outerLimit) / 2; + var half = Math.Max(0f, Math.Min(c.Settings.AsteroidBeltWidth.Evaluate(c.Distance), outerLimit - inner) / 2); + c.BeltHalfWidth = half; + outer = c.Distance + half; } } @@ -699,8 +704,8 @@ public class GeneratorPlanet public float Distance; public float Phase; public float Mass; - // A belt's half width, written by ZoneGenerator.Place: its inner edge sits outside the parent's Roche margin and its outer - // edge inside the parent's window. + // A belt's half width, written by ZoneGenerator.Place: the belt fills the slot between its siblings' spacing, the parent's + // Roche margin and the parent's window, up to the authored width (ruling belt-fills-its-slot). public float BeltHalfWidth; public bool Empty = false; public bool Belt = false; From c39a73ca12af2a31a06694790157ccbc1d6240f0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 09:00:21 +0200 Subject: [PATCH 17/22] 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; } } From 7db87cfa88e636795e4541763dbe35f5e0751eb0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 09:02:51 +0200 Subject: [PATCH 18/22] Tests: the entrance fallback reads its root's extent from the bodies alone; tail diagnostics The zone's well tree counts the station's own rail in its root's family, so the extent is rebuilt from the generated bodies. Carries a temporary DIAG line in ATurretTailStopsAtItsBaseBody. Co-Authored-By: Claude Opus 5.5 --- .../StationPlacementTests.cs | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index ccc2d309a..a7306bba0 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -157,6 +157,25 @@ public sealed class StationPlacementTests : IDisposable Assert.True(binaries > 5 && stations > 5, $"{binaries} bodyless nodes and {stations} stations: the seeds do not exercise the rule"); } + // The zone's own well tree counts a station's rail as a member of its root's family, so the extent the generator checked + // (the bodies' alone) is rebuilt here from the generated bodies' orbits and their ancestors. + private static float ExtentOfBodies(Zone zone, CultRecordKey orbit) + { + var mass = zone.Planets.Values.Where(b => !(b is AsteroidBeltData)).GroupBy(b => b.Orbit.Key).ToDictionary(g => g.Key, g => g.First().Mass); + var placed = new HashSet(); + foreach (var body in zone.Planets.Values) + for (var key = body.Orbit.Key; placed.Add(key) && zone.Orbits[key].Data.Parent.IsSet();) key = zone.Orbits[key].Data.Parent.Key; + var beltExtent = zone.AsteroidBelts.ToDictionary(b => zone.Planets[b.Key].Orbit.Key, b => b.Value.Data.Asteroids.Select(a => a.Distance).DefaultIfEmpty(0f).Max()); + var nodes = placed.Select(k => + { + var d = zone.Orbits[k].Data; + return new WellNode(k, d.Parent.Key, d.Distance, d.Phase, mass.TryGetValue(k, out var m) ? m : 0f, + beltExtent.TryGetValue(k, out var e) ? Math.Max(e, d.Distance) : d.Distance, d.FixedPosition + OrbitData.Evaluate(frac(d.Phase)) * d.Distance); + }).ToList(); + var wells = WellTree.Build(nodes, zone.Settings, zone.Pack.Radius); + return Math.Max(wells.Support(orbit), 1.5f * zone.Settings.RocheLimit.Evaluate(mass[orbit])); + } + // How far a body keeps others out: its family's support, or 1.5 Roche limits (tail-taming-law-r3-band-loose-cusp) if more. private static float BaseExtent(Zone zone, CultRecordKey orbit) { @@ -367,6 +386,7 @@ public sealed class StationPlacementTests : IDisposable 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))); + _output.WriteLine($"DIAG seed {built.Seed} total {mine.Count} sign {sign} side {side.Count} chord {chord} extent {extent} reach {reach} circ {circumference} D {orbit.Data.Distance} stationR {Contacts.Radius(station)}"); 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}"); @@ -395,7 +415,7 @@ public sealed class StationPlacementTests : IDisposable 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); + var extent = ExtentOfBodies(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}"); From f881a3bdfe6933e34ba7bd4d3c61f701f157a39d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 09:07:54 +0200 Subject: [PATCH 19/22] Tests: tail test reads stations whose turrets do not wrap the ring Co-Authored-By: Claude Opus 5.5 --- .../Aetheria.Shared.Tests/StationPlacementTests.cs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index a7306bba0..1d4e49237 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -355,14 +355,14 @@ public sealed class StationPlacementTests : IDisposable // 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 + // the base (story-turret-tail-clearance). With a single wide turret hull on offer and sixteen story turrets a 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; + const int turrets = 16; + int stations = 0, ambiguous = 0, sides = 0, stops = 0, nearBase = 0; foreach (var built in GeneratedZones(WithOnlyAWiderTurretHull, turrets, 6)) { var zone = built.Zone; @@ -374,11 +374,13 @@ public sealed class StationPlacementTests : IDisposable 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(); + // Half the ring away a turret's side is ambiguous (its signed arc wraps), so such a station is not read. + if (arcs.Any(a => Math.Abs(a) > .45f * circumference)) { ambiguous++; continue; } + stations++; foreach (var sign in new[] { -1f, 1f }) { var side = arcs.Where(a => a * sign > 0).OrderBy(a => a * sign).ToList(); @@ -386,15 +388,15 @@ public sealed class StationPlacementTests : IDisposable 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))); - _output.WriteLine($"DIAG seed {built.Seed} total {mine.Count} sign {sign} side {side.Count} chord {chord} extent {extent} reach {reach} circ {circumference} D {orbit.Data.Distance} stationR {Contacts.Radius(station)}"); if (side.Count >= turrets / 2) continue; stops++; + _output.WriteLine($"DIAG seed {built.Seed} side {side.Count} of {turrets / 2} stopped: next turret {chord / (extent + reach):F3} of the stop distance"); 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}"); + _output.WriteLine($"story stations {stations} (not read, ambiguous: {ambiguous}), sides {sides}, sides that stopped {stops}, of them with the next turret at 0.8 to 1 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"); } From c345b303de3826aeab48a44d359ff2bbe8cef481 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 09:09:03 +0200 Subject: [PATCH 20/22] Tests: tail test leaves out stations whose base family holds a belt Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/StationPlacementTests.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index 1d4e49237..bdcd6a0cf 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -378,8 +378,11 @@ public sealed class StationPlacementTests : IDisposable 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(); - // Half the ring away a turret's side is ambiguous (its signed arc wraps), so such a station is not read. - if (arcs.Any(a => Math.Abs(a) > .45f * circumference)) { ambiguous++; continue; } + // Half the ring away a turret's side is ambiguous (its signed arc wraps). A belt in the base's family has an extent the + // generator spelled from its authored width and the zone reads from its rocks, so the stop distance is not known to the + // test. Neither station is read. + bool InFamily(CultRecordKey key) { for (; zone.Orbits[key].Data.Parent.IsSet(); key = zone.Orbits[key].Data.Parent.Key) if (key.Equals(source[0])) return true; return key.Equals(source[0]); } + if (arcs.Any(a => Math.Abs(a) > .45f * circumference) || zone.AsteroidBelts.Any(b => InFamily(zone.Planets[b.Key].Orbit.Key))) { ambiguous++; continue; } stations++; foreach (var sign in new[] { -1f, 1f }) { @@ -396,7 +399,7 @@ public sealed class StationPlacementTests : IDisposable } } } - _output.WriteLine($"story stations {stations} (not read, ambiguous: {ambiguous}), sides {sides}, sides that stopped {stops}, of them with the next turret at 0.8 to 1 of the stop distance {nearBase}"); + _output.WriteLine($"story stations {stations} (not read: {ambiguous}), sides {sides}, sides that stopped {stops}, of them with the next turret at 0.8 to 1 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"); } From a54707d1d82c00467f59f4a4e27528bd819992a7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 09:10:25 +0200 Subject: [PATCH 21/22] Tests: drop the tail diagnostics Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/StationPlacementTests.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index bdcd6a0cf..2b65116d0 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -393,7 +393,6 @@ public sealed class StationPlacementTests : IDisposable 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++; - _output.WriteLine($"DIAG seed {built.Seed} side {side.Count} of {turrets / 2} stopped: next turret {chord / (extent + reach):F3} of the stop distance"); 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++; } From cf242106fadc03fb172e917402a0044e45005506 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 17 Oct 2026 09:30:03 +0200 Subject: [PATCH 22/22] Tests: every turret on a read side clears the base body by its extent and reach The 0.8 tail-extent mutant survived the stop checks alone: it places turrets inside the distance, which only a placed turret's own clearance shows. Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/StationPlacementTests.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index 2b65116d0..759e3e83d 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -388,6 +388,11 @@ public sealed class StationPlacementTests : IDisposable { var side = arcs.Where(a => a * sign > 0).OrderBy(a => a * sign).ToList(); sides++; + foreach (var placed in side) + { + var at = 2 * orbit.Data.Distance * Math.Abs((float) Math.Sin(PI * (orbit.Data.Phase + placed / circumference - zone.Orbits[source[0]].Data.Phase))); + Assert.True(at >= (extent + reach) * .999f, $"seed {built.Seed}: a turret sits {at} from its base, inside {extent + reach}"); + } 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)));