From 5363714cde021b8c542459e78c810855194d2e8f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 13 Jul 2026 16:19:35 +0100 Subject: [PATCH] Persist daemon consumable behavior state --- Aetheria.State.Daemon/Program.cs | 12 +- Aetheria.State.Import/Program.cs | 7 +- Aetheria.State.Verify/Program.cs | 13 +- Aetheria.State/Aetheria.State.csproj | 2 +- .../Documents/AetheriaItemDefinition.cs | 3 + .../AetheriaRuntimeStateDocuments.cs | 22 ++++ .../AetheriaUnityObservedEntityRestorer.cs | 13 +- Assets/Scripts/ServerShared/Entity.cs | 48 ++++++- .../Tests/DaemonRuntimeDocumentTests.cs | 110 ++++++++++++++++ .../Runtime/AetheriaRuntimeCatalogSnapshot.cs | 38 +++++- .../Runtime/AetheriaRuntimeCatalogStore.cs | 39 +++++- .../AetheriaRuntimeConsumableSimulation.cs | 117 ++++++++++++++++-- .../AetheriaRuntimeDaemonItemStatQueries.cs | 3 +- .../AetheriaRuntimeGameViewportDocuments.cs | 10 +- .../AetheriaRuntimeSnapshotDocuments.cs | 23 ++++ docs/aetheria-perfect-machine-map.md | 13 +- docs/original-game-migration-matrix.md | 2 +- 17 files changed, 445 insertions(+), 30 deletions(-) diff --git a/Aetheria.State.Daemon/Program.cs b/Aetheria.State.Daemon/Program.cs index ad38f152f..0e09d8444 100644 --- a/Aetheria.State.Daemon/Program.cs +++ b/Aetheria.State.Daemon/Program.cs @@ -2802,10 +2802,20 @@ static AetheriaRuntimeEntitySnapshotCommit ToRuntimeEntity( ActiveConsumables = (entity.ActiveConsumables ?? Array.Empty()) .Select(consumable => new AetheriaRuntimeActiveConsumableCommit { + EffectId = consumable.EffectId ?? "", ItemKey = consumable.ItemKey ?? "", Quality = consumable.Quality, RemainingDuration = consumable.RemainingDuration, - Duration = consumable.Duration + Duration = consumable.Duration, + BehaviorStates = (consumable.BehaviorStates ?? Array.Empty()) + .Select(state => new AetheriaRuntimeConsumableBehaviorStateCommit + { + BehaviorIndex = state.BehaviorIndex, + BehaviorKind = state.BehaviorKind ?? "", + ScalarState = state.ScalarState, + BehaviorId = state.BehaviorId ?? "" + }) + .ToArray() }) .ToArray(), BehaviorProgress = (entity.BehaviorProgress ?? Array.Empty()) diff --git a/Aetheria.State.Import/Program.cs b/Aetheria.State.Import/Program.cs index fc77c85c2..24f2ccdd1 100644 --- a/Aetheria.State.Import/Program.cs +++ b/Aetheria.State.Import/Program.cs @@ -65,6 +65,7 @@ static AetheriaItemDefinition ProjectDeployableWeapon(AetheriaItemDefinition ite UnionKey = behavior.UnionKey, Kind = "DeployableWeapon", Group = behavior.Group, + BehaviorId = behavior.BehaviorId, Fields = behavior.Fields .Where(field => field.Key < 26 || field.Key > 30) .Concat([ @@ -1029,11 +1030,15 @@ internal static class LegacyCatalogReader return []; } - return behaviors + var result = behaviors .Select(ReadBehaviorPayload) .Where(behavior => behavior != null) .Cast() .ToArray(); + for (var index = 0; index < result.Length; index++) + if (string.IsNullOrWhiteSpace(result[index].BehaviorId)) + result[index].BehaviorId = $"behavior:{index}:{result[index].Kind}"; + return result; } private static AetheriaBehaviorPayload? ReadBehaviorPayload(object? value) diff --git a/Aetheria.State.Verify/Program.cs b/Aetheria.State.Verify/Program.cs index 605f50e76..13894de89 100644 --- a/Aetheria.State.Verify/Program.cs +++ b/Aetheria.State.Verify/Program.cs @@ -14217,6 +14217,8 @@ static void RequireMainMenuContinueRunState(string root) "entity.RestoreStatGrids(entitySnapshot.StatGrids)", "entity.RestoreThermalExposure((float)entitySnapshot.Heatstroke, (float)entitySnapshot.Hypothermia)", "RestoreActiveConsumables(entity, entitySnapshot)", + "activeEffectIds.Add(activeConsumable.EffectId)", + "entity.RetainActiveConsumables(activeEffectIds)", "RestoreRuntimeBehaviorState(entity, entitySnapshot, restoredEntities)", "_entityIndex.PresentationEntitiesByRecordKey", "ResolveRuntimeBehavior(entity, weaponState.OwnerKind, weaponState.OwnerIndex, weaponState.BehaviorIndex)", @@ -14433,6 +14435,13 @@ static void RequireMainMenuContinueRunState(string root) string.Join(", ", missingTargetContactQuerySymbols)); } + + if (observedEntityRestorer.Contains("case \"active_consumable\":", StringComparison.Ordinal)) + { + throw new InvalidOperationException( + "Unity still restores daemon active-consumable behavior state by transient list index."); + } + if (targetPresentation.Contains("CultMeshReactiveDocument", StringComparison.Ordinal) || targetPresentation.Contains(".ReactiveZoneContacts(\"unity-observed-target-query\")", StringComparison.Ordinal) || targetPresentation.Contains("_zoneContacts?.Dispose()", StringComparison.Ordinal) || @@ -14947,9 +14956,11 @@ static void RequireMainMenuContinueRunState(string root) { "RestoreThermalExposure", "RestoreActiveConsumable", + "FindActiveConsumableByEffectId", + "RetainActiveConsumables", "RestoreStatGrids", "RestoreHullConductivityGrid", - "new ConsumableItemEffect(item, this, remainingDuration, duration)" + "new ConsumableItemEffect(item, this, effectId, remainingDuration, duration)" }; var missingEntityRestoreSymbols = requiredEntityRestoreSymbols .Where(symbol => !entitySource.Contains(symbol, StringComparison.Ordinal)) diff --git a/Aetheria.State/Aetheria.State.csproj b/Aetheria.State/Aetheria.State.csproj index b1e0aa94d..74d3d5518 100644 --- a/Aetheria.State/Aetheria.State.csproj +++ b/Aetheria.State/Aetheria.State.csproj @@ -16,7 +16,7 @@ - + diff --git a/Aetheria.State/Documents/AetheriaItemDefinition.cs b/Aetheria.State/Documents/AetheriaItemDefinition.cs index 92550d9ab..da4ed5926 100644 --- a/Aetheria.State/Documents/AetheriaItemDefinition.cs +++ b/Aetheria.State/Documents/AetheriaItemDefinition.cs @@ -277,6 +277,9 @@ public sealed class AetheriaBehaviorPayload [Key(3)] public AetheriaBehaviorField[] Fields { get; set; } = []; + + [Key(4)] + public string BehaviorId { get; set; } = ""; } [MessagePackObject] diff --git a/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs b/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs index 0982cacda..de7cedb55 100644 --- a/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs +++ b/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs @@ -719,6 +719,28 @@ public sealed class AetheriaActiveConsumableSnapshot [Key(3)] public double Duration { get; set; } + + [Key(4)] + public string EffectId { get; set; } = ""; + + [Key(5)] + public AetheriaConsumableBehaviorStateSnapshot[] BehaviorStates { get; set; } = []; +} + +[MessagePackObject] +public sealed class AetheriaConsumableBehaviorStateSnapshot +{ + [Key(0)] + public int BehaviorIndex { get; set; } = -1; + + [Key(1)] + public string BehaviorKind { get; set; } = ""; + + [Key(2)] + public double ScalarState { get; set; } + + [Key(3)] + public string BehaviorId { get; set; } = ""; } [MessagePackObject] diff --git a/Assets/Scripts/Gameplay/AetheriaUnityObservedEntityRestorer.cs b/Assets/Scripts/Gameplay/AetheriaUnityObservedEntityRestorer.cs index 0e92027ae..86e392330 100644 --- a/Assets/Scripts/Gameplay/AetheriaUnityObservedEntityRestorer.cs +++ b/Assets/Scripts/Gameplay/AetheriaUnityObservedEntityRestorer.cs @@ -135,8 +135,16 @@ public sealed class AetheriaUnityObservedEntityRestorer private void RestoreActiveConsumables(Entity entity, AetheriaRuntimeEntitySnapshot snapshot) { + var activeEffectIds = new HashSet(StringComparer.Ordinal); foreach (var activeConsumable in snapshot.ActiveConsumables) { + if (string.IsNullOrWhiteSpace(activeConsumable.EffectId)) + { + _logWarning($"Typed active consumable {activeConsumable.ItemKey} has no daemon effect identity on restored entity {snapshot.RecordKey}."); + continue; + } + + activeEffectIds.Add(activeConsumable.EffectId); var item = _createLoadoutItem(new AetheriaRuntimeLoadoutItemSnapshot( activeConsumable.ItemKey, activeConsumable.Quality, @@ -151,10 +159,13 @@ public sealed class AetheriaUnityObservedEntityRestorer } entity.RestoreActiveConsumable( + activeConsumable.EffectId, item, (float)activeConsumable.RemainingDuration, (float)activeConsumable.Duration); } + + entity.RetainActiveConsumables(activeEffectIds); } private static void RestoreRuntimeBehaviorState( @@ -328,8 +339,6 @@ public sealed class AetheriaUnityObservedEntityRestorer { case "equipment": return ownerIndex < entity.Equipment.Count ? entity.Equipment[ownerIndex].Behaviors : null; - case "active_consumable": - return ownerIndex < entity.ActiveConsumables.Count ? entity.ActiveConsumables[ownerIndex].Behaviors : null; default: return null; } diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 2fcf45e14..1cc0bce3c 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -396,12 +396,31 @@ public abstract class Entity Hypothermia = AetheriaScalar.Saturate(hypothermia); } - public void RestoreActiveConsumable(ConsumableItem item, float remainingDuration, float duration) + public void RestoreActiveConsumable(string effectId, ConsumableItem item, float remainingDuration, float duration) { - if (item == null) + if (string.IsNullOrWhiteSpace(effectId) || item == null) return; - _activeConsumables.Add(new ConsumableItemEffect(item, this, remainingDuration, duration)); + var activeConsumable = FindActiveConsumableByEffectId(effectId); + if (activeConsumable != null) + { + activeConsumable.RestorePresentationState(remainingDuration, duration); + return; + } + + _activeConsumables.Add(new ConsumableItemEffect(item, this, effectId, remainingDuration, duration)); + } + + public void RetainActiveConsumables(IReadOnlyCollection effectIds) + { + if (effectIds == null) + { + _activeConsumables.Clear(); + return; + } + + _activeConsumables.RemoveAll(effect => + string.IsNullOrWhiteSpace(effect.EffectId) || !effectIds.Contains(effect.EffectId)); } public void RestoreStatGrids(IReadOnlyList grids) @@ -441,6 +460,13 @@ public abstract class Entity return _activeConsumables.FirstOrDefault(ac => ac.Item?.ItemKey == itemKey); } + public ConsumableItemEffect FindActiveConsumableByEffectId(string effectId) + { + return string.IsNullOrWhiteSpace(effectId) + ? null + : _activeConsumables.FirstOrDefault(active => active.EffectId == effectId); + } + private static void RestoreFloatGrid(AetheriaRuntimeEntityStatGridSnapshot grid, float[,] target) { if (!CanRestoreGrid(grid, target)) @@ -1331,6 +1357,7 @@ public abstract class Entity public class ConsumableItemEffect { public float RemainingDuration { get; private set; } + public string EffectId { get; } public Entity Entity { get; } public ConsumableItem Item { get; } public Behavior[] Behaviors { get; } @@ -1341,14 +1368,20 @@ public class ConsumableItemEffect private readonly BezierCurve _effectiveness; public ConsumableItemEffect(ConsumableItem item, Entity entity) - : this(item, entity, null, null) + : this(item, entity, "", null, null) { } - public ConsumableItemEffect(ConsumableItem item, Entity entity, float? remainingDuration, float? duration) + public ConsumableItemEffect( + ConsumableItem item, + Entity entity, + string effectId, + float? remainingDuration, + float? duration) { Item = item; Entity = entity; + EffectId = effectId ?? ""; RuntimeItem = entity.ItemManager.GetRuntimeItem(item); _duration = duration.GetValueOrDefault(RuntimeItem?.Duration > 0 ? (float)RuntimeItem.Duration : 0); _effectiveness = CreateEffectivenessCurve(RuntimeItem); @@ -1359,6 +1392,11 @@ public class ConsumableItemEffect Behaviors = entity.ItemManager.CreateRuntimeBehaviors(this); } + public void RestorePresentationState(float remainingDuration, float duration) + { + RemainingDuration = AetheriaScalar.Clamp(remainingDuration, 0, Math.Max(duration, float.Epsilon)); + } + public void Update(float delta) { foreach (var behavior in Behaviors) diff --git a/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs b/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs index b644a2a7a..3b6d374d1 100644 --- a/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs +++ b/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs @@ -5045,6 +5045,8 @@ public class DaemonRuntimeDocumentTests Assert.AreEqual(1, actor.CargoContents[0].Items[0].Item.Quantity); Assert.AreEqual(1, actor.ActiveConsumables.Count); + Assert.IsFalse(string.IsNullOrWhiteSpace(actor.ActiveConsumables[0].EffectId)); + var effectId = actor.ActiveConsumables[0].EffectId; Assert.AreEqual(0.73, actor.ActiveConsumables[0].Quality, 0.0001); Assert.AreEqual(1.5, actor.ActiveConsumables[0].RemainingDuration, 0.0001); Assert.AreEqual("consumable.activated", run.GameEvents.Single().Kind); @@ -5054,6 +5056,7 @@ public class DaemonRuntimeDocumentTests AetheriaRuntimeConsumableSimulation.Step(run, Array.Empty(), catalog, 42, 0.01); Assert.AreEqual(0, actor.ActiveConsumables.Count); Assert.AreEqual(1, run.GameEvents.Count(value => value.Kind == "consumable.expired")); + StringAssert.Contains(effectId, run.GameEvents.Single(value => value.Kind == "consumable.expired").EventId); } [Test] @@ -5236,6 +5239,107 @@ public class DaemonRuntimeDocumentTests "Typed effectiveness curves must preserve Unity AnimationCurve tangents."); } + [Test] + public void ConsumableCooldownOwnsStableStateAcrossBlockedChainsAndBehaviorReordering() + { + var run = RunWithTwoEntities(); + var actor = run.Zones[0].Entities[0]; + actor.ActiveConsumables = new[] + { + new AetheriaRuntimeActiveConsumableCommit + { + EffectId = "effect:stable", + ItemKey = "field-kit", + Quality = 1, + Duration = 10, + RemainingDuration = 10 + } + }; + var energy = BehaviorPayloadId("energy", "EnergyDraw", PerformanceStatField(1, 5), BoolField(2, false)); + var cooldown = BehaviorPayloadId("cooldown", "Cooldown", PerformanceStatField(1, 1)); + var originalCatalog = new AetheriaRuntimeCatalogSnapshot( + new[] { CatalogItem("field-kit", new[] { energy, cooldown }, category: AetheriaRuntimeItemCategories.Consumable, duration: 10) }, + Array.Empty(), + Array.Empty()); + + AetheriaRuntimeConsumableSimulation.Step( + run, Array.Empty(), originalCatalog, 90, 0.25); + + var state = actor.ActiveConsumables[0].BehaviorStates.Single(value => value.BehaviorId == "cooldown"); + Assert.AreEqual(-0.25, state.ScalarState, 0.0001, + "Always-updated cooldowns must age before an earlier behavior stops the chain."); + + var reorderedCatalog = new AetheriaRuntimeCatalogSnapshot( + new[] { CatalogItem("field-kit", new[] { cooldown, energy }, category: AetheriaRuntimeItemCategories.Consumable, duration: 10) }, + Array.Empty(), + Array.Empty()); + AetheriaRuntimeConsumableSimulation.Step( + run, Array.Empty(), reorderedCatalog, 91, 0.1); + + state = actor.ActiveConsumables[0].BehaviorStates.Single(value => value.BehaviorId == "cooldown"); + Assert.AreEqual(0, state.BehaviorIndex, "Authored order is projection, not behavior identity."); + Assert.AreEqual(1, state.ScalarState, 0.0001, + "The ready cooldown should execute immediately when the reordered chain reaches it."); + + AetheriaRuntimeConsumableSimulation.Step( + run, Array.Empty(), reorderedCatalog, 92, 0.5); + Assert.AreEqual(0.5, state.ScalarState, 0.0001); + Assert.AreEqual("cooldown", run.GameEvents.Last(value => value.FrameId == 92).Reason); + + AetheriaRuntimeConsumableSimulation.Step( + run, Array.Empty(), reorderedCatalog, 93, 0.5); + Assert.AreEqual(0, state.ScalarState, 0.0001); + Assert.AreEqual("cooldown", run.GameEvents.Last(value => value.FrameId == 93).Reason, + "Exact zero remains blocked in the fossil contract."); + + AetheriaRuntimeConsumableSimulation.Step( + run, Array.Empty(), reorderedCatalog, 94, 0.01); + Assert.AreEqual(1, state.ScalarState, 0.0001); + } + + [Test] + public void ExpiringConsumableCannotTransferIdentityOrBehaviorStateToItsNeighbor() + { + var run = RunWithTwoEntities(); + var actor = run.Zones[0].Entities[0]; + actor.ActiveConsumables = new[] + { + new AetheriaRuntimeActiveConsumableCommit + { + EffectId = "effect:expires", ItemKey = "empty", Duration = 1, RemainingDuration = 0 + }, + new AetheriaRuntimeActiveConsumableCommit + { + EffectId = "effect:survives", ItemKey = "empty", Duration = 3, RemainingDuration = 2, + BehaviorStates = new[] + { + new AetheriaRuntimeConsumableBehaviorStateCommit + { + BehaviorId = "remember-me", BehaviorIndex = 0, BehaviorKind = "Cooldown", ScalarState = 0.42 + } + } + } + }; + var catalog = new AetheriaRuntimeCatalogSnapshot( + new[] + { + CatalogItem("empty", new[] + { + BehaviorPayloadId("remember-me", "Cooldown", PerformanceStatField(1, 1)) + }, category: AetheriaRuntimeItemCategories.Consumable, stackable: true, duration: 3) + }, + Array.Empty(), + Array.Empty()); + + AetheriaRuntimeConsumableSimulation.Step( + run, Array.Empty(), catalog, 95, 0.1); + + Assert.AreEqual(1, actor.ActiveConsumables.Count); + Assert.AreEqual("effect:survives", actor.ActiveConsumables[0].EffectId); + Assert.AreEqual(0.32, actor.ActiveConsumables[0].BehaviorStates.Single().ScalarState, 0.0001, + "The surviving effect keeps and advances its own nested state after array compaction."); + } + [Test] public void BehaviorStateProjectorDerivesEquipmentRowsFromCatalogPayloads() { @@ -6032,6 +6136,12 @@ public class DaemonRuntimeDocumentTests params AetheriaRuntimeBehaviorField[] fields) => new AetheriaRuntimeBehaviorPayload(0, kind, 0, fields); + private static AetheriaRuntimeBehaviorPayload BehaviorPayloadId( + string behaviorId, + string kind, + params AetheriaRuntimeBehaviorField[] fields) => + new AetheriaRuntimeBehaviorPayload(0, kind, 0, fields, behaviorId); + private static AetheriaRuntimeBehaviorField PerformanceStatField(int key, double value) => new AetheriaRuntimeBehaviorField(key, PerformanceStatValue(value, value)); diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogSnapshot.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogSnapshot.cs index 038b8d247..f31588aca 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogSnapshot.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogSnapshot.cs @@ -429,12 +429,14 @@ namespace GameCult.Aetheria.State.Verse int unionKey, string kind, int group, - IReadOnlyList fields) + IReadOnlyList fields, + string behaviorId = "") { UnionKey = unionKey; Kind = kind; Group = group; Fields = fields; + BehaviorId = behaviorId; } public int UnionKey { get; set; } @@ -444,6 +446,7 @@ namespace GameCult.Aetheria.State.Verse public int Group { get; set; } public IReadOnlyList Fields { get; set; } + public string BehaviorId { get; set; } } [MessagePackObject(true)] @@ -1056,18 +1059,49 @@ namespace GameCult.Aetheria.State.Verse [MessagePackObject(true)] public sealed class AetheriaRuntimeActiveConsumableSnapshot { - public AetheriaRuntimeActiveConsumableSnapshot(string itemKey, double quality, double remainingDuration, double duration) + public AetheriaRuntimeActiveConsumableSnapshot( + string itemKey, + double quality, + double remainingDuration, + double duration, + string effectId = "", + IReadOnlyList? behaviorStates = null) { ItemKey = itemKey; Quality = quality; RemainingDuration = remainingDuration; Duration = duration; + EffectId = effectId; + BehaviorStates = behaviorStates ?? Array.Empty(); } public string ItemKey { get; set; } public double Quality { get; set; } public double RemainingDuration { get; set; } public double Duration { get; set; } + public string EffectId { get; set; } + public IReadOnlyList BehaviorStates { get; set; } + } + + [MessagePackObject(true)] + public sealed class AetheriaRuntimeConsumableBehaviorStateSnapshot + { + public AetheriaRuntimeConsumableBehaviorStateSnapshot( + int behaviorIndex, + string behaviorKind, + double scalarState, + string behaviorId = "") + { + BehaviorIndex = behaviorIndex; + BehaviorKind = behaviorKind; + ScalarState = scalarState; + BehaviorId = behaviorId; + } + + public int BehaviorIndex { get; set; } + public string BehaviorKind { get; set; } + public double ScalarState { get; set; } + public string BehaviorId { get; set; } } [MessagePackObject(true)] diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogStore.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogStore.cs index c54287e35..9dcda89d0 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogStore.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogStore.cs @@ -401,7 +401,7 @@ namespace GameCult.Aetheria.State.Verse AetheriaRuntimeBehaviorPayload payload, IReadOnlyDictionary recipes) { - writer.WriteArrayHeader(4); + writer.WriteArrayHeader(5); writer.Write(payload.UnionKey); writer.Write(payload.Kind ?? ""); writer.Write(payload.Group); @@ -416,6 +416,7 @@ namespace GameCult.Aetheria.State.Verse ref writer, recipes.TryGetValue(recipeKey, out var recipe) ? WithStatRecipe(field.Value, recipe) : field.Value); } + writer.Write(payload.BehaviorId ?? ""); } private static AetheriaRuntimeBehaviorValue WithStatRecipe( @@ -1015,13 +1016,38 @@ namespace GameCult.Aetheria.State.Verse var quality = ReadFieldDouble(ref reader, consumableFields, 1, 1); var remainingDuration = ReadFieldDouble(ref reader, consumableFields, 2); var duration = ReadFieldDouble(ref reader, consumableFields, 3); - SkipRemaining(ref reader, consumableFields, 4); - consumables[consumable] = new AetheriaRuntimeActiveConsumableSnapshot(itemKey, quality, remainingDuration, duration); + var effectId = ReadFieldString(ref reader, consumableFields, 4); + var behaviorStates = ReadFieldConsumableBehaviorStates(ref reader, consumableFields, 5); + SkipRemaining(ref reader, consumableFields, 6); + consumables[consumable] = new AetheriaRuntimeActiveConsumableSnapshot( + itemKey, quality, remainingDuration, duration, effectId, behaviorStates); } return consumables; } + private static IReadOnlyList ReadFieldConsumableBehaviorStates( + ref MessagePackReader reader, + int fields, + int index) + { + if (index >= fields) return Array.Empty(); + var count = reader.ReadArrayHeader(); + var states = new AetheriaRuntimeConsumableBehaviorStateSnapshot[count]; + for (var stateIndex = 0; stateIndex < count; stateIndex++) + { + var stateFields = reader.ReadArrayHeader(); + var behaviorIndex = ReadFieldInt32(ref reader, stateFields, 0); + var behaviorKind = ReadFieldString(ref reader, stateFields, 1); + var scalarState = ReadFieldDouble(ref reader, stateFields, 2); + var behaviorId = ReadFieldString(ref reader, stateFields, 3); + SkipRemaining(ref reader, stateFields, 4); + states[stateIndex] = new AetheriaRuntimeConsumableBehaviorStateSnapshot( + behaviorIndex, behaviorKind, scalarState, behaviorId); + } + return states; + } + private static IReadOnlyList ReadFieldBehaviorProgress(ref MessagePackReader reader, int fields, int index) { if (index >= fields) return Array.Empty(); @@ -1677,8 +1703,11 @@ namespace GameCult.Aetheria.State.Verse var kind = ReadFieldString(ref reader, payloadFields, 1); var group = ReadFieldInt32(ref reader, payloadFields, 2); var fieldsValue = ReadFieldBehaviorFields(ref reader, payloadFields, 3); - SkipRemaining(ref reader, payloadFields, 4); - payloads[payload] = new AetheriaRuntimeBehaviorPayload(unionKey, kind, group, fieldsValue); + var behaviorId = ReadFieldString(ref reader, payloadFields, 4); + SkipRemaining(ref reader, payloadFields, 5); + if (string.IsNullOrWhiteSpace(behaviorId)) + behaviorId = $"legacy:{payload}:{kind}"; + payloads[payload] = new AetheriaRuntimeBehaviorPayload(unionKey, kind, group, fieldsValue, behaviorId); } return payloads; diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeConsumableSimulation.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeConsumableSimulation.cs index a1d8fd61a..3ad4b4819 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeConsumableSimulation.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeConsumableSimulation.cs @@ -53,13 +53,14 @@ namespace GameCult.Aetheria.State.Verse .ToArray(); for (var index = 0; index < active.Length; index++) { - ExecuteBehaviors(run, zone, entity, active[index], catalog, frameId, index, deltaSeconds); + EnsureEffectIdentity(zone, entity, active[index], index); + ExecuteBehaviors(run, zone, entity, active[index], catalog, frameId, deltaSeconds); active[index].RemainingDuration -= deltaSeconds; if (active[index].RemainingDuration < 0) { AetheriaRuntimeGameEvents.Append(run, new AetheriaRuntimeGameEventCommit { - EventId = $"frame:{frameId}:zone:{zone.ZoneIndex}:entity:{entity.EntityIndex}:consumable:{index}:expired", + EventId = $"frame:{frameId}:zone:{zone.ZoneIndex}:entity:{entity.EntityIndex}:consumable:{active[index].EffectId}:expired", Kind = "consumable.expired", FrameId = frameId, ZoneIndex = zone.ZoneIndex, @@ -79,13 +80,12 @@ namespace GameCult.Aetheria.State.Verse AetheriaRuntimeActiveConsumableCommit effect, AetheriaRuntimeCatalogSnapshot? catalog, long frameId, - int effectIndex, double deltaSeconds) { var item = catalog?.FindItem(effect.ItemKey); if (item == null) { - BehaviorStopped(run, zone, entity, effect, frameId, effectIndex, -1, "missing-catalog-item"); + BehaviorStopped(run, zone, entity, effect, frameId, -1, "missing-catalog-item"); return; } @@ -96,15 +96,22 @@ namespace GameCult.Aetheria.State.Verse ? 1 : AetheriaRuntimeDaemonItemStatQueries.SampleCurve(item.EffectivenessCurveKeys, elapsed); var payloads = item.BehaviorPayloads ?? Array.Empty(); + if (!ReconcileBehaviorStates(effect, payloads)) + { + BehaviorStopped(run, zone, entity, effect, frameId, -1, "duplicate-behavior-id"); + return; + } + UpdateAlwaysUpdatedBehaviors(effect, payloads, effectiveness, deltaSeconds); for (var behaviorIndex = 0; behaviorIndex < payloads.Count; behaviorIndex++) { var payload = payloads[behaviorIndex]; if (payload == null) continue; - if (ExecuteBehavior(entity, effect, payload, catalog, effectiveness, deltaSeconds, out var reason)) + if (ExecuteBehavior( + entity, effect, payload, behaviorIndex, catalog, effectiveness, deltaSeconds, out var reason)) continue; - BehaviorStopped(run, zone, entity, effect, frameId, effectIndex, behaviorIndex, reason); + BehaviorStopped(run, zone, entity, effect, frameId, behaviorIndex, reason); break; } } @@ -113,6 +120,7 @@ namespace GameCult.Aetheria.State.Verse AetheriaRuntimeEntitySnapshotCommit entity, AetheriaRuntimeActiveConsumableCommit effect, AetheriaRuntimeBehaviorPayload payload, + int behaviorIndex, AetheriaRuntimeCatalogSnapshot? catalog, double effectiveness, double deltaSeconds, @@ -121,6 +129,17 @@ namespace GameCult.Aetheria.State.Verse reason = ""; switch (payload.Kind) { + case "Cooldown": + { + var state = FindBehaviorState(effect, behaviorIndex, payload); + if (state.ScalarState < 0) + { + state.ScalarState = 1; + return true; + } + reason = "cooldown"; + return false; + } case "EnergyDraw": { var demand = Evaluate(payload, 1, effect, effectiveness) * (ReadBool(payload, 2) ? deltaSeconds : 1); @@ -150,6 +169,88 @@ namespace GameCult.Aetheria.State.Verse } } + private static bool ReconcileBehaviorStates( + AetheriaRuntimeActiveConsumableCommit effect, + IReadOnlyList payloads) + { + var identities = payloads + .Select((payload, behaviorIndex) => BehaviorIdentity(payload, behaviorIndex)) + .ToArray(); + if (identities.Distinct(StringComparer.Ordinal).Count() != identities.Length) + return false; + + var previousStates = (effect.BehaviorStates ?? Array.Empty()) + .Where(state => state != null) + .ToArray(); + var previousById = previousStates + .Where(state => !string.IsNullOrWhiteSpace(state.BehaviorId)) + .GroupBy(state => state.BehaviorId, StringComparer.Ordinal) + .ToDictionary(group => group.Key, group => group.First(), StringComparer.Ordinal); + effect.BehaviorStates = payloads + .Select((payload, behaviorIndex) => + { + var kind = payload?.Kind ?? ""; + var behaviorId = identities[behaviorIndex]; + if (!previousById.TryGetValue(behaviorId, out var state)) + state = previousStates.FirstOrDefault(candidate => + string.IsNullOrWhiteSpace(candidate.BehaviorId) && + candidate.BehaviorIndex == behaviorIndex && + string.Equals(candidate.BehaviorKind, kind, StringComparison.Ordinal)); + state ??= new AetheriaRuntimeConsumableBehaviorStateCommit + { + ScalarState = 0 + }; + state.BehaviorId = behaviorId; + state.BehaviorIndex = behaviorIndex; + state.BehaviorKind = kind; + return state; + }) + .ToArray(); + return true; + } + + private static string BehaviorIdentity(AetheriaRuntimeBehaviorPayload? payload, int behaviorIndex) => + !string.IsNullOrWhiteSpace(payload?.BehaviorId) + ? payload.BehaviorId + : $"legacy:{behaviorIndex}:{payload?.Kind ?? ""}"; + + private static void UpdateAlwaysUpdatedBehaviors( + AetheriaRuntimeActiveConsumableCommit effect, + IReadOnlyList payloads, + double effectiveness, + double deltaSeconds) + { + for (var behaviorIndex = 0; behaviorIndex < payloads.Count; behaviorIndex++) + { + var payload = payloads[behaviorIndex]; + if (payload == null || !string.Equals(payload.Kind, "Cooldown", StringComparison.Ordinal)) + continue; + + var duration = Evaluate(payload, 1, effect, effectiveness); + FindBehaviorState(effect, behaviorIndex, payload).ScalarState -= deltaSeconds / duration; + } + } + + private static AetheriaRuntimeConsumableBehaviorStateCommit FindBehaviorState( + AetheriaRuntimeActiveConsumableCommit effect, + int behaviorIndex, + AetheriaRuntimeBehaviorPayload payload) => + (effect.BehaviorStates ?? Array.Empty()) + .Single(state => state != null && + string.Equals(state.BehaviorId, BehaviorIdentity(payload, behaviorIndex), + StringComparison.Ordinal)); + + private static void EnsureEffectIdentity( + AetheriaRuntimeZoneSnapshotCommit zone, + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeActiveConsumableCommit effect, + int legacyIndex) + { + if (!string.IsNullOrWhiteSpace(effect.EffectId)) + return; + effect.EffectId = $"legacy:zone:{zone.ZoneIndex}:entity:{entity.EntityIndex}:effect:{legacyIndex}"; + } + private static double Evaluate( AetheriaRuntimeBehaviorPayload payload, int fieldKey, @@ -179,13 +280,12 @@ namespace GameCult.Aetheria.State.Verse AetheriaRuntimeEntitySnapshotCommit entity, AetheriaRuntimeActiveConsumableCommit effect, long frameId, - int effectIndex, int behaviorIndex, string reason) { AetheriaRuntimeGameEvents.Append(run, new AetheriaRuntimeGameEventCommit { - EventId = $"frame:{frameId}:zone:{zone.ZoneIndex}:entity:{entity.EntityIndex}:consumable:{effectIndex}:behavior:{behaviorIndex}:stopped", + EventId = $"frame:{frameId}:zone:{zone.ZoneIndex}:entity:{entity.EntityIndex}:consumable:{effect.EffectId}:behavior:{behaviorIndex}:stopped", Kind = "consumable.behavior.stopped", FrameId = frameId, ZoneIndex = zone.ZoneIndex, @@ -252,6 +352,7 @@ namespace GameCult.Aetheria.State.Verse .Where(active => active != null) .Append(new AetheriaRuntimeActiveConsumableCommit { + EffectId = $"effect:frame:{frameId}:zone:{zone.ZoneIndex}:entity:{entity.EntityIndex}:intent:{intentIndex}", ItemKey = item.ItemKey, Quality = consumed.Item.Quality, Duration = item.Duration, diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonItemStatQueries.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonItemStatQueries.cs index 045075229..134111fa9 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonItemStatQueries.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonItemStatQueries.cs @@ -121,7 +121,8 @@ namespace GameCult.Aetheria.State.Verse var weightedQuality = stat.QualityExponent == 0 ? 1 : Math.Pow(Clamp01(quality), stat.QualityExponent); - return Lerp(stat.Min, stat.Max, Clamp01(effectiveness) * weightedQuality); + var result = Lerp(stat.Min, stat.Max, Clamp01(effectiveness) * weightedQuality); + return double.IsNaN(result) ? stat.Min : result; } public static double SampleCurve(IReadOnlyList? keys, double value) diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs index 79b19da67..a66209528 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs @@ -981,7 +981,15 @@ namespace GameCult.Aetheria.State.Verse consumable.ItemKey ?? "", consumable.Quality, consumable.RemainingDuration, - consumable.Duration)) + consumable.Duration, + consumable.EffectId ?? "", + (consumable.BehaviorStates ?? Array.Empty()) + .Select(state => new AetheriaRuntimeConsumableBehaviorStateSnapshot( + state.BehaviorIndex, + state.BehaviorKind ?? "", + state.ScalarState, + state.BehaviorId ?? "")) + .ToArray())) .ToArray(), (entity.BehaviorProgress ?? Array.Empty()) .Select(progress => new AetheriaRuntimeBehaviorProgressSnapshot( diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs index 8f347519f..dabdce254 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs @@ -1127,6 +1127,9 @@ namespace GameCult.Aetheria.State.Verse [MessagePackObject] public sealed class AetheriaRuntimeActiveConsumableCommit { + [Key(0)] + public string EffectId { get; set; } = ""; + [Key(1)] public double Quality { get; set; } = 1.0; @@ -1138,6 +1141,26 @@ namespace GameCult.Aetheria.State.Verse [Key(4)] public string ItemKey { get; set; } = ""; + + [Key(5)] + public IReadOnlyList BehaviorStates { get; set; } = + Array.Empty(); + } + + [MessagePackObject] + public sealed class AetheriaRuntimeConsumableBehaviorStateCommit + { + [Key(0)] + public int BehaviorIndex { get; set; } = -1; + + [Key(1)] + public string BehaviorKind { get; set; } = ""; + + [Key(2)] + public double ScalarState { get; set; } + + [Key(3)] + public string BehaviorId { get; set; } = ""; } [MessagePackObject] diff --git a/docs/aetheria-perfect-machine-map.md b/docs/aetheria-perfect-machine-map.md index 80f7758bf..46e09d78e 100644 --- a/docs/aetheria-perfect-machine-map.md +++ b/docs/aetheria-perfect-machine-map.md @@ -132,7 +132,18 @@ legacy catalog cache, and legacy UI paths should be migration-only or deleted. fallback icon selection, and finally fall back to a generic tool icon when typed facets are incomplete. The current legacy catalog has zero populated custom action-bar icon paths, but the typed field is present and owns that - surface when data appears. Player camera articulation grouping now classifies + surface when data appears. + + Every active effect owns a stable daemon `EffectId`; each authored payload + owns a stable `BehaviorId` and nested scalar state beneath that effect. Array + position is execution order, never identity. `Cooldown` follows the fossil's + update-before-chain semantics: every cooldown ages before ordered execution, + readiness is strictly below zero, successful execution resets it to one, and + an earlier failed behavior cannot freeze it. Unity reconciles active-effect + presentation objects by `EffectId` and removes absent effects. It does not + restore active-consumable behavior state through the flattened equipment + behavior table and cannot become a second cooldown owner. + Player camera articulation grouping now classifies equipped non-launcher weapons through typed behavior kind rows instead of inspecting runtime behavior config classes. Unity boot reads typed player settings back through the package-owned CultCache reader before falling back diff --git a/docs/original-game-migration-matrix.md b/docs/original-game-migration-matrix.md index 0061a8288..4ada89dce 100644 --- a/docs/original-game-migration-matrix.md +++ b/docs/original-game-migration-matrix.md @@ -44,7 +44,7 @@ validation proves contract shape, not wiring, exclusivity, lowering, or parity. | 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; 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 | replace station/ship sensor-count shortcuts with mass/volume/power/cooling/cost allocation, then prove shutdown, threshold decay, ping, and classification timelines | | 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 | -| 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`, and `ItemUsage` payloads after energy tick initialization; false and unsupported payloads stop later execution with a typed fact; timers retain the fossil's exact-zero final tick; Unity remains a projection | stable effect identity, catalog revision pinning, cooldown/always-update state, stat modifiers, and remaining behavior families | +| 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