diff --git a/.gitignore b/.gitignore index ce9e18618..20a0dd7b9 100644 --- a/.gitignore +++ b/.gitignore @@ -105,6 +105,8 @@ Aetheria.State/bin/ Aetheria.State/obj/ Aetheria.State.Daemon/bin/ Aetheria.State.Daemon/obj/ +Aetheria.State.Daemon.Smoke/bin/ +Aetheria.State.Daemon.Smoke/obj/ Aetheria.State.Import/bin/ Aetheria.State.Import/obj/ Aetheria.State.Smoke/bin/ diff --git a/Aetheria.State.Daemon.Smoke/Aetheria.State.Daemon.Smoke.csproj b/Aetheria.State.Daemon.Smoke/Aetheria.State.Daemon.Smoke.csproj new file mode 100644 index 000000000..8c34ca0a4 --- /dev/null +++ b/Aetheria.State.Daemon.Smoke/Aetheria.State.Daemon.Smoke.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0 + enable + latest + enable + + + + + + diff --git a/Aetheria.State.Daemon.Smoke/Program.cs b/Aetheria.State.Daemon.Smoke/Program.cs new file mode 100644 index 000000000..572a4c585 --- /dev/null +++ b/Aetheria.State.Daemon.Smoke/Program.cs @@ -0,0 +1,198 @@ +using GameCult.Aetheria.State.Verse; + +var checks = new AetheriaDaemonCombatKernelSmokeChecks(); +checks.Run(); +Console.WriteLine("Daemon combat kernel smoke passed."); + +internal sealed class AetheriaDaemonCombatKernelSmokeChecks +{ + public void Run() + { + DeterministicTicksProduceSameSnapshot(); + ActionableUnresolvedTrackCanFireBeforeVisibility(); + KernelWritesNativeSnapshotRows(); + } + + private static void DeterministicTicksProduceSameSnapshot() + { + var left = Scenario(); + var right = Scenario(); + var settings = AetheriaDaemonCombatKernelSettings.Default; + + for (var i = 0; i < 8; i++) + { + AetheriaDaemonCombatKernel.Step(left, null, 0.25, catalog: null, settings); + AetheriaDaemonCombatKernel.Step(right, null, 0.25, catalog: null, settings); + } + + RequireEqual(Snapshot(left), Snapshot(right), "combat kernel should be deterministic for the same native state"); + } + + private static void ActionableUnresolvedTrackCanFireBeforeVisibility() + { + var run = Scenario( + attackerContactConfidence: 0.35, + targetShield: 0.0); + var settings = new AetheriaDaemonCombatKernelSettings + { + TrackResolutionPerSecond = 0.0, + LaunchTrackThreshold = 0.3, + VisibleTrackThreshold = 0.8, + AbstractWeaponRange = 500.0, + DefaultWeaponDamage = 10.0, + WeaponCooldownSeconds = 1.0 + }; + + var report = AetheriaDaemonCombatKernel.Step(run, null, 0.2, catalog: null, settings); + var attacker = Entity(run, 1); + var target = Entity(run, 2); + var contact = attacker.Contacts.Single(contact => contact.TargetEntityIndex == 2); + + RequireEqual(1, report.ShotCount, "actionable unresolved track should permit a committed shot"); + Require(!contact.Visible, "track should remain unresolved below visibility threshold"); + Require(Stat(target, "hull") < 100.0, "shot should apply native hull damage"); + } + + private static void KernelWritesNativeSnapshotRows() + { + var run = Scenario(); + var report = AetheriaDaemonCombatKernel.Step(run, null, 0.5, catalog: null); + var attacker = Entity(run, 1); + + Require(report.ResolvedContactCount > 0, "kernel should resolve contacts into native contact rows"); + Require(attacker.Contacts.Count > 0, "contacts should live on AetheriaRuntimeEntitySnapshotCommit"); + Require(attacker.WeaponStates.Any(state => state.OwnerKind == "daemon-combat-kernel"), "weapon state should be a native weapon state row"); + Require(attacker.StatGrids.Any(grid => grid.Name == "cognitive-load"), "cognition pressure should be a native stat grid row"); + Require(attacker.StatGrids.Any(grid => grid.Name == "heat-capacity"), "thermal capacity should be a native stat grid row"); + } + + private static AetheriaRuntimeRunCheckpointCommit Scenario( + double attackerContactConfidence = 0.7, + double targetShield = 15.0) + { + return new AetheriaRuntimeRunCheckpointCommit + { + RunId = "daemon-combat-smoke", + CurrentZoneIndex = 0, + CurrentEntityKey = "zone.0.entity.1", + Zones = + [ + new AetheriaRuntimeZoneSnapshotCommit + { + ZoneIndex = 0, + SimulationTimeSeconds = 0, + Entities = + [ + new AetheriaRuntimeEntitySnapshotCommit + { + EntityIndex = 1, + Name = "Cold hunter", + Kind = "ship", + FactionKey = "player", + PositionX = 0, + PositionZ = 0, + DirectionX = 1, + DirectionY = 0, + TargetEntityIndex = 2, + IsActive = true, + Contacts = + [ + new AetheriaRuntimeEntityContactCommit + { + TargetEntityIndex = 2, + InfoGathered = attackerContactConfidence, + Hostile = true, + Visible = attackerContactConfidence >= 0.62 + } + ], + StatGrids = + [ + Grid("hull", 100.0), + Grid("shield", 20.0), + Grid("heat", 4.0), + Grid("sensor-sensitivity", 1.3), + Grid("cognition", 1.4), + Grid("fire-control", 1.2), + Grid("signature-masking", 0.3) + ] + }, + new AetheriaRuntimeEntitySnapshotCommit + { + EntityIndex = 2, + Name = "Hot brute", + Kind = "ship", + FactionKey = "raider", + PositionX = 180, + PositionZ = 0, + DirectionX = -1, + DirectionY = 0, + TargetEntityIndex = 1, + IsActive = true, + StatGrids = + [ + Grid("hull", 100.0), + Grid("shield", targetShield), + Grid("heat", 18.0), + Grid("heat-capacity", 180.0), + Grid("signature", 1.4), + Grid("signature-masking", 0.05), + Grid("sensor-sensitivity", 0.9), + Grid("cognition", 0.85), + Grid("fire-control", 1.05) + ] + } + ] + } + ] + }; + } + + private static AetheriaRuntimeEntitySnapshotCommit Entity(AetheriaRuntimeRunCheckpointCommit run, int index) + { + return run.Zones + .SelectMany(zone => zone.Entities) + .Single(entity => entity.EntityIndex == index); + } + + private static AetheriaRuntimeEntityStatGridCommit Grid(string name, double value) + { + return new AetheriaRuntimeEntityStatGridCommit + { + Name = name, + Width = 1, + Height = 1, + Values = [value] + }; + } + + private static double Stat(AetheriaRuntimeEntitySnapshotCommit entity, string name) + { + return entity.StatGrids + .First(grid => string.Equals(grid.Name, name, StringComparison.OrdinalIgnoreCase)) + .Values + .First(); + } + + private static string Snapshot(AetheriaRuntimeRunCheckpointCommit run) + { + return string.Join( + "|", + run.Zones + .SelectMany(zone => zone.Entities) + .OrderBy(entity => entity.EntityIndex) + .Select(entity => + $"{entity.EntityIndex}:{Stat(entity, "hull"):0.000}:{Stat(entity, "shield"):0.000}:{Stat(entity, "heat"):0.000}:{Stat(entity, "cognitive-load"):0.000}:{entity.Contacts.Count}:{entity.WeaponStates.Count}")); + } + + private static void Require(bool condition, string message) + { + if (!condition) + throw new InvalidOperationException(message); + } + + private static void RequireEqual(T expected, T actual, string message) + { + if (!EqualityComparer.Default.Equals(expected, actual)) + throw new InvalidOperationException($"{message}. Expected {expected}; actual {actual}."); + } +} diff --git a/Aetheria.State.Daemon/AetheriaDaemonCombatKernel.cs b/Aetheria.State.Daemon/AetheriaDaemonCombatKernel.cs new file mode 100644 index 000000000..59854f858 --- /dev/null +++ b/Aetheria.State.Daemon/AetheriaDaemonCombatKernel.cs @@ -0,0 +1,458 @@ +using GameCult.Aetheria.State.Verse; + +public sealed class AetheriaDaemonCombatKernelSettings +{ + public static AetheriaDaemonCombatKernelSettings Default { get; } = new(); + + public double DefaultHull { get; init; } = 100.0; + public double DefaultShield { get; init; } = 35.0; + public double DefaultHeatCapacity { get; init; } = 120.0; + public double DefaultSignature { get; init; } = 1.0; + public double DefaultSensorSensitivity { get; init; } = 1.0; + public double DefaultSignatureMasking { get; init; } = 0.0; + public double DefaultCognition { get; init; } = 1.0; + public double DefaultFireControl { get; init; } = 1.0; + public double SensorFalloffDistance { get; init; } = 520.0; + public double TrackResolutionPerSecond { get; init; } = 0.46; + public double VisibleTrackThreshold { get; init; } = 0.62; + public double LaunchTrackThreshold { get; init; } = 0.34; + public double TerminalSubsystemThreshold { get; init; } = 0.82; + public double AbstractWeaponRange { get; init; } = 650.0; + public double DefaultWeaponDamage { get; init; } = 11.0; + public double WeaponCooldownSeconds { get; init; } = 1.0; + public double WeaponHeat { get; init; } = 5.5; + public double HeatDissipationPerSecond { get; init; } = 3.5; + public double HeatSignatureScale { get; init; } = 0.85; + public double MovementSignatureScale { get; init; } = 0.008; + public double CognitiveLoadDecayPerSecond { get; init; } = 0.22; + public double CognitiveLoadPerTrack { get; init; } = 0.08; + public double SubsystemHitDamageBonus { get; init; } = 0.28; +} + +public sealed class AetheriaDaemonCombatStepReport +{ + public AetheriaDaemonCombatStepReport( + IReadOnlyList engagements, + int resolvedContactCount) + { + Engagements = engagements ?? Array.Empty(); + ResolvedContactCount = resolvedContactCount; + } + + public IReadOnlyList Engagements { get; } + public int ResolvedContactCount { get; } + public int ShotCount => Engagements.Count; +} + +public sealed class AetheriaDaemonCombatEngagementReport +{ + public int AttackerEntityIndex { get; init; } + public int TargetEntityIndex { get; init; } + public double TrackConfidence { get; init; } + public double HitQuality { get; init; } + public double DamageApplied { get; init; } + public bool SubsystemQualityHit { get; init; } +} + +public static class AetheriaDaemonCombatKernel +{ + private const string Hull = "hull"; + private const string Shield = "shield"; + private const string Heat = "heat"; + private const string HeatCapacity = "heat-capacity"; + private const string Signature = "signature"; + private const string SignatureMasking = "signature-masking"; + private const string SensorSensitivity = "sensor-sensitivity"; + private const string Cognition = "cognition"; + private const string CognitiveLoad = "cognitive-load"; + private const string FireControl = "fire-control"; + private const string MunitionPressure = "munition-pressure"; + private const string KernelWeaponOwner = "daemon-combat-kernel"; + + public static AetheriaDaemonCombatStepReport Step( + AetheriaRuntimeRunCheckpointCommit? run, + AetheriaRuntimeDaemonIntentState? intents, + double deltaSeconds, + AetheriaRuntimeCatalogSnapshot? catalog, + AetheriaDaemonCombatKernelSettings? settings = null) + { + if (run == null || deltaSeconds <= 0 || !double.IsFinite(deltaSeconds)) + return new AetheriaDaemonCombatStepReport(Array.Empty(), 0); + + settings ??= AetheriaDaemonCombatKernelSettings.Default; + var engagements = new List(); + var resolvedContacts = 0; + foreach (var zone in run.Zones ?? Array.Empty()) + { + if (zone == null) + continue; + + var entities = (zone.Entities ?? Array.Empty()) + .Where(entity => entity != null) + .OrderBy(entity => entity.EntityIndex) + .ToArray(); + if (entities.Length <= 1) + continue; + + foreach (var entity in entities) + EnsureCombatStats(entity, catalog, settings); + + StepContactResolution(entities, deltaSeconds, settings, ref resolvedContacts); + StepWeapons(entities, deltaSeconds, settings, engagements); + StepThermalAndCognition(entities, deltaSeconds, settings); + } + + return new AetheriaDaemonCombatStepReport(engagements, resolvedContacts); + } + + private static void StepContactResolution( + IReadOnlyList entities, + double deltaSeconds, + AetheriaDaemonCombatKernelSettings settings, + ref int resolvedContacts) + { + foreach (var observer in entities) + { + if (!IsAlive(observer)) + continue; + + var contacts = new List(); + var existing = (observer.Contacts ?? Array.Empty()) + .Where(contact => contact != null) + .GroupBy(contact => contact.TargetEntityIndex) + .ToDictionary(group => group.Key, group => group.First()); + foreach (var target in entities) + { + if (target.EntityIndex == observer.EntityIndex || !IsAlive(target)) + continue; + + existing.TryGetValue(target.EntityIndex, out var previous); + var confidence = previous?.InfoGathered ?? 0.0; + var gain = ResolveTrackGain(observer, target, deltaSeconds, settings); + confidence = Clamp01(confidence + gain); + var visible = confidence >= settings.VisibleTrackThreshold; + if (visible) + resolvedContacts++; + + contacts.Add(new AetheriaRuntimeEntityContactCommit + { + TargetEntityIndex = target.EntityIndex, + InfoGathered = confidence, + Hostile = Hostile(observer, target), + Visible = visible + }); + } + + observer.Contacts = contacts + .OrderBy(contact => contact.TargetEntityIndex) + .ToArray(); + observer.Visibility = contacts.Count == 0 ? 0.0 : contacts.Max(contact => contact.InfoGathered); + observer.VisibilitySourceCount = contacts.Count(contact => contact.Visible); + SetStat(observer, CognitiveLoad, ClampNonNegative( + GetStat(observer, CognitiveLoad) + + contacts.Count * settings.CognitiveLoadPerTrack * deltaSeconds)); + } + } + + private static void StepWeapons( + IReadOnlyList entities, + double deltaSeconds, + AetheriaDaemonCombatKernelSettings settings, + List engagements) + { + var byIndex = entities.ToDictionary(entity => entity.EntityIndex); + foreach (var attacker in entities) + { + var weaponState = EnsureKernelWeaponState(attacker, settings); + weaponState.Firing = false; + weaponState.CooldownProgress = Math.Max(0, weaponState.CooldownProgress - deltaSeconds); + weaponState.CoolingDown = weaponState.CooldownProgress > 0; + + if (!IsAlive(attacker) || + attacker.TargetEntityIndex < 0 || + !byIndex.TryGetValue(attacker.TargetEntityIndex, out var target) || + !IsAlive(target) || + !Hostile(attacker, target) || + Distance(attacker, target) > settings.AbstractWeaponRange) + { + continue; + } + + var confidence = ContactConfidence(attacker, target.EntityIndex); + if (confidence < settings.LaunchTrackThreshold || weaponState.CooldownProgress > 0) + continue; + + var hitQuality = ResolveHitQuality(attacker, target, confidence); + var subsystemHit = confidence >= settings.TerminalSubsystemThreshold && + EffectiveCognition(attacker) > 1.15; + var damage = settings.DefaultWeaponDamage * hitQuality * + (subsystemHit ? 1.0 + settings.SubsystemHitDamageBonus : 1.0); + + ApplyDamage(target, damage); + SetStat(attacker, Heat, GetStat(attacker, Heat) + settings.WeaponHeat); + SetStat(attacker, MunitionPressure, GetStat(attacker, MunitionPressure) + confidence * 0.1); + weaponState.Firing = true; + weaponState.CoolingDown = true; + weaponState.CooldownProgress = settings.WeaponCooldownSeconds; + weaponState.LockProgress = confidence; + weaponState.LockTargetEntityIndex = target.EntityIndex; + engagements.Add(new AetheriaDaemonCombatEngagementReport + { + AttackerEntityIndex = attacker.EntityIndex, + TargetEntityIndex = target.EntityIndex, + TrackConfidence = confidence, + HitQuality = hitQuality, + DamageApplied = damage, + SubsystemQualityHit = subsystemHit + }); + } + } + + private static void StepThermalAndCognition( + IReadOnlyList entities, + double deltaSeconds, + AetheriaDaemonCombatKernelSettings settings) + { + foreach (var entity in entities) + { + SetStat(entity, Heat, Math.Max(0, GetStat(entity, Heat) - settings.HeatDissipationPerSecond * deltaSeconds)); + SetStat(entity, CognitiveLoad, Math.Max(0, GetStat(entity, CognitiveLoad) - settings.CognitiveLoadDecayPerSecond * deltaSeconds)); + entity.IsActive = IsAlive(entity); + if (!entity.IsActive) + { + entity.VelocityX = 0; + entity.VelocityY = 0; + entity.TargetEntityIndex = -1; + } + } + } + + private static void EnsureCombatStats( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeCatalogSnapshot? catalog, + AetheriaDaemonCombatKernelSettings settings) + { + var hullItem = catalog?.FindItem(entity.HullItemKey ?? ""); + EnsureStat(entity, Hull, ResolveHull(entity, hullItem, settings)); + EnsureStat(entity, Shield, settings.DefaultShield); + EnsureStat(entity, Heat, 0.0); + EnsureStat(entity, HeatCapacity, ResolveHeatCapacity(entity, catalog, hullItem, settings)); + EnsureStat(entity, Signature, settings.DefaultSignature); + EnsureStat(entity, SignatureMasking, settings.DefaultSignatureMasking); + EnsureStat(entity, SensorSensitivity, settings.DefaultSensorSensitivity); + EnsureStat(entity, Cognition, settings.DefaultCognition); + EnsureStat(entity, CognitiveLoad, 0.0); + EnsureStat(entity, FireControl, settings.DefaultFireControl); + EnsureStat(entity, MunitionPressure, 0.0); + if (!entity.IsActive && GetStat(entity, Hull) > 0) + entity.IsActive = true; + } + + private static double ResolveTrackGain( + AetheriaRuntimeEntitySnapshotCommit observer, + AetheriaRuntimeEntitySnapshotCommit target, + double deltaSeconds, + AetheriaDaemonCombatKernelSettings settings) + { + var distanceFactor = 1.0 + Distance(observer, target) / Math.Max(1.0, settings.SensorFalloffDistance); + distanceFactor *= distanceFactor; + var masking = 1.0 + Math.Max(0.0, GetStat(target, SignatureMasking)); + var sensor = Math.Max(0.05, GetStat(observer, SensorSensitivity)); + var cognition = Math.Max(0.05, EffectiveCognition(observer)); + var signature = ResolveSignature(target, settings); + return deltaSeconds * settings.TrackResolutionPerSecond * sensor * cognition * signature / (distanceFactor * masking); + } + + private static double ResolveSignature( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaDaemonCombatKernelSettings settings) + { + var capacity = Math.Max(1.0, GetStat(entity, HeatCapacity)); + var heatRatio = GetStat(entity, Heat) / capacity; + var speed = Math.Sqrt(entity.VelocityX * entity.VelocityX + entity.VelocityY * entity.VelocityY); + return Math.Max( + 0.05, + GetStat(entity, Signature) + + heatRatio * settings.HeatSignatureScale + + speed * settings.MovementSignatureScale); + } + + private static double ResolveHitQuality( + AetheriaRuntimeEntitySnapshotCommit attacker, + AetheriaRuntimeEntitySnapshotCommit target, + double confidence) + { + var fireControl = Math.Max(0.05, GetStat(attacker, FireControl)); + var cognition = Math.Max(0.05, EffectiveCognition(attacker)); + var masking = Math.Max(0.0, GetStat(target, SignatureMasking)); + var speed = Math.Sqrt(target.VelocityX * target.VelocityX + target.VelocityY * target.VelocityY); + var targetDifficulty = 1.0 + masking * 0.35 + speed * 0.003; + var quality = (0.45 + confidence * 0.75) * fireControl * (0.75 + cognition * 0.25) / targetDifficulty; + return Clamp(quality, 0.08, 1.75); + } + + private static double ResolveHull( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeCatalogItem? hullItem, + AetheriaDaemonCombatKernelSettings settings) + { + if (hullItem?.HullArmor > 0) + return hullItem.HullArmor; + if (hullItem?.Durability > 0) + return hullItem.Durability; + return string.Equals(entity.Kind, "station", StringComparison.OrdinalIgnoreCase) + ? settings.DefaultHull * 3.0 + : settings.DefaultHull; + } + + private static double ResolveHeatCapacity( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeCatalogSnapshot? catalog, + AetheriaRuntimeCatalogItem? hullItem, + AetheriaDaemonCombatKernelSettings settings) + { + var heatCapacity = CapacityFromItem(hullItem); + foreach (var slot in entity.Equipment ?? Array.Empty()) + heatCapacity += CapacityFromItem(catalog?.FindItem(slot?.Item?.ItemKey ?? "")); + return heatCapacity > 0 ? heatCapacity : settings.DefaultHeatCapacity; + } + + private static double CapacityFromItem(AetheriaRuntimeCatalogItem? item) + { + if (item == null) + return 0.0; + return Math.Max(0.0, item.Mass) * Math.Max(0.0, item.SpecificHeat); + } + + private static AetheriaRuntimeWeaponStateCommit EnsureKernelWeaponState( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaDaemonCombatKernelSettings settings) + { + var states = (entity.WeaponStates ?? Array.Empty()).ToList(); + var state = states.FirstOrDefault(candidate => + candidate != null && + string.Equals(candidate.OwnerKind, KernelWeaponOwner, StringComparison.Ordinal) && + candidate.OwnerIndex == entity.EntityIndex); + if (state != null) + return state; + + state = new AetheriaRuntimeWeaponStateCommit + { + OwnerKind = KernelWeaponOwner, + OwnerIndex = entity.EntityIndex, + BehaviorIndex = 0, + BehaviorKind = "AbstractCombatKernel", + Ammo = -1, + BurstInterval = settings.WeaponCooldownSeconds, + LockTargetEntityIndex = -1 + }; + states.Add(state); + entity.WeaponStates = states.ToArray(); + return state; + } + + private static double EffectiveCognition(AetheriaRuntimeEntitySnapshotCommit entity) + { + return GetStat(entity, Cognition) / (1.0 + Math.Max(0.0, GetStat(entity, CognitiveLoad))); + } + + private static double ContactConfidence(AetheriaRuntimeEntitySnapshotCommit observer, int targetEntityIndex) + { + return (observer.Contacts ?? Array.Empty()) + .FirstOrDefault(contact => contact.TargetEntityIndex == targetEntityIndex) + ?.InfoGathered ?? 0.0; + } + + private static bool Hostile( + AetheriaRuntimeEntitySnapshotCommit left, + AetheriaRuntimeEntitySnapshotCommit right) + { + if (string.IsNullOrWhiteSpace(left.FactionKey) || string.IsNullOrWhiteSpace(right.FactionKey)) + return false; + return !string.Equals(left.FactionKey, right.FactionKey, StringComparison.OrdinalIgnoreCase); + } + + private static bool IsAlive(AetheriaRuntimeEntitySnapshotCommit entity) + { + return entity.IsActive && GetStat(entity, Hull) > 0; + } + + private static void ApplyDamage(AetheriaRuntimeEntitySnapshotCommit target, double damage) + { + var shield = GetStat(target, Shield); + var shieldDamage = Math.Min(shield, damage); + if (shieldDamage > 0) + { + SetStat(target, Shield, shield - shieldDamage); + damage -= shieldDamage; + } + + if (damage > 0) + SetStat(target, Hull, Math.Max(0, GetStat(target, Hull) - damage)); + } + + private static void EnsureStat(AetheriaRuntimeEntitySnapshotCommit entity, string name, double value) + { + if (!HasStat(entity, name)) + SetStat(entity, name, value); + } + + private static bool HasStat(AetheriaRuntimeEntitySnapshotCommit entity, string name) + { + return (entity.StatGrids ?? Array.Empty()) + .Any(grid => string.Equals(grid?.Name, name, StringComparison.OrdinalIgnoreCase)); + } + + private static double GetStat(AetheriaRuntimeEntitySnapshotCommit entity, string name) + { + var grid = (entity.StatGrids ?? Array.Empty()) + .FirstOrDefault(candidate => string.Equals(candidate?.Name, name, StringComparison.OrdinalIgnoreCase)); + if (grid?.Values == null || grid.Values.Count == 0) + return 0.0; + return grid.Values.Average(); + } + + private static void SetStat(AetheriaRuntimeEntitySnapshotCommit entity, string name, double value) + { + var grids = (entity.StatGrids ?? Array.Empty()).ToList(); + var index = grids.FindIndex(candidate => string.Equals(candidate?.Name, name, StringComparison.OrdinalIgnoreCase)); + var grid = new AetheriaRuntimeEntityStatGridCommit + { + Name = name, + Width = 1, + Height = 1, + Values = new[] { double.IsFinite(value) ? value : 0.0 } + }; + if (index >= 0) + grids[index] = grid; + else + grids.Add(grid); + entity.StatGrids = grids; + } + + private static double Distance(AetheriaRuntimeEntitySnapshotCommit left, AetheriaRuntimeEntitySnapshotCommit right) + { + var dx = right.PositionX - left.PositionX; + var dy = right.PositionZ - left.PositionZ; + return Math.Sqrt(dx * dx + dy * dy); + } + + private static double Clamp01(double value) + { + return Clamp(value, 0.0, 1.0); + } + + private static double ClampNonNegative(double value) + { + return double.IsFinite(value) && value > 0 ? value : 0.0; + } + + private static double Clamp(double value, double min, double max) + { + if (!double.IsFinite(value)) + return min; + if (value < min) + return min; + return value > max ? max : value; + } +} diff --git a/Aetheria.State.Daemon/Program.cs b/Aetheria.State.Daemon/Program.cs index b2533fab0..a2ccccfb3 100644 --- a/Aetheria.State.Daemon/Program.cs +++ b/Aetheria.State.Daemon/Program.cs @@ -186,6 +186,19 @@ static async Task TickAsync( LoadoutTemplates = loadoutTemplates } }); + if (options.UseAbstractCombatKernel) + { + AetheriaDaemonCombatKernel.Step( + result.Frame.Run, + result.Intents, + fixedDeltaSeconds, + node.RuntimeCatalog().Latest(), + options.CombatKernelSettings); + result.Frame.Capabilities = (result.Frame.Capabilities ?? Array.Empty()) + .Concat(new[] { "aetheria.daemon.abstract_combat_kernel.v1" }) + .Distinct(StringComparer.Ordinal) + .ToArray(); + } result.Frame.CumulativeImportedFactIds = currentFrame?.CumulativeImportedFactIds ?? Array.Empty(); result.Frame.CumulativeRejectedImportedFactIds = @@ -2497,6 +2510,9 @@ internal sealed class AetheriaDaemonHostOptions AetheriaRuntimeDaemonRenderSettings.AetheriaDefault; public AetheriaRuntimeDaemonSimulationSettings SimulationSettings { get; init; } = AetheriaRuntimeDaemonSimulationSettings.AetheriaDefault; + public AetheriaDaemonCombatKernelSettings CombatKernelSettings { get; init; } = + AetheriaDaemonCombatKernelSettings.Default; + public bool UseAbstractCombatKernel { get; init; } public bool Once { get; init; } public static AetheriaDaemonHostOptions Parse(IReadOnlyList args) @@ -2553,6 +2569,7 @@ internal sealed class AetheriaDaemonHostOptions TickInterval = TimeSpan.FromMilliseconds(intervalMs), ApiPublicationInterval = TimeSpan.FromMilliseconds(apiPublicationIntervalMs), FixedDeltaSeconds = fixedDeltaMs / 1000.0, + UseAbstractCombatKernel = HasFlag(args, "--abstract-combat-kernel"), Once = HasFlag(args, "--once") }; } diff --git a/Aetheria.State/README.md b/Aetheria.State/README.md index 9cce26e0e..c832b88ca 100644 --- a/Aetheria.State/README.md +++ b/Aetheria.State/README.md @@ -49,6 +49,17 @@ renderer-side commit authority. `Aetheria.State.Daemon` owns the long-running `aetheria-daemon` heartbeat and publishes `starting`, `running`, and `stopping` states through `Aetheria.State`; legacy outbox status remains operation telemetry, not daemon-session ownership. +The daemon also owns the first deterministic abstract combat kernel. That +kernel consumes native runtime run/zone/entity snapshot commits directly and +mutates those same snapshot rows: stat grids for hull, shield, heat, thermal +capacity, signature masking, cognition, cognitive load, fire control, and +munition pressure; contact rows for track confidence and visibility; and native +weapon-state rows for abstract firing and lock state. It is meant for +out-of-view combat advancement and balance simulation without creating a second +private combat state model. The current C# host exposes it behind +`--abstract-combat-kernel` while the older shared daemon simulation remains the +default compatibility path. The promotion path is to move this authority into +the Rust daemon/Ymir simulation body, not into Unity or a renderer package. Unity Eve surfaces construct typed `gamecult.eve.command.v1` command documents. `AetheriaRuntimeVerseClient` is the shared CultMesh client boundary for headless, Unity, and non-Unity runtimes. Typed command clients submit directly diff --git a/Aetheria.State/docs/daemon-code-map-for-rust-port.md b/Aetheria.State/docs/daemon-code-map-for-rust-port.md index 61eafd852..bcbed0ce5 100644 --- a/Aetheria.State/docs/daemon-code-map-for-rust-port.md +++ b/Aetheria.State/docs/daemon-code-map-for-rust-port.md @@ -31,6 +31,7 @@ flowchart TD Tick["Tick runner"] Ops["Operations executor\nmutates run checkpoint"] Sim["Daemon sim\nmovement, AI, combat, contacts"] + CombatKernel["Abstract combat kernel\nnative snapshots, pressure clocks"] Frame["Frame document\nrun snapshot + facts"] Projection["Game viewport documents\nviewport, gravity, inventory"] Publications["Publications\nCultNet records, .cc files, RUDP snapshots, Eve surfaces"] @@ -43,7 +44,9 @@ flowchart TD Authority --> Tick Tick --> Ops Ops --> Sim + Ops --> CombatKernel Sim --> Frame + CombatKernel --> Frame Frame --> Projection Frame --> Publications Projection --> Publications @@ -83,6 +86,7 @@ These files define the deprecated reference surface. They should be treated as A | Command application | `Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs` | Current meaning of every gameplay command and rejection. | | Tick composition | `Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs` | Current order of command filtering, operation execution, sim step, frame creation, publication payloads. | | Daemon sim | `Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs` | Existing movement, hostile AI, combat, heat, and contact rules. | +| Abstract combat kernel | `Aetheria.State.Daemon/AetheriaDaemonCombatKernel.cs` | Daemon-owned deterministic combat pressure model over native run/zone/entity snapshot commits. This is the first out-of-view combat oracle shape and should be promoted into the Rust daemon simulation body, not into Unity. | | Game viewport documents | `Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs` | Existing map, object, gravity, selected object, docking, refit, sector, and inventory projections. | | Client facade | `Packages/org.gamecult.aetheria.state/Runtime/AetheriaClient.cs` | C# client observation and typed operation ergonomics. | | Verse client | `Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeVerseClient.cs` | Current lower-level typed document reads/watches and command submission. | @@ -94,6 +98,41 @@ These files define the deprecated reference surface. They should be treated as A | Ymir Unity bridge | `Assets/Scripts/Gameplay/Physics/AetheriaYmirPhysicsBridge.cs` | Current Unity presentation adapter that maps daemon SoA bodies into typed Ymir query worlds. | | Ymir query tests | `Assets/Scripts/Tests/YmirPhysicsQueryTests.cs` | Current expectations for integration, radial fields, contacts, overlap sphere/circle, and cast sphere/circle; useful semantics should survive, DTO/endpoint shape should not. | +## Abstract Combat Kernel + +`Aetheria.State.Daemon/AetheriaDaemonCombatKernel.cs` is the first daemon-owned +combat oracle for out-of-view simulation and balance runs. It is deliberately +not a Unity feature and not a renderer projection. Its input is the same native +`AetheriaRuntimeRunCheckpointCommit` graph the daemon already publishes in +frames: zones, entities, stat grids, contacts, weapon states, target indices, +factions, velocities, equipment, and optional runtime catalog facts. Its output +is mutation of that same graph plus a transient step report for smoke tests and +future balance harnesses. + +The current kernel models pressure rather than rendered combat: + +- thermal pressure through `heat` and `heat-capacity` stat grids; +- detection pressure through `signature`, `signature-masking`, + `sensor-sensitivity`, and native contact confidence rows; +- cognition pressure through `cognition`, `cognitive-load`, and + `fire-control` stat grids; +- munition/commitment pressure through `munition-pressure`, native + `AetheriaRuntimeWeaponStateCommit` rows, launch thresholds, lock confidence, + and subsystem-quality damage bonuses. + +The invariant is state compatibility. Out-of-view combat must be able to become +visible combat by handing the frame back to a client or future presentation +runtime without translating a private oracle state. Mechanics not yet present in +visible gameplay may exist as named stat grids or transient reports, but they +must not become a hidden second save model. + +The C# host currently gates the kernel behind `--abstract-combat-kernel` because +`AetheriaRuntimeDaemonTickRunner` still calls the older shared daemon +simulation. That is a temporary compatibility boundary, not a second owner. The +rebuild target is one daemon simulation body where command application, +abstract combat, visible physics, contacts, heat, and publications all commit to +the same typed state primitive. + ## Current Control Flow The C# host does this today: