RegionClock: the player's zone steps, every other zone's facilities advance by 60 s spans, entering settles the zone and records what the player saw leaving

RegionClock.Step is a run's one driver (ActionGameManager no longer calls Zone.Update); Zone.AdvanceTo runs the off-screen facilities by the span a zone missed and places its orbits at the new time. RegionClock.Enter is the one writer of VisitedZones and GalaxyZone.LastSeen (SavedZone Key 7). PackedContents is a Zone's construction input, cleared by RunStart.Live. The sector map reads RegionClock.Seen. Galaxy's save constructor copies the pack it builds a Zone from, so a Continue in the same process reads the save as written.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-28 20:43:11 +01:00
commit fb1f1df869
10 changed files with 156 additions and 53 deletions

View file

@ -849,9 +849,15 @@ public class ActionGameManager : MonoBehaviour
{
if (galaxyZone == null) throw new ArgumentNullException(nameof(galaxyZone));
// RunStart.Materialize owns every zone's existence; entering only reads it.
CurrentGalaxy.VisitedZones.Add(galaxyZone);
Zone = galaxyZone.Contents ?? throw new InvalidOperationException($"Zone {galaxyZone.Name} has no live contents.");
// RunStart.Materialize owns every zone's existence; RegionClock.Enter settles the zone entered, records the sighting
// of the zone left and writes the visit. The traveller leaves first, so the sighting holds no player.
var leaving = Zone;
if (CurrentEntity != null)
{
CurrentEntity.Deactivate();
CurrentEntity.Zone.Remove(CurrentEntity);
}
Zone = RegionClock.Enter(CurrentGalaxy, leaving, galaxyZone);
_zoneEntered = true; // the clock forgets its lead between frames, never inside a step
PlayMusic(MusicType.Overworld);
_music = MusicType.Overworld;
@ -860,8 +866,6 @@ public class ActionGameManager : MonoBehaviour
if (CurrentEntity != null)
{
CurrentEntity.Deactivate();
CurrentEntity.Zone.Remove(CurrentEntity);
CurrentEntity.Zone = Zone;
Zone.Admit(CurrentEntity, piloted: false);
}
@ -1624,7 +1628,7 @@ public class ActionGameManager : MonoBehaviour
Clock.Advance(_paused ? 0f : Time.deltaTime, delta =>
{
if (Zone != steppedZone) return;
steppedZone.Update(delta);
RegionClock.Step(steppedZone, delta);
// A warning lives one tick, so sweeps are collected per tick, never read per frame.
if (CurrentEntity != null && CurrentEntity.Zone == steppedZone)
foreach (var warning in CurrentEntity.IncomingPaints)

View file

@ -19,8 +19,7 @@ public class FacilityData : BehaviorData
}
// The installed facility (ruling demand-consumed-inputs-processed-by-facilities). It ticks once per zone step, from EquippedItem.Update
// while the item is active, and on screen only; an unloaded zone is frozen and the strategic tick (target r3 cut 8) calls the same
// Production.Advance for what is off screen. Its recipes are the run list of its design, fixed for a run because the catalog is.
// while the item is active, on screen; off screen RegionClock.AdvanceFacilities calls Execute with the span the zone missed. Its recipes are the run list of its design, fixed for a run because the catalog is.
public class Facility : Behavior
{
private IReadOnlyList<RecipeData> _runList;

View file

@ -92,7 +92,10 @@ public class Galaxy
{
Name = zone.Name,
Position = zone.Position,
PackedContents = zone.Contents
// The cache's record is the save: the Zone built from this pack must not be able to change it, so a Continue
// after play in the same process reads the save as it was written.
PackedContents = zone.Contents == null ? null : EntitySerializer.Copy(zone.Contents),
LastSeen = zone.LastSeen
};
}).ToArray();
foreach (var i in savedGame.DiscoveredZones) DiscoveredZones.Add(Zones[i]);
@ -101,6 +104,11 @@ public class Galaxy
foreach (var i in savedGame.VisitedZones) VisitedZones.Add(Zones[i]);
else
foreach (var zone in Zones.Where(zone => zone.PackedContents != null)) VisitedZones.Add(zone);
// A save from before sightings froze every zone but the player's, so a visited zone it holds is exactly as the
// player left it.
for (var i = 0; i < Zones.Length; i++)
if (i != savedGame.CurrentZone && Zones[i].LastSeen == null && savedZones[i].Contents != null && VisitedZones.Contains(Zones[i]))
Zones[i].LastSeen = EntitySerializer.Copy(savedZones[i].Contents);
for (var i = 0; i < Zones.Length; i++)
{
Zones[i].AdjacentZones = savedZones[i].AdjacentZones.Select(azi => Zones[azi]).ToList();
@ -678,7 +686,12 @@ public class GalaxyZone
public Faction[] Factions;
public Faction Owner;
public Zone Contents;
// A zone's construction input: RunStart.Materialize generates it or the save supplies it, and the Zone built from it
// clears it. Nothing reads it in play.
public ZonePack PackedContents;
// What the player saw of this zone when he last left it: a copy no later step touches, display-only (the sector map).
// Written only by RegionClock.Enter and Galaxy's save constructor; read by RegionClock.Seen and RunSave.Capture.
public ZonePack LastSeen;
public GalaxyProvince Province;
public bool NamedZone;
public List<LocationStory> Locations = new List<LocationStory>();

View file

@ -0,0 +1,64 @@
/* 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;
// What simulation time does to a run's region (ruling demo-chain-spans-the-region). The player's zone steps every game
// step; every other zone's facilities are advanced to the player's zone's time at each Span boundary, by the span they
// missed, and entering a zone settles it and records what the player saw of the zone left. It is a run's one driver:
// nothing else steps a zone in play, advances an off-screen zone, writes a visit or writes a sighting. Time has no stored
// state of its own: the player's zone's ExactTime is the region's time, an off-screen zone's span is that time minus its
// own, and both persist in ZonePack.Time. Off screen only facilities run (the tick conjures nothing, ruling
// economy-is-never-faked): thermal, flight and combat are on-screen detail.
public static class RegionClock
{
// Sim seconds between advances of the zones the player is not in. One advance per Span is about 2.3 ms on a 64-zone
// region, about 1.3 us per game step amortized (research region-tick-map.cost-probe).
public const double Span = 60;
// One game step of the run: the player's zone steps, and when its time crosses a multiple of Span every other zone of
// its galaxy that exists is advanced to it, in index order.
public static void Step(Zone current, float delta)
{
var boundary = Math.Floor(current.ExactTime / Span);
current.Update(delta);
if (current.Galaxy == null || Math.Floor(current.ExactTime / Span) <= boundary) return;
foreach (var zone in current.Galaxy.Zones)
if (zone.Contents != null && zone.Contents != current) zone.Contents.AdvanceTo(current.ExactTime);
}
// The player goes to `entering`. A zone of this galaxy being left is recorded as the player saw it (LastSeen, a copy
// that no later step touches), and the entering zone, which lags by less than a Span, is settled to the time of the
// zone left. Only a zone of this galaxy counts as left: the previous run's zone, or none (a new run, Continue), is no
// sighting. The visit is written here and nowhere else in play. Returns the zone entered.
public static Zone Enter(Galaxy galaxy, Zone leaving, GalaxyZone entering)
{
var contents = entering.Contents ?? throw new InvalidOperationException($"Zone {entering.Name} has no live contents.");
if (leaving != null && leaving.Galaxy == galaxy && leaving.GalaxyZone != null && leaving != contents)
{
leaving.GalaxyZone.LastSeen = leaving.Snapshot();
contents.AdvanceTo(leaving.ExactTime);
}
galaxy.VisitedZones.Add(entering);
return contents;
}
// What the map may say of a zone: the live zone as it stands, a zone left as the player saw it leaving, and null for a
// zone never seen.
public static ZonePack Seen(GalaxyZone zone, Zone current) =>
zone.Contents != null && zone.Contents == current ? current.PackZone() : zone.LastSeen;
// Every facility of the entity runs `seconds`, as EquippedItem.Update runs it each step: a unit that is enabled and not
// destroyed (Active also needs ThermalOnline, which only a stepped entity sets, so it is not the off-screen gate). The
// units in Equipment order, each unit's Facility behaviours in order.
public static void AdvanceFacilities(Entity entity, double seconds)
{
foreach (var unit in entity.Equipment)
{
if (!unit.Enabled.Value || unit.EquippableItem.IsDestroyed) continue;
foreach (var behavior in unit.Behaviors)
if (behavior is Facility facility) facility.Execute((float) seconds);
}
}
}

View file

@ -37,8 +37,8 @@ public static class RunStart
// The one owner of whether a zone of the run exists: every zone, in index order, has a generation snapshot and a live
// Zone. A zone draws its items from the run seed and its index alone (RegionStep), so the order zones are generated
// in, or whether the rest were generated at all, moves none of them. A fresh run generates every zone but its arena
// (GenerateArena's); a saved run generates only a zone its save holds no pack for. Idempotent, and ambient: only the
// arena takes the scenario's orders and Ambient rule. Nothing steps but the player's zone, so the others stay frozen.
// (GenerateArena's); a saved run generates only a zone it holds neither a Zone nor a pack for. Idempotent, and ambient: only the
// arena takes the scenario's orders and Ambient rule. RegionClock advances the zones the player is not in.
// SCAFFOLDING (ruling economy-is-never-faked): GenerateZone conjures every zone's station stock and loadouts (the
// generated station gear, hardpoint fit, facilities, consumable stock, and the ships and turrets of its ambient
// populace). This makes them exist across the whole region from tick zero; they stay until the production that should
@ -51,7 +51,7 @@ public static class RunStart
{
progress?.Invoke($"Materializing zones: {i + 1} of {galaxy.Zones.Length}");
var zone = galaxy.Zones[i];
if (zone.PackedContents == null)
if (zone.Contents == null && zone.PackedContents == null)
{
SeedItems(itemManager, galaxy, RegionStep + (uint) i);
zone.PackedContents = ZoneGenerator.GenerateZone(itemManager, zoneSettings, planetSettings, galaxy, zone);
@ -60,8 +60,15 @@ public static class RunStart
}
}
private static Zone Live(ItemManager itemManager, PlanetSettings planetSettings, Galaxy galaxy, GalaxyZone zone) =>
zone.Contents ??= new Zone(itemManager, planetSettings, zone.PackedContents, zone, 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)
{
if (zone.Contents != null) return zone.Contents;
zone.Contents = new Zone(itemManager, planetSettings, zone.PackedContents, zone, galaxy);
zone.PackedContents = null;
return zone.Contents;
}
// What a new run does, in order, for the game and for tests alike: the arena is generated and given its Zone, `enter`
// makes it the player's zone, the scenario stages, and only a staged scenario has the rest of the region materialized,

View file

@ -154,6 +154,7 @@ public static class RunSave
Factions = zone.Factions.Select(f => Array.IndexOf(factions, f)).ToArray(),
Contents = (zone.Contents ?? throw new InvalidOperationException($"Zone {zone.Name} has no live contents to save.")).Snapshot(),
Owner = zone.Owner == null ? -1 : Array.IndexOf(factions, zone.Owner),
LastSeen = zone.LastSeen, // never mutated, so the save may share it
Province = Array.IndexOf(galaxy.Zones, zone.Province.Seed)
}).ToArray();
game.Provinces = galaxy.Provinces.Select(province => new SavedProvince
@ -172,7 +173,7 @@ public static class RunSave
var where = zoneRef.Key.Value;
var zone = cache.Get(zoneRef) ?? throw MalformedSave($"zone {where} has no record");
// A zone's contents are null only in a save from before the region was live (RunStart.Materialize fills it).
foreach (var pack in zone.Contents?.Entities ?? new List<EntityPack>())
foreach (var pack in (zone.Contents?.Entities ?? new List<EntityPack>()).Concat(zone.LastSeen?.Entities ?? new List<EntityPack>()))
foreach (var item in EntitySerializer.Items(pack))
designs.Add((item ?? throw MalformedSave($"an item in {where} is null")).Data.Key);
}
@ -242,7 +243,7 @@ public static class RunSave
// Every crafted item roots, Lot 0 included: a crafted item with no lot is corruption and Reachable throws on it.
// A simple commodity has no lot.
var roots = zones
.SelectMany(zone => zone.Contents?.Entities ?? new List<EntityPack>())
.SelectMany(zone => (zone.Contents?.Entities ?? new List<EntityPack>()).Concat(zone.LastSeen?.Entities ?? new List<EntityPack>()))
.SelectMany(EntitySerializer.Items)
.OfType<CraftedItemInstance>()
.Select(item => item.Lot);
@ -345,6 +346,11 @@ public class SavedZone
// constructor; meaningful only when SavedGame.Provinces is present.
[Key(6)]
public int Province;
// What the player saw of the zone when he last left it (GalaxyZone.LastSeen). Written only by RunSave.Capture and read
// only by Galaxy's save constructor; null in a save from before it, and for a zone never left.
[Key(7)]
public ZonePack LastSeen;
}
[MessagePackObject,

View file

@ -15,7 +15,7 @@ public sealed class SimClock
public const float MaxFrameSeconds = .1f;
// Game steps per real second at design speed 1, and the sim seconds one step carries. The one owner of the game's
// tick: every driver of a game history steps Zone.Update by GameStep. Design speed (ruling sim-speed-surface) will
// tick: RegionClock.Step is the one driver of a run's history and steps Zone.Update by GameStep. Design speed (ruling sim-speed-surface) will
// set Step = DesignSpeed / TickRate in ForGame and nowhere else.
public const int TickRate = 30;
public const float GameStep = 1f / TickRate;

View file

@ -363,6 +363,20 @@ public class Zone
private bool IsExpired(ChunkWear wear) => wear.Damage <= 0f && (!wear.BrokenUntil.HasValue || wear.BrokenUntil.Value <= _time);
// A zone the player is not in, brought to `time` (RegionClock.Step and Enter only): its facilities run the span it missed,
// its clock moves, and every orbit is placed at the new time so the next Update differences from it, not from where the
// zone was left.
public void AdvanceTo(double time)
{
var span = time - _time;
if (!(span > 0)) return;
foreach (var entity in Entities.ToArray()) RegionClock.AdvanceFacilities(entity, span);
_time = time;
_updatedOrbits.Clear();
foreach (var orbit in Orbits) GetOrbitPosition(orbit.Key);
}
// The tactical step: one game step of this zone. A run's zones step through RegionClock.Step, its one driver.
public void Update(float deltaTime)
{
_time += deltaTime;

View file

@ -72,38 +72,35 @@ public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IS
var mass = GameManager.Settings.ZoneSettings.ZoneMass.Evaluate(density);
Properties.AddProperty("Mass", () => ActionGameManager.PlayerSettings.Format(mass));
Properties.AddProperty("Radius", () => ActionGameManager.PlayerSettings.Format(radius));
if (!ActionGameManager.CurrentGalaxy.VisitedZones.Contains(zone))
// The map shows the zone the player is in live and every other zone as he last saw it (RegionClock.Seen).
var seen = RegionClock.Seen(zone, GameManager.Zone);
if (seen == null)
{
Properties.AddProperty(() => "Has not been visited");
return;
}
else
string Count(System.Func<BodyData, bool> where) => seen.Planets.Select(body => ActionGameManager.CultCache.Get(body)).Count(where).ToString();
string Hulls(HullType type) => seen.Entities
.Count(entity => ((HullData) GameManager.ItemManager.GetData(entity.Hull)).HullType == type).ToString();
var planetCount = Count(body => body is PlanetData);
Properties.AddProperty("Planets", () => planetCount);
var beltCount = Count(body => body is AsteroidBeltData);
Properties.AddProperty("Asteroid Belts", () => beltCount);
var giantCount = Count(body => body is GasGiantData && !(body is SunData));
Properties.AddProperty("Gas Giants", () => giantCount);
var starCount = Count(body => body is SunData);
Properties.AddProperty("Stars", () => starCount);
var stationCount = Hulls(HullType.Station);
Properties.AddProperty("Stations", () => stationCount);
var turretCount = Hulls(HullType.Turret);
Properties.AddProperty("Turrets", () => turretCount);
var shipCount = Hulls(HullType.Ship);
Properties.AddProperty("Ships", () => shipCount);
if (zone.Contents != GameManager.Zone)
{
var planetCount = zone.PackedContents.Planets.Count(body => ActionGameManager.CultCache.Get(body) is PlanetData).ToString();
Properties.AddProperty("Planets", () => planetCount);
var beltCount = zone.PackedContents.Planets.Count(body => ActionGameManager.CultCache.Get(body) is AsteroidBeltData).ToString();
Properties.AddProperty("Asteroid Belts", () => beltCount);
var giantCount = zone.PackedContents.Planets.Count(body => ActionGameManager.CultCache.Get(body) is GasGiantData && !(ActionGameManager.CultCache.Get(body) is SunData)).ToString();
Properties.AddProperty("Gas Giants", () => giantCount);
var starCount = zone.PackedContents.Planets.Count(body => ActionGameManager.CultCache.Get(body) is SunData).ToString();
Properties.AddProperty("Stars", () => starCount);
var stationCount = zone.PackedContents.Entities
.Count(entity => ((HullData) GameManager.ItemManager.GetData(entity.Hull)).HullType == HullType.Station)
.ToString();
Properties.AddProperty("Stations", () => stationCount);
var turretCount = zone.PackedContents.Entities
.Count(entity => ((HullData) GameManager.ItemManager.GetData(entity.Hull)).HullType == HullType.Turret)
.ToString();
Properties.AddProperty("Turrets", () => turretCount);
var shipCount = zone.PackedContents.Entities
.Count(entity => ((HullData) GameManager.ItemManager.GetData(entity.Hull)).HullType == HullType.Ship)
.ToString();
Properties.AddProperty("Ships", () => shipCount);
var age = System.TimeSpan.FromSeconds(System.Math.Max(0, GameManager.Zone.ExactTime - seen.Time));
var ago = age.TotalMinutes < 1 ? $"{age.Seconds} s" : age.TotalHours < 1 ? $"{age.Minutes} min" : $"{(int) age.TotalHours} h {age.Minutes} min";
Properties.AddProperty("Last seen", () => $"{ago} ago");
}
});
}

View file

@ -19,13 +19,14 @@ public sealed partial class RunStartTests
var (galaxy, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => seed));
Assert.True(failures.Count == 0, $"seed {seed}: " + string.Join("; ", failures));
galaxy.Entrance.Contents = arena;
galaxy.Entrance.PackedContents = null; // the pack is the Zone's construction input, which RunStart.Live clears
if (materialize) RunStart.Materialize(_items, _zoneSettings, _planetSettings, galaxy);
return (galaxy, arena, staged);
}
// What a zone's generation drew, as a person reads it: each entity's hull, faction, kind, equipment and cargo designs.
// A lot's workmanship is a draw; its serial counts the run's mints, which no zone's draws decide, so it is left out.
private string[] Drawn(GalaxyZone zone) => zone.PackedContents.Entities.Select(entity =>
private string[] Drawn(GalaxyZone zone) => zone.Contents.PackZone().Entities.Select(entity =>
{
string Design(ItemInstance item) => _items.GetData(item).Name
+ (item is ICommodityStack stack ? "x" + stack.Quantity : "")
@ -46,10 +47,10 @@ public sealed partial class RunStartTests
for (var i = 0; i < galaxy.Zones.Length; i++)
{
Assert.True(galaxy.Zones[i].Contents != null, $"seed {seed}: zone {i} has no Contents");
Assert.True(galaxy.Zones[i].PackedContents != null, $"seed {seed}: zone {i} has no pack");
Assert.True(galaxy.Zones[i].PackedContents == null, $"seed {seed}: zone {i} still holds its construction pack");
}
Assert.Same(arena, galaxy.Entrance.Contents);
Assert.Contains(galaxy.Zones, zone => zone != galaxy.Entrance && zone.PackedContents.Entities.Count > 0);
Assert.Contains(galaxy.Zones, zone => zone != galaxy.Entrance && zone.Contents.Entities.Count > 0);
}
}
@ -78,13 +79,11 @@ public sealed partial class RunStartTests
{
var (galaxy, _, _) = RegionRun(1);
var contents = galaxy.Zones.Select(zone => zone.Contents).ToArray();
var packs = galaxy.Zones.Select(zone => zone.PackedContents).ToArray();
_items.Random = new CultMath.Random(12345u); // a canary: any reseed in Materialize replaces it
RunStart.Materialize(_items, _zoneSettings, _planetSettings, galaxy);
for (var i = 0; i < galaxy.Zones.Length; i++)
{
Assert.Same(contents[i], galaxy.Zones[i].Contents);
Assert.Same(packs[i], galaxy.Zones[i].PackedContents);
}
Assert.Equal(new CultMath.Random(12345u).NextUInt(), _items.Random.NextUInt()); // nothing reseeded, so nothing generated
}
@ -135,7 +134,7 @@ public sealed partial class RunStartTests
var galaxy = RunStart.Generate(scenario, Inputs(() => seed));
var failures = new List<string>();
var staged = RunStart.Begin(_items, _zoneSettings, _planetSettings, galaxy, scenario, _startingHull, failures,
() => galaxy.VisitedZones.Add(galaxy.Entrance)); // PopulateLevel's entry
() => RegionClock.Enter(galaxy, null, galaxy.Entrance)); // PopulateLevel's entry
return (galaxy, staged, failures);
}
@ -168,7 +167,7 @@ public sealed partial class RunStartTests
var (galaxy, staged, _) = Begun(new DemoTerminus(), 1);
Assert.Equal(new[] { galaxy.Entrance }, galaxy.VisitedZones);
var neighbour = galaxy.Entrance.AdjacentZones[0];
galaxy.VisitedZones.Add(neighbour);
RegionClock.Enter(galaxy, galaxy.Entrance.Contents, neighbour);
var (game, zones) = RunSave.Capture(_cache, galaxy, galaxy.Entrance.Contents, staged.Player, new SavedActionBarBinding[0], 0);
RunSave.Commit(_cache, game, zones, _items.Lots);
var restored = new Galaxy(_cache, _cache.GetGlobal<SavedGame>(), _ => { });
@ -202,7 +201,7 @@ public sealed partial class RunStartTests
Assert.DoesNotContain("Done!", heard);
var failures = new List<string>();
var staged = RunStart.Begin(_items, _zoneSettings, _planetSettings, galaxy, scenario, _startingHull, failures,
() => galaxy.VisitedZones.Add(galaxy.Entrance));
() => RegionClock.Enter(galaxy, null, galaxy.Entrance));
Assert.NotNull(staged);
var count = galaxy.Zones.Length;
var zones = heard.Where(line => line.StartsWith("Materializing zones: ")).ToList();