diff --git a/Assets/Scripts/ServerShared/RegionLegs.cs b/Assets/Scripts/ServerShared/RegionLegs.cs new file mode 100644 index 000000000..5125cc4c9 --- /dev/null +++ b/Assets/Scripts/ServerShared/RegionLegs.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using static CultMath.math; +using float3 = CultMath.float3; + +// The standing haul legs a fresh run starts with (aetheria-living-world:ruling:demo-chain-spans-the-region, economy-is-never-faked): +// for every station and every good its installed gear could draw that it does not make itself, one order from the nearest station of +// its own faction that makes the good, and one hauler per order to fly it (HaulRun.Fly off screen, the pilot on screen). Written once, at +// generation: orders are run documents and the haulers zone members, so a save carries them and Continue seeds nothing. +// +// INTERIM SCAFFOLDING (economy-is-never-faked, demo-hulls-staged): each hauler's hull and loadout is conjured by the faction's +// LoadoutGenerator, as the demo's hauler is. Follow-up conjuring-site-deletions deletes the draw when a shipyard of the faction in the +// region's chain builds it. A killed hauler is not replaced (demo-hauler-not-replaced); its order stands. +// +// A good only another faction makes gets no order (region-cross-faction-legs). +public static class RegionLegs +{ + public const string Commitment = "generation:region-legs"; + + private sealed class Leg + { + public GalaxyZone FromZone; + public OrbitalEntity From, To; + public List Goods = new List(); + } + + // Writes the orders in one Commit batch, then admits one hauler per order at its From station's orbit, piloted, in that station's + // zone. Pure in the run seed, the dealt stations and the catalog; draws only from the item stream, which RunStart.SeedLegs seeds. + // Returns the haulers admitted, in order. + public static IReadOnlyList Seed(ItemManager items, Galaxy galaxy) + { + // Every station of the region: an orbital with a kind and an orbit, in zone index then entity order. + var stations = new List<(GalaxyZone Zone, OrbitalEntity Station, IReadOnlyCollection Makes)>(); + foreach (var zone in galaxy.Zones.Where(zone => zone.Contents != null)) + foreach (var station in zone.Contents.Entities.OfType().Where(entity => entity.Kind.IsSet() && entity.OrbitData.IsSet())) + stations.Add((zone, station, StationWants.Makes(station))); + + var legs = new List(); + var byEnds = new Dictionary<(OrbitalEntity, OrbitalEntity), Leg>(); + foreach (var (zone, station, makes) in stations) + { + if (station.Faction == null) continue; + foreach (var good in StationWants.Drawable(station).Where(good => !makes.Contains(good)).OrderBy(good => good.Value, StringComparer.Ordinal)) + { + // The nearest producer of its own faction by jumps, then zone index, then entity order (the list's order: the first + // of equals wins). + (GalaxyZone Zone, OrbitalEntity Station, IReadOnlyCollection Makes)? nearest = null; + foreach (var candidate in stations) + { + if (candidate.Station == station || candidate.Station.Faction != station.Faction || !candidate.Makes.Contains(good)) continue; + if (nearest == null || zone.Distance[candidate.Zone] < zone.Distance[nearest.Value.Zone]) nearest = candidate; + } + if (nearest == null) continue; // only another faction makes it: region-cross-faction-legs + var from = nearest.Value; + if (!byEnds.TryGetValue((from.Station, station), out var leg)) + { + leg = new Leg { FromZone = from.Zone, From = from.Station, To = station }; + byEnds.Add((from.Station, station), leg); + legs.Add(leg); + } + leg.Goods.Add(good); + } + } + if (legs.Count == 0) return Array.Empty(); + + string IdOf(Leg leg) => $"region:{leg.From.OrbitData.Value}:{leg.To.OrbitData.Value}"; + items.ItemData.Commit(batch => + { + foreach (var leg in legs) + batch.Upsert(typeof(HaulOrderData), new HaulOrderData + { + From = new CultRecordRef(leg.From.OrbitData), To = new CultRecordRef(leg.To.OrbitData), + Goods = leg.Goods.Select(good => new CultRecordRef(good)).ToList(), Commitment = Commitment + }, HaulOrderData.KeyOf(IdOf(leg))); + }); + + var haulers = new List(); + foreach (var leg in legs) + { + var home = leg.FromZone.Contents; + var generator = new LoadoutGenerator(ref items.Random, items, galaxy, leg.FromZone, leg.From.Faction, 2); + var pack = generator.GenerateShipLoadout(); + items.Random = generator.Random; // the generator draws on its own copy of the stream: carrying it back is what makes the next hauler differ + if (pack == null) continue; // the faction fields no ship hull: the order stands with no one to fly it + if (!(EntitySerializer.Unpack(items, home, pack) is Ship hauler)) continue; + var at = home.GetOrbitPosition(leg.From.OrbitData); + hauler.Position = float3(at.x, 0, at.y); + hauler.Haul = new CultRecordRef(HaulOrderData.KeyOf(IdOf(leg))); + home.Admit(hauler, piloted: true); + haulers.Add(hauler); + } + return haulers; + } +} diff --git a/Assets/Scripts/ServerShared/RegionLegs.cs.meta b/Assets/Scripts/ServerShared/RegionLegs.cs.meta new file mode 100644 index 000000000..b63ec95cc --- /dev/null +++ b/Assets/Scripts/ServerShared/RegionLegs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d23c676e0ae04fa795f625de181970a5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/RunStart.cs b/Assets/Scripts/ServerShared/RunStart.cs index 0de066c81..f488fe34a 100644 --- a/Assets/Scripts/ServerShared/RunStart.cs +++ b/Assets/Scripts/ServerShared/RunStart.cs @@ -60,6 +60,14 @@ public static class RunStart } } + // The region's standing haul legs, seeded once a run is generated and never on Continue (orders are run documents and haulers live in + // zone packs): the items stream is the legs' own (LegStep), then RegionLegs writes the orders and admits the haulers. + internal static void SeedLegs(ItemManager itemManager, Galaxy galaxy) + { + SeedItems(itemManager, galaxy, LegStep); + RegionLegs.Seed(itemManager, galaxy); + } + // The pack is the Zone's construction input: once the Zone exists the pack is cleared, so nothing reads a stale copy of a // zone that has since moved on. private static Zone Live(ItemManager itemManager, PlanetSettings planetSettings, Galaxy galaxy, GalaxyZone zone) @@ -82,6 +90,7 @@ public static class RunStart var staged = Stage(itemManager, arena, scenario, startingHull, failures); if (staged == null) return null; Materialize(itemManager, zoneSettings, planetSettings, galaxy, galaxy.Progress); + SeedLegs(itemManager, galaxy); galaxy.Progress?.Invoke("Done!"); // generation's last word comes after the last zone exists return staged; } @@ -129,6 +138,8 @@ public static class RunStart public const uint ArenaStep = 1; public const uint StageStep = 2; public const uint ContinueStep = 3; + // The region's standing haul legs (RegionLegs.Seed): its own stream, clear of the steps above and of RegionStep, so seeding moves no zone's items. + public const uint LegStep = 4; // Zone i of the region draws its items from ItemSeed(galaxy, RegionStep + i). It sits clear of the steps above, since // zone indices start at 0 and the steps end at ContinueStep (3): no zone's stream is another step's. diff --git a/tests/Aetheria.Shared.Tests/RegionLegsTests.cs b/tests/Aetheria.Shared.Tests/RegionLegsTests.cs new file mode 100644 index 000000000..9c8bb55e8 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/RegionLegsTests.cs @@ -0,0 +1,70 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using Xunit; +using float2 = CultMath.float2; + +// The region's standing haul legs (aetheria-living-world, cut region-haul-legs; rulings demo-chain-spans-the-region, +// economy-is-never-faked, demo-hauler-not-replaced, comms-cells-are-zones): RegionLegs seeds same-faction legs at generation, +// haulers are zone members flown by the full sim on screen and by HaulRun.Fly off screen. +public sealed partial class RunStartTests +{ + private static string Name(CultRecordKey key) => key.Value; + + private IEnumerable<(string Id, HaulOrderData Order)> SeededOrders() => + _cache.GetAll().Where(order => order.Commitment == RegionLegs.Commitment) + .Select(order => (order.From.Key.Value + ">" + order.To.Key.Value, order)); + + private static IEnumerable<(GalaxyZone Zone, OrbitalEntity Station)> RegionStations(Galaxy galaxy) => + galaxy.Zones.SelectMany(zone => zone.Contents.Entities.OfType().Where(entity => entity.Kind.IsSet() && entity.OrbitData.IsSet()).Select(station => (zone, station))); + + // Every (station, drawable good it does not make) with a same-faction producer has exactly one order naming the good, from the nearest + // such producer by jumps, then zone index, then entity order; a draw only another faction makes has none; no order names a good its To + // station makes; the ends of an order share a faction. The expectation is recomputed here by ordering, not by the rule's loop. + [Fact] + public void SeededLegsJoinOneFactionNearestFirst() + { + foreach (var seed in RegionSeeds) + { + var (galaxy, _, failures) = Begun(new DemoTerminus(), seed); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var stations = RegionStations(galaxy).ToArray(); + // The run store is shared by the seeds of one test: this seed's orders are those whose ends are its stations. + var orders = SeededOrders().Select(x => x.Order).Where(order => stations.Any(s => s.Station.OrbitData.Equals(order.From.Key))).ToArray(); + Assert.NotEmpty(orders); + Assert.Equal(orders.Length, orders.Select(order => (order.From.Key, order.To.Key)).Distinct().Count()); + OrbitalEntity At(CultRecordKey orbit) => stations.Single(s => s.Station.OrbitData.Equals(orbit)).Station; + foreach (var order in orders) + { + Assert.Same(At(order.From.Key).Faction, At(order.To.Key).Faction); + Assert.Equal(order.Goods.Select(good => good.Key.Value).OrderBy(v => v, StringComparer.Ordinal), order.Goods.Select(good => good.Key.Value)); + Assert.Empty(order.Goods.Select(good => good.Key).Intersect(StationWants.Makes(At(order.To.Key)))); + } + var expectedGoods = 0; + for (var s = 0; s < stations.Length; s++) + { + var (zone, station) = stations[s]; + if (station.Faction == null) continue; + var makes = StationWants.Makes(station); + foreach (var good in StationWants.Drawable(station).Where(good => !makes.Contains(good))) + { + var producers = stations.Select((x, index) => (x.Zone, x.Station, index)).Where(x => x.Station != station && x.Station.Faction == station.Faction + && StationWants.Makes(x.Station).Contains(good)).ToArray(); + var naming = orders.Where(order => order.To.Key.Equals(station.OrbitData) && order.Goods.Any(g => g.Key.Equals(good))).ToArray(); + if (producers.Length == 0) { Assert.Empty(naming); continue; } + var nearest = producers.OrderBy(x => zone.Distance[x.Zone]).ThenBy(x => Array.IndexOf(galaxy.Zones, x.Zone)).ThenBy(x => x.index).First(); + Assert.Equal(nearest.Station.OrbitData, Assert.Single(naming).From.Key); + expectedGoods++; + } + } + Assert.Equal(expectedGoods, orders.Sum(order => order.Goods.Count)); + // Seeds 1 to 97 hold the whole range the spec probed: dozens of orders, and legs that jump. + Assert.InRange(orders.Length, 20, 80); + } + } +} diff --git a/tools/AetherDb/EconomyLoop.cs b/tools/AetherDb/EconomyLoop.cs index 609c4499c..d6834b276 100644 --- a/tools/AetherDb/EconomyLoop.cs +++ b/tools/AetherDb/EconomyLoop.cs @@ -146,7 +146,11 @@ public static class EconomyLoop if (failures.Count > 0 || staged == null) throw new InvalidOperationException($"seed {seed}: staging failed: {string.Join("; ", failures)}"); demo.Player = staged.Player; // A region boot stages as RunStart.Begin does, then has every other zone of the galaxy generated and live. - if (region) RunStart.Materialize(items, zoneSettings, planetSettings, galaxy); + if (region) + { + RunStart.Materialize(items, zoneSettings, planetSettings, galaxy); + RunStart.SeedLegs(items, galaxy); + } // The station that buys a sortie's ore and the one that holds it for onward haul, found by what they are for. OrbitalEntity OfKind(string kind) => arena.Entities.OfType().Single(entity => entity.Kind.Key.Equals(StationKindData.KeyOf(kind))); demo.Processing = OfKind("processing");