diff --git a/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs b/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs index 279630145..6ab6da796 100644 --- a/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs +++ b/Assets/Scripts/Tests/DaemonRuntimeDocumentTests.cs @@ -5035,6 +5035,117 @@ public class DaemonRuntimeDocumentTests Assert.IsFalse(capability.Actions.Any(action => action.Operation.EndsWith("ActivateConsumable", StringComparison.Ordinal) && action.Payload["itemKey"] == "ore")); } + [Test] + public void ConsumableBehaviorsStopInAuthoredOrderWhenEnergyCannotBeDrawn() + { + var run = RunWithTwoEntities(); + var actor = run.Zones[0].Entities[0]; + actor.CargoContents = new[] + { + new AetheriaRuntimeCargoBayLoadoutCommit + { + Items = new[] + { + new AetheriaRuntimeLoadoutItemSlotCommit + { + Item = new AetheriaRuntimeLoadoutItemCommit { ItemKey = "catalyst", Quantity = 2 } + } + } + } + }; + actor.ActiveConsumables = new[] + { + new AetheriaRuntimeActiveConsumableCommit + { + ItemKey = "field-kit", + Quality = 1, + Duration = 3, + RemainingDuration = 3 + } + }; + var catalog = new AetheriaRuntimeCatalogSnapshot( + new[] + { + CatalogItem("field-kit", new[] + { + BehaviorPayload("EnergyDraw", PerformanceStatField(1, 5), BoolField(2, false)), + BehaviorPayload("ItemUsage", ItemKeyField(1, "catalyst")) + }, category: AetheriaRuntimeItemCategories.Consumable, duration: 3), + CatalogItem("catalyst", Array.Empty()) + }, + Array.Empty(), + Array.Empty()); + + AetheriaRuntimeConsumableSimulation.Step(run, Array.Empty(), catalog, 80, 0.5); + + Assert.AreEqual(2, actor.CargoContents[0].Items[0].Item.Quantity); + Assert.AreEqual(2.5, actor.ActiveConsumables[0].RemainingDuration, 0.0001); + var stopped = run.GameEvents.Single(value => value.Kind == "consumable.behavior.stopped"); + Assert.AreEqual("insufficient-energy", stopped.Reason); + Assert.AreEqual(0, stopped.ScalarValue); + } + + [Test] + public void ConsumableBehaviorsConsumeOneItemThenStopAtUnsupportedPayload() + { + var run = RunWithTwoEntities(); + var actor = run.Zones[0].Entities[0]; + actor.CargoContents = new[] + { + new AetheriaRuntimeCargoBayLoadoutCommit + { + Items = new[] + { + new AetheriaRuntimeLoadoutItemSlotCommit + { + Item = new AetheriaRuntimeLoadoutItemCommit { ItemKey = "catalyst", Quantity = 2 } + } + } + } + }; + actor.ActiveConsumables = new[] + { + new AetheriaRuntimeActiveConsumableCommit { ItemKey = "field-kit", Quality = 1, Duration = 3, RemainingDuration = 3 } + }; + var catalog = new AetheriaRuntimeCatalogSnapshot( + new[] + { + CatalogItem("field-kit", new[] + { + BehaviorPayload("ItemUsage", ItemKeyField(1, "catalyst")), + BehaviorPayload("FutureBehavior"), + BehaviorPayload("ItemUsage", ItemKeyField(1, "catalyst")) + }, category: AetheriaRuntimeItemCategories.Consumable, duration: 3), + CatalogItem("catalyst", Array.Empty()) + }, + Array.Empty(), + Array.Empty()); + + AetheriaRuntimeConsumableSimulation.Step(run, Array.Empty(), catalog, 81, 0.25); + + Assert.AreEqual(1, actor.CargoContents[0].Items[0].Item.Quantity); + var stopped = run.GameEvents.Single(value => value.Kind == "consumable.behavior.stopped"); + Assert.AreEqual("unsupported-behavior:FutureBehavior", stopped.Reason); + Assert.AreEqual(1, stopped.ScalarValue); + } + + [Test] + public void ConsumablePerformanceStatUsesEffectivenessAndQuality() + { + var value = PerformanceStatValue(2, 10, qualityExponent: 2); + var curve = new[] + { + new AetheriaRuntimeCurveKey(0, 0, 0, 2), + new AetheriaRuntimeCurveKey(1, 1, 0, 0) + }; + + var result = AetheriaRuntimeDaemonItemStatQueries.EvaluateConsumablePerformanceStat(value, 0.5, 0.5); + + Assert.AreEqual(3, result, 0.0001); + Assert.AreEqual(0.75, AetheriaRuntimeDaemonItemStatQueries.SampleCurve(curve, 0.5), 0.0001, + "Typed effectiveness curves must preserve Unity AnimationCurve tangents."); + } + [Test] public void BehaviorStateProjectorDerivesEquipmentRowsFromCatalogPayloads() { @@ -5826,6 +5937,43 @@ public class DaemonRuntimeDocumentTests Array.Empty()); } + private static AetheriaRuntimeBehaviorPayload BehaviorPayload( + string kind, + params AetheriaRuntimeBehaviorField[] fields) => + new AetheriaRuntimeBehaviorPayload(0, kind, 0, fields); + + private static AetheriaRuntimeBehaviorField PerformanceStatField(int key, double value) => + new AetheriaRuntimeBehaviorField(key, PerformanceStatValue(value, value)); + + private static AetheriaRuntimeBehaviorField BoolField(int key, bool value) => + new AetheriaRuntimeBehaviorField(key, new AetheriaRuntimeBehaviorValue( + "bool", "", 0, value, "", "", + Array.Empty(), + Array.Empty())); + + private static AetheriaRuntimeBehaviorField ItemKeyField(int key, string itemKey) => + new AetheriaRuntimeBehaviorField(key, new AetheriaRuntimeBehaviorValue( + "item", "", 0, false, "", itemKey, + Array.Empty(), + Array.Empty())); + + private static AetheriaRuntimeBehaviorValue PerformanceStatValue( + double min, + double max, + double qualityExponent = 0) => + new AetheriaRuntimeBehaviorValue( + "performance-stat", "", 0, false, "", "", + new[] + { + NumberValue(min), + NumberValue(max), + NumberValue(0), + NumberValue(0), + NumberValue(qualityExponent), + EmptyBehaviorValue("stat-recipe") + }, + Array.Empty()); + private static AetheriaRuntimeBehaviorValue EmptyBehaviorValue(string kind) { return new AetheriaRuntimeBehaviorValue( diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeConsumableSimulation.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeConsumableSimulation.cs index c21455952..a1d8fd61a 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeConsumableSimulation.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeConsumableSimulation.cs @@ -18,15 +18,32 @@ namespace GameCult.Aetheria.State.Verse if (run == null || deltaSeconds <= 0) return; + foreach (var zone in run.Zones ?? Array.Empty()) + StepZone(run, zone, zone?.Entities ?? Array.Empty(), intents, catalog, frameId, deltaSeconds); + } + + public static void StepZone( + AetheriaRuntimeRunCheckpointCommit run, + AetheriaRuntimeZoneSnapshotCommit? zone, + IReadOnlyList entities, + IEnumerable intents, + AetheriaRuntimeCatalogSnapshot? catalog, + long frameId, + double deltaSeconds) + { + if (run == null || zone == null || deltaSeconds <= 0) + return; + var intentIndex = 0; foreach (var intent in intents ?? Enumerable.Empty()) { - Activate(run, intent, catalog, frameId, intentIndex); + if (AetheriaRuntimeRunCheckpointCommit.TryParseEntityKey(intent?.ActorEntityKey ?? "", out var intentZone, out _) && + intentZone == zone.ZoneIndex) + Activate(run, intent, catalog, frameId, intentIndex); intentIndex++; } - foreach (var zone in run.Zones ?? Array.Empty()) - foreach (var entity in zone?.Entities ?? Array.Empty()) + foreach (var entity in entities ?? Array.Empty()) { if (entity == null) continue; @@ -36,6 +53,7 @@ namespace GameCult.Aetheria.State.Verse .ToArray(); for (var index = 0; index < active.Length; index++) { + ExecuteBehaviors(run, zone, entity, active[index], catalog, frameId, index, deltaSeconds); active[index].RemainingDuration -= deltaSeconds; if (active[index].RemainingDuration < 0) { @@ -54,6 +72,130 @@ namespace GameCult.Aetheria.State.Verse } } + private static void ExecuteBehaviors( + AetheriaRuntimeRunCheckpointCommit run, + AetheriaRuntimeZoneSnapshotCommit zone, + AetheriaRuntimeEntitySnapshotCommit entity, + 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"); + return; + } + + var elapsed = effect.Duration <= 0 + ? 1 + : Math.Max(0, Math.Min(1, (effect.Duration - effect.RemainingDuration) / effect.Duration)); + var effectiveness = item.EffectivenessCurveKeys == null || item.EffectivenessCurveKeys.Count == 0 + ? 1 + : AetheriaRuntimeDaemonItemStatQueries.SampleCurve(item.EffectivenessCurveKeys, elapsed); + var payloads = item.BehaviorPayloads ?? Array.Empty(); + 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)) + continue; + + BehaviorStopped(run, zone, entity, effect, frameId, effectIndex, behaviorIndex, reason); + break; + } + } + + private static bool ExecuteBehavior( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeActiveConsumableCommit effect, + AetheriaRuntimeBehaviorPayload payload, + AetheriaRuntimeCatalogSnapshot? catalog, + double effectiveness, + double deltaSeconds, + out string reason) + { + reason = ""; + switch (payload.Kind) + { + case "EnergyDraw": + { + var demand = Evaluate(payload, 1, effect, effectiveness) * (ReadBool(payload, 2) ? deltaSeconds : 1); + if (AetheriaRuntimeEnergySimulation.TryConsume(entity, catalog, demand)) + return true; + reason = "insufficient-energy"; + return false; + } + case "Heat": + // The fossil only added heat to equipped items; consumable heat was intentionally a no-op. + return true; + case "ItemUsage": + { + var itemKey = ReadItemKey(payload, 1); + if (!string.IsNullOrWhiteSpace(itemKey) && + AetheriaRuntimeCargoTransactions.TryFind(entity, itemKey, out var cargoIndex, out var x, out var y) && + AetheriaRuntimeCargoTransactions.TryRemoveQuantity(entity, cargoIndex, itemKey, x, y, 1, out _)) + return true; + reason = "missing-required-item"; + return false; + } + case "Wear": + return true; + default: + reason = "unsupported-behavior:" + (payload.Kind ?? ""); + return false; + } + } + + private static double Evaluate( + AetheriaRuntimeBehaviorPayload payload, + int fieldKey, + AetheriaRuntimeActiveConsumableCommit effect, + double effectiveness) => + AetheriaRuntimeDaemonItemStatQueries.EvaluateConsumablePerformanceStat( + Field(payload, fieldKey)?.Value, + effect.Quality, + effectiveness); + + private static bool ReadBool(AetheriaRuntimeBehaviorPayload payload, int fieldKey) => + Field(payload, fieldKey)?.Value?.BoolValue ?? false; + + private static string ReadItemKey(AetheriaRuntimeBehaviorPayload payload, int fieldKey) + { + var value = Field(payload, fieldKey)?.Value; + return value?.ItemKeyValue ?? value?.StringValue ?? ""; + } + + private static AetheriaRuntimeBehaviorField? Field(AetheriaRuntimeBehaviorPayload payload, int fieldKey) => + (payload.Fields ?? Array.Empty()) + .FirstOrDefault(field => field != null && field.Key == fieldKey); + + private static void BehaviorStopped( + AetheriaRuntimeRunCheckpointCommit run, + AetheriaRuntimeZoneSnapshotCommit zone, + 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", + Kind = "consumable.behavior.stopped", + FrameId = frameId, + ZoneIndex = zone.ZoneIndex, + SourceEntityIndex = entity.EntityIndex, + ItemKey = effect.ItemKey, + ScalarValue = behaviorIndex, + Reason = reason + }); + } + public static bool CanActivate( AetheriaRuntimeEntitySnapshotCommit entity, AetheriaRuntimeCatalogSnapshot? catalog, diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonItemStatQueries.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonItemStatQueries.cs index 82db5c9ca..045075229 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonItemStatQueries.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonItemStatQueries.cs @@ -112,6 +112,52 @@ namespace GameCult.Aetheria.State.Verse ConditionsFor(item, heat)); } + public static double EvaluateConsumablePerformanceStat( + AetheriaRuntimeBehaviorValue? value, + double quality, + double effectiveness) + { + var stat = ReadPerformanceStat(value); + var weightedQuality = stat.QualityExponent == 0 + ? 1 + : Math.Pow(Clamp01(quality), stat.QualityExponent); + return Lerp(stat.Min, stat.Max, Clamp01(effectiveness) * weightedQuality); + } + + public static double SampleCurve(IReadOnlyList? keys, double value) + { + if (keys == null || keys.Count == 0) + return Clamp01(value); + + var ordered = keys.OrderBy(key => key.Time).ToArray(); + if (value <= ordered[0].Time) + return Clamp01(ordered[0].Value); + + for (var index = 1; index < ordered.Length; index++) + { + var next = ordered[index]; + var previous = ordered[index - 1]; + if (value > next.Time) + continue; + + var span = next.Time - previous.Time; + var t = span <= double.Epsilon ? 1 : Clamp01((value - previous.Time) / span); + var t2 = t * t; + var t3 = t2 * t; + var h00 = 2 * t3 - 3 * t2 + 1; + var h10 = t3 - 2 * t2 + t; + var h01 = -2 * t3 + 3 * t2; + var h11 = t3 - t2; + return Clamp01( + h00 * previous.Value + + h10 * span * previous.OutTangent + + h01 * next.Value + + h11 * span * next.InTangent); + } + + return Clamp01(ordered[ordered.Length - 1].Value); + } + public static double EvaluatePerformanceStat( AetheriaRuntimePerformanceStat? stat, AetheriaRuntimeStatRecipePreviewState conditions) @@ -270,30 +316,6 @@ namespace GameCult.Aetheria.State.Verse return value; } - private static double SampleCurve(IReadOnlyList? keys, double value) - { - if (keys == null || keys.Count == 0) - return Clamp01(value); - - var ordered = keys.OrderBy(key => key.Time).ToArray(); - if (value <= ordered[0].Time) - return Clamp01(ordered[0].Value); - - for (var index = 1; index < ordered.Length; index++) - { - var next = ordered[index]; - var previous = ordered[index - 1]; - if (value > next.Time) - continue; - - var span = next.Time - previous.Time; - var t = span <= double.Epsilon ? 1 : Clamp01((value - previous.Time) / span); - return Clamp01(Lerp(previous.Value, next.Value, t)); - } - - return Clamp01(ordered[ordered.Length - 1].Value); - } - private static double ChildNumber(AetheriaRuntimeBehaviorValue? value, int index) { return ChildValue(value, index)?.NumberValue ?? 0; diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs index ba4e8afed..0d91673d4 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs @@ -32,13 +32,6 @@ namespace GameCult.Aetheria.State.Verse if (worldPhysics == null) throw new ArgumentNullException(nameof(worldPhysics)); - AetheriaRuntimeConsumableSimulation.Step( - run, - intents?.Consumables ?? Enumerable.Empty(), - catalog, - frameId, - deltaSeconds); - foreach (var zone in run.Zones ?? Array.Empty()) { if (zone == null) @@ -60,6 +53,14 @@ namespace GameCult.Aetheria.State.Verse AetheriaRuntimeThermalSimulation.UpdateEquipmentStates(entity, catalog, deltaSeconds); AetheriaRuntimeEnergySimulation.BeginTick(entity, catalog); } + AetheriaRuntimeConsumableSimulation.StepZone( + run, + zone, + entities, + intents?.Consumables ?? Enumerable.Empty(), + catalog, + frameId, + deltaSeconds); foreach (var movement in intents?.Movements ?? Enumerable.Empty()) ApplyMovementIntent(run, entities, movement, settings); StepTractorPower(entities, deltaSeconds); diff --git a/docs/aetheria-perfect-machine-map.md b/docs/aetheria-perfect-machine-map.md index 125cd5bde..4bce7cec7 100644 --- a/docs/aetheria-perfect-machine-map.md +++ b/docs/aetheria-perfect-machine-map.md @@ -118,6 +118,14 @@ legacy catalog cache, and legacy UI paths should be migration-only or deleted. only currently activatable consumable actions from this state; Unity's restored `ConsumableItemEffect` and action-bar fill are read models and cannot consume cargo or advance timers. + Active effects execute their typed payload array in authored order after + capacitor/reactor tick initialization. `EnergyDraw` delegates to the shared + energy ledger and `ItemUsage` delegates to the shared cargo transaction; a + failed or unsupported payload stops every later payload and publishes the + exact behavior index and reason. Consumable performance stats preserve the + fossil's lifetime-effectiveness and quality weighting. Consumable `Heat` + remains a successful no-op because the fossil explicitly added heat only to + equipped items; changing that balance requires an explicit design decision. Consumable activation, active-duration fill, runtime duration, and effectiveness curves now use typed item rows with neutral defaults for missing optional facets. Gear action-bar bindings read custom icon resource paths from typed item rows, then use typed weapon and hardpoint facets for diff --git a/docs/original-game-migration-matrix.md b/docs/original-game-migration-matrix.md index af0464c0d..7e428715c 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 now derives from enabled installed Sensor behaviors with diminishing-return array composition regardless of entity kind; contact refresh no longer overwrites emitted visibility; the old station range survives only as obsolete snapshot compatibility | author station/ship sensor loadout budgets, then prove power/thermal 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, advances timers on daemon time with the fossil's exact-zero final tick, removes expired effects, and emits activation/refusal/expiry facts; Unity remains a projection | execute authored behavior payloads in fossil order, including resource failure, effectiveness curves, and modifier cleanup | +| 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 | ## Ownership Invariants