diff --git a/Aetheria.State.Daemon.Smoke/Program.cs b/Aetheria.State.Daemon.Smoke/Program.cs index 4439146d3..bd4d772de 100644 --- a/Aetheria.State.Daemon.Smoke/Program.cs +++ b/Aetheria.State.Daemon.Smoke/Program.cs @@ -11,6 +11,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks public void Run() { YmirMovesProjectileAndReportsStableContact(); + InstantWeaponRequestSurvivesLockAcquisition(); ConstantWeaponRunsOnDaemonThroughYmirBeamContact(); ChargedWeaponCannotBypassChargeLifecycle(); ChargedWeaponHoldRiskMalfunctionsDeterministically(); @@ -83,7 +84,8 @@ internal sealed class AetheriaDaemonYmirSmokeChecks var run = new AetheriaRuntimeRunCheckpointCommit { RunId = "constant-weapon-smoke", CurrentZoneIndex = 0, - CurrentEntityKey = "zone.0.entity.0", Zones = [zone] + CurrentEntityKey = AetheriaRuntimeRunCheckpointCommit.EntityRecordKey("constant-weapon-smoke", 0, 0), + Zones = [zone] }; var payload = new AetheriaRuntimeBehaviorPayload(0, AetheriaRuntimeBehaviorKinds.ConstantWeapon, 0, [ @@ -139,10 +141,11 @@ internal sealed class AetheriaDaemonYmirSmokeChecks new AetheriaRuntimeDaemonFrameDocument { FrameId = 11, Run = run }, new AetheriaRuntimeDaemonHealthDocument(), AetheriaRuntimeDaemonCommandBoundaryDocument.Create("daemon")); - Require(Flatten(surface.Surface.Root).Any(node => node.Kind == "weapon.state" && + var weaponNodes = Flatten(surface.Surface.Root).Where(node => node.Kind == "weapon.state").ToArray(); + Require(weaponNodes.Any(node => node.Props["behaviorKind"] == AetheriaRuntimeBehaviorKinds.ConstantWeapon && node.Props["itemKey"] == "test-beam" && node.Props["firing"] == "false"), - "Eve world entity must project recoverable generic ConstantWeapon state"); + $"Eve world entity must project recoverable generic ConstantWeapon state; nodes={string.Join(";", weaponNodes.Select(node => string.Join(",", node.Props.Select(pair => $"{pair.Key}={pair.Value}"))))}"); Require(Flatten(surface.Surface.Root).Any(node => node.Kind == "feedback.event" && node.Props["eventKind"] == "weapon.firing.started" && node.Props["itemKey"] == "test-beam"), "Eve feedback stream must project continuous weapon transition chronology"); @@ -234,6 +237,63 @@ internal sealed class AetheriaDaemonYmirSmokeChecks "Eve feedback must expose charged solution commit chronology"); } + private static void InstantWeaponRequestSurvivesLockAcquisition() + { + var source = Entity(0, 0, "player"); + source.DirectionX = 1; + source.VelocityX = 1; + source.TargetEntityIndex = 1; + source.Contacts = [new AetheriaRuntimeEntityContactCommit + { + TargetEntityIndex = 1, InfoGathered = 1, Hostile = true, Visible = true + }]; + source.WeaponGroups = [new[] { 0 }]; + source.Equipment = [new AetheriaRuntimeLoadoutItemSlotCommit + { + Item = new AetheriaRuntimeLoadoutItemCommit + { ItemKey = "test-instant", Quality = 1, Durability = 1, Enabled = true } + }]; + var target = Entity(1, 80, "raider"); + var zone = new AetheriaRuntimeZoneSnapshotCommit { ZoneIndex = 0, Entities = [source, target] }; + var run = new AetheriaRuntimeRunCheckpointCommit + { + RunId = "instant-trigger-smoke", CurrentZoneIndex = 0, + CurrentEntityKey = "zone.0.entity.0", Zones = [zone] + }; + var payload = new AetheriaRuntimeBehaviorPayload(0, AetheriaRuntimeBehaviorKinds.InstantWeapon, 0, + [ + new AetheriaRuntimeBehaviorField(2, PerformanceStat(20)), + new AetheriaRuntimeBehaviorField(6, PerformanceStat(150)), + new AetheriaRuntimeBehaviorField(15, PerformanceStat(0)), + new AetheriaRuntimeBehaviorField(16, PerformanceStat(200)), + new AetheriaRuntimeBehaviorField(17, PerformanceStat(1)), + new AetheriaRuntimeBehaviorField(19, PerformanceStat(0.5)), + new AetheriaRuntimeBehaviorField(23, PerformanceStat(360)), + new AetheriaRuntimeBehaviorField(24, PerformanceStat(0)) + ]); + var catalog = new AetheriaRuntimeCatalogSnapshot([CatalogItem("test-instant", payload)], [], []); + var fire = new AetheriaRuntimeDaemonIntentState(); + fire.WeaponGroups.Add(new AetheriaRuntimeDaemonWeaponGroupIntent + { + ActorEntityKey = "zone.0.entity.0", WeaponGroup = 0, Fire = true, Active = true + }); + + AetheriaRuntimeDaemonSimulation.Step(run, fire, 0.1, + AetheriaRuntimeDaemonSimulationSettings.AetheriaDefault, new AetheriaYmirPhysicalPayloadPhysics(), + new AetheriaYmirWorldPhysics(), catalog, 0, 0); + for (var frame = 1; frame < 12 && run.ShotReceipts.Count == 0; frame++) + AetheriaRuntimeDaemonSimulation.Step(run, new AetheriaRuntimeDaemonIntentState(), 0.1, + AetheriaRuntimeDaemonSimulationSettings.AetheriaDefault, new AetheriaYmirPhysicalPayloadPhysics(), + new AetheriaYmirWorldPhysics(), catalog, frame, frame * 0.1); + + Require(run.ShotReceipts.Count == 1 && run.ShotReceipts[0].SourceEntityIndex == source.EntityIndex, + $"one instant weapon request must remain pending until daemon lock acquisition commits its shot; " + + $"receipts={run.ShotReceipts.Count}, direction={source.DirectionX},{source.DirectionY}, contacts={string.Join(";", (source.Contacts ?? []).Select(value => $"{value.TargetEntityIndex}:{value.InfoGathered}"))}, states={string.Join(";", (source.WeaponStates ?? []).Select(value => $"{value.BehaviorKind}:pending={value.TriggerPending}:lock={value.LockProgress}:target={value.LockTargetEntityIndex}:burst={value.BurstRemaining}"))}"); + var state = source.WeaponStates.Single(value => value.BehaviorKind == AetheriaRuntimeBehaviorKinds.InstantWeapon); + Require(!state.TriggerPending, + "instant weapon request must clear after the committed burst begins"); + } + private static void DeployableWeaponRunsThroughYmirAndDetonatesOnDaemon() { var source = Entity(0, 0, "player"); diff --git a/Aetheria.State.Daemon/AetheriaDaemonLoadoutGenerator.cs b/Aetheria.State.Daemon/AetheriaDaemonLoadoutGenerator.cs index a6c65c7c2..7bf2eb6f8 100644 --- a/Aetheria.State.Daemon/AetheriaDaemonLoadoutGenerator.cs +++ b/Aetheria.State.Daemon/AetheriaDaemonLoadoutGenerator.cs @@ -74,6 +74,8 @@ public sealed class AetheriaDaemonLoadoutGenerator var cargoBay = AddFreeSpaceItem(hull, availabilityFactionKey, occupied, slots, 3, item => string.Equals(item.Category, AetheriaRuntimeItemCategories.CargoBay, StringComparison.Ordinal)); + AddFreeSpaceItem(hull, availabilityFactionKey, occupied, slots, 2, item => + IsGear(item) && HasBehavior(item, "Reactor")); AddFreeSpaceItem(hull, availabilityFactionKey, occupied, slots, 2, item => IsGear(item) && HasBehavior(item, "Capacitor")); @@ -90,7 +92,16 @@ public sealed class AetheriaDaemonLoadoutGenerator PriceExponent = _priceExponent, Selections = selectedKeys.Select(value => Selection(value.Role, value.Key, availabilityFactionKey)).ToArray() }; - return new AetheriaDaemonLoadout(hull.ItemKey, slots.ToArray(), cargo, receipt); + var equipment = slots.ToArray(); + var defaultWeaponGroup = equipment + .Select((slot, index) => (slot, index)) + .Where(value => IsWeapon(_catalog.FindItem(value.slot.ItemKey))) + .Select(value => value.index) + .ToArray(); + var weaponGroups = defaultWeaponGroup.Length == 0 + ? Array.Empty() + : new[] { defaultWeaponGroup }; + return new AetheriaDaemonLoadout(hull.ItemKey, equipment, cargo, weaponGroups, receipt); } private AetheriaLoadoutGenerationSelection Selection(string role, string itemKey, string factionKey) @@ -327,6 +338,12 @@ public sealed class AetheriaDaemonLoadoutGenerator string.Equals(item.Category, AetheriaRuntimeItemCategories.Gear, StringComparison.Ordinal) || string.Equals(item.Category, AetheriaRuntimeItemCategories.Weapon, StringComparison.Ordinal); + private static bool IsWeapon(AetheriaRuntimeCatalogItem? item) => + item != null && + (string.Equals(item.Category, AetheriaRuntimeItemCategories.Weapon, StringComparison.Ordinal) || + (item.BehaviorKinds ?? Array.Empty()).Any(kind => + kind.Contains("Weapon", StringComparison.Ordinal))); + private static AetheriaEntityItemSlot Slot(int x, int y, string itemKey) => new() { Position = new AetheriaGridCoord { X = x, Y = y }, ItemKey = itemKey, @@ -347,4 +364,5 @@ public sealed record AetheriaDaemonLoadout( string HullItemKey, AetheriaEntityItemSlot[] Equipment, AetheriaLoadoutItemSlot[] Cargo, + int[][] WeaponGroups, AetheriaLoadoutGenerationReceipt Receipt); diff --git a/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs b/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs index 3754300d8..a8bbcc580 100644 --- a/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs +++ b/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs @@ -211,10 +211,10 @@ internal static class AetheriaDaemonZoneGenerator Entity(loadouts, availabilityFactions, "Torch Three", "ship", -235, 210, 8, -4, "player", 500, keys[7], [keys[0], keys[1], keys[7]], ["micro-missile", "coolant-pack"]), Entity(loadouts, availabilityFactions, "Foundry Tug", "ship", 330, -155, -2, 3, "player", 390, keys[6], [keys[0], keys[1], keys[6], keys[10]], ["ore-canister", "field-rations"]), Entity(loadouts, availabilityFactions, "Derelict Relay", "station", -390, 270, 0, 0, "neutral", 160, "", [keys[0], keys[3]], ["ancient-transponder"]), - Entity(loadouts, availabilityFactions, "Ash Raider", "ship", 455, 180, -5, -2, "raider", 320, keys[1], [keys[0], keys[1], keys[2], keys[4]], ["scrap-metal", "stolen-capacitor"]), - Entity(loadouts, availabilityFactions, "Cinder Knife", "ship", 585, -115, -7, 1, "raider", 280, keys[3], [keys[0], keys[3]], ["volatile-fuel"]), - Entity(loadouts, availabilityFactions, "Blackwake", "ship", 690, 300, -4, -3, "raider", 230, keys[2], [keys[2]], ["ore-cache", "burned-relay-core"]), - Entity(loadouts, availabilityFactions, "Vesper Sloop", "ship", 960, 620, -3, -5, "raider", 250, keys[4], [keys[4]], ["stolen-map-fragment"]), + Entity(loadouts, availabilityFactions, "Ash Raider", "ship", 100, -30, -5, -2, "raider", 320, "", [keys[0], keys[1], keys[2], keys[4]], ["scrap-metal", "stolen-capacitor"]), + Entity(loadouts, availabilityFactions, "Cinder Knife", "ship", 585, -115, -7, 1, "raider", 280, "", [keys[0], keys[3]], ["volatile-fuel"]), + Entity(loadouts, availabilityFactions, "Blackwake", "ship", 690, 300, -4, -3, "raider", 230, "", [keys[2]], ["ore-cache", "burned-relay-core"]), + Entity(loadouts, availabilityFactions, "Vesper Sloop", "ship", 960, 620, -3, -5, "raider", 250, "", [keys[4]], ["stolen-map-fragment"]), Entity(loadouts, availabilityFactions, "Survey Skiff", "ship", -610, -365, 3, 5, "neutral", 210, "", [keys[4], keys[5]], ["soil-sample", "deep-scan"]), Entity(loadouts, availabilityFactions, "Lagrange Beacon", "station", 105, 510, 0, 0, "neutral", 190, "", [keys[0], keys[1], keys[6]], ["navigation-key"]) }; @@ -272,6 +272,9 @@ internal static class AetheriaDaemonZoneGenerator StatGrid("heat", 0) ], Equipment = loadout.Equipment, + WeaponGroups = loadout.WeaponGroups + .Select(indices => new AetheriaWeaponGroupSnapshot { EquipmentIndices = indices }) + .ToArray(), CargoContents = [ new AetheriaCargoBayLoadout diff --git a/Aetheria.State.Daemon/Program.cs b/Aetheria.State.Daemon/Program.cs index 8932668d4..e8efd6c04 100644 --- a/Aetheria.State.Daemon/Program.cs +++ b/Aetheria.State.Daemon/Program.cs @@ -8,6 +8,7 @@ using GameCult.Mesh; using GameCult.Networking; using MessagePack; using System.Globalization; +using System.Diagnostics; using System.Net; using System.Net.Sockets; @@ -50,7 +51,8 @@ using var clientSubscriptions = new CultNetDatabaseSubscriptionServer(cultMeshRu using var clientPumpCancellation = new CancellationTokenSource(); var clientPump = RunClientCultMeshPumpAsync(cultMeshRudpHost, clientPumpCancellation.Token); var nextApiPublicationUtc = DateTimeOffset.UtcNow; -var firstTick = await TickAsync(node, options, physicalPayloadPhysics, worldPhysics, latestFrame, buildPublications: true).ConfigureAwait(false); +var ingressState = new AetheriaDaemonIngressState(); +var firstTick = await TickAsync(node, options, physicalPayloadPhysics, worldPhysics, latestFrame, ingressState, buildPublications: true).ConfigureAwait(false); ThrowIfClientPumpFaulted(clientPump); latestFrame = firstTick.Frame; nextApiPublicationUtc = DateTimeOffset.UtcNow.Add(options.ApiPublicationInterval); @@ -75,6 +77,7 @@ await PublishRuntimeSessionAsync(node, options, startedAtUtc, "running").Configu Console.WriteLine("Aetheria Verse daemon is running. Press Ctrl+C to stop."); var nextTickUtc = DateTimeOffset.UtcNow.Add(options.TickInterval); +Task publicationTask = Task.CompletedTask; while (!stopped.Task.IsCompleted) { ThrowIfClientPumpFaulted(clientPump); @@ -87,17 +90,19 @@ while (!stopped.Task.IsCompleted) } var buildPublications = DateTimeOffset.UtcNow >= nextApiPublicationUtc; - var tick = await TickAsync(node, options, physicalPayloadPhysics, worldPhysics, latestFrame, buildPublications).ConfigureAwait(false); + var tick = await TickAsync(node, options, physicalPayloadPhysics, worldPhysics, latestFrame, ingressState, buildPublications: false).ConfigureAwait(false); ThrowIfClientPumpFaulted(clientPump); latestFrame = tick.Frame; nextTickUtc += options.TickInterval; if (nextTickUtc < DateTimeOffset.UtcNow - options.TickInterval) nextTickUtc = DateTimeOffset.UtcNow; - if (buildPublications) + if (buildPublications && publicationTask.IsCompleted) { + if (publicationTask.IsFaulted) + await publicationTask.ConfigureAwait(false); + var publication = PreparePublication(node.StatePath, options, tick, ingressState); + publicationTask = PublishPreparedDocumentsAsync(node, options, publication); nextApiPublicationUtc = DateTimeOffset.UtcNow.Add(options.ApiPublicationInterval); - discoveryHost.Update(await node.MutableDocument(AetheriaStateNode.VerseHostSettingsKey).ReadAsync().ConfigureAwait(false)); - await PublishRuntimeSessionAsync(node, options, startedAtUtc, "running").ConfigureAwait(false); } if (tick.Frame.FrameId % (traceClientRudp ? 10 : 120) == 0) { @@ -109,6 +114,7 @@ while (!stopped.Task.IsCompleted) } await PublishRuntimeSessionAsync(node, options, startedAtUtc, "stopping").ConfigureAwait(false); +await publicationTask.ConfigureAwait(false); clientPumpCancellation.Cancel(); await clientPump.ConfigureAwait(false); Console.WriteLine("Aetheria Verse daemon stopping."); @@ -130,12 +136,32 @@ static async Task TickAsync( IAetheriaRuntimePhysicalPayloadPhysics physicalPayloadPhysics, IAetheriaRuntimeWorldPhysics worldPhysics, AetheriaRuntimeDaemonFrameDocument? currentFrame, + AetheriaDaemonIngressState ingressState, bool buildPublications) { + var traceTickPhases = string.Equals( + Environment.GetEnvironmentVariable("AETHERIA_TRACE_TICK_PHASES"), + "1", + StringComparison.Ordinal); + var phase = Stopwatch.StartNew(); + void TracePhase(string name) + { + if (traceTickPhases && phase.ElapsedMilliseconds >= 20) + Console.WriteLine($"Aetheria tick phase {name} took {phase.ElapsedMilliseconds}ms."); + phase.Restart(); + } + await AcceptCoreEveInvocationsAsync(node, options, currentFrame).ConfigureAwait(false); - await AcceptEveCommandsAsync(node, options).ConfigureAwait(false); + TracePhase("core-ingress"); + await AcceptEveCommandsAsync(node, options, ingressState).ConfigureAwait(false); + TracePhase("provider-ingress"); if (await ApplyRequestedTerminusSessionAsync(node, options).ConfigureAwait(false)) + { currentFrame = null; + ingressState.ControlPlaneInitialized = false; + } + if (!ingressState.ControlPlaneInitialized || buildPublications) + await RefreshControlPlaneInputsAsync(node, ingressState).ConfigureAwait(false); var fixedDeltaSeconds = currentFrame?.FixedDeltaSeconds > 0 ? currentFrame.FixedDeltaSeconds @@ -150,10 +176,7 @@ static async Task TickAsync( : await ReadRuntimeRunCheckpointAsync(node, options.RenderSettings).ConfigureAwait(false) ?? new AetheriaRuntimeRunCheckpointCommit(); ApplyDaemonRenderSettings(run, options.RenderSettings); - var loadoutTemplates = node.Cache - .GetAll() - .Select(ToLoadoutTemplateCommit) - .ToArray(); + var loadoutTemplates = ingressState.LoadoutTemplates; var observedCommands = node.Documents() .OrderBy(command => command.IssuedAtUtc ?? "", StringComparer.Ordinal) .ThenBy(command => command.CommandId ?? "", StringComparer.Ordinal) @@ -165,16 +188,17 @@ static async Task TickAsync( .Where(command => command != null && !accountedCommandIds.Contains(command.CommandId ?? "")) .ToArray(); var policyRejectedCommandIds = new List(); - var authorityPolicy = await node.MutableDocument(AetheriaRuntimeVerseRecordKeys.VerseAuthorityPolicy).ReadAsync().ConfigureAwait(false); - var starbridgeScenario = await node.MutableDocument(AetheriaRuntimeVerseRecordKeys.StarbridgeScenarioLatest).ReadAsync().ConfigureAwait(false); - var starbridgeSession = await node.MutableDocument(AetheriaRuntimeVerseRecordKeys.StarbridgeSessionLatest).ReadAsync().ConfigureAwait(false); - var authorityLeases = node.Documents(); + var authorityPolicy = ingressState.AuthorityPolicy; + var starbridgeScenario = ingressState.StarbridgeScenario; + var starbridgeSession = ingressState.StarbridgeSession; + var authorityLeases = ingressState.AuthorityLeases; var authorizedCommands = AetheriaRuntimeAuthorityRouter.AuthorizedCommands( pendingObservedCommands, authorityPolicy, authorityLeases, options.DaemonId, policyRejectedCommandIds); + TracePhase("tick-inputs"); var result = AetheriaRuntimeDaemonTickRunner.Tick( node.StatePath, @@ -193,7 +217,7 @@ static async Task TickAsync( PreRejectedCommandIds = policyRejectedCommandIds, CumulativeAppliedCommandIds = currentFrame?.CumulativeAppliedCommandIds ?? currentFrame?.AppliedCommandIds ?? Array.Empty(), CumulativeRejectedCommandIds = currentFrame?.CumulativeRejectedCommandIds ?? currentFrame?.RejectedCommandIds ?? Array.Empty(), - Catalog = node.RuntimeCatalog().Latest(), + Catalog = ingressState.Catalog, RenderSettings = options.RenderSettings, SimulationSettings = options.SimulationSettings, PhysicalPayloadPhysics = physicalPayloadPhysics, @@ -206,6 +230,7 @@ static async Task TickAsync( LoadoutTemplates = loadoutTemplates } }); + TracePhase("simulation"); if (string.Equals(Environment.GetEnvironmentVariable("AETHERIA_TRACE_EVE_SNAPSHOTS"), "1", StringComparison.Ordinal) && result.Frame.AppliedCommandIds.Count > 0) { @@ -230,17 +255,83 @@ static async Task TickAsync( pendingObservedCommands, authorizedCommands, policyRejectedCommandIds).ConfigureAwait(false); + TracePhase("command-facts"); if (buildPublications) { await PublishDaemonApiDocumentsAsync(node, options, result).ConfigureAwait(false); + TracePhase("api-publication"); await PublishStateSurfacesAsync(node, options, result.Frame.PublishedAtUtc).ConfigureAwait(false); + TracePhase("state-surfaces"); await PublishOdinSurfaceAnnouncementsAsync(node, options, result.Frame.PublishedAtUtc).ConfigureAwait(false); + TracePhase("odin-announcements"); } return result; } +static AetheriaRuntimeDaemonTickResult PreparePublication( + string statePath, + AetheriaDaemonHostOptions options, + AetheriaRuntimeDaemonTickResult tick, + AetheriaDaemonIngressState ingressState) +{ + var frameBytes = MessagePackSerializer.Serialize(tick.Frame); + var frame = MessagePackSerializer.Deserialize(frameBytes); + var operation = new AetheriaRuntimeDaemonOperationResult( + frame.Run ?? new AetheriaRuntimeRunCheckpointCommit(), + tick.OperationResult.AppliedCommandIds.ToArray(), + tick.OperationResult.RejectedCommandIds.ToArray()); + return AetheriaRuntimeDaemonTickRunner.BuildPublications( + statePath, + operation, + frame, + new AetheriaRuntimeDaemonTickOptions + { + DaemonId = options.DaemonId, + VerseId = options.VerseId, + CultMeshAddress = options.CultMeshAddress, + Catalog = ingressState.Catalog, + StarbridgeScenario = ingressState.StarbridgeScenario, + StarbridgeSession = ingressState.StarbridgeSession, + RenderSettings = options.RenderSettings, + SimulationSettings = options.SimulationSettings + }, + frame.AccountedCommandIds?.Count ?? 0); +} + +static async Task PublishPreparedDocumentsAsync( + AetheriaStateNode node, + AetheriaDaemonHostOptions options, + AetheriaRuntimeDaemonTickResult publication) +{ + await PublishDaemonApiDocumentsAsync(node, options, publication).ConfigureAwait(false); + await PublishStateSurfacesAsync(node, options, publication.Frame.PublishedAtUtc).ConfigureAwait(false); + await PublishOdinSurfaceAnnouncementsAsync(node, options, publication.Frame.PublishedAtUtc).ConfigureAwait(false); +} + +static async Task RefreshControlPlaneInputsAsync( + AetheriaStateNode node, + AetheriaDaemonIngressState ingressState) +{ + ingressState.LoadoutTemplates = node.Cache + .GetAll() + .Select(ToLoadoutTemplateCommit) + .ToArray(); + ingressState.Catalog = node.RuntimeCatalog().Latest(); + ingressState.AuthorityPolicy = await node + .MutableDocument(AetheriaRuntimeVerseRecordKeys.VerseAuthorityPolicy) + .ReadAsync().ConfigureAwait(false); + ingressState.StarbridgeScenario = await node + .MutableDocument(AetheriaRuntimeVerseRecordKeys.StarbridgeScenarioLatest) + .ReadAsync().ConfigureAwait(false); + ingressState.StarbridgeSession = await node + .MutableDocument(AetheriaRuntimeVerseRecordKeys.StarbridgeSessionLatest) + .ReadAsync().ConfigureAwait(false); + ingressState.AuthorityLeases = node.Documents().ToArray(); + ingressState.ControlPlaneInitialized = true; +} + static async Task PublishCommittedCommandFactsAsync( AetheriaStateNode node, AetheriaDaemonHostOptions options, @@ -1774,9 +1865,15 @@ static async Task AcceptCoreEveInvocationsAsync( } } -static async Task AcceptEveCommandsAsync(AetheriaStateNode node, AetheriaDaemonHostOptions options) +static async Task AcceptEveCommandsAsync( + AetheriaStateNode node, + AetheriaDaemonHostOptions options, + AetheriaDaemonIngressState ingressState) { var commandCountBefore = node.Documents().Count; + if (commandCountBefore == ingressState.ObservedEveCommandCount) + return; + ingressState.ObservedEveCommandCount = commandCountBefore; var now = DateTimeOffset.UtcNow.ToString("O"); try { @@ -2956,6 +3053,18 @@ static AetheriaRuntimeLoadoutItemCommit ToLoadoutItemCommit(AetheriaLoadoutItem? }; } +internal sealed class AetheriaDaemonIngressState +{ + public int ObservedEveCommandCount { get; set; } = -1; + public bool ControlPlaneInitialized { get; set; } + public AetheriaRuntimeLoadoutTemplateCommit[] LoadoutTemplates { get; set; } = []; + public AetheriaRuntimeCatalogSnapshot? Catalog { get; set; } + public AetheriaRuntimeVerseAuthorityPolicyDocument? AuthorityPolicy { get; set; } + public AetheriaRuntimeStarbridgeScenarioDocument? StarbridgeScenario { get; set; } + public AetheriaRuntimeStarbridgeSessionDocument? StarbridgeSession { get; set; } + public AetheriaRuntimeAuthorityLeaseDocument[] AuthorityLeases { get; set; } = []; +} + internal sealed class AetheriaDaemonHostOptions { public string StatePath { get; init; } = ""; diff --git a/Aetheria.State.Smoke/Program.cs b/Aetheria.State.Smoke/Program.cs index 1230f5768..49c08551a 100644 --- a/Aetheria.State.Smoke/Program.cs +++ b/Aetheria.State.Smoke/Program.cs @@ -891,4 +891,39 @@ await using (var reopened = await AetheriaStateNode.OpenAsync(statePath, "aether } } +var capabilityRun = new AetheriaRuntimeRunCheckpointCommit +{ + RunId = "capability-smoke", + CurrentZoneIndex = 0, + CurrentEntityKey = AetheriaRuntimeRunCheckpointCommit.EntityRecordKey("capability-smoke", 0, 7), + Zones = + [ + new AetheriaRuntimeZoneSnapshotCommit + { + ZoneIndex = 0, + Entities = + [ + new AetheriaRuntimeEntitySnapshotCommit + { + EntityIndex = 7, + EntityId = AetheriaRuntimeRunCheckpointCommit.EntityRecordKey("capability-smoke", 0, 7), + WeaponGroups = [new[] { 2 }] + } + ] + } + ] +}; +var capability = AetheriaRuntimeInputCapabilityDocument.FromFrame(new AetheriaRuntimeDaemonFrameDocument +{ + FrameId = 12, + Run = capabilityRun +}).ToEveDocument(); +var advertisedActionIds = capability.Actions.Select(action => action.ActionId).ToHashSet(StringComparer.Ordinal); +if (!advertisedActionIds.Contains("weapon-group.0.fire") || + capability.DefaultProfiles.SelectMany(profile => profile.Bindings) + .Any(binding => !advertisedActionIds.Contains(binding.ActionId))) +{ + throw new InvalidOperationException("Portable Eve input capability did not preserve weapon groups and valid default bindings."); +} + Console.WriteLine($"Aetheria typed state smoke passed: {statePath}"); diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonGameSurfaceBuilder.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonGameSurfaceBuilder.cs index 55b089645..0483b01eb 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonGameSurfaceBuilder.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonGameSurfaceBuilder.cs @@ -91,6 +91,12 @@ namespace GameCult.Aetheria.State.Verse CommandButton("aetheria.daemon.game.commands.undock", "Undock", AetheriaRuntimeDaemonCommandKinds.Undock), CommandButton("aetheria.daemon.game.commands.ping", "Sensor Ping", AetheriaRuntimeDaemonCommandKinds.SensorPing))) }; + if (entity != null) + surfaceChildren.Add(Node( + "aetheria.daemon.game.weapon-state", + "state.group", + Array.Empty<(string Key, string Value)>(), + WeaponStateItems(entity, run, zone))); return new AetheriaRuntimeSurfaceDocument( providerId: "aetheria.daemon", @@ -765,6 +771,7 @@ namespace GameCult.Aetheria.State.Verse ("behaviorKind", value.BehaviorKind), ("itemKey", itemKey), ("firing", value.Firing ? "true" : "false"), + ("triggerPending", value.TriggerPending ? "true" : "false"), ("ammo", value.Ammo.ToString(CultureInfo.InvariantCulture)), ("ammoIntervalProgress", FormatNumber(value.AmmoIntervalProgress)), ("burstRemaining", value.BurstRemaining.ToString(CultureInfo.InvariantCulture)), diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs index 5552f9f9b..8c9145c5c 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs @@ -56,8 +56,6 @@ namespace GameCult.Aetheria.State.Verse foreach (var movement in intents?.Movements ?? Enumerable.Empty()) ApplyMovementIntent(run, entities, movement, settings); StepTractorPower(entities, deltaSeconds); - StepRaiderAi(entities); - StepTargetPursuit(entities, settings); var worldStep = StepWorldPhysics(zone, entities, deltaSeconds, worldPhysics); ResolvePickupContacts(run, zone, entities, worldStep, catalog, frameId); StepCombat(run, zone, entities, intents, deltaSeconds, settings, physicalPayloadPhysics, catalog, @@ -114,62 +112,6 @@ namespace GameCult.Aetheria.State.Verse Face(entity, normalized.X, normalized.Y); } - private static void StepRaiderAi(IReadOnlyList entities) - { - foreach (var raider in entities.Where(entity => string.Equals(entity.FactionKey, "raider", StringComparison.OrdinalIgnoreCase))) - { - if (!IsAlive(raider)) - continue; - - var target = entities - .Where(IsPlayerOwned) - .Where(IsAlive) - .OrderBy(candidate => DistanceSq(raider, candidate)) - .FirstOrDefault(); - if (target == null) - continue; - - raider.TargetEntityIndex = target.EntityIndex; - } - } - - private static void StepTargetPursuit( - IReadOnlyList entities, - AetheriaRuntimeDaemonSimulationSettings settings) - { - var byIndex = entities.ToDictionary(entity => entity.EntityIndex); - foreach (var entity in entities) - { - if (!IsAlive(entity) || - entity.TargetEntityIndex < 0 || - !byIndex.TryGetValue(entity.TargetEntityIndex, out var target) || - !IsAlive(target)) - { - continue; - } - - var dx = target.PositionX - entity.PositionX; - var dy = target.PositionZ - entity.PositionZ; - var distance = Math.Sqrt(dx * dx + dy * dy); - if (distance <= settings.AttackRange * settings.AttackHoldRatio) - { - entity.VelocityX *= 0.72; - entity.VelocityY *= 0.72; - Face(entity, dx, dy); - continue; - } - - if (string.Equals(entity.FactionKey, "raider", StringComparison.OrdinalIgnoreCase)) - { - var direction = Normalize(dx, dy); - var speed = ResolveSpeed(entity, settings); - entity.VelocityX = direction.X * speed; - entity.VelocityY = direction.Y * speed; - Face(entity, direction.X, direction.Y); - } - } - } - private static AetheriaRuntimeWorldStep StepWorldPhysics( AetheriaRuntimeZoneSnapshotCommit zone, IReadOnlyList entities, @@ -260,6 +202,8 @@ namespace GameCult.Aetheria.State.Verse foreach (var weapon in weapons) { weapon.State.Firing = false; + if (weaponGroup >= 0) + weapon.State.TriggerPending = true; if (weapon.State.Reloading) { weapon.State.ReloadProgress = Math.Max(0, weapon.State.ReloadProgress - deltaSeconds); @@ -284,18 +228,21 @@ namespace GameCult.Aetheria.State.Verse { weapon.State.LockTargetEntityIndex = -1; weapon.State.LockProgress = 0; + weapon.State.TriggerPending = false; } continue; } - if (IsPlayerOwned(attacker) && weaponGroup < 0) - continue; - foreach (var weapon in weapons) { UpdateWeaponLock(attacker, target, weapon, deltaSeconds, settings); - if (DistanceSq(attacker, target) > weapon.Range * weapon.Range || - weapon.State.LockProgress <= 0.99 || + if (DistanceSq(attacker, target) > weapon.Range * weapon.Range) + { + weapon.State.LastRefusalReason = "out-of-range"; + weapon.State.TriggerPending = false; + continue; + } + if (weapon.State.LockProgress <= 0.99 || weapon.State.Reloading) continue; @@ -309,7 +256,11 @@ namespace GameCult.Aetheria.State.Verse if (triggerResult == WeaponRoundResult.ReloadStarted) AppendWeaponEvent(run, zone, attacker, weapon, frameId, "weapon.reload.started"); PublishWeaponRoundResult(run, zone, attacker, weapon, frameId, triggerResult); - if (triggerResult != WeaponRoundResult.Fired) continue; + if (triggerResult != WeaponRoundResult.Fired) + { + weapon.State.TriggerPending = false; + continue; + } } weapon.State.BurstRemaining = weapon.BurstCount; weapon.State.BurstInterval = weapon.BurstTime / weapon.BurstCount; @@ -339,6 +290,7 @@ namespace GameCult.Aetheria.State.Verse CommitShotResolution(run, zone, attacker, target, weapon, shotId, frameId, catalog, settings); AppendShotCommittedEvent(run, zone, attacker, target, weapon, shotId, frameId); weapon.State.Firing = true; + weapon.State.TriggerPending = false; AetheriaRuntimeThermalSimulation.AddHeatToEquipment(attacker, catalog, weapon.State.OwnerIndex, weapon.Heat); ApplyWeaponWear(attacker, weapon.State, 1); @@ -1439,8 +1391,10 @@ namespace GameCult.Aetheria.State.Verse var authored = AetheriaRuntimeEquippedBehaviorQueries.Find(entity, catalog, AetheriaRuntimeBehaviorKinds.InstantWeapon) .Where(behavior => !string.Equals(behavior.Payload.Kind, AetheriaRuntimeBehaviorKinds.ChargedWeapon, StringComparison.Ordinal)) .Where(behavior => !string.Equals(behavior.Payload.Kind, AetheriaRuntimeBehaviorKinds.DeployableWeapon, StringComparison.Ordinal)) - .Where(behavior => equipmentIndices.Contains(behavior.EquipmentIndex)) .Select(behavior => ResolveAuthoredWeapon(entity, behavior, settings)) + .Where(weapon => weaponGroup >= 0 + ? equipmentIndices.Contains(weapon.State.OwnerIndex) + : weapon.State.TriggerPending || weapon.State.BurstRemaining > 0) .ToArray(); if (catalog != null) return authored; diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs index 519ce1e33..21eb2456b 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; #nullable enable @@ -105,8 +106,17 @@ namespace GameCult.Aetheria.State.Verse options ??= new AetheriaRuntimeDaemonTickOptions(); options.OperationContext ??= new AetheriaRuntimeDaemonOperationContext(); options.OperationContext.Catalog = options.Catalog; + var trace = string.Equals(Environment.GetEnvironmentVariable("AETHERIA_TRACE_TICK_PHASES"), "1", StringComparison.Ordinal); + var phase = Stopwatch.StartNew(); + void Trace(string name) + { + if (trace && phase.ElapsedMilliseconds >= 20) + Console.WriteLine($"Aetheria simulation phase {name} took {phase.ElapsedMilliseconds}ms."); + phase.Restart(); + } EnsureEntityIds(run); EnsureBehaviorStates(run, options.Catalog); + Trace("state-projection"); var observedCommands = (options.ObservedCommands ?? Array.Empty()) .Where(command => command != null) @@ -122,6 +132,7 @@ namespace GameCult.Aetheria.State.Verse run, commands, options.OperationContext); + Trace("command-execution"); var preRejectedCommandIds = (options.PreRejectedCommandIds ?? Array.Empty()) .Where(commandId => !string.IsNullOrWhiteSpace(commandId)) .Distinct(StringComparer.Ordinal) @@ -142,6 +153,7 @@ namespace GameCult.Aetheria.State.Verse options.FrameId, options.Catalog, options.SimulationTimeSeconds); + Trace("agent-planning"); if (agentCommands.Count > 0) { var agentResult = AetheriaRuntimeDaemonOperations.Execute( @@ -157,7 +169,7 @@ namespace GameCult.Aetheria.State.Verse agentResult.Run, operationResult.AppliedCommandIds.Concat(agentResult.AppliedCommandIds).ToArray(), operationResult.RejectedCommandIds.Concat(agentResult.RejectedCommandIds).ToArray(), - agentResult.Intents); + MergeIntents(operationResult.Intents, agentResult.Intents)); } AetheriaRuntimeDaemonSimulation.Step( operationResult.Run, @@ -169,6 +181,7 @@ namespace GameCult.Aetheria.State.Verse options.Catalog, options.FrameId, options.SimulationTimeSeconds); + Trace("world-step"); StampZoneSimulationTime(operationResult.Run, options.SimulationTimeSeconds); var frame = AetheriaRuntimeDaemonFrameDocument.Create( @@ -180,6 +193,7 @@ namespace GameCult.Aetheria.State.Verse options.FixedDeltaSeconds, renderSettings: options.RenderSettings, simulationSettings: options.SimulationSettings); + Trace("frame-projection"); frame.AppliedCommandIds = operationResult.AppliedCommandIds; frame.RejectedCommandIds = operationResult.RejectedCommandIds; frame.AccountedCommandIds = accountedBeforeTick @@ -220,6 +234,16 @@ namespace GameCult.Aetheria.State.Verse frame); } + return BuildPublications(stateFilePath, operationResult, frame, options, observedCommands.Length); + } + + public static AetheriaRuntimeDaemonTickResult BuildPublications( + string stateFilePath, + AetheriaRuntimeDaemonOperationResult operationResult, + AetheriaRuntimeDaemonFrameDocument frame, + AetheriaRuntimeDaemonTickOptions options, + int observedCommandCount) + { var soaView = AetheriaRuntimeDaemonSoaFramePublisher.BuildCurrentZoneEntities(stateFilePath, frame); var commandBoundary = AetheriaRuntimeDaemonCommandBoundaryDocument.Create(options.DaemonId); var providerAdvertisement = AetheriaRuntimeDaemonProviderAdvertisementDocument.Create( @@ -234,7 +258,7 @@ namespace GameCult.Aetheria.State.Verse PublishedAtUtc = DateTime.UtcNow.ToString("O"), StatePath = stateFilePath, FrameId = frame.FrameId, - ObservedCommandCount = observedCommands.Length, + ObservedCommandCount = observedCommandCount, AppliedCommandCount = operationResult.AppliedCommandIds.Count, RejectedCommandCount = operationResult.RejectedCommandIds.Count, Status = operationResult.RejectedCommandIds.Count == 0 ? "healthy" : "commands-rejected", @@ -285,6 +309,29 @@ namespace GameCult.Aetheria.State.Verse editorSurface); } + private static AetheriaRuntimeDaemonIntentState MergeIntents( + AetheriaRuntimeDaemonIntentState commands, + AetheriaRuntimeDaemonIntentState agents) + { + var merged = new AetheriaRuntimeDaemonIntentState + { + SensorPingRequested = commands.SensorPingRequested || agents.SensorPingRequested + }; + merged.Movements.AddRange(commands.Movements); + merged.Movements.AddRange(agents.Movements); + merged.WeaponGroups.AddRange(commands.WeaponGroups); + merged.WeaponGroups.AddRange(agents.WeaponGroups); + merged.Behaviors.AddRange(commands.Behaviors); + merged.Behaviors.AddRange(agents.Behaviors); + merged.Consumables.AddRange(commands.Consumables); + merged.Consumables.AddRange(agents.Consumables); + merged.Docking.AddRange(commands.Docking); + merged.Docking.AddRange(agents.Docking); + merged.Wormholes.AddRange(commands.Wormholes); + merged.Wormholes.AddRange(agents.Wormholes); + return merged; + } + private static void EnsureEntityIds(AetheriaRuntimeRunCheckpointCommit run) { var used = new HashSet(StringComparer.Ordinal); diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs index 8848ff4e0..9eb0e4a7b 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs @@ -1223,6 +1223,7 @@ namespace GameCult.Aetheria.State.Verse [Key(21)] public int ChargeRiskChecks { get; set; } [Key(22)] public double ChargeMalfunctionRisk { get; set; } [Key(23)] public long ShotSequence { get; set; } + [Key(24)] public bool TriggerPending { get; set; } } [MessagePackObject]