StationDeck deals every station of a region; Choose and the zone-stream count draw are deleted

StationKinds.Choose (the per-station site hash) becomes PoolOf, the fieldable kinds with Choose's logged fallback and no hash. StationDeck.Deal owns which stations every zone holds: a zone's slots come from the run seed and its presence, a thin territory gets slots until a faction can stand every kind it fields outside the entrance, hands are dealt per region and faction by decks of one card per kind, and Ring places a hand frontier first. ZoneGenerator seats every dealt card (the rail shortfall path is every zone's; an ordered entrance seats its orders alone) and reads nearest faction, presence and structure faction from StationDeck. StationKindTests re-pointed from Choose to PoolOf and the deal.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-28 22:53:17 +01:00
commit baec7f5f7c
5 changed files with 226 additions and 87 deletions

View file

@ -30,8 +30,8 @@ public abstract class Scenario
// declaration: nothing tests a scenario's type to decide saving.
public virtual bool Saved => true;
// The stations the arena's zone always gets, in slot order after its story stations, whatever its seed rolls
// (ZoneGenerator). Empty: its stations are rolled like any other zone's.
// The arena's ambient stations, in slot order after its story stations, whatever the deal gives its zone (ZoneGenerator):
// given orders are exactly its ambient stations, its story stations staying. Empty: its dealt stations (StationDeck).
public virtual IReadOnlyList<EntranceStationOrder> EntranceStations => EntranceStationOrder.Any;
// Which galaxy the run is in: stage.Main() or stage.Cast(cast).
@ -50,7 +50,7 @@ public enum ScenarioStance
}
// One station a scenario's entrance zone must hold. Faction is a cast name Galaxy.ResolveFaction resolves (null: the zone's
// structure faction); Kind is a station-kind id, StationKindData.KeyOf (null: StationKinds.Choose picks one).
// structure faction); Kind is a station-kind id, StationKindData.KeyOf (null: the faction's first StationKinds.PoolOf kind).
public sealed class EntranceStationOrder
{
public string Faction { get; }
@ -58,7 +58,7 @@ public sealed class EntranceStationOrder
public EntranceStationOrder(string faction, string kind) { Faction = faction; Kind = kind; }
// One default order: the zone's structure faction, a chosen kind.
// One default order: the zone's structure faction, its first pool kind.
public static readonly IReadOnlyList<EntranceStationOrder> Any = new[] { new EntranceStationOrder(null, null) };
public static readonly IReadOnlyList<EntranceStationOrder> None = Array.Empty<EntranceStationOrder>();
}

View file

