diff --git a/tests/Aetheria.Shared.Tests/RegionClockTests.cs b/tests/Aetheria.Shared.Tests/RegionClockTests.cs index 500509f1c..0be395b20 100644 --- a/tests/Aetheria.Shared.Tests/RegionClockTests.cs +++ b/tests/Aetheria.Shared.Tests/RegionClockTests.cs @@ -5,7 +5,12 @@ using System; using System.Collections.Generic; using System.Linq; +using CultMath; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; using Xunit; +using static CultMath.math; // Every zone of a run is live; a test that builds a galaxy by hand and saves it fills the zones it does not care about. public static class LiveRegion @@ -21,7 +26,7 @@ public static class LiveRegion // steps, every other zone's facilities advance by spans, entering settles the zone, and saves and sightings are copies. public sealed partial class RunStartTests { - // The first stack and the first facility unit held by stations of non-entrance zones, with the zone and entity holding each. + // The stations of the zones other than the entrance, each with its zone. private static IEnumerable<(Zone zone, OrbitalEntity station)> StationsElsewhere(Galaxy galaxy) => galaxy.Zones.Where(zone => zone != galaxy.Entrance) .SelectMany(zone => zone.Contents.Entities.OfType().Select(station => (zone.Contents, station))); @@ -52,4 +57,258 @@ public sealed partial class RunStartTests var storedFacility = storedFacilityStation.Equipment[facilityStation.Equipment.IndexOf(facility)].item; Assert.Equal(run?.Progress, storedFacility.Run?.Progress); } + + private static readonly CultRecordKey GoldOre = new CultRecordKey("commodity:native-gold"); + private static readonly MessagePackSerializerOptions Wire = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + + // Bounds (ruling lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped reading and the + // named mutant's, measured at the head on Starfire, Debug, seed 1). + // AdvanceSlack: progress off 120 s after two boundaries. Shipped 7.6e-6; the mutants that run no off-screen facility (no + // boundary advance; the gate on Active, which no off-screen unit is) read 120. sqrt(7.6e-6 * 120) = 0.030. + private const double AdvanceSlack = 0.030; + // SettleSlack: progress against the player who stayed. Shipped 1.8e-6 (float steps against double spans); entering + // without the settle reads 30 at both leaving times. sqrt(1.8e-6 * 30) = 0.0073. + private const double SettleSlack = 0.0073; + // KickSlack: the largest change of an orbit's velocity between the first and the second step after an advance. Shipped + // 0.054 (the orbit's own curvature); an advance that leaves the orbits where they were 18299. sqrt(0.054 * 18299) = 31. + private const double KickSlack = 31; + + private static bool IsFacility(EquippedItem unit) => unit.Behaviors.OfType().Any(); + + // The entrance's one processing station. + private static OrbitalEntity ProcessingStation(Zone zone) => zone.Entities.OfType().First(station => station.Equipment.Any(IsFacility)); + + // The entrance's haulers stop hauling (they leave the zone), so what the station holds is only what a test puts there. + private static void Park(Zone zone) + { + foreach (var hauler in zone.Entities.Where(entity => entity.Haul.Key.IsSet()).ToArray()) + { + hauler.Deactivate(); + zone.Remove(hauler); + } + } + + // The ore the station's refinery wants, as stacks of the design's size, wherever the bays have room. + private void Fill(OrbitalEntity station, int units) + { + for (var left = units; left > 0;) + { + var stack = new SimpleCommodity { Data = new CultRecordRef(GoldOre), Quantity = 1 }; + stack.Quantity = Math.Min(left, _items.MaxStack(stack)); + Assert.True(station.CargoBays.Any(bay => bay.TryStore(stack)), $"no room for {left} more units"); + left -= stack.Quantity; + } + } + + // The player goes to `to`: the traveller leaves first, so the sighting holds no player, as ActionGameManager does. + private static Zone Leave(Galaxy galaxy, RunStart.Staged staged, Zone from, GalaxyZone to) + { + if (from.Entities.Contains(staged.Player)) + { + staged.Player.Deactivate(); + from.Remove(staged.Player); + } + return RegionClock.Enter(galaxy, from, to); + } + + private static void StepFor(Zone zone, double seconds) + { + for (var at = (int) Math.Round(seconds / SimClock.GameStep); at > 0; at--) RegionClock.Step(zone, SimClock.GameStep); + } + + // What the station holds, design by design, and the recipe each facility is on, as a person reads them. + private static string Held(OrbitalEntity station) => string.Join(" ", station.CargoBays.SelectMany(bay => bay.Cargo.Keys).OfType() + .GroupBy(stack => ((ItemInstance) stack).Data.Key.Value).OrderBy(group => group.Key, StringComparer.Ordinal) + .Select(group => $"{group.Key}={group.Sum(stack => stack.Quantity)}")) + + " | " + string.Join(" ", station.Equipment.Where(IsFacility).Select(unit => unit.EquippableItem.Run?.Recipe.Key.Value ?? "-")); + + private static double Progress(OrbitalEntity station) => station.Equipment.First(IsFacility).EquippableItem.Run?.Progress ?? 0; + + // Off screen the entrance's time stays put between boundaries and equals the player's zone's at each, so its facility's + // progress is the span it missed. + [Fact] + public void OffScreenZonesAdvanceOnSpanBoundaries() + { + var (galaxy, arena, staged) = RegionRun(1); + Park(arena); + var station = ProcessingStation(arena); + Fill(station, 30); + var neighbour = Leave(galaxy, staged, arena, galaxy.Entrance.AdjacentZones[0]); + Assert.Equal(0, arena.ExactTime); + + var boundaries = 0; + var settled = 0.0; + for (var steps = (int) Math.Round((2 * RegionClock.Span + 30) / SimClock.GameStep); steps > 0; steps--) + { + var before = Math.Floor(neighbour.ExactTime / RegionClock.Span); + RegionClock.Step(neighbour, SimClock.GameStep); + if (Math.Floor(neighbour.ExactTime / RegionClock.Span) > before) + { + boundaries++; + settled = neighbour.ExactTime; + } + Assert.Equal(settled, arena.ExactTime); + } + Assert.Equal(2, boundaries); + var progress = Progress(station); + Assert.True(Math.Abs(progress - 2 * RegionClock.Span) <= AdvanceSlack, $"progress {progress}"); + } + + // The same facility, run for the same time, ends in the same place whether the player stayed, left at once or left half + // way and came back: on screen by steps, off screen by spans, and Enter settles what the last span left over. + [Fact] + public void StepsAndSpansAgree() + { + var window = 2 * RegionClock.Span + 30; + (string held, double progress) Run(double leaveAt) + { + var (galaxy, arena, staged) = RegionRun(1); + Park(arena); + var station = ProcessingStation(arena); + Fill(station, 30); + StepFor(arena, leaveAt); + if (leaveAt < window) + { + var elsewhere = Leave(galaxy, staged, arena, galaxy.Entrance.AdjacentZones[0]); + StepFor(elsewhere, window - leaveAt); + Assert.Same(arena, RegionClock.Enter(galaxy, elsewhere, galaxy.Entrance)); + } + return (Held(station), Progress(station)); + } + + var stayed = Run(window); + Assert.Contains("commodity:native-gold", stayed.held); + Assert.InRange(stayed.progress, 1, 2 * window); + var drifts = new List(); + foreach (var leaveAt in new[] { 0, window / 2 }) + { + var left = Run(leaveAt); + Assert.Equal(stayed.held, left.held); + drifts.Add(Math.Abs(left.progress - stayed.progress)); + } + Assert.True(drifts.Max() <= SettleSlack, $"progress drifts {string.Join(", ", drifts)}"); + } + + // A zone that lags by less than a span is brought to the time of the zone left when it is entered. + [Fact] + public void EnteringSettlesTheZone() + { + var (galaxy, arena, staged) = RegionRun(1); + var neighbour = Leave(galaxy, staged, arena, galaxy.Entrance.AdjacentZones[0]); + StepFor(neighbour, 90); + Assert.InRange(arena.ExactTime, RegionClock.Span, RegionClock.Span + 1); // advanced at the boundary, 30 s behind + Assert.InRange(neighbour.ExactTime - arena.ExactTime, 29, 31); + Assert.Same(arena, RegionClock.Enter(galaxy, neighbour, galaxy.Entrance)); + Assert.Equal(neighbour.ExactTime, arena.ExactTime); + } + + // The map's sighting is the zone as the player left it: the live zone has moved on, an unvisited zone has none, and the + // zone he is in is read live. + [Fact] + public void LastSeenIsWhatThePlayerSawLeaving() + { + var (galaxy, arena, staged) = RegionRun(1); + Park(arena); + var station = ProcessingStation(arena); + Fill(station, 30); + var stationIndex = arena.Entities.IndexOf(station); + var neighbour = Leave(galaxy, staged, arena, galaxy.Entrance.AdjacentZones[0]); + StepFor(neighbour, 3 * RegionClock.Span); + + int Gold(IEnumerable items) => items.OfType().Where(stack => stack.Data.Key.Equals(GoldOre)).Sum(stack => stack.Quantity); + var seen = RegionClock.Seen(galaxy.Entrance, neighbour); + var seenStation = (OrbitalEntityPack) seen.Entities[stationIndex]; + Assert.Equal(30, Gold(seenStation.CargoContents.SelectMany(bay => bay).Select(c => c.item))); + Assert.True(Gold(station.CargoBays.SelectMany(bay => bay.Cargo.Keys)) < 30, "the live station has taken ore into a cycle"); + Assert.Equal(0, seen.Time); + var here = galaxy.Zones.Single(zone => zone.Contents == neighbour); + Assert.Equal(neighbour.PackZone().Entities.Count, RegionClock.Seen(here, neighbour).Entities.Count); + Assert.Null(RegionClock.Seen(galaxy.Zones.First(zone => zone != galaxy.Entrance && zone != here), neighbour)); + } + + private static byte[] Bytes(T value) => MessagePackSerializer.Serialize(value, Wire); + + // The sighting rides the save. A save from before sightings gives each visited zone that is not the player's a copy of + // what it holds, since that save froze every zone but the player's: the copy is its own, whatever the built Zone does. + [Fact] + public void LastSeenSurvivesContinue() + { + var (galaxy, arena, staged) = RegionRun(1); + RegionClock.Enter(galaxy, null, galaxy.Entrance); // the run's first entry, as Begin makes it + var neighbourZone = galaxy.Entrance.AdjacentZones[0]; + var neighbour = Leave(galaxy, staged, arena, neighbourZone); + var entrance = Array.IndexOf(galaxy.Zones, galaxy.Entrance); + var (game, zones) = RunSave.Capture(_cache, galaxy, neighbour, null, new SavedActionBarBinding[0], 0); + RunSave.Commit(_cache, game, zones, _items.Lots); + var restored = new Galaxy(_cache, _cache.GetGlobal(), _ => { }); + Assert.Equal(Bytes(galaxy.Entrance.LastSeen), Bytes(restored.Zones[entrance].LastSeen)); + Assert.Null(restored.Zones[Array.IndexOf(galaxy.Zones, neighbourZone)].LastSeen); + + foreach (var saved in zones) saved.LastSeen = null; // a save from before sightings + RunSave.Commit(_cache, game, zones, _items.Lots); + restored = new Galaxy(_cache, _cache.GetGlobal(), _ => { }); + var held = Bytes(zones[entrance].Contents); + Assert.Equal(held, Bytes(restored.Zones[entrance].LastSeen)); + Assert.Null(restored.Zones[Array.IndexOf(galaxy.Zones, neighbourZone)].LastSeen); + RunStart.Materialize(_items, _zoneSettings, _planetSettings, restored); + var stack = restored.Zones[entrance].Contents.Entities.OfType().SelectMany(station => station.CargoBays) + .SelectMany(bay => bay.Cargo.Keys).OfType().First(); + stack.Quantity += 5; + Assert.Equal(held, Bytes(restored.Zones[entrance].LastSeen)); + } + + // One committed save restored twice, each with its own ItemManager, lives the same history to the same bytes: nothing the + // region does reads a clock, a draw or an address. + [Fact] + public void TwoIdenticalHistoriesEndByteIdentical() + { + var (galaxy, arena, staged) = RegionRun(1); + Park(arena); + Fill(ProcessingStation(arena), 30); + var (game, zones) = RunSave.Capture(_cache, galaxy, arena, null, new SavedActionBarBinding[0], 0); + RunSave.Commit(_cache, game, zones, _items.Lots); + + byte[][] History() + { + var saved = _cache.GetGlobal(); + var items = new ItemManager(1u, _cache, EntitySerializer.Copy(RunSave.Lots(_cache)), _items.GameplaySettings, _ => { }); + var region = new Galaxy(_cache, saved, _ => { }); + RunStart.Materialize(items, _zoneSettings, _planetSettings, region); + var first = RegionClock.Enter(region, null, region.Zones[saved.CurrentZone]); + StepFor(first, 2 * RegionClock.Span + 10); + var second = RegionClock.Enter(region, first, region.Zones[saved.CurrentZone].AdjacentZones[0]); + StepFor(second, RegionClock.Span + 10); + var (endGame, endZones) = RunSave.Capture(_cache, region, second, null, new SavedActionBarBinding[0], 0); + return new[] { Bytes(endGame) }.Concat(endZones.Select(Bytes)).ToArray(); + } + + var one = History(); + var two = History(); + Assert.Equal(one.Length, two.Length); + for (var i = 0; i < one.Length; i++) + Assert.True(one[i].SequenceEqual(two[i]), $"record {i} differs"); + } + + // Off screen runs a Facility alone, so no other behaviour may ride facility gear: it would be skipped there. + [Fact] + public void FacilityGearCarriesOnlyFacilities() + { + var gear = _cache.GetAll().Where(design => design.Behaviors.OfType().Any()).ToArray(); + Assert.NotEmpty(gear); + foreach (var design in gear) Assert.True(design.Behaviors.All(behavior => behavior is FacilityData), $"{design.Name} carries more than a facility"); + } + + // A zone advanced by a span places its orbits at the new time: the first step after it moves them as far as the second. + [Fact] + public void NoOrbitKickAfterAnAdvance() + { + var (galaxy, _, _) = RegionRun(1); + var zone = galaxy.Zones.First(candidate => candidate != galaxy.Entrance && candidate.Contents.Orbits.Count > 1).Contents; + zone.AdvanceTo(RegionClock.Span); + zone.Update(SimClock.GameStep); + var first = zone.Orbits.ToDictionary(orbit => orbit.Key, orbit => orbit.Value.Velocity); + zone.Update(SimClock.GameStep); + var kick = zone.Orbits.Max(orbit => length(orbit.Value.Velocity - first[orbit.Key])); + Assert.True(kick <= KickSlack, $"kick {kick}"); + } }