From fa5663f228764b2d0003838ce7c05a2562c64758 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 16 Jul 2026 23:30:19 +0100 Subject: [PATCH] Restore authoritative wormhole traversal --- Aetheria.State.Daemon.Smoke/Program.cs | 131 +++++++++++- .../AetheriaYmirWorldPhysics.cs | 3 +- Aetheria.State.Verify/Program.cs | 17 +- .../Tests/DaemonRuntimeDocumentTests.cs | 65 ++++-- .../Runtime/AetheriaRuntimeAgentTasks.cs | 6 +- .../AetheriaRuntimeDaemonIntentState.cs | 8 +- .../AetheriaRuntimeDaemonOperations.cs | 92 ++++++--- .../AetheriaRuntimeDaemonRenderQueries.cs | 2 + .../AetheriaRuntimeDaemonSimulation.cs | 191 +++++++++++++++++- ...AetheriaRuntimeDaemonSimulationSettings.cs | 29 ++- .../AetheriaRuntimeDaemonTickRunner.cs | 1 + .../AetheriaRuntimeFlightSimulation.cs | 2 +- .../Runtime/AetheriaRuntimeGameDocuments.cs | 16 +- .../AetheriaRuntimeGameViewportDocuments.cs | 14 ++ .../AetheriaRuntimeSnapshotDocuments.cs | 23 +++ docs/aetheria-perfect-machine-map.md | 23 +++ docs/original-game-migration-matrix.md | 25 ++- 17 files changed, 567 insertions(+), 81 deletions(-) diff --git a/Aetheria.State.Daemon.Smoke/Program.cs b/Aetheria.State.Daemon.Smoke/Program.cs index 44eb63ee2..58b33379e 100644 --- a/Aetheria.State.Daemon.Smoke/Program.cs +++ b/Aetheria.State.Daemon.Smoke/Program.cs @@ -190,6 +190,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks SchedulerRequeuesTaskFromDeadAgent, SchedulerCollapsesDuplicateAssignmentMarkers, SchedulerAssignsShortestGalaxyRoute, + WormholeTraversalUsesPersistedEnterTransferExitPhases, AgentTraversesGalaxyRouteBeforeExecutingTask, IdleAgentReturnsToCanonicalHomeAndDocks, ControlledShipDoesNotReceiveAutonomousHelmCommands, @@ -2781,7 +2782,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks var appliedTravelCommands = 0; var appliedApproachCommands = 0; var physics = NewPhysics(); - for (var frame = 0; frame < 100; frame++) + for (var frame = 0; frame < 400; frame++) { var tick = AetheriaRuntimeDaemonTickRunner.Tick( Path.Combine(Path.GetTempPath(), "aetheria-agent-route-travel-smoke.cc"), @@ -2791,8 +2792,8 @@ internal sealed class AetheriaDaemonYmirSmokeChecks WorldPhysics = physics, Catalog = catalog, FrameId = frame, - FixedDeltaSeconds = 0.1, - SimulationTimeSeconds = frame * 0.1, + FixedDeltaSeconds = 0.25, + SimulationTimeSeconds = frame * 0.25, BuildPublications = false }); appliedTravelCommands += tick.OperationResult.AppliedCommandIds.Count(id => id.EndsWith(":travel", StringComparison.Ordinal)); @@ -2813,6 +2814,120 @@ internal sealed class AetheriaDaemonYmirSmokeChecks "agent must execute the task only after arriving in its destination zone"); } + private static void WormholeTraversalUsesPersistedEnterTransferExitPhases() + { + var ship = Entity(0, 75, "player"); + ship.EntityId = "wormhole-traveler"; + var run = new AetheriaRuntimeRunCheckpointCommit + { + RunId = "wormhole-transition-smoke", + GenerationSeed = 77, + CurrentZoneIndex = 0, + CurrentEntityKey = "zone.0.entity.0", + DiscoveredZoneIndices = [0], + Zones = + [ + new AetheriaRuntimeZoneSnapshotCommit + { + ZoneIndex = 0, PositionX = 0, GravityTerrainRadius = 100, + AdjacentZoneIndices = [1], Entities = [ship] + }, + new AetheriaRuntimeZoneSnapshotCommit + { + ZoneIndex = 1, PositionX = 100, GravityTerrainRadius = 100, + AdjacentZoneIndices = [0, 2], Entities = Array.Empty() + }, + new AetheriaRuntimeZoneSnapshotCommit + { + ZoneIndex = 2, PositionX = 200, GravityTerrainRadius = 100, + AdjacentZoneIndices = [1], Entities = Array.Empty() + } + ] + }; + AetheriaRuntimeDaemonCommandDocument Travel(string id) + { + var command = AetheriaRuntimeDaemonCommandDocument.Create( + AetheriaRuntimeDaemonCommandKinds.EnterWormhole, + "pilot", + id, + 0, + run.CurrentEntityKey); + command.CommandId = id; + command.TargetZoneIndex = 1; + return command; + } + var physics = NewPhysics(); + AetheriaRuntimeDaemonTickResult Tick(int frame, params AetheriaRuntimeDaemonCommandDocument[] commands) => + AetheriaRuntimeDaemonTickRunner.Tick( + Path.Combine(Path.GetTempPath(), "aetheria-wormhole-transition-smoke.cc"), + run, + new AetheriaRuntimeDaemonTickOptions + { + WorldPhysics = physics, + FrameId = frame, + FixedDeltaSeconds = 1, + SimulationTimeSeconds = frame + 1, + ObservedCommands = commands, + BuildPublications = false + }); + + var entering = Tick(0, Travel("wormhole-start"), Travel("wormhole-same-batch")); + Require(entering.OperationResult.RejectedCommandIds.Any(id => id.Contains("wormhole-same-batch", StringComparison.Ordinal)), + "one command batch must not admit two competing transition intents for the same entity"); + RequireEqual(0, run.CurrentZoneIndex, + "wormhole command acceptance must not splice the ship into the destination immediately"); + RequireEqual("entering", ship.WormholeTransition?.Phase ?? "", + "daemon must persist the entering phase on the authoritative entity"); + Require(Math.Abs((ship.WormholeTransition?.Progress ?? 0) - 0.25) < 0.0001, + "fossil four-second entry timing must advance from fixed daemon time"); + Require(Math.Abs((ship.WormholeTransition?.VisualDepthOffset ?? 0) + 250) < 0.0001, + "transition must expose the fossil depth lever without making the client own motion"); + var enteringView = AetheriaRuntimeGameDocuments.CurrentEntity(entering.Frame).WormholeTransition; + RequireEqual("entering", enteringView?.Phase ?? "", + "current-entity projection must expose the same transition state to Eve consumers"); + + run = MessagePack.MessagePackSerializer.Deserialize( + MessagePack.MessagePackSerializer.Serialize(run)); + ship = run.Zones.Single(zone => zone.ZoneIndex == 0).Entities.Single(); + physics.Dispose(); + physics = NewPhysics(); + RequireEqual("entering", ship.WormholeTransition?.Phase ?? "", + "daemon restart must retain the exact mid-entry phase instead of repairing it from client state"); + + var duplicate = Tick(1, Travel("wormhole-duplicate")); + Require(duplicate.OperationResult.RejectedCommandIds.Any(id => id.Contains("wormhole-duplicate", StringComparison.Ordinal)), + "an entity already inside a wormhole transition must reject a second traversal owner"); + Tick(2); + Tick(3); + RequireEqual(1, run.CurrentZoneIndex, + "zone ownership must transfer only after the entering phase completes"); + var arrived = run.Zones.Single(zone => zone.ZoneIndex == 1).Entities.Single(); + RequireEqual("exiting", arrived.WormholeTransition?.Phase ?? "", + "transferred ship must persist a distinct exiting phase"); + Require(run.DiscoveredZoneIndices.Contains(2), + "arrival must reveal the destination adjacency using the fossil discovery rule"); + + Tick(4); + Tick(5); + Tick(6); + Tick(7); + RequireEqual("completed", arrived.WormholeTransition?.Phase ?? "", + "the completion frame must preserve a presentation lever before normal physics resumes"); + Require(Math.Abs(Math.Sqrt(arrived.VelocityX * arrived.VelocityX + arrived.VelocityY * arrived.VelocityY) - 20) < 0.0001, + "completed exit must restore the fossil twenty-unit launch velocity"); + Require(Math.Abs(Math.Sqrt(Math.Pow(arrived.PositionX + 75, 2) + Math.Pow(arrived.PositionZ, 2)) - 50) < 0.001, + "completed exit must place the ship fifty units from the destination wormhole"); + Tick(8); + Require(arrived.WormholeTransition == null, + "the tick after completion must release input and Ymir instead of leaving a permanent transition flag"); + RequireEqual(1, run.GameEvents.Count(value => value.Kind == "wormhole.enter.started"), + "entry feedback must have stable exactly-once chronology"); + RequireEqual(1, run.GameEvents.Count(value => value.Kind == "wormhole.transferred"), + "transfer feedback must have stable exactly-once chronology"); + RequireEqual(1, run.GameEvents.Count(value => value.Kind == "wormhole.exit.completed"), + "exit feedback must have stable exactly-once chronology"); + } + private static void IdleAgentReturnsToCanonicalHomeAndDocks() { var worker = Entity(0, 0, "workers"); @@ -2838,7 +2953,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks var sawDock = false; var rejectedHomeCommands = new List(); var physics = NewPhysics(); - for (var frame = 0; frame < 120; frame++) + for (var frame = 0; frame < 500; frame++) { var tick = AetheriaRuntimeDaemonTickRunner.Tick( Path.Combine(Path.GetTempPath(), "aetheria-agent-return-home-smoke.cc"), @@ -2848,8 +2963,8 @@ internal sealed class AetheriaDaemonYmirSmokeChecks WorldPhysics = physics, Catalog = catalog, FrameId = frame, - FixedDeltaSeconds = 0.1, - SimulationTimeSeconds = frame * 0.1, + FixedDeltaSeconds = 0.25, + SimulationTimeSeconds = frame * 0.25, BuildPublications = false }); sawApproach |= tick.OperationResult.AppliedCommandIds.Any(id => id.Contains(":home-approach", StringComparison.Ordinal)); @@ -2875,8 +2990,8 @@ internal sealed class AetheriaDaemonYmirSmokeChecks run, new AetheriaRuntimeDaemonTickOptions { - WorldPhysics = physics, Catalog = catalog, FrameId = 121, - FixedDeltaSeconds = 0.1, SimulationTimeSeconds = 12.1, BuildPublications = false + WorldPhysics = physics, Catalog = catalog, FrameId = 501, + FixedDeltaSeconds = 0.25, SimulationTimeSeconds = 125.25, BuildPublications = false }); Require(!settled.OperationResult.AppliedCommandIds.Any(id => id.Contains(":home-", StringComparison.Ordinal)), "docked worker must not emit a perpetual homecoming repair loop"); diff --git a/Aetheria.State.Daemon/AetheriaYmirWorldPhysics.cs b/Aetheria.State.Daemon/AetheriaYmirWorldPhysics.cs index b7d8323b3..ad4934ccd 100644 --- a/Aetheria.State.Daemon/AetheriaYmirWorldPhysics.cs +++ b/Aetheria.State.Daemon/AetheriaYmirWorldPhysics.cs @@ -509,7 +509,8 @@ public sealed class AetheriaYmirWorldPhysics : IAetheriaRuntimeWorldPhysics, IDi { var source = entities ?? Array.Empty(); var attached = source.SelectMany(entity => entity.ChildEntityIndices ?? Array.Empty()).ToHashSet(); - return source.Where(entity => entity.IsActive && !attached.Contains(entity.EntityIndex)).ToArray(); + return source.Where(entity => entity.IsActive && entity.WormholeTransition == null && + !attached.Contains(entity.EntityIndex)).ToArray(); } private static IReadOnlyList ActivePickups( diff --git a/Aetheria.State.Verify/Program.cs b/Aetheria.State.Verify/Program.cs index f7765b977..5b1137519 100644 --- a/Aetheria.State.Verify/Program.cs +++ b/Aetheria.State.Verify/Program.cs @@ -15170,6 +15170,7 @@ static void RequireUnityObserverDoesNotTickLocalSimulation(string root) var daemonDocumentsPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeDaemonDocuments.cs"); var daemonOperationClientPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeDaemonOperationClient.cs"); var daemonRuntimeOperationsPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeDaemonOperations.cs"); + var daemonRuntimeSimulationPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeDaemonSimulation.cs"); var daemonIntentPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeDaemonIntentState.cs"); var zoneRenderDocumentsPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeGameViewportDocuments.cs"); var daemonObserverPath = Path.Combine(root, "Assets", "Scripts", "Gameplay", "AetheriaDaemonObserver.cs"); @@ -15208,6 +15209,9 @@ static void RequireUnityObserverDoesNotTickLocalSimulation(string root) var daemonOperationsSource = File.Exists(daemonRuntimeOperationsPath) ? File.ReadAllText(daemonRuntimeOperationsPath) : throw new InvalidOperationException("Cannot verify Unity observer authority; daemon operations is missing."); + var daemonSimulationSource = File.Exists(daemonRuntimeSimulationPath) + ? File.ReadAllText(daemonRuntimeSimulationPath) + : throw new InvalidOperationException("Cannot verify Unity observer authority; daemon simulation is missing."); var daemonIntent = File.Exists(daemonIntentPath) ? File.ReadAllText(daemonIntentPath) : throw new InvalidOperationException("Cannot verify Unity observer authority; daemon intent state is missing."); @@ -16072,20 +16076,25 @@ static void RequireUnityObserverDoesNotTickLocalSimulation(string root) var requiredDaemonNavigationAuthoritySymbols = new[] { - "ApplyEnterWormholeIntent(run, command, context.Intents)", + "ApplyEnterWormholeIntent(run, command, context.Intents,", "ApplyTowToStation(run, command, context.DockingDistance)", - "MoveEntityToZone(run, actor, command.TargetZoneIndex", + "intents.Wormholes.Add", + "entity.WormholeTransition != null", + "StepWormholeTransitions(", + "AetheriaRuntimeDaemonOperations.MoveEntityToZone(", + "entity.WormholeTransition = null", "run.CurrentZoneIndex = targetZoneIndex", "run.CurrentEntityKey = movedEntityKey", "run.DiscoveredZoneIndices = discovered.ToArray()" }; + var daemonNavigationCorpus = daemonOperationsSource + "\n" + daemonSimulationSource; var missingDaemonNavigationAuthoritySymbols = requiredDaemonNavigationAuthoritySymbols - .Where(symbol => !daemonOperationsSource.Contains(symbol, StringComparison.Ordinal)) + .Where(symbol => !daemonNavigationCorpus.Contains(symbol, StringComparison.Ordinal)) .ToArray(); if (missingDaemonNavigationAuthoritySymbols.Length > 0) { throw new InvalidOperationException( - "Daemon navigation commands no longer mutate canonical run state inside the daemon operation layer: " + + "Daemon navigation no longer validates intent then commits canonical transition state inside daemon-owned operations/simulation: " + string.Join(", ", missingDaemonNavigationAuthoritySymbols)); } diff --git a/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs b/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs index 864987d91..cd6389e3b 100644 --- a/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs +++ b/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs @@ -4747,9 +4747,23 @@ public class DaemonRuntimeDocumentTests } [Test] - public void DaemonOperationsMovesEntityThroughWormholeInDaemonState() + public void DaemonOperationsQueuesCanonicalWormholeTransitionWithoutMovingEntity() { var run = RunWithTwoEntities(); + run.Zones[0].GravityTerrainRadius = 100; + run.Zones[0].AdjacentZoneIndices = new[] { 2 }; + run.Zones[0].Entities[0].PositionX = 100; + run.Zones = run.Zones.Concat(new[] + { + new AetheriaRuntimeZoneSnapshotCommit + { + ZoneIndex = 2, + PositionX = 100, + GravityTerrainRadius = 100, + AdjacentZoneIndices = new[] { 0 }, + Entities = Array.Empty() + } + }).ToArray(); var command = AetheriaRuntimeDaemonCommandDocument.Create( AetheriaRuntimeDaemonCommandKinds.EnterWormhole, "codex", @@ -4757,34 +4771,42 @@ public class DaemonRuntimeDocumentTests 45, "zone.0.entity.0"); command.TargetZoneIndex = 2; - command.PositionX = 100; - command.PositionY = 200; var result = AetheriaRuntimeDaemonOperations.Execute(run, new[] { command }); var sourceZone = FindZone(run, 0); var targetZone = FindZone(run, 2); Assert.AreEqual(1, result.AppliedCommandIds.Count); - Assert.AreEqual(2, run.CurrentZoneIndex); - Assert.AreEqual("global:aetheria.run_state.daemon-command-apply-run.zone.2.entity.0.v1", run.CurrentEntityKey); - Assert.AreEqual(1, sourceZone.Entities.Count); - Assert.AreEqual("Target", sourceZone.Entities[0].Name); - Assert.AreEqual(0, sourceZone.Entities[0].EntityIndex); - Assert.AreEqual(1, targetZone.Entities.Count); - Assert.AreEqual("Player", targetZone.Entities[0].Name); - Assert.AreEqual(0, targetZone.Entities[0].EntityIndex); - Assert.AreEqual(100, targetZone.Entities[0].PositionX, 0.0001); - Assert.AreEqual(200, targetZone.Entities[0].PositionZ, 0.0001); - CollectionAssert.Contains(run.DiscoveredZoneIndices, 2); + Assert.AreEqual(0, run.CurrentZoneIndex); + Assert.AreEqual("zone.0.entity.0", run.CurrentEntityKey); + Assert.AreEqual(2, sourceZone.Entities.Count); + Assert.AreEqual(0, targetZone.Entities.Count); Assert.AreEqual(1, result.Intents.Wormholes.Count); - Assert.AreEqual("global:aetheria.run_state.daemon-command-apply-run.zone.2.entity.0.v1", result.Intents.Wormholes[0].ActorEntityKey); + Assert.AreEqual("zone.0.entity.0", result.Intents.Wormholes[0].ActorEntityKey); + Assert.AreEqual(0, result.Intents.Wormholes[0].SourceZoneIndex); Assert.AreEqual(2, result.Intents.Wormholes[0].TargetZoneIndex); + Assert.AreEqual(75, result.Intents.Wormholes[0].EntryWormholeX, 0.0001); + Assert.AreEqual(-75, result.Intents.Wormholes[0].ExitWormholeX, 0.0001); } [Test] public void DaemonOperationsRejectsWormholeMoveWhenEntityIsDocked() { var run = RunWithTwoEntities(); + run.Zones[0].GravityTerrainRadius = 100; + run.Zones[0].AdjacentZoneIndices = new[] { 2 }; + run.Zones[0].Entities[0].PositionX = 100; + run.Zones = run.Zones.Concat(new[] + { + new AetheriaRuntimeZoneSnapshotCommit + { + ZoneIndex = 2, + PositionX = 100, + GravityTerrainRadius = 100, + AdjacentZoneIndices = new[] { 0 }, + Entities = Array.Empty() + } + }).ToArray(); run.Zones[0].Entities[1].ChildEntityIndices = new[] { 0 }; run.Zones[0].Entities[1].DockingBayAssignments = new[] { 0, -1 }; var command = AetheriaRuntimeDaemonCommandDocument.Create( @@ -4836,6 +4858,7 @@ public class DaemonRuntimeDocumentTests Assert.AreEqual(0, undockedActor.VelocityY); var wormholeRun = RunWithTwoEntities(); + wormholeRun.Zones[0].GravityTerrainRadius = 10; wormholeRun.Zones[0].AdjacentZoneIndices = new[] { 2 }; wormholeRun.Zones[0].Entities[0].PositionX = 0; wormholeRun.Zones[0].Entities[0].PositionZ = 0; @@ -4846,7 +4869,9 @@ public class DaemonRuntimeDocumentTests { ZoneIndex = 2, PositionX = 3, - PositionY = 4 + PositionY = 4, + GravityTerrainRadius = 10, + AdjacentZoneIndices = new[] { 0 } } }) .ToArray(); @@ -4857,14 +4882,14 @@ public class DaemonRuntimeDocumentTests 47, "zone.0.entity.0"); wormhole.ScalarValue = 10; - wormhole.PositionX = 10; + wormhole.PositionX = 11; var wormholeResult = AetheriaRuntimeDaemonOperations.Execute(wormholeRun, new[] { wormhole }); Assert.AreEqual(1, wormholeResult.AppliedCommandIds.Count); Assert.AreEqual(1, wormholeResult.Intents.Wormholes.Count); - Assert.AreEqual(2, wormholeRun.CurrentZoneIndex); - Assert.AreEqual(3, FindZone(wormholeRun, 2).Entities[0].PositionX, 0.0001); - Assert.AreEqual(4, FindZone(wormholeRun, 2).Entities[0].PositionZ, 0.0001); + Assert.AreEqual(0, wormholeRun.CurrentZoneIndex); + Assert.AreEqual(4.5, wormholeResult.Intents.Wormholes[0].EntryWormholeX, 0.0001); + Assert.AreEqual(6, wormholeResult.Intents.Wormholes[0].EntryWormholeZ, 0.0001); var dockRun = RunWithTwoEntities(); dockRun.Zones[0].Entities[0].PositionX = 0; diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeAgentTasks.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeAgentTasks.cs index 2ae3ec5c7..11697190a 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeAgentTasks.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeAgentTasks.cs @@ -228,7 +228,8 @@ namespace GameCult.Aetheria.State.Verse var exit = AetheriaRuntimeDaemonRenderQueries.QueryWormholeExits( run, assignment.Zone, - AetheriaRuntimeDaemonRenderQueries.ResolveZoneRenderRadius(assignment.Zone, 1200), + AetheriaRuntimeDaemonRenderQueries.ResolveZoneRenderRadius( + assignment.Zone, AetheriaRuntimeDaemonRenderQueries.DefaultZoneRenderRadius), settings.WormholeDistanceRatio) .First(candidate => candidate.TargetZoneIndex == route[1]); var travelDx = exit.PositionX - assignment.Entity.PositionX; @@ -681,7 +682,8 @@ namespace GameCult.Aetheria.State.Verse var exit = AetheriaRuntimeDaemonRenderQueries.QueryWormholeExits( run, worker.Zone, - AetheriaRuntimeDaemonRenderQueries.ResolveZoneRenderRadius(worker.Zone, 1200), + AetheriaRuntimeDaemonRenderQueries.ResolveZoneRenderRadius( + worker.Zone, AetheriaRuntimeDaemonRenderQueries.DefaultZoneRenderRadius), settings.WormholeDistanceRatio) .First(candidate => candidate.TargetZoneIndex == route[1]); var dx = exit.PositionX - worker.Entity.PositionX; diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonIntentState.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonIntentState.cs index ba8bfdc17..dae4e042d 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonIntentState.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonIntentState.cs @@ -74,9 +74,13 @@ namespace GameCult.Aetheria.State.Verse public sealed class AetheriaRuntimeDaemonWormholeIntent { public string ActorEntityKey { get; set; } = ""; + public int SourceZoneIndex { get; set; } = -1; public int TargetZoneIndex { get; set; } = -1; - public double PositionX { get; set; } - public double PositionY { get; set; } + public double EntryWormholeX { get; set; } + public double EntryWormholeZ { get; set; } + public double ExitWormholeX { get; set; } + public double ExitWormholeZ { get; set; } + public string CommandId { get; set; } = ""; } } diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs index 4f4e072e1..da216bed2 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs @@ -39,6 +39,8 @@ namespace GameCult.Aetheria.State.Verse public double DockingDistance { get; set; } = AetheriaRuntimeDaemonOperationContext.DefaultDockingDistance; public double WormholeExitRadius { get; set; } = AetheriaRuntimeDaemonOperationContext.DefaultWormholeExitRadius; + public double WormholeDistanceRatio { get; set; } = + AetheriaRuntimeDaemonRenderSettings.AetheriaDefault.WormholeDistanceRatio; public AetheriaRuntimeCatalogSnapshot? Catalog { get; set; } } @@ -169,9 +171,11 @@ namespace GameCult.Aetheria.State.Verse command, context.Intents, context.DockingDistance, - context.WormholeExitRadius); + context.WormholeExitRadius, + context.WormholeDistanceRatio); case AetheriaRuntimeDaemonCommandKinds.EnterWormhole: - return ApplyEnterWormholeIntent(run, command, context.Intents); + return ApplyEnterWormholeIntent(run, command, context.Intents, + context.WormholeExitRadius, context.WormholeDistanceRatio); case AetheriaRuntimeDaemonCommandKinds.TowToStation: return ApplyTowToStation(run, command, context.DockingDistance); case AetheriaRuntimeDaemonCommandKinds.IssueAgentTask: @@ -1401,7 +1405,8 @@ namespace GameCult.Aetheria.State.Verse AetheriaRuntimeDaemonCommandDocument command, AetheriaRuntimeDaemonIntentState intents, double defaultDockingDistance, - double defaultWormholeExitRadius) + double defaultWormholeExitRadius, + double wormholeDistanceRatio) { var actorKey = ResolveActorEntityKey(run, command); if (string.IsNullOrWhiteSpace(actorKey) || @@ -1417,14 +1422,14 @@ namespace GameCult.Aetheria.State.Verse run, actorKey, ResolveInteractionDistance(command.PositionX, defaultWormholeExitRadius), + wormholeDistanceRatio, out var targetZoneIndex, - out var entryX, - out var entryY)) + out _, + out _)) { command.TargetZoneIndex = targetZoneIndex; - command.PositionX = entryX; - command.PositionY = entryY; - return ApplyEnterWormholeIntent(run, command, intents); + return ApplyEnterWormholeIntent(run, command, intents, + defaultWormholeExitRadius, wormholeDistanceRatio); } return ApplyDockNearestIntent(run, command, intents, defaultDockingDistance); @@ -1486,6 +1491,7 @@ namespace GameCult.Aetheria.State.Verse AetheriaRuntimeRunCheckpointCommit run, string actorEntityKey, double maxDistance, + double wormholeDistanceRatio, out int targetZoneIndex, out double entryX, out double entryY) @@ -1503,23 +1509,23 @@ namespace GameCult.Aetheria.State.Verse var maxDistanceSq = maxDistance > 0.0 ? maxDistance * maxDistance : double.PositiveInfinity; var closestDistanceSq = double.PositiveInfinity; - foreach (var adjacentZoneIndex in zone.AdjacentZoneIndices ?? Array.Empty()) + foreach (var exit in AetheriaRuntimeDaemonRenderQueries.QueryWormholeExits( + run, + zone, + AetheriaRuntimeDaemonRenderQueries.ResolveZoneRenderRadius( + zone, AetheriaRuntimeDaemonRenderQueries.DefaultZoneRenderRadius), + wormholeDistanceRatio)) { - var candidate = (run.Zones ?? Array.Empty()) - .FirstOrDefault(candidateZone => candidateZone != null && candidateZone.ZoneIndex == adjacentZoneIndex); - if (candidate == null) - continue; - - var deltaX = candidate.PositionX - actor.PositionX; - var deltaY = candidate.PositionY - actor.PositionZ; + var deltaX = exit.PositionX - actor.PositionX; + var deltaY = exit.PositionZ - actor.PositionZ; var distanceSq = (deltaX * deltaX) + (deltaY * deltaY); if (distanceSq >= maxDistanceSq || distanceSq >= closestDistanceSq) continue; closestDistanceSq = distanceSq; - targetZoneIndex = adjacentZoneIndex; - entryX = candidate.PositionX; - entryY = candidate.PositionY; + targetZoneIndex = exit.TargetZoneIndex; + entryX = exit.PositionX; + entryY = exit.PositionZ; } return targetZoneIndex >= 0; @@ -1662,21 +1668,55 @@ namespace GameCult.Aetheria.State.Verse private static bool ApplyEnterWormholeIntent( AetheriaRuntimeRunCheckpointCommit run, AetheriaRuntimeDaemonCommandDocument command, - AetheriaRuntimeDaemonIntentState intents) + AetheriaRuntimeDaemonIntentState intents, + double maximumDistance, + double wormholeDistanceRatio) { var actor = ResolveActorEntityKey(run, command); - if (string.IsNullOrWhiteSpace(actor) || command.TargetZoneIndex < 0) + if (string.IsNullOrWhiteSpace(actor) || command.TargetZoneIndex < 0 || + !TryResolveEntity(run, actor, out var sourceZoneIndex, out var sourceEntityIndex, out var entity) || + IsChildReferencedInZone(run, sourceZoneIndex, sourceEntityIndex) || + intents.Wormholes.Any(intent => string.Equals(intent.ActorEntityKey, actor, StringComparison.Ordinal)) || + entity.WormholeTransition != null) return false; - if (!MoveEntityToZone(run, actor, command.TargetZoneIndex, command.PositionX, command.PositionY, out var movedEntityKey)) + var zone = (run.Zones ?? Array.Empty()) + .FirstOrDefault(candidate => candidate != null && candidate.ZoneIndex == sourceZoneIndex); + var exit = AetheriaRuntimeDaemonRenderQueries.QueryWormholeExits( + run, + zone, + AetheriaRuntimeDaemonRenderQueries.ResolveZoneRenderRadius( + zone, AetheriaRuntimeDaemonRenderQueries.DefaultZoneRenderRadius), + wormholeDistanceRatio) + .FirstOrDefault(candidate => candidate.TargetZoneIndex == command.TargetZoneIndex); + if (exit.TargetZoneIndex != command.TargetZoneIndex) + return false; + var dx = exit.PositionX - entity.PositionX; + var dz = exit.PositionZ - entity.PositionZ; + if (dx * dx + dz * dz >= maximumDistance * maximumDistance) + return false; + var targetZone = (run.Zones ?? Array.Empty()) + .FirstOrDefault(candidate => candidate != null && candidate.ZoneIndex == command.TargetZoneIndex); + var returnExit = AetheriaRuntimeDaemonRenderQueries.QueryWormholeExits( + run, + targetZone, + AetheriaRuntimeDaemonRenderQueries.ResolveZoneRenderRadius( + targetZone, AetheriaRuntimeDaemonRenderQueries.DefaultZoneRenderRadius), + wormholeDistanceRatio) + .FirstOrDefault(candidate => candidate.TargetZoneIndex == sourceZoneIndex); + if (returnExit.TargetZoneIndex != sourceZoneIndex) return false; intents.Wormholes.Add(new AetheriaRuntimeDaemonWormholeIntent { - ActorEntityKey = movedEntityKey, + ActorEntityKey = actor, + SourceZoneIndex = sourceZoneIndex, TargetZoneIndex = command.TargetZoneIndex, - PositionX = command.PositionX, - PositionY = command.PositionY + EntryWormholeX = exit.PositionX, + EntryWormholeZ = exit.PositionZ, + ExitWormholeX = returnExit.PositionX, + ExitWormholeZ = returnExit.PositionZ, + CommandId = command.CommandId ?? "" }); return true; } @@ -1706,7 +1746,7 @@ namespace GameCult.Aetheria.State.Verse station.OrbitKey = orbitKey; return true; } - private static bool MoveEntityToZone( + internal static bool MoveEntityToZone( AetheriaRuntimeRunCheckpointCommit run, string entityKey, int targetZoneIndex, diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonRenderQueries.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonRenderQueries.cs index e69af8fcb..85f44e54c 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonRenderQueries.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonRenderQueries.cs @@ -698,6 +698,8 @@ namespace GameCult.Aetheria.State.Verse public static class AetheriaRuntimeDaemonRenderQueries { + public const double DefaultZoneRenderRadius = 2000.0; + public static AetheriaRuntimeEffectiveContact[] QueryEffectiveContacts( AetheriaRuntimeZoneSnapshotCommit? zone, int observerEntityIndex) diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs index 599f8ad14..984d38792 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs @@ -30,6 +30,15 @@ namespace GameCult.Aetheria.State.Verse if (worldPhysics == null) throw new ArgumentNullException(nameof(worldPhysics)); + StepWormholeTransitions( + run, + intents == null + ? Array.Empty() + : intents.Wormholes, + deltaSeconds, + settings, + frameId); + worldPhysics.RetainWorlds( run.RunId, (run.Zones ?? Array.Empty()) @@ -87,6 +96,181 @@ namespace GameCult.Aetheria.State.Verse } } + private static void StepWormholeTransitions( + AetheriaRuntimeRunCheckpointCommit run, + IReadOnlyList intents, + double deltaSeconds, + AetheriaRuntimeDaemonSimulationSettings settings, + long frameId) + { + foreach (var intent in intents ?? Array.Empty()) + { + if (intent == null || !TryResolveEntity(run, intent.ActorEntityKey, out var entity) || + entity.WormholeTransition != null) + continue; + entity.TargetEntityIndex = -1; + entity.VelocityX = 0; + entity.VelocityY = 0; + entity.HelmStrafe = 0; + entity.HelmForward = 0; + entity.WormholeTransition = new AetheriaRuntimeWormholeTransitionCommit + { + TransitionId = string.IsNullOrWhiteSpace(intent.CommandId) + ? $"wormhole:{entity.EntityId}:{frameId}" + : $"wormhole:{intent.CommandId}", + Phase = "entering", + SourceZoneIndex = intent.SourceZoneIndex, + TargetZoneIndex = intent.TargetZoneIndex, + EntryStartX = entity.PositionX, + EntryStartZ = entity.PositionZ, + EntryWormholeX = intent.EntryWormholeX, + EntryWormholeZ = intent.EntryWormholeZ, + ExitWormholeX = intent.ExitWormholeX, + ExitWormholeZ = intent.ExitWormholeZ, + StartedFrameId = frameId + }; + AppendWormholeEvent(run, entity, entity.WormholeTransition, frameId, "wormhole.enter.started"); + } + + var transitioning = (run.Zones ?? Array.Empty()) + .Where(zone => zone != null) + .SelectMany(zone => (zone.Entities ?? Array.Empty()) + .Where(entity => entity?.WormholeTransition != null) + .Select(entity => (Zone: zone, Entity: entity!))) + .ToArray(); + foreach (var (zone, entity) in transitioning) + { + var transition = entity.WormholeTransition!; + if (string.Equals(transition.Phase, "completed", StringComparison.Ordinal)) + { + entity.WormholeTransition = null; + continue; + } + transition.Progress = Math.Min(1, transition.Progress + deltaSeconds / settings.WormholeAnimationDuration); + if (string.Equals(transition.Phase, "entering", StringComparison.Ordinal)) + { + var entrySpan = Math.Max(0.000001, 1 - settings.WormholeExitCurveStart); + var entry = SmootherStep(Math.Min(1, transition.Progress / entrySpan)); + entity.PositionX = Lerp(transition.EntryStartX, transition.EntryWormholeX, entry); + entity.PositionZ = Lerp(transition.EntryStartZ, transition.EntryWormholeZ, entry); + transition.VisualDepthOffset = -settings.WormholeDepth * transition.Progress; + if (transition.Progress < 1) + continue; + + var sourceEntityKey = AetheriaRuntimeRunCheckpointCommit.EntityRecordKey( + run.RunId, zone.ZoneIndex, entity.EntityIndex); + if (!AetheriaRuntimeDaemonOperations.MoveEntityToZone( + run, + sourceEntityKey, + transition.TargetZoneIndex, + transition.ExitWormholeX, + transition.ExitWormholeZ, + out _)) + throw new InvalidOperationException($"Wormhole transition '{transition.TransitionId}' could not transfer its entity."); + var direction = StableDirection(run.GenerationSeed, transition.TransitionId); + transition.ExitVelocityX = direction.X * settings.WormholeExitVelocity; + transition.ExitVelocityZ = direction.Y * settings.WormholeExitVelocity; + transition.Phase = "exiting"; + transition.Progress = 0; + transition.VisualDepthOffset = -settings.WormholeDepth; + DiscoverArrival(run, transition.TargetZoneIndex); + AppendWormholeEvent(run, entity, transition, frameId, "wormhole.transferred"); + continue; + } + + if (!string.Equals(transition.Phase, "exiting", StringComparison.Ordinal)) + continue; + var exitSpan = Math.Max(0.000001, 1 - settings.WormholeExitCurveStart); + var exit = SmootherStep(Math.Max(0, transition.Progress - settings.WormholeExitCurveStart) / exitSpan); + var velocityLength = Math.Sqrt( + transition.ExitVelocityX * transition.ExitVelocityX + + transition.ExitVelocityZ * transition.ExitVelocityZ); + var directionX = velocityLength <= 0.000001 ? 1 : transition.ExitVelocityX / velocityLength; + var directionZ = velocityLength <= 0.000001 ? 0 : transition.ExitVelocityZ / velocityLength; + entity.PositionX = transition.ExitWormholeX + directionX * exit * settings.WormholeExitRadius; + entity.PositionZ = transition.ExitWormholeZ + directionZ * exit * settings.WormholeExitRadius; + transition.VisualDepthOffset = -settings.WormholeDepth * (1 - transition.Progress); + if (transition.Progress < 1) + continue; + entity.DirectionX = directionX; + entity.DirectionY = directionZ; + entity.LookDirectionX = directionX; + entity.LookDirectionY = directionZ; + entity.VelocityX = transition.ExitVelocityX; + entity.VelocityY = transition.ExitVelocityZ; + AppendWormholeEvent(run, entity, transition, frameId, "wormhole.exit.completed"); + transition.Phase = "completed"; + } + } + + private static bool TryResolveEntity( + AetheriaRuntimeRunCheckpointCommit run, + string entityKey, + out AetheriaRuntimeEntitySnapshotCommit entity) + { + entity = null!; + if (!AetheriaRuntimeRunCheckpointCommit.TryParseEntityKey(entityKey, out var zoneIndex, out var entityIndex)) + return false; + entity = (run.Zones ?? Array.Empty()) + .FirstOrDefault(zone => zone != null && zone.ZoneIndex == zoneIndex)? + .Entities?.FirstOrDefault(candidate => candidate != null && candidate.EntityIndex == entityIndex)!; + return entity != null; + } + + private static void DiscoverArrival(AetheriaRuntimeRunCheckpointCommit run, int zoneIndex) + { + var discovered = new HashSet(run.DiscoveredZoneIndices ?? Array.Empty()) { zoneIndex }; + var zone = (run.Zones ?? Array.Empty()) + .FirstOrDefault(candidate => candidate != null && candidate.ZoneIndex == zoneIndex); + foreach (var adjacent in zone?.AdjacentZoneIndices ?? Array.Empty()) + discovered.Add(adjacent); + run.DiscoveredZoneIndices = discovered.OrderBy(value => value).ToArray(); + } + + private static void AppendWormholeEvent( + AetheriaRuntimeRunCheckpointCommit run, + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeWormholeTransitionCommit transition, + long frameId, + string kind) + { + AetheriaRuntimeGameEvents.Append(run, new AetheriaRuntimeGameEventCommit + { + EventId = $"{transition.TransitionId}:{kind}", + Kind = kind, + FrameId = frameId, + ZoneIndex = string.Equals(kind, "wormhole.enter.started", StringComparison.Ordinal) + ? transition.SourceZoneIndex + : transition.TargetZoneIndex, + SourceEntityIndex = entity.EntityIndex, + SubjectKey = transition.TransitionId, + ScalarValue = transition.Progress, + AuxiliaryValue = transition.VisualDepthOffset, + PositionX = entity.PositionX, + PositionZ = entity.PositionZ + }); + } + + private static (double X, double Y) StableDirection(uint seed, string value) + { + var hash = seed == 0 ? 2166136261u : seed; + foreach (var character in value ?? "") + { + hash ^= character; + hash *= 16777619u; + } + var angle = hash / ((double)uint.MaxValue + 1) * Math.PI * 2; + return (Math.Cos(angle), Math.Sin(angle)); + } + + private static double SmootherStep(double value) + { + value = Clamp01(value); + return value * value * value * (value * (value * 6 - 15) + 10); + } + + private static double Lerp(double from, double to, double value) => from + (to - from) * value; + private static void StepPickupLifetimes(AetheriaRuntimeRunCheckpointCommit run, AetheriaRuntimeZoneSnapshotCommit zone, long frameId, double deltaSeconds) { foreach (var pickup in zone.DroppedPickups ?? Array.Empty()) @@ -119,8 +303,11 @@ namespace GameCult.Aetheria.State.Verse double deltaSeconds, IAetheriaRuntimeWorldPhysics worldPhysics) { - var result = worldPhysics.Step(runId, frameId, simulationStepIndex, zone, entities, deltaSeconds); - var byIndex = entities.ToDictionary(entity => entity.EntityIndex); + var physicalEntities = entities + .Where(entity => entity.WormholeTransition == null) + .ToArray(); + var result = worldPhysics.Step(runId, frameId, simulationStepIndex, zone, physicalEntities, deltaSeconds); + var byIndex = physicalEntities.ToDictionary(entity => entity.EntityIndex); foreach (var body in result.Bodies) { if (!byIndex.TryGetValue(body.EntityIndex, out var entity)) continue; diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulationSettings.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulationSettings.cs index 32e7248b9..11c04c2bb 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulationSettings.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulationSettings.cs @@ -50,7 +50,12 @@ namespace GameCult.Aetheria.State.Verse agentRangeExponent: 0.25, agentForwardLerp: 0.5, agentMaxForwardDistance: 50, - agentDpsSampleCount: 32); + agentDpsSampleCount: 32, + wormholeAnimationDuration: 4, + wormholeExitCurveStart: 0.8, + wormholeExitVelocity: 20, + wormholeExitRadius: 50, + wormholeDepth: 1000); public AetheriaRuntimeDaemonSimulationSettings( double pawnSpeed, @@ -98,7 +103,12 @@ namespace GameCult.Aetheria.State.Verse double agentRangeExponent = AetheriaDefaultRaw.AgentRangeExponent, double agentForwardLerp = AetheriaDefaultRaw.AgentForwardLerp, double agentMaxForwardDistance = AetheriaDefaultRaw.AgentMaxForwardDistance, - int agentDpsSampleCount = AetheriaDefaultRaw.AgentDpsSampleCount) + int agentDpsSampleCount = AetheriaDefaultRaw.AgentDpsSampleCount, + double wormholeAnimationDuration = AetheriaDefaultRaw.WormholeAnimationDuration, + double wormholeExitCurveStart = AetheriaDefaultRaw.WormholeExitCurveStart, + double wormholeExitVelocity = AetheriaDefaultRaw.WormholeExitVelocity, + double wormholeExitRadius = AetheriaDefaultRaw.WormholeExitRadius, + double wormholeDepth = AetheriaDefaultRaw.WormholeDepth) { PawnSpeed = PositiveOr(pawnSpeed, AetheriaDefaultRaw.PawnSpeed); RaiderSpeed = PositiveOr(raiderSpeed, AetheriaDefaultRaw.RaiderSpeed); @@ -146,6 +156,11 @@ namespace GameCult.Aetheria.State.Verse AgentForwardLerp = Clamp01Or(agentForwardLerp, AetheriaDefaultRaw.AgentForwardLerp); AgentMaxForwardDistance = PositiveOr(agentMaxForwardDistance, AetheriaDefaultRaw.AgentMaxForwardDistance); AgentDpsSampleCount = agentDpsSampleCount > 0 ? agentDpsSampleCount : AetheriaDefaultRaw.AgentDpsSampleCount; + WormholeAnimationDuration = PositiveOr(wormholeAnimationDuration, AetheriaDefaultRaw.WormholeAnimationDuration); + WormholeExitCurveStart = Clamp01Or(wormholeExitCurveStart, AetheriaDefaultRaw.WormholeExitCurveStart); + WormholeExitVelocity = PositiveOr(wormholeExitVelocity, AetheriaDefaultRaw.WormholeExitVelocity); + WormholeExitRadius = PositiveOr(wormholeExitRadius, AetheriaDefaultRaw.WormholeExitRadius); + WormholeDepth = PositiveOr(wormholeDepth, AetheriaDefaultRaw.WormholeDepth); } public double PawnSpeed { get; } @@ -196,6 +211,11 @@ namespace GameCult.Aetheria.State.Verse public double AgentForwardLerp { get; } public double AgentMaxForwardDistance { get; } public int AgentDpsSampleCount { get; } + public double WormholeAnimationDuration { get; } + public double WormholeExitCurveStart { get; } + public double WormholeExitVelocity { get; } + public double WormholeExitRadius { get; } + public double WormholeDepth { get; } private static double PositiveOr(double value, double fallback) { @@ -260,6 +280,11 @@ namespace GameCult.Aetheria.State.Verse public const double AgentForwardLerp = 0.5; public const double AgentMaxForwardDistance = 50.0; public const int AgentDpsSampleCount = 32; + public const double WormholeAnimationDuration = 4.0; + public const double WormholeExitCurveStart = 0.8; + public const double WormholeExitVelocity = 20.0; + public const double WormholeExitRadius = 50.0; + public const double WormholeDepth = 1000.0; } } } diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs index 22f551940..d923afb5c 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs @@ -108,6 +108,7 @@ namespace GameCult.Aetheria.State.Verse options ??= new AetheriaRuntimeDaemonTickOptions(); options.OperationContext ??= new AetheriaRuntimeDaemonOperationContext(); options.OperationContext.Catalog = options.Catalog; + options.OperationContext.WormholeDistanceRatio = options.RenderSettings.WormholeDistanceRatio; var trace = string.Equals(Environment.GetEnvironmentVariable("AETHERIA_TRACE_TICK_PHASES"), "1", StringComparison.Ordinal); var phase = Stopwatch.StartNew(); void Trace(string name) diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeFlightSimulation.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeFlightSimulation.cs index f8ecca9e7..2e990418e 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeFlightSimulation.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeFlightSimulation.cs @@ -22,7 +22,7 @@ namespace GameCult.Aetheria.State.Verse return; var active = (entities ?? Array.Empty()) - .Where(entity => entity != null && entity.IsActive) + .Where(entity => entity != null && entity.IsActive && entity.WormholeTransition == null) .ToArray(); var byIndex = active.ToDictionary(entity => entity.EntityIndex); foreach (var movement in movements ?? Array.Empty()) diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameDocuments.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameDocuments.cs index d47751968..6e141a8b6 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameDocuments.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameDocuments.cs @@ -606,7 +606,18 @@ namespace GameCult.Aetheria.State.Verse Equipment = inventory.Where(item => string.Equals(item.Source, "equipment", StringComparison.Ordinal)).ToArray(), Cargo = inventory.Where(item => string.Equals(item.Source, "cargo", StringComparison.Ordinal)).ToArray(), ShutdownPerformance = entity?.ShutdownPerformance ?? 0, - Hud = CurrentEntityHudStatus(entity) + Hud = CurrentEntityHudStatus(entity), + WormholeTransition = entity?.WormholeTransition == null + ? null + : new AetheriaRuntimeWormholeTransitionView + { + TransitionId = entity.WormholeTransition.TransitionId, + Phase = entity.WormholeTransition.Phase, + Progress = entity.WormholeTransition.Progress, + SourceZoneIndex = entity.WormholeTransition.SourceZoneIndex, + TargetZoneIndex = entity.WormholeTransition.TargetZoneIndex, + VisualDepthOffset = entity.WormholeTransition.VisualDepthOffset + } }; } @@ -886,7 +897,8 @@ namespace GameCult.Aetheria.State.Verse var context = Context(frame); var run = context.Run; var zone = context.Zone; - var zoneRenderRadius = AetheriaRuntimeDaemonRenderQueries.ResolveZoneRenderRadius(zone, 2000); + var zoneRenderRadius = AetheriaRuntimeDaemonRenderQueries.ResolveZoneRenderRadius( + zone, AetheriaRuntimeDaemonRenderQueries.DefaultZoneRenderRadius); return new AetheriaRuntimeZoneRenderDocument { diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs index eea332a64..02bf73672 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs @@ -233,6 +233,20 @@ namespace GameCult.Aetheria.State.Verse [Key(14)] public AetheriaRuntimeCurrentEntityHudStatus Hud { get; set; } = new AetheriaRuntimeCurrentEntityHudStatus(); + + [Key(15)] + public AetheriaRuntimeWormholeTransitionView? WormholeTransition { get; set; } + } + + [MessagePackObject] + public sealed class AetheriaRuntimeWormholeTransitionView + { + [Key(0)] public string TransitionId { get; set; } = ""; + [Key(1)] public string Phase { get; set; } = ""; + [Key(2)] public double Progress { get; set; } + [Key(3)] public int SourceZoneIndex { get; set; } = -1; + [Key(4)] public int TargetZoneIndex { get; set; } = -1; + [Key(5)] public double VisualDepthOffset { get; set; } } [MessagePackObject] diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs index 51591c3b8..ed9ff70cd 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs @@ -1092,6 +1092,29 @@ namespace GameCult.Aetheria.State.Verse [Key(52)] public double HelmForward { get; set; } + + [Key(53)] + public AetheriaRuntimeWormholeTransitionCommit? WormholeTransition { get; set; } + } + + [MessagePackObject] + public sealed class AetheriaRuntimeWormholeTransitionCommit + { + [Key(0)] public string TransitionId { get; set; } = ""; + [Key(1)] public string Phase { get; set; } = ""; + [Key(2)] public double Progress { get; set; } + [Key(3)] public int SourceZoneIndex { get; set; } = -1; + [Key(4)] public int TargetZoneIndex { get; set; } = -1; + [Key(5)] public double EntryStartX { get; set; } + [Key(6)] public double EntryStartZ { get; set; } + [Key(7)] public double EntryWormholeX { get; set; } + [Key(8)] public double EntryWormholeZ { get; set; } + [Key(9)] public double ExitWormholeX { get; set; } + [Key(10)] public double ExitWormholeZ { get; set; } + [Key(11)] public double ExitVelocityX { get; set; } + [Key(12)] public double ExitVelocityZ { get; set; } + [Key(13)] public double VisualDepthOffset { get; set; } + [Key(14)] public long StartedFrameId { get; set; } = -1; } [MessagePackObject] diff --git a/docs/aetheria-perfect-machine-map.md b/docs/aetheria-perfect-machine-map.md index af531f148..a141654c2 100644 --- a/docs/aetheria-perfect-machine-map.md +++ b/docs/aetheria-perfect-machine-map.md @@ -1059,6 +1059,29 @@ projectile lead, hardpoint gating, progressive lock, and target destruction. thrust/turn feedback still require proof. +### Daemon Wormhole Transition + +- Owner: the daemon persists one wormhole transition on the moving entity. +- Inputs: actor identity, current and adjacent zones, canonical wormhole + positions, proximity, fixed simulation time, run seed, and the fossil timing + constants. +- Outputs: four-second `entering`, authoritative zone transfer, four-second + `exiting`, and one-frame `completed` state; deterministic exit pose/velocity; + destination-adjacency discovery; and stable start/transfer/completion events. +- Derived state: `VisualDepthOffset` is the fossil 1000-unit presentation lever. + Camera roll, corkscrew, fade, audio, and native effects may lower it but cannot + move the entity. +- Forbidden writers: `ActionGameManager`, `Ship.EnterWormhole`, client + transforms, and command-supplied positions cannot transfer a ship. +- Shared paths: player interact, explicit travel, agent task routing, and agent + homecoming all initialize the same canonical transition. +- Cut line: command application no longer splices zone arrays. Flight and the + world-physics port exclude transitioning bodies, and Ymir resumes only on the + tick after completion. +- Proof: daemon smoke serializes and rehydrates mid-entry, rejects a second + transition owner, verifies exact enter/transfer/exit timing and discovery, + and runs multi-edge task and home routes through the same boundary. + ### Flight Post-Processing Contract - Owner: Aetheria selects the logical flight profile and owns its native asset diff --git a/docs/original-game-migration-matrix.md b/docs/original-game-migration-matrix.md index d24ea8967..343b6a506 100644 --- a/docs/original-game-migration-matrix.md +++ b/docs/original-game-migration-matrix.md @@ -26,8 +26,9 @@ validation proves contract shape, not wiring, exclusivity, lowering, or parity. | Thermal/energy | cell conduction, capacitor/reactor/radiator network, and cockpit thermal exposure | daemon | ship/equipment power, temperature, medical state, risk and death feedback | schematic/post effects | owner-exists; wired; exclusive; projected; generic timing and native asset delivery lowered: catalog hull and installed-item shapes derive cell mass/conductivity/topology; local temperature derives thermal performance, wear potential and online state; all consumers share capacitor-first/reactor-residual transactions; powered radiators pump before reactor settlement; reactor heat then enters the same cell network before conduction/radiation; cockpit-cell temperature drives the fossil nonlinear heatstroke/hypothermia accumulation, linear recovery, severe-risk crossings, and ordinary exactly-once destruction with a typed cause; Eve exposes cockpit, risk, heatstroke source-weight, phasing and death-transition facts; EveUnity generically resolves the original severe pulse plus live/reconnect-safe cause-specific death crossfade; Aetheria deterministically translates the five legacy profiles into URP profiles, persists every override as a real profile sub-asset, advertises them by semantic role through CultMesh CDN, and binds them in the canonical client through a weight-only native sink; rotated equipment topology, parent/child radiation, schematic composition, legacy SSR/AO/roundness equivalents, and live/reconnect death-fade parity remain incomplete | multi-consumer ordering, multi-radiator visibility, rotated topology, generic schematic meters, renderer-feature parity, and live/reconnect death-fade screenshots | | Weapons | ServerShared behaviors + Unity effects | daemon plus Ymir geometry/kinematics | action capability, weapon state, shot/damage receipts | effects/audio/HUD | instant and constant resource/timing lifecycles are daemon-owned; charged weapons accept one semantic request, spool without requiring a solution, hold at full charge, commit automatically when a solution appears, and perform deterministic once-per-second malfunction hazard checks after the authored safe hold interval with increasing persisted risk; generic Eve `weapon.state` exposes charge hold/risk and feedback exposes readiness, commit, refusal, and malfunction chronology; committed direct damage now enters the shared daemon armor-cell transaction | guided persistent payloads, visibility/wear, remaining impact-distribution parity, and Unity effect reconciliation | | Destruction/drops | hull death, 25% equipment rolls, unconditional cargo drops, 25-unit launch, 30-second pickups | daemon | destruction identity, death/drop events, typed pickups | provider-advertised destruction effect and pickups | owner-exists; wired; exclusive; projected: direct and deployable lethal damage commit one deterministic destruction transaction, clear live references, retain only a non-rendered identity tombstone, and emit exact pickups/events; the reserved client `DestroyEntity` command is rejected; Aetheria advertises its original big explosion as `effect.feedback.entity.destroyed`, lowered generically by EveUnity | equipment-destruction-before-hull parity and multiplayer reconnect chronology | -| Tractor/scoop | analog tractor and physical timed pickups | daemon + Ymir | tractor power, pickup body and receipt | pickup world entity plus beam/interaction feedback | fossil 2/s power ramp and authored forward radius/traction/distance feed pickup bodies into the shared Ymir world; ship contact collects exactly once when capacity permits or applies the fossil 25-unit rejection kick; Aetheria maps pickup collision only against ship bodies, so stations and other world bodies cannot become cargo writers; 30s daemon lifetime; instant cargo teleport deleted; current-zone pickups occupy ordinary rows in the shared Eve entity SoA body with stable logical identity and provider-owned assets; `pilot.scoop` advertises a generic `button-hold.v1` scalar contract, the released client sends `1` on press and `0` on release through `SetTractorPower`, both receipts reconcile, and daemon power returns exactly to zero; the provider build removes the fossil's embedded tractor object from ship prefabs, and `beam.presentation` attaches the sole standalone effect to the SoA ship; the warm released witness proves one pickup becomes zero after one Ymir Begin fact, one `pickup.collected` event, and an exact cargo delta from `0` to `1`; capacity rejection publishes `cargo-capacity` and unchanged cargo through Eve in the daemon smoke | polish provider beam shape/attachment and add a released-client capacity-rejection scenario | +| Tractor/scoop | analog tractor and physical timed pickups | daemon + Ymir | tractor power, pickup body and receipt | pickup world entity plus beam/interaction feedback | fossil 2/s power ramp and authored forward radius/traction/distance feed pickup bodies into the shared Ymir world; ship contact collects exactly once when capacity permits or applies the fossil 25-unit rejection kick; Aetheria maps pickup collision only against ship bodies, so stations and other world bodies cannot become cargo writers; 30s daemon lifetime; instant cargo teleport deleted; current-zone pickups occupy ordinary rows in the shared Eve entity SoA body with stable logical identity and provider-owned assets; `pilot.scoop` advertises a generic `button-hold.v1` scalar contract, the released client sends `1` on press and `0` on release through `SetTractorPower`, both receipts reconcile, and daemon power returns exactly to zero; the provider build removes the fossil's embedded tractor object from ship prefabs, and `beam.presentation` attaches the sole standalone effect to the SoA ship; released warm witnesses prove successful exactly-once Ymir collection and controlled-player `cargo-capacity` rejection with unchanged cargo | polish provider beam shape/attachment | | Dock/undock | wormhole-first interact; first eligible bay; component prerequisites | daemon + Ymir placement | dock commands/context | camera/UI transition | live generic Unity witness now proves advertised dock/undock actions, daemon bay assignment, dock-parent inclusion in the SoA view, sharing of the dock parent's equipment-derived contact picture, generic camera retargeting, controlled-subject hiding, movement suppression, and restoration on undock; the starter station and local raider form a deterministic Terminus departure proof | restore fossil component-prerequisite rejection reasons, exact undock placement, wormhole priority, reconnect, and docked inventory/trade surfaces | +| Wormhole travel | `ActionGameManager.EnterWormhole` plus `Ship` enter/exit state | daemon fixed-step transition plus Ymir exclusion | current-entity transition state and feedback chronology | provider-selected generic transition lowering | command acceptance no longer moves an entity immediately; player interact, explicit travel, and agent routing derive the same canonical adjacent-zone wormhole and proximity gate, then persist four-second `entering`, authoritative transfer, four-second `exiting`, and one-frame `completed` phases. The daemon owns smootherstep XZ motion, the fossil 1000-unit visual-depth lever, deterministic 20-unit exit direction, 50-unit exit radius, target-adjacency discovery, and exactly-once start/transfer/completion events. Flight and every world-physics implementation receive no transitioning body; Ymir resumes on the tick after completion. Smoke serializes and rehydrates mid-entry and proves agents traverse multi-edge routes through the same command boundary | generic provider transition effect/camera lowering and live multi-zone pilot witness | | Inventory/equipment | inventory panels + ServerShared | daemon | inventory/equipment surfaces | generic UI | owner-exists; wired/projected in fragments; not proven | all transfer directions and rejection | | Trade | trade UI/economy | daemon | stock, quote, purchase commands | generic UI | daemon derives station, stock row, catalog item, current price, quantity, credits, target capacity, and hull-vs-cargo result; Eve advertises only currently available stock actions; generic Unity live witness receives an authoritative purchase receipt while paused | sell flow, quote expiry, contested stock, and full trade surface parity | | Action bar/input | input shell and rebinding UI | daemon advertises actions; client owns bindings | input capability and action descriptors | universal binding UI | contracts wired; cargo actions are catalog-filtered to consumables the current actor can actually activate, including suppression of active non-stackable items | dynamic equipment behavior validity and runtime action-bar quantity/fill proof | @@ -44,7 +45,7 @@ validation proves contract shape, not wiring, exclusivity, lowering, or parity. | Starbridge | original/shared architecture intent | one daemon session | pilot + commander surfaces | Unity + Electron | commander task board and autonomous explore execution wired; Electron Eve lowering and split-target proof missing | commander orders plus four pilots and autonomous workers | | Behavior engine | `ServerShared/Behaviors` composition | daemon | executable action/status projection | action bar and feedback | tick reconciles equipped catalog payloads into persistent behavior state; shared evaluated-stat query proven; execution families remain partial | every behavior family, ordering, resource transaction and modifier lifecycle | | Sensors/visibility | installed sensor sensitivity, decaying signature sources, and observer information thresholds | daemon | contacts and ping events | indicators/maps | passive reach derives from enabled installed Sensor behaviors with diminishing-return array composition regardless of entity kind; station-scale arrays are ordinary gear installed into larger hull-authored sensor hardpoints, with smaller same-type arrays remaining valid fallbacks; generation prefers the largest fitting footprint and contains no station/ship sensor-count branch; contact refresh no longer overwrites emitted visibility; docked craft consume one daemon-derived union of craft and dock-parent contacts through both Eve rows and SoA bodies, with sensor-source provenance; the old station range survives only as obsolete snapshot compatibility | prove shutdown, threshold decay, ping, classification timelines, and canonical catalog station-array data | -| AI/tasks | corporation task scheduler plus agent state machines | daemon | commander task board, corporation survey ledger, and shared semantic controls | Eve commander/pilot clients | point exploration, attack with optimum-range control, same-zone haul, mining/offload, resource surveying, physical station towing, persistent orbit patrol, route-aware assignment, and autonomous return home wired through shared commands; attack admission rejects missing/friendly targets and unavailable weapon groups before durable queueing; capability/priority assignment and rejection behavior proven; generic Electron commander lowering proves the worker roster | cross-zone logistics execution, cancellation, reconnect, and multi-client command transfer | +| AI/tasks | corporation task scheduler plus agent state machines | daemon | commander task board, corporation survey ledger, and shared semantic controls | Eve commander/pilot clients | point exploration, loadout-driven attack, haul, mining/offload, resource surveying, physical station towing, persistent orbit patrol, route-aware assignment, and autonomous return home are wired through shared commands. Combat samples the fossil DPS/range policy, selects live weapon groups, leads projectiles, strafes relative to target attitude, and gates fire on catalog placement rotation. Cross-zone task and home routes now survive the full daemon-owned wormhole timeline instead of instant transfer; attack admission rejects missing/friendly targets and unavailable weapon groups before durable queueing | cancellation, reconnect, multi-client command transfer, and model-local barrel-direction metadata | | Consumables | cargo-backed timed behavior containers | daemon | dynamic actions, active effects, and lifecycle facts | action bar/schematic | daemon atomically resolves typed metadata and concrete cargo, preserves consumed-instance quality, enforces authored stacking, evaluates effectiveness/quality, and executes ordered `EnergyDraw`, fossil-compatible no-op `Heat`, `ItemUsage`, and stateful `Cooldown` payloads after energy tick initialization; every effect and payload state has stable authored identity; cooldowns update before the ordered chain, require state strictly below zero, reset to one on success, and continue aging behind earlier failures; false and unsupported payloads stop later execution with a typed fact; timers retain the fossil's exact-zero final tick; Unity reconciles presentation by effect identity and cannot restore active behavior state by list index | catalog revision pinning, stat modifiers, remaining behavior families, and reconnect presentation proof | ## Ownership Invariants @@ -94,17 +95,19 @@ owner. These are source-confirmed ownership failures, not feature backlog: -1. **Physics delegation is incomplete.** Daemon projectile and entity-world - integration now use `Ymir.Core`, including radial fields and body contacts, - but tractor forces, docking placement, authored drive torque, and the Unity - bridge/query path still need full authority and parity proofs. -2. **Persisted behavior is not executable behavior.** Snapshot schemas preserve - broad equipment/behavior state while active simulation executes one - synthetic projectile weapon and simplified raider pursuit. +1. **Physics parity is incomplete.** Daemon entity, pickup, tractor, physical + payload, and wormhole-exclusion paths now use the embedded Ymir owner, but + docking/undocking placement and the Unity bridge/query path still need full + authority and parity proofs. +2. **Executable behavior coverage remains partial.** Snapshot schemas preserve + broad equipment/behavior state and the daemon executes the migrated weapon, + propulsion, energy, thermal, consumable, mining, survey, and agent families; + remaining catalog behavior families and exact execution order still need proof. 3. **Client feedback chronology is incomplete.** Pickup collection, rejection, expiry, projectile launch/impact, damage, and destruction now use a bounded - deduplicated daemon ledger projected through Eve, but lock transitions, - damage topology, thermal warnings, and docking effects still need event families. + deduplicated daemon ledger projected through Eve, including lock, damage, and + wormhole transition chronology; thermal warnings and docking effects still + need complete event families. 4. **View composition remains partial.** Pilot surfaces now exclude semantic render channels and runtime asset variants map those channels to native layers without leaking Unity masks into portable state. Entity presentation