@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Caching;
// One card of a zone's deal: the faction that holds the station and the kind it is.
public readonly struct StationCard
{
public readonly Faction Faction;
public readonly CultRecordRef<StationKindData> Kind;
public StationCard(Faction faction, CultRecordRef<StationKindData> kind)
{
Faction = faction;
Kind = kind;
}
}
// The one owner of which stations a run's zones hold (aetheria-living-world, cut region-chain-deck; ruling demo-chain-spans-the-region):
// how many, whose and of what kind, dealt per region the way Provinces.Deal deals types. Pure: it reads the galaxy's persisted facts and
// the catalog, draws from no random stream and stores nothing, so a generated zone, a Continue and a test all see the same deal.
//
// Slots. A zone holds one slot per story station (the story's faction) and floor(u * (Presence + 1)) ambient slots of its
// StructureFaction, u a stable hash of the run seed and the zone's index. A faction whose non-entrance zones of a region hold fewer
// ambient slots than the kinds it fields gets one slot more in each of those zones, nearest its home first and cycling, until they match.
//
// Cards. A faction's hand in a region is dealt from a deck of one card per kind it fields, drawn without replacement and restored whole
// when empty. The first deck goes to its non-entrance ambient slots, so every kind it fields stands outside the entrance; later cards fill
// the rest of those slots, then its story slots, then its entrance slots.
//
// Placement. Its non-entrance ambient slots lie frontier first (farthest from its home), its cards by StationKindData.Ring ascending:
// raw extraction at the frontier and the chain's heart toward home.
public static class StationDeck
{
// The faction whose home is nearest the zone.
public static Faction NearestFaction(Galaxy galaxy, GalaxyZone zone) =>
galaxy.Factions.MinBy(faction => galaxy.HomeZones[faction].Distance[zone]);
// How far the zone lies inside its nearest faction's influence, plus one.
public static int Presence(Galaxy galaxy, GalaxyZone zone)
{
var nearest = NearestFaction(galaxy, zone);
return galaxy.InfluenceOf(nearest) - galaxy.HomeZones[nearest].Distance[zone] + 1;
}
// In a galaxy with a gate antagonist that faction raids by DemoPressure's curve; inside its grace its stations and turrets are as
// absent as its ships, so the zone's structures belong to the nearest faction that is not the antagonist.
public static Faction StructureFaction(Galaxy galaxy, GalaxyZone zone)
{
var nearest = NearestFaction(galaxy, zone);
var antagonist = galaxy.Antagonist;
return antagonist != null && nearest == antagonist && DemoPressure.InGrace(galaxy, zone)
? galaxy.Factions.Where(faction => faction != antagonist).MinBy(faction => galaxy.HomeZones[faction].Distance[zone])
: nearest;
}
// Every zone's cards by zone index: its story stations' cards first, in Locations order, then its ambient ones.
public static StationCard[][] Deal(Galaxy galaxy, CultCache catalog, Action<string> log = null)
{
var zones = galaxy.Zones;
var structure = zones.Select(zone => StructureFaction(galaxy, zone)).ToArray();
var stories = zones.Select(zone => zone.Locations.Where(story => story.Type == LocationType.Station).ToArray()).ToArray();
// The zone's ambient slot count: u in [0, 1) from the run seed and the zone's index, scaled by presence + 1 and floored,
// a negative count reading 0.
var slots = zones.Select((zone, index) =>
Math.Max(0, (int) Math.Floor($"{galaxy.Seed}:station-slots:{index}".StableHash() / 4294967296.0 * (Presence(galaxy, zone) + 1)))).ToArray();
var pools = new Dictionary<string, CultRecordRef<StationKindData>[]>(StringComparer.Ordinal);
string KeyOf(Faction faction) => faction == null ? "" : catalog.RefOf(faction).Key.Value;
CultRecordRef<StationKindData>[] PoolOf(Faction faction)
{
var key = KeyOf(faction);
if (!pools.TryGetValue(key, out var pool)) pools[key] = pool = StationKinds.PoolOf(catalog, faction, log);
return pool;
}
var regions = Enumerable.Range(0, zones.Length).GroupBy(z => zones[z].Province.Region).OrderBy(group => group.Key)
.Select(group => (group.Key, Members: group.ToArray())).ToArray();
// A thin territory gets slots first, so every deal below counts the slots a zone really holds.
foreach (var (_, members) in regions)
foreach (var group in members.Where(z => zones[z] != galaxy.Entrance).GroupBy(z => structure[z]))
{
var needed = PoolOf(group.Key).Length;
var total = group.Sum(z => slots[z]);
var nearestFirst = group.OrderBy(z => galaxy.HomeZones[group.Key].Distance[zones[z]]).ThenBy(z => z).ToArray();
for (var k = 0; total < needed; k = (k + 1) % nearestFirst.Length, total++) slots[nearestFirst[k]]++;
}
var told = stories.Select(zone => new StationCard[zone.Length]).ToArray();
var ambient = slots.Select(count => new StationCard[count]).ToArray();
foreach (var (region, members) in regions)
foreach (var faction in members.SelectMany(z => stories[z].Select(story => story.Faction)).Concat(members.Select(z => structure[z]))
.Distinct().OrderBy(KeyOf, StringComparer.Ordinal))
{
// A slot is (zone, place): the slot's number in the zone's ambient cards, or the story's index in its zone.
var outside = members.Where(z => zones[z] != galaxy.Entrance && structure[z] == faction)
.SelectMany(z => Enumerable.Range(0, slots[z]).Select(k => (zone: z, place: k)))
.OrderByDescending(slot => galaxy.HomeZones[faction].Distance[zones[slot.zone]]).ThenBy(slot => slot.zone).ThenBy(slot => slot.place).ToArray();
var story = members.SelectMany(z => stories[z].Select((entry, s) => (zone: z, place: s, entry.Faction)).Where(slot => slot.Faction == faction))
.Select(slot => (slot.zone, slot.place)).ToArray();
var entrance = members.Where(z => zones[z] == galaxy.Entrance && structure[z] == faction)
.SelectMany(z => Enumerable.Range(0, slots[z]).Select(k => (zone: z, place: k))).ToArray();
var count = outside.Length + story.Length + entrance.Length;
if (count == 0) continue;
var hand = Hand(PoolOf(faction), $"{galaxy.Seed}:station-deal:{region}:{KeyOf(faction)}", count);
var frontierFirst = hand.Take(outside.Length).OrderBy(kind => kind.IsSet() ? catalog.Get(kind)?.Ring ?? 0 : 0).ToArray();
for (var i = 0; i < outside.Length; i++) ambient[outside[i].zone][outside[i].place] = new StationCard(faction, frontierFirst[i]);
for (var i = 0; i < story.Length; i++) told[story[i].zone][story[i].place] = new StationCard(faction, hand[outside.Length + i]);
for (var i = 0; i < entrance.Length; i++) ambient[entrance[i].zone][entrance[i].place] = new StationCard(faction, hand[outside.Length + story.Length + i]);
}
return told.Select((cards, z) => cards.Concat(ambient[z]).ToArray()).ToArray();
}
// n kinds drawn from a deck of one card per pool kind, each draw one weighted pick at a site named by the run, region, faction and
// the draw's place over the cards remaining; the deck is restored whole when it runs out. An empty pool deals unset kinds.
private static CultRecordRef<StationKindData>[] Hand(CultRecordRef<StationKindData>[] pool, string site, int n)
{
var hand = new CultRecordRef<StationKindData>[n];
if (pool.Length == 0) return hand;
var remaining = pool.Select(_ => 1.0).ToArray();
for (var draw = 0; draw < n; draw++)
{
if (remaining.Sum() <= 0) remaining = pool.Select(_ => 1.0).ToArray();
var card = FieldKinds.Pick($"{site}:{draw}", remaining);
remaining[card] = 0;
hand[draw] = pool[card];
}
return hand;
}
}

