diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index 53e1235bc..f8b234833 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -273,13 +273,25 @@ public class ActionGameManager : MonoBehaviour private void OnApplicationQuit() { SaveRun(); + DiscardSimulation(); SavePlayerSettings(); } - // Wormhole arrival and quit save the run; a dead run has no galaxy, so it is not saved. + // The live simulation (Scenario.Saved false), or null while a saved run or nothing is live. Whether the session is + // saved is derived from it alone: StartScenario is the only setter and DiscardSimulation the only clearer. + public static RunSave.Simulation Simulation { get; private set; } + + // Removes what the simulation wrote to the run store, so the saved run and the next run never see it. + private void DiscardSimulation() + { + Simulation?.Discard(CultCache); + Simulation = null; + } + + // Wormhole arrival and quit save the run; a dead run has no galaxy, so it is not saved, and a simulation never is. public void SaveRun() { - if (CurrentGalaxy != null) + if (Simulation == null && CurrentGalaxy != null) { var (game, zones) = RunSave.Capture(CultCache, CurrentGalaxy, Zone, DockedEntity ?? CurrentEntity, _actionBarSlots.Select(s => s.Save()).ToArray(), Credits); @@ -391,6 +403,15 @@ public class ActionGameManager : MonoBehaviour foreach (var wormhole in ZoneRenderer.WormholeInstances.Keys) { if (!(length(wormhole.Position - CurrentEntity.Position.xz) < Settings.GameplaySettings.WormholeExitRadius)) continue; + if (Simulation != null) + { + // The simulation's wormhole is its exit (ruling ifl-wormhole-exit-standin). + Dialog.Clear(); + Dialog.Title.text = "Leave the simulation and start a run?"; + Dialog.Show(onConfirm: LeaveSimulation, onCancel: () => { }, confirmText: "Leave", cancelText: "Stay"); + Dialog.MoveToCursor(); + return; + } if (wormhole.Exit) { // The exit gate leads nowhere: TryWin consults RunGoal and ends the run when the gate is open. @@ -665,6 +686,12 @@ public class ActionGameManager : MonoBehaviour //Temporary, or not ConsoleController.AddCommand("tow", _ => TowShip()); + ConsoleController.AddCommand("leave", _ => + { + if (Simulation == null) Debug.Log("leave: only a simulation can be left; there is no simulation"); + else LeaveSimulation(); + }); + // Manual IFF override for the player's current target, for hand-testing combat. // "iff hostile"/"iff neutral" force a stance; "iff clear" restores the derived faction rule. ConsoleController.AddCommand("iff", args => @@ -769,6 +796,13 @@ public class ActionGameManager : MonoBehaviour }; } + // The one way out of a simulation: starts the Terminus run. AL7 puts the pilot pick in front of this call. + public void LeaveSimulation() + { + MainMenu.gameObject.SetActive(true); // Launch starts a coroutine on it + MainMenu.Launch(Scenarios.Terminus); + } + public void PopulateLevel(GalaxyZone galaxyZone) { if (galaxyZone == null) throw new ArgumentNullException(nameof(galaxyZone)); @@ -858,6 +892,7 @@ public class ActionGameManager : MonoBehaviour private void StartGame() { + DiscardSimulation(); // a run's Replace never sees simulation records if (CurrentGalaxy != null) { if (PendingScenario != null) StartScenario(); @@ -889,19 +924,27 @@ public class ActionGameManager : MonoBehaviour } // RunStart owns what a new run starts with (docs/scenarios-cut.md, R.4); this enters and binds. The saved run is - // replaced only once the scenario has staged. A start that fails leaves the saved run as it was and says why on + // replaced only once the scenario has staged; a simulation starts beside it and never replaces it. A start that fails leaves the saved run as it was and says why on // the main menu, where Continue still resumes the saved run. private void StartScenario() { var scenario = PendingScenario; PendingScenario = null; var failures = new List(); - var staged = RunStart.Launch(() => RunSave.Replace(CultCache, () => + RunSave.Simulation simulation = null; + Func start = () => { RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, scenario); PopulateLevel(CurrentGalaxy.Entrance); return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, failures); - }), failures, Debug.LogException); + }; + var staged = RunStart.Launch(() => + { + if (scenario.Saved) return RunSave.Replace(CultCache, start); + var (started, begun) = RunSave.Beside(CultCache, start); + simulation = begun; + return started; + }, failures, Debug.LogException); if (staged == null) { @@ -910,6 +953,7 @@ public class ActionGameManager : MonoBehaviour MainMenu.Refuse($"{scenario.Name} could not start", string.Join("\n", failures)); return; } + Simulation = simulation; Credits = staged.Credits; SectorMap.QueueZoneReveal(CurrentGalaxy.Entrance.AdjacentZones.Prepend(CurrentGalaxy.Entrance)); BindToEntity(staged.Player); @@ -1313,7 +1357,8 @@ public class ActionGameManager : MonoBehaviour MainMenu.gameObject.SetActive(true); Menu.gameObject.SetActive(false); CurrentGalaxy = null; - RunSave.Clear(CultCache); + if (Simulation != null) DiscardSimulation(); + else RunSave.Clear(CultCache); SavePlayerSettings(); } @@ -1335,7 +1380,7 @@ public class ActionGameManager : MonoBehaviour var deathTime = Time.time; EndRun(); Observable.EveryUpdate() - .Where(_ => Time.time - deathTime < DeathPostTransitionTime) + .TakeWhile(_ => Time.time - deathTime < DeathPostTransitionTime) .Subscribe(_ => { var t = (Time.time - deathTime) / DeathPostTransitionTime; @@ -1358,6 +1403,8 @@ public class ActionGameManager : MonoBehaviour HypothermiaPost.weight = 0; SevereHypothermiaPost.weight = 0; DeathPost.weight = 1; + // Every run begins in the simulation (ruling terminus-boots-into-ifl), so death anywhere returns to it. + MainMenu.Launch(Scenarios.Simulation); }); } diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index 429b50d4d..e726b2e77 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -270,6 +270,34 @@ public static class RunSave return started; } + // A simulation starts beside the saved run and never replaces it. start runs with the saved run still in the store. + // When it returns null or throws, the records it wrote go and the saved run stays. When it returns a value, both the + // value and the Simulation that discards what start wrote come back; the saved run's records are never removed. + public static (T started, Simulation simulation) Beside(CultCache cache, Func start) where T : class + { + var saved = Records(cache); + T started = null; + try + { + started = start(); + } + finally + { + if (started == null) Remove(cache, Records(cache).Except(saved).ToArray()); + } + return started == null ? (null, null) : (started, new Simulation(saved)); + } + + // The run-record keys stored when a simulation began: everything else in the run store is the simulation's. + public sealed class Simulation + { + private readonly CultRecordKey[] _saved; + + internal Simulation(CultRecordKey[] saved) => _saved = saved; + + public void Discard(CultCache cache) => Remove(cache, Records(cache).Except(_saved).ToArray()); + } + private static CultRecordKey[] Records(CultCache cache) => cache.AllStoredDocuments .Where(stored => IsRunRecord(stored.Descriptor.DocumentType)) diff --git a/Assets/Scripts/ServerShared/Scenario.cs b/Assets/Scripts/ServerShared/Scenario.cs index 1db6d7687..4d0806597 100644 --- a/Assets/Scripts/ServerShared/Scenario.cs +++ b/Assets/Scripts/ServerShared/Scenario.cs @@ -22,6 +22,11 @@ public abstract class Scenario // the scenario's conditions. public virtual bool Ambient => true; + // False: the scenario is a simulation. It starts through RunSave.Beside, so the saved run stays in the store and + // stays resumable; it is never captured or committed, and its records are discarded when it ends. The one + // declaration: nothing tests a scenario's type to decide saving. + public virtual bool Saved => true; + // True: the arena's zone always gets a generated faction station with a docking bay, whatever its seed rolls // (ZoneGenerator). False: its stations are rolled like any other zone's. public virtual bool EntranceStation => true; diff --git a/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs b/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs new file mode 100644 index 000000000..96b401457 --- /dev/null +++ b/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs @@ -0,0 +1,18 @@ +using static CultMath.math; + +// Nibu's private simulation (ruling terminus-boots-into-ifl): New Game boots it, nothing in it is saved, and its +// wormhole asks to leave and starts a Terminus run (ruling ifl-wormhole-exit-standin). It stages the Longinus until +// the Nibu stand-in hull exists (ruling nibu-demo-hull-agent-standin); swapping the hull is the one line below. +public sealed class InfiniteFunLand : Scenario +{ + public override string Name => "Infinite Fun Land"; + public override string Id => "infinite-fun-land"; + public override string Brief => "Nibu's private simulation. Nothing in it is saved; leaving it starts a Terminus run."; + public override uint Seed => 7; + public override bool Ambient => false; + public override bool Saved => false; + + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); + + public override void Stage(ScenarioStage stage) => stage.Player(stage.Generated("Longinus"), float2(0, 0)); +} diff --git a/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs.meta b/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs.meta new file mode 100644 index 000000000..edf080d2b --- /dev/null +++ b/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5a68fbe628ad4a49b947a97d4118c703 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs b/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs index 60d291985..615d6b139 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs @@ -3,9 +3,14 @@ // editor and development builds. public static class Scenarios { - public static readonly Scenario[] Modes = { new DemoTerminus() }; + // New Game boots Nibu's simulation; Terminus is the run its exit launches (a development build lists it too). + public static readonly Scenario Simulation = new InfiniteFunLand(); - public static readonly Scenario[] Development = { new MainGalaxy() }; + public static readonly Scenario Terminus = new DemoTerminus(); + + public static readonly Scenario[] Modes = { Simulation }; + + public static readonly Scenario[] Development = { new MainGalaxy(), Terminus }; public static readonly Scenario[] Tests = { diff --git a/Assets/Scripts/UI/MainMenu.cs b/Assets/Scripts/UI/MainMenu.cs index f867b9e8c..1b57b14c9 100644 --- a/Assets/Scripts/UI/MainMenu.cs +++ b/Assets/Scripts/UI/MainMenu.cs @@ -237,7 +237,7 @@ public class MainMenu : MonoBehaviour // The only way into a new run: generates the scenario's galaxy off the main thread and enters the game, where // StartGame has RunStart stage it and only then replaces the saved run. A galaxy that cannot generate is refused // here, with the saved run untouched. - private void Launch(Scenario scenario) + public void Launch(Scenario scenario) { var generatorState = "Loading Database Contents"; diff --git a/tests/Aetheria.Shared.Tests/RunSaveTests.cs b/tests/Aetheria.Shared.Tests/RunSaveTests.cs index 33b139fb9..3c4882531 100644 --- a/tests/Aetheria.Shared.Tests/RunSaveTests.cs +++ b/tests/Aetheria.Shared.Tests/RunSaveTests.cs @@ -328,6 +328,95 @@ public sealed class RunSaveTests : IDisposable } } + // A simulation starts beside the saved run: while it lives the store holds the saved run and what the simulation + // wrote, and discarding it leaves exactly the saved run, which the next open still resumes. + [Fact] + public void ASimulationNeverTouchesTheSavedRun() + { + using (var cache = Open()) + RunSave.Commit(cache, Game(cache), Zones(3, StageZoneContents(cache), 0), new ProvenanceLedger()); + string[] saved; + using (var cache = Open()) + saved = RunKeys(cache); + + using (var cache = Open()) + { + var (started, simulation) = RunSave.Beside(cache, () => + { + WriteAnOrbitTheSavedRunLacks(cache); + return StageZoneContents(cache); + }); + Assert.NotNull(started); + Assert.Equal(saved.Length + 4, RunKeys(cache).Length); + Assert.All(saved, key => Assert.Contains(key, RunKeys(cache))); + simulation.Discard(cache); + Assert.Equal(saved, RunKeys(cache)); + } + using (var cache = Open()) + { + Assert.Equal(saved, RunKeys(cache)); + Assert.NotNull(cache.GetGlobal()); + } + } + + // A simulation that does not start, by returning nothing or by throwing, takes away only what it wrote. + [Fact] + public void AFailedSimulationTakesAwayOnlyWhatItWrote() + { + using (var cache = Open()) + RunSave.Commit(cache, Game(cache), Zones(3, StageZoneContents(cache), 0), new ProvenanceLedger()); + string[] saved; + using (var cache = Open()) + saved = RunKeys(cache); + + using (var cache = Open()) + { + var (started, simulation) = RunSave.Beside(cache, () => + { + WriteAnOrbitTheSavedRunLacks(cache); + return null; + }); + Assert.Null(started); + Assert.Null(simulation); + Assert.Equal(saved, RunKeys(cache)); + } + using (var cache = Open()) + { + Assert.Throws(() => RunSave.Beside(cache, () => + { + WriteAnOrbitTheSavedRunLacks(cache); + throw new InvalidOperationException("the arena would not generate"); + })); + Assert.Equal(saved, RunKeys(cache)); + } + using (var cache = Open()) + { + Assert.Equal(saved, RunKeys(cache)); + Assert.NotNull(cache.GetGlobal()); + } + } + + // A run started after a discarded simulation replaces the saved run and leaves nothing of the simulation behind. + [Fact] + public void ARunStartedAfterADiscardedSimulationReplacesOnlyTheSave() + { + using (var cache = Open()) + RunSave.Commit(cache, Game(cache), Zones(3, StageZoneContents(cache), 0), new ProvenanceLedger()); + + ZonePack started; + using (var cache = Open()) + { + RunSave.Beside(cache, () => StageZoneContents(cache)).simulation.Discard(cache); + started = RunSave.Replace(cache, () => StageZoneContents(cache)); + } + using (var cache = Open()) + { + Assert.Null(cache.GetGlobal()); + Assert.Equal(started.Orbits.Select(orbit => orbit.Key.Value).Concat(started.Planets.Select(body => body.Key.Value)) + .OrderBy(key => key, StringComparer.Ordinal), RunKeys(cache)); + } + } + private static string[] RunKeys(CultCache cache) => cache.AllStoredDocuments .Where(stored => RunSave.IsRunRecord(stored.Descriptor.DocumentType)) .Select(stored => stored.Key.Value) diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index 3be4c5c0e..1a8516bc5 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -147,6 +147,20 @@ public sealed partial class RunStartTests Assert.Contains(main.arena.Pack.Entities, entity => entity is ShipPack { IsPlayerShip: false }); } + // New Game boots Nibu's simulation, which is never saved; the run its exit launches is a development entry, and + // every other scenario is a run that saves. + [Fact] + public void InfiniteFunLandIsASimulation() + { + Assert.False(Scenarios.Simulation.Saved); + Assert.False(Scenarios.Simulation.Ambient); + Assert.NotEqual(0u, Scenarios.Simulation.Seed); + Assert.Equal(new[] { Scenarios.Simulation }, Scenarios.Modes); + Assert.Contains(Scenarios.Terminus, Scenarios.Development); + Assert.All(Scenarios.Modes.Concat(Scenarios.Development).Concat(Scenarios.Tests).Where(scenario => scenario != Scenarios.Simulation), + scenario => Assert.True(scenario.Saved, scenario.Id)); + } + // Everything a galaxy's layout fixes: each zone's name, position, owner, factions and links, the homes, the // entrance, the exit and the background. private static string Layout(Galaxy galaxy) =>