View file

@ -71,22 +71,17 @@ public static class StationKinds
public static CultRecordRef<StationKindData>[] FieldableKindsOf(CultCache catalog, Faction faction) =>
KindsOf(catalog, faction).Where(kind => HasModel(catalog, faction, kind) || LiveStandIn(catalog, faction, kind).IsSet()).ToArray();
// A station's kind: a stable pick among the faction's kinds it can field, by the station's site, which generation names by the
// zone's seed and the station's place in its orbit order (never by a key the cache mints). It draws nothing from any random
// stream, so adding the kind to generation moves no other roll. A kind the faction places but cannot field (neither its own
// model nor a stand-in's hull kind is carried by any offered station hull) is not in the pool; a faction left with no kind to
// field falls back to any kind some offered station hull carries, logged, and the hull draw then falls back to any maker.
// Unset when the catalog has none.
public static CultRecordRef<StationKindData> Choose(CultCache catalog, Faction faction, string site, Action<string> log = null)
// The kinds a faction's stations are dealt from (StationDeck): those it can field. A kind the faction places but cannot field
// (neither its own model nor a stand-in's hull kind is carried by any offered station hull) is not in the pool; a faction left
// with no kind to field falls back to any kind some offered station hull carries, logged, and the hull draw then falls back to any
// maker. Empty when the catalog offers none. Ordered by key, and it draws nothing.
public static CultRecordRef<StationKindData>[] PoolOf(CultCache catalog, Faction faction, Action<string> log = null)
{
var pool = FieldableKindsOf(catalog, faction);
if (pool.Length == 0)
{
pool = Ordered(OfferedKinds(catalog));
if (pool.Length == 0) return default;
log?.Invoke($"{faction?.Name ?? "This galaxy"} builds no station kind it can field; placing a station of any kind some maker offers.");
}
return pool[(int) (site.StableHash() % (uint) pool.Length)];
if (pool.Length > 0) return pool;
pool = Ordered(OfferedKinds(catalog));
if (pool.Length > 0) log?.Invoke($"{faction?.Name ?? "This galaxy"} builds no station kind it can field; placing a station of any kind some maker offers.");
return pool;
}
// The kind of hull a faction builds for a station kind: the kind itself when the faction offers a model of it (a model

View file

@ -37,7 +37,8 @@ public static class ZoneGenerator
private const int MaximumPlacementSamples = 32;
// entranceStations: the stations the scenario's arena must hold (Scenario.EntranceStations); the orders apply only
// when galaxyZone == galaxy.Entrance, null or empty rolls the zone's stations like any other's.
// when galaxyZone == galaxy.Entrance and are then its ambient stations exactly. Null or empty seats the zone's dealt
// cards like any other's: every zone, the entrance included, seats what StationDeck.Deal gives it.
// ambient: false keeps the planets, orbits and stations but generates no ship and no turret, so nothing wanders
// into a scenario's authored conditions (docs/scenarios-cut.md, 2.1). The rule is applied here, not by pruning.
public static ZonePack GenerateZone(
@ -290,26 +291,22 @@ public static class ZoneGenerator
}
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;
// In a galaxy with a gate antagonist that faction raids by DemoPressure's curve (below); inside its grace its stations and
// turrets are as absent as its ships, so the zone's structures belong to the nearest faction that is not the antagonist.
// Who holds the zone is StationDeck's rule (it deals the stations too); a galaxy with a gate antagonist is raided by it by
// DemoPressure's curve (below), and inside its grace the zone's structures belong to the nearest faction that is not it.
var nearestFaction = StationDeck.NearestFaction(galaxy, galaxyZone);
var factionPresence = StationDeck.Presence(galaxy, galaxyZone);
var antagonist = galaxy.Antagonist;
var structureFaction = antagonist != null && nearestFaction == antagonist && DemoPressure.InGrace(galaxy, galaxyZone)
? galaxy.Factions.Where(f => f != antagonist).MinBy(f => galaxy.HomeZones[f].Distance[galaxyZone])
: nearestFaction;
var structureFaction = StationDeck.StructureFaction(galaxy, galaxyZone);
var storyStations = galaxyZone.Locations.Where(story => story.Type == LocationType.Station).ToArray();
var stationCount = (int)(random.NextFloat() * (factionPresence + 1)) + storyStations.Length;
// Enemy count below is based on this pre-override value, so the entrance station zone doesn't gain an enemy
// just because its station got forced.
var baseStationCount = stationCount;
// The zone's stations are the deal's: its story cards first, then its ambient ones. Enemy count below is based on the
// dealt count, so an ordered entrance doesn't gain an enemy just because its orders replaced its dealt stations.
var dealt = StationDeck.Deal(galaxy, cache, itemManager.Log)[Array.IndexOf(galaxy.Zones, galaxyZone)];
var baseStationCount = dealt.Length;
// Operator ruling, 2026-09-25 (docs/locomotion-cut.md): a scenario that declares entrance stations
// (Scenario.EntranceStations) gets them in its entrance zone, deterministically, one per order after the story
// stations. A cast galaxy's halved influence and its lowest-influence unowned Entrance otherwise roll
// stationCount 0 on every seed. galaxy.Entrance is reference-identity, not a name comparison.
// stations, in place of the dealt ambient ones. A cast galaxy's halved influence and its lowest-influence unowned Entrance
// otherwise deal 0 on every seed. galaxy.Entrance is reference-identity, not a name comparison.
var orders = galaxyZone == galaxy.Entrance && entranceStations != null ? entranceStations : Array.Empty<EntranceStationOrder>();
var orderFactions = new Faction[orders.Count];
var orderKinds = new CultRecordRef<StationKindData>[orders.Count];
@ -328,8 +325,17 @@ public static class ZoneGenerator
throw new InvalidOperationException($"Entrance station order kind {orders[o].Kind} is not in the catalog.");
}
}
var required = storyStations.Length + orders.Count;
if (orders.Count > 0 && stationCount < required) stationCount = required;
// Given orders are the entrance's ambient stations exactly: a scenario that orders a kind never also gets the deal's card of
// it (ScenarioStage.Station and EconomyLoop.Boot refuse two stations of one kind). A null faction is the zone's structure
// faction and a null kind the faction's first pool kind.
var ambientCards = new StationCard[orders.Count > 0 ? orders.Count : dealt.Length - storyStations.Length];
for (var o = 0; o < orders.Count; o++)
{
var orderFaction = orderFactions[o] ?? structureFaction;
ambientCards[o] = new StationCard(orderFaction, orders[o].Kind != null ? orderKinds[o] : StationKinds.PoolOf(cache, orderFaction, itemManager.Log).FirstOrDefault());
}
if (orders.Count == 0) Array.Copy(dealt, storyStations.Length, ambientCards, 0, ambientCards.Length);
var required = storyStations.Length + ambientCards.Length;
// 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) 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.
@ -343,18 +349,18 @@ public static class ZoneGenerator
.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)
var sources = candidates.Skip(candidates.Length / 2).Take(stationCount)
var sources = candidates.Skip(candidates.Length / 2).Take(required)
.Select(p => (orbit: orbitMap[p], extent: Extent(p), direct: false)).ToArray();
if (orders.Count > 0 && sources.Length < required)
if (sources.Length < required)
{
// An order the rails cannot seat orbits a root node beyond its ring group (or, for a body, its whole family), never at
// A station the rails cannot seat 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. The shortfall shares the first one's phase
// (drawn once) spread evenly round the turn.
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 entrance station zone must always get its stations, but it has no candidate orbit at all -- every planet in the zone is a parentless root.");
$"Zone {galaxyZone.Name} must seat all {required} of its dealt stations, but it has no candidate orbit at all -- every planet in the zone is a parentless root.");
var distance = rootNode.Empty
? (1 + GravityField.RingReach) * GravityField.Beta * rootNode.Children.Where(Massive).Min(c => c.Distance)
: Extent(rootNode);
@ -451,11 +457,9 @@ public static class ZoneGenerator
for (var i = 0; i < storyStations.Length; i++)
{
var story = storyStations[i];
if (i >= 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(
StationKinds.Choose(cache, story.Faction, $"{seed}:station:{i}", itemManager.Log));
var station = GetLoadoutGenerator(story.Faction).GenerateStationLoadout(dealt[i].Kind);
if (station == null)
{
itemManager.Log($"Story station for {story.Faction?.Name} could not be generated; its story has nowhere to live!");
@ -477,10 +481,8 @@ public static class ZoneGenerator
var slot = i - storyStations.Length;
var isOrder = slot < orders.Count;
var slotFaction = isOrder && orderFactions[slot] != null ? orderFactions[slot] : structureFaction;
var slotKind = isOrder && orders[slot].Kind != null
? orderKinds[slot]
: StationKinds.Choose(cache, slotFaction, $"{seed}:station:{i}", itemManager.Log);
var slotFaction = ambientCards[slot].Faction;
var slotKind = ambientCards[slot].Kind;
var lagrangeOrbit = CreateLagrangeOrbit(orbit);
var station = GetLoadoutGenerator(slotFaction).GenerateStationLoadout(slotKind);
if (station == null)

View file

@ -286,18 +286,34 @@ public sealed class StationKindTests : IDisposable
var kinds = StationKinds.KindsOf(world.Cache, world.Au).Select(kind => kind.Key.Value).ToArray();
Assert.Equal(new[] { StationKindData.KeyOf("mining").Value, StationKindData.KeyOf("shipyard").Value }, kinds);
var seen = new HashSet<string>();
var pool = StationKinds.PoolOf(world.Cache, world.Au);
Assert.Equal(kinds, pool.Select(kind => kind.Key.Value).ToArray());
for (var site = 0; site < 40; site++)
{
var kind = StationKinds.Choose(world.Cache, world.Au, "site-" + site);
Assert.Contains(kind.Key.Value, kinds);
seen.Add(kind.Key.Value);
var kind = pool[site % pool.Length];
var pack = world.Generator(world.Au, (uint) site + 1).GenerateStationLoadout(kind);
Assert.NotNull(pack);
Assert.Equal(kind.Key, pack.Kind.Key);
Assert.Equal(kind.Key, world.HullOf(pack).Kind.Key);
}
Assert.Equal(kinds.Length, seen.Count);
// Every kind a faction fields stands somewhere outside the entrance of its region: the deal gives it each one.
Assert.Equal(kinds.OrderBy(k => k, StringComparer.Ordinal), DealtOutsideTheEntrance(world, world.Au));
}
private Galaxy GalaxyOf(World w, uint seed) =>
new Galaxy(TestCasts.Wide, AuthoredSettings.Load(RunStartTests.FindRepoRoot()).Read<SectorBackgroundSettings>("CastBackgroundSettings"), w.Cache, _ => { }, null, seed);
// The kinds the deal gives a faction outside the entrance, in the region of the first non-entrance zone it holds.
private string[] DealtOutsideTheEntrance(World w, Faction faction)
{
var galaxy = GalaxyOf(w, 3);
var deal = StationDeck.Deal(galaxy, w.Cache);
var holder = Enumerable.Range(0, galaxy.Zones.Length).First(z => galaxy.Zones[z] != galaxy.Entrance && StationDeck.StructureFaction(galaxy, galaxy.Zones[z]) == faction);
var region = galaxy.Zones[holder].Province.Region;
return Enumerable.Range(0, galaxy.Zones.Length)
.Where(z => galaxy.Zones[z] != galaxy.Entrance && galaxy.Zones[z].Province.Region == region)
.SelectMany(z => deal[z]).Where(card => card.Faction == faction).Select(card => card.Kind.Key.Value).Distinct().OrderBy(k => k, StringComparer.Ordinal).ToArray();
}
[Fact]
@ -349,7 +365,7 @@ public sealed class StationKindTests : IDisposable
Assert.Equal(new[] { Kind("mining").Key }, StationKinds.KindsOf(world.Cache, world.Lucent).Select(kind => kind.Key));
var logged = new List<string>();
var kind = StationKinds.Choose(world.Cache, world.Lucent, "site", logged.Add);
var kind = Assert.Single(StationKinds.PoolOf(world.Cache, world.Lucent, logged.Add));
Assert.Equal(Kind("shipyard").Key, kind.Key);
Assert.Contains(world.Lucent.Name, Assert.Single(logged));
var pack = world.Generator(world.Lucent).GenerateStationLoadout(kind);
@ -358,7 +374,7 @@ public sealed class StationKindTests : IDisposable
world.Sell(world.Au, "depot");
var kept = new List<string>();
var placed = StationKinds.Choose(world.Cache, world.Lucent, "site", kept.Add);
var placed = Assert.Single(StationKinds.PoolOf(world.Cache, world.Lucent, kept.Add));
Assert.Equal(Kind("mining").Key, placed.Key);
Assert.Empty(kept);
var depotStation = world.Generator(world.Lucent).GenerateStationLoadout(placed);
@ -374,12 +390,12 @@ public sealed class StationKindTests : IDisposable
Assert.Empty(StationKinds.KindsOf(world.Cache, world.Lucent));
var logged = new List<string>();
var kind = StationKinds.Choose(world.Cache, world.Lucent, "site", logged.Add);
var kind = Assert.Single(StationKinds.PoolOf(world.Cache, world.Lucent, logged.Add));
Assert.Equal(Kind("shipyard").Key, kind.Key);
Assert.Single(logged);
Assert.Contains(world.Lucent.Name, logged[0]);
var anonymous = new List<string>();
StationKinds.Choose(world.Cache, null, "site", anonymous.Add);
StationKinds.PoolOf(world.Cache, null, anonymous.Add);
Assert.Contains("This galaxy", Assert.Single(anonymous));
world.StandIn("mining", world.Au, "shipyard");
Assert.Equal(Kind("mining").Key, StationKinds.HullKindFor(world.Cache, null, Kind("mining")).Key);
@ -390,6 +406,8 @@ public sealed class StationKindTests : IDisposable
Assert.Equal(kind.Key, pack.Kind.Key);
}
// The deal draws nothing from any zone's random stream: a zone generated after extra Deal calls packs exactly as one generated
// without them, and the deal itself is the same twice.
[Fact]
public void KindChoiceLeavesRandomStream()
{
@ -397,28 +415,22 @@ public sealed class StationKindTests : IDisposable
world.Sell(world.Au, "mining");
world.Sell(world.Au, "shipyard");
world.Sell(world.Au, "depot");
var keys = Enumerable.Range(0, 30).Select(i => "orbit-" + i).ToArray();
var first = keys.Select(key => StationKinds.Choose(world.Cache, world.Au, key).Key.Value).ToArray();
Assert.Equal(first, keys.Reverse().Select(key => StationKinds.Choose(world.Cache, world.Au, key).Key.Value).Reverse().ToArray());
Assert.True(first.Distinct().Count() > 1, "the stable hash spreads sites over the faction's kinds");
var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot());
string[][] Kinds() => StationDeck.Deal(GalaxyOf(world, 3), world.Cache).Select(cards => cards.Select(card => card.Kind.Key.Value).ToArray()).ToArray();
Assert.Equal(Kinds(), Kinds());
// Generating a zone with one station kind in the catalog and with several draws the same orbits and turrets.
(float, float)[] Orbits(Action<World> stock)
(float, float)[] Orbits(int extraDeals)
{
var w = World.Make(this, zenithOffered: true);
stock?.Invoke(w);
var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot());
var dir = Path.Combine(_root, "galaxy" + _worlds++);
var galaxy = new Galaxy(TestCasts.Wide,
authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), w.Cache, _ => { }, null, 3);
w.Sell(w.Au, "mining");
var galaxy = GalaxyOf(w, 3);
for (var i = 0; i < extraDeals; i++) StationDeck.Deal(galaxy, w.Cache);
var pack = ZoneGenerator.GenerateZone(w.Items, authored.Read<ZoneGenerationSettings>("ZoneSettings"),
authored.Read<PlanetSettings>("PlanetSettings"), galaxy, galaxy.Entrance, EntranceStationOrder.Any, true);
Assert.NotEmpty(pack.Entities.OfType<OrbitalEntityPack>());
return pack.Orbits.Select(orbit => w.Cache.Get(orbit)).Select(orbit => (orbit.Distance, orbit.Phase)).ToArray();
}
var one = Orbits(null);
var several = Orbits(w => { w.Sell(w.Au, "mining"); w.Sell(w.Zh, "shipyard"); w.Sell(w.Lucent, "depot"); });
Assert.Equal(one, several);
Assert.Equal(Orbits(0), Orbits(3));
}
// A station's kind is a function of the zone's seed and the orbit's place in generation, not of a key the cache mints:
@ -501,7 +513,7 @@ public sealed class StationKindTests : IDisposable
return own;
}
// Choose keeps a kind exactly when GenerateStationLoadout can draw a hull of it: a hull sold at Price 0, or by a product with no
// PoolOf keeps a kind exactly when GenerateStationLoadout can draw a hull of it: a hull sold at Price 0, or by a product with no
// maker, is no hull a draw reaches, so a faction standing in on its kind is not seated on it. The tutorial entrance still gets a station.
[Theory]
[InlineData(false)]
@ -519,12 +531,11 @@ public sealed class StationKindTests : IDisposable
world.StandIn("mining", world.Zh, "shipyard");
foreach (var faction in new[] { world.Au, world.Lucent, world.Zh })
for (var site = 0; site < 12; site++)
{
var kind = StationKinds.Choose(world.Cache, faction, "site-" + site);
Assert.Equal(Kind("mining").Key, kind.Key);
Assert.NotNull(world.Generator(faction).GenerateStationLoadout(kind));
}
{
var kind = Assert.Single(StationKinds.PoolOf(world.Cache, faction));
Assert.Equal(Kind("mining").Key, kind.Key);
Assert.NotNull(world.Generator(faction).GenerateStationLoadout(kind));
}
var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot());
var galaxy = new Galaxy(TestCasts.Wide,
@ -545,12 +556,11 @@ public sealed class StationKindTests : IDisposable
Assert.Equal(2, StationKinds.KindsOf(world.Cache, world.Lucent).Length);
var logged = new List<string>();
for (var site = 0; site < 40; site++)
Assert.Equal(Kind("mining").Key, StationKinds.Choose(world.Cache, world.Lucent, "site-" + site, logged.Add).Key);
Assert.Equal(Kind("mining").Key, Assert.Single(StationKinds.PoolOf(world.Cache, world.Lucent, logged.Add)).Key);
Assert.Empty(logged);
}
// The fallback pool is every kind some maker offers, spread over sites, not the first of them.
// The fallback pool is every kind some maker offers, and a faction on it is dealt each of them in its region.
[Fact]
public void TheFallbackSpreadsSitesOverEveryOfferedKind()
{
@ -558,9 +568,9 @@ public sealed class StationKindTests : IDisposable
world.Sell(world.Au, "mining");
world.Sell(world.Au, "shipyard");
world.Sell(world.Au, "depot");
var chosen = Enumerable.Range(0, 40).Select(site => StationKinds.Choose(world.Cache, world.Lucent, "site-" + site).Key.Value).ToHashSet();
Assert.Equal(new[] { Kind("depot"), Kind("mining"), Kind("shipyard") }.Select(kind => kind.Key.Value).OrderBy(k => k, StringComparer.Ordinal),
chosen.OrderBy(k => k, StringComparer.Ordinal));
var expected = new[] { Kind("depot"), Kind("mining"), Kind("shipyard") }.Select(kind => kind.Key.Value).OrderBy(k => k, StringComparer.Ordinal).ToArray();
Assert.Equal(expected, StationKinds.PoolOf(world.Cache, world.Lucent).Select(kind => kind.Key.Value).ToArray());
Assert.Equal(expected, DealtOutsideTheEntrance(world, world.Lucent));
}
[Fact]
@ -598,7 +608,7 @@ public sealed class StationKindTests : IDisposable
// Every stand-in is judged from the catalog: its target is a real kind; the faction owns no model of the kind it stands in for; and
// the stand-in is live (the faction can field the kind) exactly when some maker sells a hull of the target kind. A stand-in
// no maker can field is not a defect: the generator drops the kind from the faction's pool and seats it by the any-maker
// fallback, logged (StationKinds.Choose). Returns how many stand-ins were live, so a caller can see the catalog's state.
// fallback, logged (StationKinds.PoolOf). Returns how many stand-ins were live, so a caller can see the catalog's state.
private static int AssertStandInsLive(CultCache cache)
{
var live = 0;
@ -615,11 +625,11 @@ public sealed class StationKindTests : IDisposable
if (carried) { live++; continue; }
if (StationKinds.FieldableKindsOf(cache, faction).Length > 0) continue;
var logged = new List<string>();
var seated = StationKinds.Choose(cache, faction, "site", logged.Add);
var seated = StationKinds.PoolOf(cache, faction, logged.Add);
if (OracleOfferedKinds(cache).Count > 0)
{
Assert.Single(logged);
Assert.Contains(seated.Key.Value, OracleOfferedKinds(cache));
Assert.All(seated, kind => Assert.Contains(kind.Key.Value, OracleOfferedKinds(cache)));
}
}
return live;
@ -655,7 +665,7 @@ public sealed class StationKindTests : IDisposable
nowhere.StandIn("shipyard", nowhere.Lucent, "power");
Assert.Equal(0, AssertStandInsLive(nowhere.Cache));
var logged = new List<string>();
Assert.Equal(Kind("mining").Key, StationKinds.Choose(nowhere.Cache, nowhere.Lucent, "site", logged.Add).Key);
Assert.Equal(Kind("mining").Key, Assert.Single(StationKinds.PoolOf(nowhere.Cache, nowhere.Lucent, logged.Add)).Key);
Assert.Single(logged);
var missing = World.Make(this, zenithOffered: false);