diff --git a/Aetheria.State.Daemon.Smoke/Program.cs b/Aetheria.State.Daemon.Smoke/Program.cs index 2dae5a3b3..1e8ae3312 100644 --- a/Aetheria.State.Daemon.Smoke/Program.cs +++ b/Aetheria.State.Daemon.Smoke/Program.cs @@ -179,6 +179,9 @@ internal sealed class AetheriaDaemonYmirSmokeChecks ThermalMedicalExposureUsesCockpitTemperature, ThermalMedicalDeathUsesOrdinaryDestructionPath, MultipleActorsUseTheSameMovementLever, + DirectionalThrustersOwnOrdinaryFlightFeedback, + UnpoweredThrustersCannotMoveOrAdvertisePlume, + RareAetherDriveSpoolsOnlyOnModifiedHullFixture, LookDirectionRejectsInvalidVectorsWithoutMutatingTheShip, AgentClaimsAndCompletesExploreTaskThroughCommands, SchedulerAssignsHighestPriorityCompatibleTask, @@ -1033,6 +1036,21 @@ internal sealed class AetheriaDaemonYmirSmokeChecks { var catalog = AetheriaRuntimeCatalogStore.OpenReadOnly( Path.Combine(Directory.GetCurrentDirectory(), "GameData", "aetheria-world.cc")); + var drives = catalog.Items + .Where(item => item.BehaviorKinds.Contains(AetheriaRuntimeBehaviorKinds.AetherDrive)) + .ToArray(); + var driveHulls = catalog.Items + .Where(item => item.Hardpoints.Any(point => point.Type == "AetherDrive")) + .ToArray(); + Require(drives.Length == 1 && drives[0].Name == "Traction" && + drives[0].HardpointType == "AetherDrive" && drives[0].Price == 250000, + "canonical AetherDrive must remain the singular expensive Traction retrofit"); + Require(driveHulls.Length == 1 && driveHulls[0].Name == "LonginusX" && + driveHulls[0].Price == 7500000, + "canonical AetherDrive compatibility must remain confined to the rare modified LonginusX hull"); + Require(catalog.Items.Count(item => !string.IsNullOrWhiteSpace(item.HullType) && + item.Hardpoints.All(point => point.Type != "AetherDrive")) > driveHulls.Length, + "ordinary hull variants must outnumber and exclude the AetherDrive retrofit path"); var mine = catalog.Items.Single(item => item.ItemKey == "aetheria.item_definition:legacy:e78d3670-3ac6-4d9b-834c-1da4228ac311"); RequireEqual("Mine Launcher", mine.Name, "recovered item must retain fossil identity"); @@ -1695,6 +1713,133 @@ internal sealed class AetheriaDaemonYmirSmokeChecks Array.Empty(), Array.Empty()); + private static AetheriaRuntimeBehaviorValue Vector(params double[] values) => new( + "float3", + "", + 0, + false, + "", + "", + values.Select(Number).ToArray(), + Array.Empty()); + + private static AetheriaRuntimeBehaviorValue Curve(params AetheriaRuntimeCurveKey[] keys) => new( + "bezier-curve", + "", + 0, + false, + "", + "", + keys.Select(key => Vector(key.Time, key.Value, key.InTangent, key.OutTangent)).ToArray(), + Array.Empty()); + + private static AetheriaRuntimeBehaviorPayload AetherDrivePayload( + double couplingEfficiency = 1, + double energyDraw = 0) => new( + 0, + AetheriaRuntimeBehaviorKinds.AetherDrive, + 0, + [ + new AetheriaRuntimeBehaviorField(1, Vector(100, 100, 100)), + new AetheriaRuntimeBehaviorField(2, Vector(10, 10, 0.1)), + new AetheriaRuntimeBehaviorField(3, PerformanceStat(100)), + new AetheriaRuntimeBehaviorField(4, Vector(10, 10, 10)), + new AetheriaRuntimeBehaviorField(5, PerformanceStat(1)), + new AetheriaRuntimeBehaviorField(6, PerformanceStat(couplingEfficiency)), + new AetheriaRuntimeBehaviorField(7, PerformanceStat(10000)), + new AetheriaRuntimeBehaviorField(8, Curve( + new AetheriaRuntimeCurveKey(0, 1, 0, 0), + new AetheriaRuntimeCurveKey(1, 1, 0, 0))), + new AetheriaRuntimeBehaviorField(9, PerformanceStat(energyDraw)), + new AetheriaRuntimeBehaviorField(10, PerformanceStat(0)) + ]); + + private static AetheriaRuntimeBehaviorPayload ThrusterPayload() => new( + 0, + AetheriaRuntimeBehaviorKinds.Thruster, + 0, + [ + new AetheriaRuntimeBehaviorField(1, PerformanceStat(90)), + new AetheriaRuntimeBehaviorField(2, PerformanceStat(2)), + new AetheriaRuntimeBehaviorField(3, PerformanceStat(1)), + new AetheriaRuntimeBehaviorField(4, PerformanceStat(0)) + ]); + + private static AetheriaRuntimeCatalogSnapshot EquipThrusterBank( + IEnumerable entities, + params AetheriaRuntimeCatalogItem[] additionalItems) + { + var hull = HullCatalogItem("smoke-standard-thruster-hull", 5, 5, 0); + hull.HullDrag = 1; + var thruster = CatalogItem("smoke-directional-thruster", ThrusterPayload()); + var placements = new[] + { + (0, 2, "None"), (4, 2, "None"), + (0, 1, "Half"), (4, 1, "Half"), + (2, 0, "CounterClockwise"), (2, 4, "CounterClockwise"), + (1, 0, "Clockwise"), (1, 4, "Clockwise") + }; + foreach (var entity in entities.Where(entity => entity.Kind == "ship")) + { + if (string.IsNullOrWhiteSpace(entity.HullItemKey)) + entity.HullItemKey = hull.ItemKey; + entity.Equipment = (entity.Equipment ?? Array.Empty()) + .Concat(placements.Select(value => new AetheriaRuntimeLoadoutItemSlotCommit + { + X = value.Item1, + Y = value.Item2, + Rotation = value.Item3, + Item = new AetheriaRuntimeLoadoutItemCommit + { + ItemKey = thruster.ItemKey, + Quantity = 1, + Durability = 1, + Enabled = true + } + })) + .ToArray(); + } + return new AetheriaRuntimeCatalogSnapshot( + additionalItems.Concat([hull, thruster]).ToArray(), [], []); + } + + private static AetheriaRuntimeCatalogSnapshot EquipAetherDrive( + IEnumerable entities, + params AetheriaRuntimeCatalogItem[] additionalItems) + { + var hull = HullCatalogItem("smoke-rare-aether-drive-hull", 3, 3, 0); + hull.Hardpoints = + [ + new AetheriaRuntimeHardpoint( + "AetherDrive", 1, 1, 1, 1, 1, + [new AetheriaRuntimeShapeCell(0, 0)], "", "None", 0) + ]; + var drive = CatalogItem("smoke-aether-drive", AetherDrivePayload()); + drive.HardpointType = "AetherDrive"; + foreach (var entity in entities.Where(entity => entity.Kind == "ship")) + { + if (string.IsNullOrWhiteSpace(entity.HullItemKey)) + entity.HullItemKey = hull.ItemKey; + entity.Equipment = (entity.Equipment ?? Array.Empty()) + .Concat([new AetheriaRuntimeLoadoutItemSlotCommit + { + X = 1, + Y = 1, + Rotation = "None", + Item = new AetheriaRuntimeLoadoutItemCommit + { + ItemKey = drive.ItemKey, + Quantity = 1, + Durability = 1, + Enabled = true + } + }]) + .ToArray(); + } + return new AetheriaRuntimeCatalogSnapshot( + additionalItems.Concat([hull, drive]).ToArray(), [], []); + } + private static AetheriaRuntimeBehaviorPayload CapacitorPayload(double capacity, double efficiency) => new( 0, "Capacitor", 0, [ @@ -1748,6 +1893,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks { var agent = Entity(0, 0, "workers"); agent.AgentTaskCapabilities = [AetheriaRuntimeAgentTaskTypes.Defend]; + var catalog = EquipThrusterBank([agent]); var run = new AetheriaRuntimeRunCheckpointCommit { RunId = "agent-patrol-smoke", @@ -1791,14 +1937,16 @@ internal sealed class AetheriaDaemonYmirSmokeChecks }; var sawWestLeg = false; var sawReturnToEast = false; - for (var frame = 0; frame < 30; frame++) + var physics = NewPhysics(); + for (var frame = 0; frame < 100; frame++) { var tick = AetheriaRuntimeDaemonTickRunner.Tick( Path.Combine(Path.GetTempPath(), "aetheria-agent-patrol-smoke.cc"), run, new AetheriaRuntimeDaemonTickOptions { - WorldPhysics = NewPhysics(), + WorldPhysics = physics, + Catalog = catalog, FrameId = frame, FixedDeltaSeconds = 0.1, SimulationTimeSeconds = frame * 0.1, @@ -1997,10 +2145,10 @@ internal sealed class AetheriaDaemonYmirSmokeChecks new AetheriaRuntimeBehaviorField(24, PerformanceStat(1)), new AetheriaRuntimeBehaviorField(25, PerformanceStat(1)) ]); - var catalog = new AetheriaRuntimeCatalogSnapshot( - [CatalogItem("test-lock-cannon", weaponPayload), CatalogItem("test-attack-capacitor", CapacitorPayload(50, 1))], - Array.Empty(), - Array.Empty()); + var catalog = EquipThrusterBank( + [agent], + CatalogItem("test-lock-cannon", weaponPayload), + CatalogItem("test-attack-capacitor", CapacitorPayload(50, 1))); var target = Entity(1, 105, "raider"); target.Kind = "station"; target.StatGrids = [Grid("hull", 14), Grid("shield", 0), Grid("heat", 0)]; @@ -2035,6 +2183,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks var lockTrace = new List(); var attackTrace = new List(); var firstLaunchFrame = -1; + var physics = NewPhysics(); for (var frame = 0; frame < 60; frame++) { var tick = AetheriaRuntimeDaemonTickRunner.Tick( @@ -2042,7 +2191,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks run, new AetheriaRuntimeDaemonTickOptions { - WorldPhysics = NewPhysics(), + WorldPhysics = physics, FrameId = frame, FixedDeltaSeconds = 0.1, SimulationTimeSeconds = frame * 0.1, @@ -2343,6 +2492,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks var agent = Entity(0, 0, "workers"); agent.EntityId = "worker.cross-zone.stable"; agent.AgentTaskCapabilities = [AetheriaRuntimeAgentTaskTypes.Explore]; + var catalog = EquipThrusterBank([agent]); var task = AgentTask("cross-zone", 10); task.ZoneIndex = 2; task.TargetPositionX = 0; @@ -2359,14 +2509,16 @@ internal sealed class AetheriaDaemonYmirSmokeChecks }; var appliedTravelCommands = 0; var appliedApproachCommands = 0; - for (var frame = 0; frame < 24; frame++) + var physics = NewPhysics(); + for (var frame = 0; frame < 100; frame++) { var tick = AetheriaRuntimeDaemonTickRunner.Tick( Path.Combine(Path.GetTempPath(), "aetheria-agent-route-travel-smoke.cc"), run, new AetheriaRuntimeDaemonTickOptions { - WorldPhysics = NewPhysics(), + WorldPhysics = physics, + Catalog = catalog, FrameId = frame, FixedDeltaSeconds = 0.1, SimulationTimeSeconds = frame * 0.1, @@ -2399,6 +2551,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks var home = Entity(0, 60, "workers"); home.EntityId = "station.home"; home.Kind = "station"; + var catalog = EquipThrusterBank([worker]); var run = new AetheriaRuntimeRunCheckpointCommit { RunId = "agent-return-home-smoke", @@ -2413,14 +2566,16 @@ internal sealed class AetheriaDaemonYmirSmokeChecks var travelCount = 0; var sawDock = false; var rejectedHomeCommands = new List(); - for (var frame = 0; frame < 40; frame++) + var physics = NewPhysics(); + for (var frame = 0; frame < 120; frame++) { var tick = AetheriaRuntimeDaemonTickRunner.Tick( Path.Combine(Path.GetTempPath(), "aetheria-agent-return-home-smoke.cc"), run, new AetheriaRuntimeDaemonTickOptions { - WorldPhysics = NewPhysics(), + WorldPhysics = physics, + Catalog = catalog, FrameId = frame, FixedDeltaSeconds = 0.1, SimulationTimeSeconds = frame * 0.1, @@ -2449,8 +2604,8 @@ internal sealed class AetheriaDaemonYmirSmokeChecks run, new AetheriaRuntimeDaemonTickOptions { - WorldPhysics = NewPhysics(), FrameId = 41, - FixedDeltaSeconds = 0.1, SimulationTimeSeconds = 4.1, BuildPublications = false + WorldPhysics = physics, Catalog = catalog, FrameId = 121, + FixedDeltaSeconds = 0.1, SimulationTimeSeconds = 12.1, BuildPublications = false }); Require(!settled.OperationResult.AppliedCommandIds.Any(id => id.Contains(":home-", StringComparison.Ordinal)), "docked worker must not emit a perpetual homecoming repair loop"); @@ -2487,6 +2642,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks { var agent = Entity(0, 0, "workers"); agent.AgentTaskCapabilities = [AetheriaRuntimeAgentTaskTypes.Explore]; + var catalog = EquipThrusterBank([agent]); var run = new AetheriaRuntimeRunCheckpointCommit { RunId = "agent-task-smoke", @@ -2513,18 +2669,20 @@ internal sealed class AetheriaDaemonYmirSmokeChecks CompletionRadius = 5 }; var completed = false; - for (var frame = 0; frame <= 20; frame++) + var physics = NewPhysics(); + for (var frame = 0; frame <= 60; frame++) { var tick = AetheriaRuntimeDaemonTickRunner.Tick( Path.Combine(Path.GetTempPath(), "aetheria-agent-task-smoke.cc"), run, new AetheriaRuntimeDaemonTickOptions { - WorldPhysics = NewPhysics(), + WorldPhysics = physics, FrameId = frame, FixedDeltaSeconds = 0.1, SimulationTimeSeconds = frame * 0.1, ObservedCommands = frame == 0 ? [issue] : Array.Empty(), + Catalog = catalog, BuildPublications = false }); if (frame == 0) @@ -2539,7 +2697,8 @@ internal sealed class AetheriaDaemonYmirSmokeChecks break; } - Require(completed, "agent must complete an explore task without direct position mutation"); + Require(completed, + $"agent must complete an explore task without direct position mutation; position={agent.PositionX:0.###},{agent.PositionZ:0.###} velocity={agent.VelocityX:0.###},{agent.VelocityY:0.###}"); Require(string.IsNullOrWhiteSpace(agent.AssignedAgentTaskId), "completed task must release the agent"); Require(agent.PositionX >= 45, "agent must reach the task through repeated movement commands"); @@ -2575,7 +2734,8 @@ internal sealed class AetheriaDaemonYmirSmokeChecks private static void MultipleActorsUseTheSameMovementLever() { var player = Entity(0, 0, "player"); - var agent = Entity(1, 0, "worker"); + var agent = Entity(1, 200, "worker"); + var catalog = EquipThrusterBank([player, agent]); player.TargetEntityIndex = agent.EntityIndex; var run = new AetheriaRuntimeRunCheckpointCommit { @@ -2592,16 +2752,20 @@ internal sealed class AetheriaDaemonYmirSmokeChecks var operation = AetheriaRuntimeDaemonOperations.Execute(run, commands); RequireEqual(2, operation.Intents.Movements.Count, "movement intent must retain one lever position per actor"); - AetheriaRuntimeDaemonSimulation.Step( - run, - operation.Intents, - 0.1, - AetheriaRuntimeDaemonSimulationSettings.AetheriaDefault, - NewPhysics()); - Require(player.VelocityX > 0 && Math.Abs(player.VelocityY) < 0.001, - "player command must drive its actor through the shared movement lever"); - Require(agent.VelocityY > 0 && Math.Abs(agent.VelocityX) < 0.001, - "agent command must drive its actor through the shared movement lever"); + var physics = NewPhysics(); + for (var step = 0; step < 2; step++) + AetheriaRuntimeDaemonSimulation.Step( + run, + operation.Intents, + 0.1, + AetheriaRuntimeDaemonSimulationSettings.AetheriaDefault, + physics, + catalog, + step + 1); + Require(player.VelocityX > 0 && Math.Abs(player.VelocityY) < Math.Abs(player.VelocityX) * 0.1, + $"player command must drive its actor through the shared movement lever; velocity={player.VelocityX:0.###},{player.VelocityY:0.###}"); + Require(agent.VelocityY > 0 && Math.Abs(agent.VelocityX) < Math.Abs(agent.VelocityY) * 0.1, + $"agent command must drive its actor through the shared movement lever; velocity={agent.VelocityX:0.###},{agent.VelocityY:0.###}"); var release = MovementCommand("player-release", "zone.0.entity.0", 0, 0); release.ScalarValue = 0; @@ -2611,11 +2775,124 @@ internal sealed class AetheriaDaemonYmirSmokeChecks releaseOperation.Intents, 0.1, AetheriaRuntimeDaemonSimulationSettings.AetheriaDefault, - NewPhysics()); + physics, + catalog, + 3); RequireEqual(agent.EntityIndex, player.TargetEntityIndex, "releasing the movement lever must not steal targeting authority"); } + private static void DirectionalThrustersOwnOrdinaryFlightFeedback() + { + var ship = Entity(0, 0, "player"); + var catalog = EquipThrusterBank([ship]); + var run = new AetheriaRuntimeRunCheckpointCommit + { + RunId = "ordinary-thruster-flight-smoke", + CurrentZoneIndex = 0, + CurrentEntityKey = "zone.0.entity.0", + Zones = [new AetheriaRuntimeZoneSnapshotCommit { ZoneIndex = 0, Entities = [ship] }] + }; + var operation = AetheriaRuntimeDaemonOperations.Execute( + run, [MovementCommand("forward-thrust", "zone.0.entity.0", 0, 1)]); + var physics = NewPhysics(); + AetheriaRuntimeDaemonSimulation.Step( + run, operation.Intents, 0.1, + AetheriaRuntimeDaemonSimulationSettings.AetheriaDefault, + physics, catalog, 1); + + var thrusterStates = ship.BehaviorStates + .Where(value => value.BehaviorKind == AetheriaRuntimeBehaviorKinds.Thruster) + .ToArray(); + RequireEqual(8, thrusterStates.Length, + "ordinary hull fixture must fly through its directional thruster bank"); + Require(thrusterStates.Count(value => value.ThrusterAxis > 0.99) == 2 && + thrusterStates.Where(value => value.ThrusterAxis > 0.99) + .All(value => ship.Equipment[value.OwnerIndex].Rotation == "Half"), + "forward helm must fire only the reversed forward-thrust pair when no turn is requested"); + Require(thrusterStates.Where(value => value.ThrusterAxis > 0.99) + .All(value => value.ThrusterThrust > 0 && Math.Abs(value.ThrusterTorque) > 0.5), + "thruster state must expose evaluated thrust and placement-derived torque"); + Require(ship.VelocityY > 0 && Math.Abs(ship.VelocityX) < Math.Abs(ship.VelocityY) * 0.1, + "ordinary thrust must become Ymir-integrated forward velocity"); + Require(ship.Visibility > 1.9, + "successful thruster execution must publish its maximum plume visibility"); + Require(thrusterStates.Where(value => value.ThrusterAxis > 0.99) + .Any(value => AetheriaRuntimeThermalSimulation.EquipmentTemperature( + ship, catalog, value.OwnerIndex) > ship.EquipmentStates + .Single(state => state.EquipmentIndex == value.OwnerIndex).Temperature), + "successful thruster execution must deposit authored heat into daemon equipment cells"); + Require(!ship.BehaviorStates.Any(value => value.BehaviorKind == AetheriaRuntimeBehaviorKinds.AetherDrive), + "ordinary flight must not manufacture an AetherDrive behavior"); + } + + private static void UnpoweredThrustersCannotMoveOrAdvertisePlume() + { + var ship = Entity(0, 0, "player"); + var catalog = EquipThrusterBank([ship]); + var thruster = catalog.Items.Single(value => value.ItemKey == "smoke-directional-thruster"); + thruster.BehaviorPayloads.Single().Fields = thruster.BehaviorPayloads.Single().Fields + .Select(field => field.Key == 4 + ? new AetheriaRuntimeBehaviorField(4, PerformanceStat(10)) + : field) + .ToArray(); + var run = new AetheriaRuntimeRunCheckpointCommit + { + RunId = "unpowered-thruster-smoke", + CurrentZoneIndex = 0, + CurrentEntityKey = "zone.0.entity.0", + Zones = [new AetheriaRuntimeZoneSnapshotCommit { ZoneIndex = 0, Entities = [ship] }] + }; + var operation = AetheriaRuntimeDaemonOperations.Execute( + run, [MovementCommand("unpowered-forward", "zone.0.entity.0", 0, 1)]); + AetheriaRuntimeDaemonSimulation.Step( + run, operation.Intents, 0.1, + AetheriaRuntimeDaemonSimulationSettings.AetheriaDefault, + NewPhysics(), catalog, 1); + + RequireNear(0, ship.VelocityX, 0.000001, + "an unfunded thruster bank must not create lateral velocity"); + RequireNear(0, ship.VelocityY, 0.000001, + "an unfunded thruster bank must not create forward velocity"); + RequireNear(0, ship.Visibility, 0.000001, + "an unfunded thruster bank must not advertise a plume that did not execute"); + } + + private static void RareAetherDriveSpoolsOnlyOnModifiedHullFixture() + { + var ship = Entity(0, 0, "player"); + var catalog = EquipAetherDrive([ship]); + var hull = catalog.FindItem(ship.HullItemKey)!; + var drive = catalog.Items.Single(value => value.ItemKey == "smoke-aether-drive"); + Require(drive.HardpointType == "AetherDrive" && + hull.Hardpoints.Count(value => value.Type == drive.HardpointType) == 1, + "rare AetherDrive fixture must use an explicit modified-hull hardpoint instead of the ordinary hull path"); + var run = new AetheriaRuntimeRunCheckpointCommit + { + RunId = "rare-aether-drive-smoke", + CurrentZoneIndex = 0, + CurrentEntityKey = "zone.0.entity.0", + Zones = [new AetheriaRuntimeZoneSnapshotCommit { ZoneIndex = 0, Entities = [ship] }] + }; + var operation = AetheriaRuntimeDaemonOperations.Execute( + run, [MovementCommand("rare-drive-forward", "zone.0.entity.0", 0, 1)]); + var physics = NewPhysics(); + for (var frame = 1; frame <= 2; frame++) + AetheriaRuntimeDaemonSimulation.Step( + run, operation.Intents, 0.1, + AetheriaRuntimeDaemonSimulationSettings.AetheriaDefault, + physics, catalog, frame); + + var state = ship.BehaviorStates.Single(value => + value.BehaviorKind == AetheriaRuntimeBehaviorKinds.AetherDrive); + Require(state.AetherDriveRpmX > 0 && state.AetherDriveMaximumRpm > 0, + "rare installed drive must persist rotor spool state"); + Require(ship.VelocityY > 0, + "rare installed drive must contribute force only after its rotor has spooled"); + Require(!ship.BehaviorStates.Any(value => value.BehaviorKind == AetheriaRuntimeBehaviorKinds.Thruster), + "isolated AetherDrive proof must not conceal its force behind ordinary thrusters"); + } + private static void LookDirectionRejectsInvalidVectorsWithoutMutatingTheShip() { var player = Entity(0, 0, "player"); diff --git a/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs b/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs index 913073022..b5a08b077 100644 --- a/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs +++ b/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs @@ -310,6 +310,7 @@ internal static class AetheriaDaemonZoneGenerator Kind = kind, Position = Vec3(x, 0, z), Direction = Vec2(vx == 0 && vy == 0 ? 0 : vx, vx == 0 && vy == 0 ? 1 : vy), + LookDirection = Vec2(vx == 0 && vy == 0 ? 0 : vx, vx == 0 && vy == 0 ? 1 : vy), Velocity = Vec2(vx, vy), FactionKey = faction, HullItemKey = loadout.HullItemKey, diff --git a/Aetheria.State.Daemon/Program.cs b/Aetheria.State.Daemon/Program.cs index 41f983eca..2215eec33 100644 --- a/Aetheria.State.Daemon/Program.cs +++ b/Aetheria.State.Daemon/Program.cs @@ -2656,6 +2656,10 @@ static AetheriaRuntimeEntitySnapshotCommit ToRuntimeEntity( PositionZ = entity.Position?.Z ?? 0, DirectionX = entity.Direction?.X ?? 0, DirectionY = entity.Direction?.Y ?? 1, + LookDirectionX = entity.LookDirection?.X ?? entity.Direction?.X ?? 0, + LookDirectionY = entity.LookDirection?.Y ?? entity.Direction?.Y ?? 1, + HelmStrafe = entity.HelmInput?.X ?? 0, + HelmForward = entity.HelmInput?.Y ?? 0, FactionKey = entity.FactionKey ?? "", HullItemKey = entity.HullItemKey ?? "", Equipment = equipment, diff --git a/Aetheria.State.Smoke/Program.cs b/Aetheria.State.Smoke/Program.cs index c2a0ef42c..bee862e33 100644 --- a/Aetheria.State.Smoke/Program.cs +++ b/Aetheria.State.Smoke/Program.cs @@ -269,6 +269,8 @@ await using (var node = await AetheriaStateNode.OpenAsync(statePath, "aetheria-s Kind = "ship", Position = new AetheriaVector3 { X = 12.5, Y = 0.0, Z = -3.25 }, Direction = new AetheriaVector2 { X = 0.0, Y = 1.0 }, + LookDirection = new AetheriaVector2 { X = 0.8, Y = 0.6 }, + HelmInput = new AetheriaVector2 { X = -0.25, Y = 0.75 }, FactionKey = factionKey.ToString(), HullItemKey = itemKey.ToString(), Equipment = @@ -890,6 +892,10 @@ await using (var reopened = await AetheriaStateNode.OpenAsync(statePath, "aether } if (entitySnapshot?.Kind != "ship" || + entitySnapshot.LookDirection.X != 0.8 || + entitySnapshot.LookDirection.Y != 0.6 || + entitySnapshot.HelmInput.X != -0.25 || + entitySnapshot.HelmInput.Y != 0.75 || entitySnapshot.Equipment.Length != 1 || entitySnapshot.Equipment[0].Quality != 0.9 || entitySnapshot.Equipment[0].Durability != 0.8 || diff --git a/Aetheria.State.Verify/Program.cs b/Aetheria.State.Verify/Program.cs index 961e08136..960ec95e3 100644 --- a/Aetheria.State.Verify/Program.cs +++ b/Aetheria.State.Verify/Program.cs @@ -16805,6 +16805,12 @@ static void RequireUnityDoesNotCallSharedSimulationTicks(string root) "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeDaemonSimulationSettings.cs"); + var flightSimulationPath = Path.Combine( + root, + "Packages", + "org.gamecult.aetheria.state", + "Runtime", + "AetheriaRuntimeFlightSimulation.cs"); var worldPhysicsContractPath = Path.Combine( root, "Packages", @@ -16870,6 +16876,9 @@ static void RequireUnityDoesNotCallSharedSimulationTicks(string root) var daemonSimulationSettings = File.Exists(daemonSimulationSettingsPath) ? File.ReadAllText(daemonSimulationSettingsPath) : throw new InvalidOperationException("Cannot verify daemon simulation authority; daemon simulation settings are missing."); + var flightSimulation = File.Exists(flightSimulationPath) + ? File.ReadAllText(flightSimulationPath) + : throw new InvalidOperationException("Cannot verify daemon flight authority; actuator simulation is missing."); var worldPhysicsContract = File.Exists(worldPhysicsContractPath) ? File.ReadAllText(worldPhysicsContractPath) : throw new InvalidOperationException("Cannot verify daemon projectile authority; shared world physics port is missing."); @@ -17162,6 +17171,41 @@ static void RequireUnityDoesNotCallSharedSimulationTicks(string root) "Daemon combat regressed to runtime-named simulation, hardcoded game feel, direct target damage, or local projectile physics instead of daemon settings plus Ymir-shaped projectile contact damage."); } + var requiredFlightAuthoritySymbols = new[] + { + "ConfigureThrusterAxes(", + "StepThruster(", + "ResolveThrusterTorque(", + "AetheriaRuntimeEnergySimulation.TryConsume(", + "AetheriaRuntimeThermalSimulation.AddHeatToEquipment(", + "ApplyThrusterVisibility(", + "StepAetherDrive(", + "entity.HelmStrafe", + "entity.LookDirectionX" + }; + var missingFlightAuthoritySymbols = requiredFlightAuthoritySymbols + .Where(symbol => !flightSimulation.Contains(symbol, StringComparison.Ordinal)) + .ToArray(); + var forbiddenDirectFlightSymbols = new[] + { + "ResolveSpeed(entity, settings)", + "entity.VelocityX = normalized.X * speed", + "entity.VelocityY = normalized.Y * speed", + "settings.PawnSpeed", + "settings.RaiderSpeed" + }; + var directFlightHits = forbiddenDirectFlightSymbols + .Where(symbol => daemonSimulation.Contains(symbol, StringComparison.Ordinal) || + flightSimulation.Contains(symbol, StringComparison.Ordinal)) + .ToArray(); + if (missingFlightAuthoritySymbols.Length > 0 || directFlightHits.Length > 0) + { + throw new InvalidOperationException( + "Daemon flight must be owned by installed Thruster/AetherDrive actuators and may not restore faction-speed velocity assignment. Missing: " + + string.Join(", ", missingFlightAuthoritySymbols) + "; forbidden: " + + string.Join(", ", directFlightHits)); + } + var forbiddenRuntimeSpecificAuthorityPolicySymbols = new[] { "ElectronLaunchedDaemon", diff --git a/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs b/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs index 165ae702e..9307829aa 100644 --- a/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs +++ b/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs @@ -618,6 +618,12 @@ public sealed class AetheriaEntitySnapshot [Key(32)] public AetheriaLoadoutGenerationReceipt? LoadoutGeneration { get; set; } + + [Key(33)] + public AetheriaVector2 LookDirection { get; set; } = new(); + + [Key(34)] + public AetheriaVector2 HelmInput { get; set; } = new(); } [MessagePackObject] diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeAgentTasks.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeAgentTasks.cs index 3d0bcbde7..201809715 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeAgentTasks.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeAgentTasks.cs @@ -331,6 +331,11 @@ namespace GameCult.Aetheria.State.Verse var commands = new List { Movement(task, agent, frameId, dx * radial, dz * radial, thrust), + Command(task, agent, frameId, AetheriaRuntimeDaemonCommandKinds.SetLookDirection, "look", command => + { + command.DirectionX = dx; + command.PositionZ = dz; + }), Command(task, agent, frameId, AetheriaRuntimeDaemonCommandKinds.SetTarget, "target", command => command.TargetEntityKey = EntityKey(run, task.ZoneIndex, target.EntityIndex)) }; @@ -414,9 +419,7 @@ namespace GameCult.Aetheria.State.Verse var length = Math.Sqrt(dx * dx + dz * dz); return IdleCommand(zoneIndex, entity, frameId, AetheriaRuntimeDaemonCommandKinds.SetMoveVector, phase, command => { - command.DirectionX = length <= 0.0001 ? 0 : dx / length; - command.DirectionY = length <= 0.0001 ? 0 : dz / length; - command.ScalarValue = length <= 0.0001 ? 0 : 1; + SetLocalHelmAxes(command, entity, dx, dz, length <= 0.0001 ? 0 : 1); }); } @@ -771,10 +774,7 @@ namespace GameCult.Aetheria.State.Verse { return Command(task, agent, frameId, AetheriaRuntimeDaemonCommandKinds.SetMoveVector, "move", command => { - var length = Math.Sqrt(dx * dx + dz * dz); - command.DirectionX = length <= 0.0001 ? 0 : dx / length; - command.DirectionY = length <= 0.0001 ? 0 : dz / length; - command.ScalarValue = magnitude; + SetLocalHelmAxes(command, agent, dx, dz, magnitude); }); } @@ -794,12 +794,39 @@ namespace GameCult.Aetheria.State.Verse $"zone.{zoneIndex}.entity.{agent.EntityIndex}"); command.CommandId = CommandId(task, frameId, "travel-approach"); var length = Math.Sqrt(dx * dx + dz * dz); - command.DirectionX = length <= 0.0001 ? 0 : dx / length; - command.DirectionY = length <= 0.0001 ? 0 : dz / length; - command.ScalarValue = length <= 0.0001 ? 0 : 1; + SetLocalHelmAxes(command, agent, dx, dz, length <= 0.0001 ? 0 : 1); return command; } + private static void SetLocalHelmAxes( + AetheriaRuntimeDaemonCommandDocument command, + AetheriaRuntimeEntitySnapshotCommit entity, + double worldX, + double worldZ, + double magnitude) + { + var desiredLength = Math.Sqrt(worldX * worldX + worldZ * worldZ); + if (desiredLength <= 0.0001 || magnitude <= 0) + { + command.DirectionX = 0; + command.DirectionY = 0; + command.ScalarValue = 0; + return; + } + + var forwardLength = Math.Sqrt( + entity.DirectionX * entity.DirectionX + entity.DirectionY * entity.DirectionY); + var forwardX = forwardLength <= 0.0001 ? 0 : entity.DirectionX / forwardLength; + var forwardZ = forwardLength <= 0.0001 ? 1 : entity.DirectionY / forwardLength; + var desiredX = worldX / desiredLength; + var desiredZ = worldZ / desiredLength; + var rightX = forwardZ; + var rightZ = -forwardX; + command.DirectionX = desiredX * rightX + desiredZ * rightZ; + command.DirectionY = desiredX * forwardX + desiredZ * forwardZ; + command.ScalarValue = Math.Min(1, magnitude); + } + private static double InteractionRadius(AetheriaRuntimeEntitySnapshotCommit entity) => string.Equals(entity.Kind, "station", StringComparison.OrdinalIgnoreCase) ? 48 : 20; diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeBehaviorKinds.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeBehaviorKinds.cs index 079ef9df9..cd32d73dd 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeBehaviorKinds.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeBehaviorKinds.cs @@ -13,6 +13,8 @@ namespace GameCult.Aetheria.State.Verse public const string ChargedWeapon = "ChargedWeapon"; public const string AutoWeapon = "AutoWeapon"; public const string DeployableWeapon = "DeployableWeapon"; + public const string AetherDrive = "AetherDrive"; + public const string Thruster = "Thruster"; private static readonly ISet WeaponKinds = new HashSet(StringComparer.Ordinal) { diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogSnapshot.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogSnapshot.cs index b55909c46..f701d44d5 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogSnapshot.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCatalogSnapshot.cs @@ -914,7 +914,11 @@ namespace GameCult.Aetheria.State.Verse double visibility, int visibilitySourceCount, IReadOnlyList contacts, - double shutdownPerformance) + double shutdownPerformance, + double lookDirectionX = 0, + double lookDirectionY = 0, + double helmStrafe = 0, + double helmForward = 0) { RecordKey = recordKey; EntityIndex = entityIndex; @@ -953,6 +957,10 @@ namespace GameCult.Aetheria.State.Verse VisibilitySourceCount = visibilitySourceCount; Contacts = contacts; ShutdownPerformance = shutdownPerformance; + LookDirectionX = lookDirectionX; + LookDirectionY = lookDirectionY; + HelmStrafe = helmStrafe; + HelmForward = helmForward; } public string RecordKey { get; set; } @@ -992,6 +1000,10 @@ namespace GameCult.Aetheria.State.Verse public int VisibilitySourceCount { get; set; } public IReadOnlyList Contacts { get; set; } public double ShutdownPerformance { get; set; } + public double LookDirectionX { get; set; } + public double LookDirectionY { get; set; } + public double HelmStrafe { get; set; } + public double HelmForward { get; set; } } [MessagePackObject(true)] diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs index b68ea5123..4f4e072e1 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs @@ -537,8 +537,8 @@ namespace GameCult.Aetheria.State.Verse return ApplyCurrentEntity(run, command, entity => { - entity.DirectionX = command.DirectionX / length; - entity.DirectionY = command.PositionZ / length; + entity.LookDirectionX = command.DirectionX / length; + entity.LookDirectionY = command.PositionZ / length; }); } diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs index eac73b017..63a3f0a7e 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulation.cs @@ -64,8 +64,15 @@ namespace GameCult.Aetheria.State.Verse catalog, frameId, deltaSeconds); - foreach (var movement in intents?.Movements ?? Enumerable.Empty()) - ApplyMovementIntent(run, entities, movement, settings); + AetheriaRuntimeFlightSimulation.Step( + entities, + intents?.Movements, + catalog, + deltaSeconds, + settings.AetherTorqueMultiplier, + settings.AetherHeatMultiplier, + settings.TorqueFloor, + settings.TorqueMultiplier); StepTractorPower(entities, deltaSeconds); var worldStep = StepWorldPhysics( run.RunId, frameId, simulationStepIndex, zone, entities, deltaSeconds, worldPhysics); @@ -103,32 +110,6 @@ namespace GameCult.Aetheria.State.Verse } } - private static void ApplyMovementIntent( - AetheriaRuntimeRunCheckpointCommit run, - IReadOnlyList entities, - AetheriaRuntimeDaemonMovementIntent? movement, - AetheriaRuntimeDaemonSimulationSettings settings) - { - if (movement == null || !TryParseEntityIndex(movement.ActorEntityKey, out var entityIndex)) - return; - - var entity = entities.FirstOrDefault(candidate => candidate.EntityIndex == entityIndex); - if (entity == null || !IsAlive(entity)) - return; - - var magnitude = Clamp01(movement.Magnitude); - var normalized = Normalize(movement.DirectionX, movement.DirectionY); - var speed = ResolveSpeed(entity, settings); - entity.VelocityX = normalized.X * speed * magnitude; - entity.VelocityY = normalized.Y * speed * magnitude; - var target = entities.FirstOrDefault(candidate => - candidate.EntityIndex == entity.TargetEntityIndex && IsAlive(candidate)); - if (target != null) - Face(entity, target.PositionX - entity.PositionX, target.PositionZ - entity.PositionZ); - else if (magnitude > 0.001) - Face(entity, normalized.X, normalized.Y); - } - private static AetheriaRuntimeWorldStep StepWorldPhysics( string runId, long frameId, @@ -2246,18 +2227,6 @@ namespace GameCult.Aetheria.State.Verse string.Equals(right.FactionKey, "raider", StringComparison.OrdinalIgnoreCase)); } - private static double ResolveSpeed( - AetheriaRuntimeEntitySnapshotCommit entity, - AetheriaRuntimeDaemonSimulationSettings settings) - { - if (string.Equals(entity.Kind, "station", StringComparison.OrdinalIgnoreCase)) - return 0; - - return string.Equals(entity.FactionKey, "raider", StringComparison.OrdinalIgnoreCase) - ? settings.RaiderSpeed - : settings.PawnSpeed; - } - private static double ResolveSensorRange( AetheriaRuntimeEntitySnapshotCommit entity, AetheriaRuntimeDaemonSimulationSettings settings, diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulationSettings.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulationSettings.cs index 63df148d4..8483f0ce6 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulationSettings.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSimulationSettings.cs @@ -86,7 +86,11 @@ namespace GameCult.Aetheria.State.Verse double hypothermiaTemperature = AetheriaDefaultRaw.HypothermiaTemperature, double hypothermiaMultiplier = AetheriaDefaultRaw.HypothermiaMultiplier, double hypothermiaExponent = AetheriaDefaultRaw.HypothermiaExponent, - double hypothermiaRecoveryPerSecond = AetheriaDefaultRaw.HypothermiaRecoveryPerSecond) + double hypothermiaRecoveryPerSecond = AetheriaDefaultRaw.HypothermiaRecoveryPerSecond, + double aetherTorqueMultiplier = AetheriaDefaultRaw.AetherTorqueMultiplier, + double aetherHeatMultiplier = AetheriaDefaultRaw.AetherHeatMultiplier, + double torqueFloor = AetheriaDefaultRaw.TorqueFloor, + double torqueMultiplier = AetheriaDefaultRaw.TorqueMultiplier) { PawnSpeed = PositiveOr(pawnSpeed, AetheriaDefaultRaw.PawnSpeed); RaiderSpeed = PositiveOr(raiderSpeed, AetheriaDefaultRaw.RaiderSpeed); @@ -126,6 +130,10 @@ namespace GameCult.Aetheria.State.Verse HypothermiaMultiplier = NonNegativeOr(hypothermiaMultiplier, AetheriaDefaultRaw.HypothermiaMultiplier); HypothermiaExponent = PositiveOr(hypothermiaExponent, AetheriaDefaultRaw.HypothermiaExponent); HypothermiaRecoveryPerSecond = NonNegativeOr(hypothermiaRecoveryPerSecond, AetheriaDefaultRaw.HypothermiaRecoveryPerSecond); + AetherTorqueMultiplier = NonNegativeOr(aetherTorqueMultiplier, AetheriaDefaultRaw.AetherTorqueMultiplier); + AetherHeatMultiplier = NonNegativeOr(aetherHeatMultiplier, AetheriaDefaultRaw.AetherHeatMultiplier); + TorqueFloor = NonNegativeOr(torqueFloor, AetheriaDefaultRaw.TorqueFloor); + TorqueMultiplier = NonNegativeOr(torqueMultiplier, AetheriaDefaultRaw.TorqueMultiplier); } public double PawnSpeed { get; } @@ -168,6 +176,10 @@ namespace GameCult.Aetheria.State.Verse public double HypothermiaMultiplier { get; } public double HypothermiaExponent { get; } public double HypothermiaRecoveryPerSecond { get; } + public double AetherTorqueMultiplier { get; } + public double AetherHeatMultiplier { get; } + public double TorqueFloor { get; } + public double TorqueMultiplier { get; } private static double PositiveOr(double value, double fallback) { @@ -224,6 +236,10 @@ namespace GameCult.Aetheria.State.Verse public const double HypothermiaMultiplier = 0.00001; public const double HypothermiaExponent = 2.0; public const double HypothermiaRecoveryPerSecond = 0.2; + public const double AetherTorqueMultiplier = 0.1; + public const double AetherHeatMultiplier = 0.25; + public const double TorqueFloor = 0.5; + public const double TorqueMultiplier = 0.1; } } } diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEquippedBehaviorQueries.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEquippedBehaviorQueries.cs index dbf3f893d..e8cf8da16 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEquippedBehaviorQueries.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEquippedBehaviorQueries.cs @@ -11,6 +11,7 @@ namespace GameCult.Aetheria.State.Verse public AetheriaRuntimeEquippedBehavior( int equipmentIndex, int behaviorIndex, + AetheriaRuntimeLoadoutItemSlotCommit slot, AetheriaRuntimeLoadoutItemCommit item, AetheriaRuntimeCatalogItem catalogItem, AetheriaRuntimeBehaviorPayload payload, @@ -18,6 +19,7 @@ namespace GameCult.Aetheria.State.Verse { EquipmentIndex = equipmentIndex; BehaviorIndex = behaviorIndex; + Slot = slot; Item = item; CatalogItem = catalogItem; Payload = payload; @@ -26,6 +28,7 @@ namespace GameCult.Aetheria.State.Verse public int EquipmentIndex { get; } public int BehaviorIndex { get; } + public AetheriaRuntimeLoadoutItemSlotCommit Slot { get; } public AetheriaRuntimeLoadoutItemCommit Item { get; } public AetheriaRuntimeCatalogItem CatalogItem { get; } public AetheriaRuntimeBehaviorPayload Payload { get; } @@ -78,6 +81,7 @@ namespace GameCult.Aetheria.State.Verse found.Add(new AetheriaRuntimeEquippedBehavior( equipmentIndex, behaviorIndex, + equipment[equipmentIndex], item, catalogItem, payload, diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeFlightSimulation.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeFlightSimulation.cs new file mode 100644 index 000000000..9d827869d --- /dev/null +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeFlightSimulation.cs @@ -0,0 +1,557 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +#nullable enable + +namespace GameCult.Aetheria.State.Verse +{ + public static class AetheriaRuntimeFlightSimulation + { + public static void Step( + IReadOnlyList? entities, + IReadOnlyList? movements, + AetheriaRuntimeCatalogSnapshot? catalog, + double deltaSeconds, + double aetherTorqueMultiplier, + double aetherHeatMultiplier, + double torqueFloor, + double torqueMultiplier) + { + if (catalog == null || deltaSeconds <= 0) + return; + + var active = (entities ?? Array.Empty()) + .Where(entity => entity != null && entity.IsActive) + .ToArray(); + var byIndex = active.ToDictionary(entity => entity.EntityIndex); + foreach (var movement in movements ?? Array.Empty()) + { + if (movement == null || + !TryParseEntityIndex(movement.ActorEntityKey, out var entityIndex) || + !byIndex.TryGetValue(entityIndex, out var entity)) + { + continue; + } + + SetHelmAxes(entity, movement); + } + + foreach (var entity in active.Where(entity => + string.Equals(entity.Kind, "ship", StringComparison.OrdinalIgnoreCase))) + { + var mass = ResolveMass(entity, byIndex, catalog, new HashSet()); + var deltaRotation = ResolveTurnAxis(entity, deltaSeconds); + var thrusters = Online(entity, catalog, AetheriaRuntimeBehaviorKinds.Thruster); + ConfigureThrusterAxes(entity, thrusters, catalog, deltaRotation, torqueFloor); + var activeThrusters = new List(); + foreach (var thruster in thrusters) + if (StepThruster(entity, thruster, mass, deltaSeconds, catalog, torqueMultiplier)) + activeThrusters.Add(thruster); + ApplyThrusterVisibility(entity, activeThrusters); + SetDriveAxes(entity, catalog, deltaRotation); + foreach (var drive in Online(entity, catalog, AetheriaRuntimeBehaviorKinds.AetherDrive)) + StepAetherDrive(entity, drive, mass, deltaSeconds, catalog, + aetherTorqueMultiplier, aetherHeatMultiplier); + ApplyHullDrag(entity, catalog, deltaSeconds); + } + } + + private static double ResolveTurnAxis( + AetheriaRuntimeEntitySnapshotCommit entity, + double deltaSeconds) + { + var direction = Normalize(entity.DirectionX, entity.DirectionY, 0, 1); + var look = Normalize(entity.LookDirectionX, entity.LookDirectionY, direction.X, direction.Y); + var right = new Vector2(direction.Y, -direction.X); + var deltaRotation = look.X * right.X + look.Y * right.Y; + if (Math.Abs(deltaRotation) < 0.01) + { + var blend = Math.Min(deltaSeconds, 1); + direction = Normalize( + direction.X + (look.X - direction.X) * blend, + direction.Y + (look.Y - direction.Y) * blend, + direction.X, + direction.Y); + entity.DirectionX = direction.X; + entity.DirectionY = direction.Y; + deltaRotation = 0; + } + else + { + deltaRotation = Math.Sqrt(Math.Abs(deltaRotation)) * Sign(deltaRotation); + } + + return deltaRotation; + } + + private static void SetHelmAxes( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeDaemonMovementIntent movement) + { + var magnitude = Clamp01(movement.Magnitude); + var length = Math.Sqrt( + movement.DirectionX * movement.DirectionX + + movement.DirectionY * movement.DirectionY); + var strafe = length <= 0.000001 ? 0 : movement.DirectionX / length * magnitude; + var forward = length <= 0.000001 ? 0 : movement.DirectionY / length * magnitude; + entity.HelmStrafe = strafe; + entity.HelmForward = forward; + } + + private static void SetDriveAxes( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeCatalogSnapshot catalog, + double deltaRotation) + { + foreach (var drive in AetheriaRuntimeEquippedBehaviorQueries.Find( + entity, catalog, AetheriaRuntimeBehaviorKinds.AetherDrive)) + { + drive.State.AetherDriveAxisX = Clamp(entity.HelmForward, -1, 1); + drive.State.AetherDriveAxisY = Clamp(entity.HelmStrafe, -1, 1); + drive.State.AetherDriveAxisZ = Clamp(deltaRotation, -1, 1); + } + } + + private static void ConfigureThrusterAxes( + AetheriaRuntimeEntitySnapshotCommit entity, + IReadOnlyList thrusters, + AetheriaRuntimeCatalogSnapshot catalog, + double deltaRotation, + double torqueFloor) + { + foreach (var thruster in thrusters) + { + thruster.State.ThrusterAxis = 0; + thruster.State.ThrusterThrust = Math.Max(0, + thruster.EvaluateStat(1, ThermalPerformance(entity, thruster.EquipmentIndex))); + thruster.State.ThrusterTorque = ResolveThrusterTorque(entity, thruster, catalog); + } + + var right = thrusters.Where(value => Rotation(value) == 1).ToArray(); + var left = thrusters.Where(value => Rotation(value) == 3).ToArray(); + ApplyStrafeBank(right, entity.HelmStrafe, entity.HelmStrafe); + ApplyStrafeBank(left, -entity.HelmStrafe, entity.HelmStrafe); + foreach (var thruster in thrusters.Where(value => Rotation(value) == 2)) + thruster.State.ThrusterAxis += entity.HelmForward; + foreach (var thruster in thrusters.Where(value => Rotation(value) == 0)) + thruster.State.ThrusterAxis -= entity.HelmForward; + foreach (var thruster in thrusters.Where(value => value.State.ThrusterTorque > torqueFloor)) + thruster.State.ThrusterAxis += deltaRotation; + foreach (var thruster in thrusters.Where(value => value.State.ThrusterTorque < -torqueFloor)) + thruster.State.ThrusterAxis -= deltaRotation; + foreach (var thruster in thrusters) + thruster.State.ThrusterAxis = Clamp01(thruster.State.ThrusterAxis); + } + + private static void ApplyStrafeBank( + IReadOnlyList bank, + double baseAxis, + double strafeAxis) + { + var totalTorque = bank.Sum(value => value.State.ThrusterTorque * value.State.ThrusterThrust); + var sign = Sign(totalTorque); + var compensation = bank.Where(value => Sign(value.State.ThrusterTorque) == sign).ToArray(); + var compensationPerThruster = compensation.Length == 0 + ? 0 + : Math.Abs(totalTorque) / compensation.Length; + foreach (var thruster in bank) + { + thruster.State.ThrusterAxis += baseAxis; + if (!compensation.Contains(thruster)) + continue; + var denominator = Math.Abs(thruster.State.ThrusterTorque) * thruster.State.ThrusterThrust; + if (denominator <= 0.000001) + continue; + var correction = strafeAxis * compensationPerThruster / denominator; + thruster.State.ThrusterAxis += Rotation(thruster) == 1 ? -correction : correction; + } + } + + private static bool StepThruster( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeEquippedBehavior thruster, + double entityMass, + double deltaSeconds, + AetheriaRuntimeCatalogSnapshot catalog, + double torqueMultiplier) + { + var axis = Clamp01(thruster.State.ThrusterAxis); + if (axis <= 0.01 || !AetheriaRuntimeEnergySimulation.TryConsume( + entity, catalog, + axis * Math.Max(0, thruster.EvaluateStat(4, + ThermalPerformance(entity, thruster.EquipmentIndex))))) + return false; + + var direction = RotateQuarter( + Normalize(entity.DirectionX, entity.DirectionY, 0, 1), + Rotation(thruster)); + var thrust = Math.Max(0, thruster.EvaluateStat(1, + ThermalPerformance(entity, thruster.EquipmentIndex))); + thruster.State.ThrusterThrust = thrust; + entity.VelocityX -= direction.X * axis * thrust / entityMass * deltaSeconds; + entity.VelocityY -= direction.Y * axis * thrust / entityMass * deltaSeconds; + var rotation = axis * thruster.State.ThrusterTorque * thrust * + Math.Max(0, torqueMultiplier) / entityMass * deltaSeconds; + var rotated = RotateRadians( + Normalize(entity.DirectionX, entity.DirectionY, 0, 1), rotation); + entity.DirectionX = rotated.X; + entity.DirectionY = rotated.Y; + AetheriaRuntimeThermalSimulation.AddHeatToEquipment( + entity, + catalog, + thruster.EquipmentIndex, + axis * Math.Max(0, thruster.EvaluateStat(3, + ThermalPerformance(entity, thruster.EquipmentIndex))) * deltaSeconds); + return true; + } + + private static void ApplyThrusterVisibility( + AetheriaRuntimeEntitySnapshotCommit entity, + IReadOnlyList thrusters) + { + const string gridName = "thruster-visibility"; + var grids = (entity.StatGrids ?? Array.Empty()).ToList(); + var grid = grids.FirstOrDefault(value => string.Equals(value.Name, gridName, StringComparison.Ordinal)); + var previous = grid?.Values.FirstOrDefault() ?? 0; + var visibility = thrusters + .Where(value => value.State.ThrusterAxis > 0.01) + .Select(value => value.State.ThrusterAxis * Math.Max(0, + value.EvaluateStat(2, ThermalPerformance(entity, value.EquipmentIndex)))) + .DefaultIfEmpty(0) + .Max(); + entity.Visibility = Math.Max(0, entity.Visibility - previous) + visibility; + if (grid == null) + { + grid = new AetheriaRuntimeEntityStatGridCommit { Name = gridName, Width = 1, Height = 1 }; + grids.Add(grid); + entity.StatGrids = grids; + } + grid.Values = new[] { visibility }; + } + + private static double ResolveThrusterTorque( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeEquippedBehavior thruster, + AetheriaRuntimeCatalogSnapshot catalog) + { + var hull = catalog.FindItem(entity.HullItemKey ?? ""); + var slot = (entity.Equipment ?? Array.Empty()) + .ElementAtOrDefault(thruster.EquipmentIndex); + if (hull == null || slot == null) + return 0; + var hullCenter = ShapeCenter(hull.ShapeCells, 0, 0, 0, hull.ShapeWidth, hull.ShapeHeight); + var itemCenter = ShapeCenter( + thruster.CatalogItem.ShapeCells, + slot.X, + slot.Y, + Rotation(thruster), + thruster.CatalogItem.ShapeWidth, + thruster.CatalogItem.ShapeHeight); + var toCenter = Normalize( + hullCenter.X - itemCenter.X, + hullCenter.Y - itemCenter.Y, + 0, + 0); + if (Math.Abs(toCenter.X) <= 0.000001 && Math.Abs(toCenter.Y) <= 0.000001) + return 0; + var itemDirection = RotateQuarter(new Vector2(1, 0), Rotation(thruster)); + return -(toCenter.X * itemDirection.X + toCenter.Y * itemDirection.Y); + } + + private static Vector2 ShapeCenter( + IReadOnlyList? cells, + int offsetX, + int offsetY, + int rotation, + int width, + int height) + { + var values = (cells ?? Array.Empty()).ToArray(); + if (values.Length == 0) + return new Vector2(offsetX, offsetY); + double sumX = 0; + double sumY = 0; + foreach (var cell in values) + { + var x = cell.X; + var y = cell.Y; + switch (rotation) + { + case 1: x = height - 1 - cell.Y; y = cell.X; break; + case 2: x = width - 1 - cell.X; y = height - 1 - cell.Y; break; + case 3: x = cell.Y; y = width - 1 - cell.X; break; + } + sumX += x + offsetX; + sumY += y + offsetY; + } + return new Vector2(sumX / values.Length, sumY / values.Length); + } + + private static int Rotation(AetheriaRuntimeEquippedBehavior behavior) + { + var rotation = behavior.Slot?.Rotation ?? ""; + if (string.Equals(rotation, "CounterClockwise", StringComparison.OrdinalIgnoreCase)) return 1; + if (string.Equals(rotation, "Half", StringComparison.OrdinalIgnoreCase) || + string.Equals(rotation, "Reversed", StringComparison.OrdinalIgnoreCase)) return 2; + if (string.Equals(rotation, "Clockwise", StringComparison.OrdinalIgnoreCase)) return 3; + return 0; + } + + private static void StepAetherDrive( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeEquippedBehavior drive, + double entityMass, + double deltaSeconds, + AetheriaRuntimeCatalogSnapshot catalog, + double aetherTorqueMultiplier, + double aetherHeatMultiplier) + { + var axis = new Vector3( + Clamp(drive.State.AetherDriveAxisX, -1, 1), + Clamp(drive.State.AetherDriveAxisY, -1, 1), + Clamp(drive.State.AetherDriveAxisZ, -1, 1)); + var rotorDiameter = ReadVector3(drive.Payload, 1); + var rotorMass = ReadVector3(drive.Payload, 2); + var couplingLambda = ReadVector3(drive.Payload, 4); + var rpm = new Vector3( + drive.State.AetherDriveRpmX, + drive.State.AetherDriveRpmY, + drive.State.AetherDriveRpmZ); + var maximumRpm = Math.Max(0, drive.EvaluateStat(3, ThermalPerformance(entity, drive.EquipmentIndex))); + var lambdaMultiplier = Math.Max(0, drive.EvaluateStat(5, ThermalPerformance(entity, drive.EquipmentIndex))); + var couplingEfficiency = Clamp01(drive.EvaluateStat(6, ThermalPerformance(entity, drive.EquipmentIndex))); + var passiveCoupling = Math.Max(0, drive.EvaluateStat(10, ThermalPerformance(entity, drive.EquipmentIndex))); + + var direction = Normalize(entity.DirectionX, entity.DirectionY, 0, 1); + var right = new Vector2(direction.Y, -direction.X); + var forwardSpeed = entity.VelocityX * direction.X + entity.VelocityY * direction.Y; + var strafeSpeed = entity.VelocityX * right.X + entity.VelocityY * right.Y; + var rotorSpeed = rotorDiameter * rpm / 100; + var efficiency = new Vector3( + Clamp01(1 - forwardSpeed / Math.Max(rotorSpeed.X, 1) * Sign(axis.X)) * couplingEfficiency, + Clamp01(1 - strafeSpeed / Math.Max(rotorSpeed.Y, 1) * Sign(axis.Y)) * couplingEfficiency, + 1); + + var idleDecay = Decay(rpm, couplingLambda, deltaSeconds); + var thrust = (rpm - idleDecay) * rotorMass * efficiency; + var activeLambda = couplingLambda * lambdaMultiplier * Max(Abs(axis), passiveCoupling); + var previousRpm = rpm; + rpm = Decay(rpm, activeLambda, deltaSeconds); + var rpmLoss = previousRpm - rpm; + var force = rpmLoss * rotorMass * efficiency; + var heat = rpmLoss * rotorMass * (1 - couplingEfficiency); + AetheriaRuntimeThermalSimulation.AddHeatToEquipment( + entity, + catalog, + drive.EquipmentIndex, + (heat.X + heat.Y + heat.Z) * Math.Max(0, aetherHeatMultiplier)); + + var thrustDirection = direction * (axis.X * force.X / entityMass) + + right * (axis.Y * force.Y / entityMass); + entity.VelocityX += thrustDirection.X; + entity.VelocityY += thrustDirection.Y; + var rotation = force.Z * axis.Z * Math.Max(0, aetherTorqueMultiplier) / entityMass; + var rotated = RotateRadians(direction, rotation); + entity.DirectionX = rotated.X; + entity.DirectionY = rotated.Y; + + var torqueProfile = ReadCurveKeys(drive.Payload, 8); + var potentialTorque = Math.Max(0, drive.EvaluateStat(7, ThermalPerformance(entity, drive.EquipmentIndex))) * + new Vector3( + AetheriaRuntimeDaemonItemStatQueries.SampleCurve(torqueProfile, Ratio(rpm.X, maximumRpm)), + AetheriaRuntimeDaemonItemStatQueries.SampleCurve(torqueProfile, Ratio(rpm.Y, maximumRpm)), + AetheriaRuntimeDaemonItemStatQueries.SampleCurve(torqueProfile, Ratio(rpm.Z, maximumRpm))); + var rotorMassLength = Math.Max(0.000001, rotorMass.Length); + var potentialRpmDelta = potentialTorque / rotorMassLength * deltaSeconds; + var actualRpmDelta = Min(new Vector3(maximumRpm, maximumRpm, maximumRpm) - rpm, potentialRpmDelta); + var torqueRatio = DivideOrZero(actualRpmDelta, potentialRpmDelta); + var energyDraw = Math.Max(0, drive.EvaluateStat(9, ThermalPerformance(entity, drive.EquipmentIndex))); + var draw = (torqueRatio.X + torqueRatio.Y + torqueRatio.Z) * energyDraw / 3 * deltaSeconds; + if (AetheriaRuntimeEnergySimulation.TryConsume(entity, catalog, draw)) + rpm += actualRpmDelta; + + drive.State.AetherDriveThrustX = thrust.X; + drive.State.AetherDriveThrustY = thrust.Y; + drive.State.AetherDriveThrustZ = thrust.Z; + drive.State.AetherDriveRpmX = rpm.X; + drive.State.AetherDriveRpmY = rpm.Y; + drive.State.AetherDriveRpmZ = rpm.Z; + drive.State.AetherDriveMaximumRpm = maximumRpm; + drive.State.AetherDriveThrustDirectionX = thrustDirection.X; + drive.State.AetherDriveThrustDirectionY = thrustDirection.Y; + } + + private static void ApplyHullDrag( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeCatalogSnapshot catalog, + double deltaSeconds) + { + var drag = Math.Max(0, catalog.FindItem(entity.HullItemKey ?? "")?.HullDrag ?? 0); + var speed = Math.Sqrt(entity.VelocityX * entity.VelocityX + entity.VelocityY * entity.VelocityY); + if (speed <= 0.01 || drag <= 0) + return; + var decayed = speed * Math.Exp(-drag * deltaSeconds); + entity.VelocityX = entity.VelocityX / speed * decayed; + entity.VelocityY = entity.VelocityY / speed * decayed; + } + + private static double ResolveMass( + AetheriaRuntimeEntitySnapshotCommit entity, + IReadOnlyDictionary entities, + AetheriaRuntimeCatalogSnapshot catalog, + HashSet path) + { + if (!path.Add(entity.EntityIndex)) + throw new InvalidOperationException($"Entity mass cycle contains {entity.EntityIndex}."); + var mass = Math.Max(0, catalog.FindItem(entity.HullItemKey ?? "")?.Mass ?? 0); + mass += SlotsMass(entity.Equipment, catalog); + mass += (entity.CargoContents ?? Array.Empty()) + .Sum(bay => SlotsMass(bay?.Items, catalog)); + foreach (var childIndex in entity.ChildEntityIndices ?? Array.Empty()) + if (entities.TryGetValue(childIndex, out var child)) + mass += ResolveMass(child, entities, catalog, path); + path.Remove(entity.EntityIndex); + return Math.Max(0.000001, mass); + } + + private static double SlotsMass( + IReadOnlyList? slots, + AetheriaRuntimeCatalogSnapshot catalog) => + (slots ?? Array.Empty()) + .Where(slot => slot?.Item != null) + .Sum(slot => Math.Max(0, catalog.FindItem(slot.Item.ItemKey ?? "")?.Mass ?? 0) * + Math.Max(1, slot.Item.Quantity)); + + private static IReadOnlyList Online( + AetheriaRuntimeEntitySnapshotCommit entity, + AetheriaRuntimeCatalogSnapshot catalog, + string kind) + { + var states = (entity.EquipmentStates ?? Array.Empty()) + .Where(state => state != null) + .ToDictionary(state => state.EquipmentIndex); + return AetheriaRuntimeEquippedBehaviorQueries.Find(entity, catalog, kind) + .Where(value => value.Item.Enabled && value.Item.Durability > 0.01 && + (!states.TryGetValue(value.EquipmentIndex, out var state) || state.Online)) + .ToArray(); + } + + private static double ThermalPerformance(AetheriaRuntimeEntitySnapshotCommit entity, int equipmentIndex) => + (entity.EquipmentStates ?? Array.Empty()) + .FirstOrDefault(state => state != null && state.EquipmentIndex == equipmentIndex)? + .ThermalPerformance ?? 1; + + private static Vector3 ReadVector3(AetheriaRuntimeBehaviorPayload payload, int key) + { + var value = Field(payload, key); + return new Vector3(ChildNumber(value, 0), ChildNumber(value, 1), ChildNumber(value, 2)); + } + + private static IReadOnlyList ReadCurveKeys( + AetheriaRuntimeBehaviorPayload payload, + int key) + { + var value = Field(payload, key); + return (value?.Children ?? Array.Empty()) + .Select(curveKey => new AetheriaRuntimeCurveKey( + ChildNumber(curveKey, 0), + ChildNumber(curveKey, 1), + ChildNumber(curveKey, 2), + ChildNumber(curveKey, 3))) + .ToArray(); + } + + private static AetheriaRuntimeBehaviorValue? Field(AetheriaRuntimeBehaviorPayload payload, int key) => + (payload.Fields ?? Array.Empty()) + .FirstOrDefault(field => field != null && field.Key == key)?.Value; + + private static double ChildNumber(AetheriaRuntimeBehaviorValue? value, int index) => + value != null && value.Children != null && value.Children.Count > index + ? value.Children[index].NumberValue + : 0; + + private static double Ratio(double value, double divisor) => divisor <= 0.000001 ? 0 : value / divisor; + private static double Sign(double value) => value < 0 ? -1 : value > 0 ? 1 : 0; + private static double Clamp01(double value) => Clamp(value, 0, 1); + private static double Clamp(double value, double minimum, double maximum) => + value < minimum ? minimum : value > maximum ? maximum : value; + + private static Vector2 Normalize(double x, double y, double fallbackX, double fallbackY) + { + var length = Math.Sqrt(x * x + y * y); + return length <= 0.000001 ? new Vector2(fallbackX, fallbackY) : new Vector2(x / length, y / length); + } + + private static Vector2 RotateRadians(Vector2 value, double radians) + { + var cosine = Math.Cos(radians); + var sine = Math.Sin(radians); + return Normalize( + value.X * cosine + value.Y * sine, + -value.X * sine + value.Y * cosine, + value.X, + value.Y); + } + + private static Vector2 RotateQuarter(Vector2 value, int rotation) => rotation switch + { + 1 => new Vector2(-value.Y, value.X), + 2 => new Vector2(-value.X, -value.Y), + 3 => new Vector2(value.Y, -value.X), + _ => value + }; + + private static Vector3 Decay(Vector3 source, Vector3 lambda, double deltaSeconds) => new( + source.X * Math.Exp(-lambda.X * deltaSeconds), + source.Y * Math.Exp(-lambda.Y * deltaSeconds), + source.Z * Math.Exp(-lambda.Z * deltaSeconds)); + + private static Vector3 Abs(Vector3 value) => new(Math.Abs(value.X), Math.Abs(value.Y), Math.Abs(value.Z)); + private static Vector3 Max(Vector3 value, double scalar) => new( + Math.Max(value.X, scalar), Math.Max(value.Y, scalar), Math.Max(value.Z, scalar)); + private static Vector3 Min(Vector3 left, Vector3 right) => new( + Math.Min(left.X, right.X), Math.Min(left.Y, right.Y), Math.Min(left.Z, right.Z)); + private static Vector3 DivideOrZero(Vector3 value, Vector3 divisor) => new( + Math.Abs(divisor.X) <= 0.000001 ? 0 : value.X / divisor.X, + Math.Abs(divisor.Y) <= 0.000001 ? 0 : value.Y / divisor.Y, + Math.Abs(divisor.Z) <= 0.000001 ? 0 : value.Z / divisor.Z); + + private static bool TryParseEntityIndex(string? entityKey, out int entityIndex) + { + entityIndex = -1; + if (string.IsNullOrWhiteSpace(entityKey)) return false; + var marker = entityKey.LastIndexOf(".entity.", StringComparison.OrdinalIgnoreCase); + if (marker < 0) return false; + var start = marker + ".entity.".Length; + var end = start; + while (end < entityKey.Length && char.IsDigit(entityKey[end])) end++; + return end > start && int.TryParse(entityKey.Substring(start, end - start), out entityIndex); + } + + private readonly struct Vector2 + { + public Vector2(double x, double y) { X = x; Y = y; } + public double X { get; } + public double Y { get; } + public static Vector2 operator *(Vector2 value, double scalar) => new(value.X * scalar, value.Y * scalar); + public static Vector2 operator +(Vector2 left, Vector2 right) => new(left.X + right.X, left.Y + right.Y); + } + + private readonly struct Vector3 + { + public Vector3(double x, double y, double z) { X = x; Y = y; Z = z; } + public double X { get; } + public double Y { get; } + public double Z { get; } + public double Length => Math.Sqrt(X * X + Y * Y + Z * Z); + public static Vector3 One => new(1, 1, 1); + public static Vector3 operator +(Vector3 left, Vector3 right) => new(left.X + right.X, left.Y + right.Y, left.Z + right.Z); + public static Vector3 operator -(Vector3 left, Vector3 right) => new(left.X - right.X, left.Y - right.Y, left.Z - right.Z); + public static Vector3 operator *(Vector3 left, Vector3 right) => new(left.X * right.X, left.Y * right.Y, left.Z * right.Z); + public static Vector3 operator *(Vector3 value, double scalar) => new(value.X * scalar, value.Y * scalar, value.Z * scalar); + public static Vector3 operator *(double scalar, Vector3 value) => value * scalar; + public static Vector3 operator /(Vector3 value, double scalar) => new(value.X / scalar, value.Y / scalar, value.Z / scalar); + } + } +} diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeFlightSimulation.cs.meta b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeFlightSimulation.cs.meta new file mode 100644 index 000000000..1fa568cd5 --- /dev/null +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeFlightSimulation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8e09a25f522b4ee3aeb84f320dcd7f31 diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs index 2f12a600f..eea332a64 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeGameViewportDocuments.cs @@ -1014,7 +1014,11 @@ namespace GameCult.Aetheria.State.Verse contact.Hostile, contact.Visible)) .ToArray(), - entity.ShutdownPerformance); + entity.ShutdownPerformance, + entity.LookDirectionX, + entity.LookDirectionY, + entity.HelmStrafe, + entity.HelmForward); } private static AetheriaRuntimeEntityItemSlotSnapshot[] CreateEntityItemSlots( diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs index 866b6441d..51591c3b8 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs @@ -1080,6 +1080,18 @@ namespace GameCult.Aetheria.State.Verse [Key(48)] public string CauseOfDeath { get; set; } = ""; + + [Key(49)] + public double LookDirectionX { get; set; } + + [Key(50)] + public double LookDirectionY { get; set; } + + [Key(51)] + public double HelmStrafe { get; set; } + + [Key(52)] + public double HelmForward { get; set; } } [MessagePackObject] diff --git a/docs/aetheria-perfect-machine-map.md b/docs/aetheria-perfect-machine-map.md index bf676be83..e63f331c9 100644 --- a/docs/aetheria-perfect-machine-map.md +++ b/docs/aetheria-perfect-machine-map.md @@ -930,6 +930,58 @@ legacy catalog cache, and legacy UI paths should be migration-only or deleted. - Cut line: the unconditional `planar.top-down-follow.v1` projection no longer collapses the fossil dock and flight cameras into one false top-down view. +### Authoritative Flight Actuator Contract + +- Owner: Aetheria daemon owns persistent local helm axes, desired look + direction, installed-actuator evaluation, energy/heat/visibility consequences, + hull drag, and the velocity/direction submitted to physics. Ymir owns body + integration and contacts. Eve clients own input sampling and interpolation, + never accepted motion. +- Inputs: accepted semantic movement/look commands; current hull direction and + velocity; catalog hull/item shapes and masses; equipment placement and + rotation; online/durability/thermal state; behavior payload performance stats; + capacitor/reactor availability; fixed delta. +- Outputs: actual entity direction and velocity, persistent helm/look state, + typed Thruster/AetherDrive behavior state, equipment heat, plume visibility, + and the Ymir-integrated body pose. +- Ordinary-flight invariant: standard ships fly through directional thrusters. + The daemon clears and reallocates their axes each tick using the fossil + forward/reverse/left/right rotation groups, symmetric lateral-torque + compensation, placement-derived torque, and desired-look turn demand. A + thruster that cannot fund its authored energy demand produces no force, heat, + or plume visibility. +- Variant invariant: AetherDrive is not baseline propulsion. The canonical + catalog contains the single 250,000-credit `Traction` drive with hardpoint + type `AetherDrive`, and only the 7,500,000-credit modified `LonginusX` hull + exposes that hardpoint. Its rotor RPM, coupling, torque curve, energy, heat, + and thrust run only when that rare equipment is actually installed. Ordinary + flight fixtures explicitly prove that no AetherDrive state is manufactured. +- Derived state: Eve actuator rows, RPM gauges, plume/effect intensity, sound + parameters, and interpolated transforms are presentation projections. They + cannot write velocity, direction, heat, energy, or equipment state back. +- Forbidden writers: faction speed constants, command reducers, task planners, + Eve lowerers, and Unity transforms cannot assign accepted ship velocity or + heading. `SetLookDirection` now writes desired look only; physical actuators + turn the hull. World-space autonomous travel must be translated into the same + local strafe/forward helm axes used by a pilot. +- Shared paths: manual movement, autonomous exploration/haul/patrol/attack, + cross-zone approach, and home docking all enter the same command reducer, + actuator step, and Ymir world step. AetherDrive and Thruster share mass, + thermal, energy, drag, and physics owners without pretending to be the same + equipment class. +- Cut line: `ApplyMovementIntent` and faction `PawnSpeed`/`RaiderSpeed` motion + are gone. No compatibility fallback may restore direct velocity assignment. +- Verification: daemon smoke proves local-axis dominance through ordinary + thrusters, placement-derived torque/thrust state, funded heat and plume, + unfunded no-motion/no-plume behavior, progressive hardware turning before + weapon lock, autonomous navigation and cross-zone travel through Ymir, and + isolated rare AetherDrive spool/force on a modified-hull fixture. Canonical + catalog assertions lock the `Traction`/`LonginusX` rarity boundary. +- Open parity: hardpoint transform directions, exact per-equipment behavior + execution ordering, float32/CultMath parity against the fossil, production + generation-frequency evidence, and generic native thrust/turn feedback still + require proof. + ### Flight Post-Processing Contract - Owner: Aetheria selects the logical flight profile and owns its native asset diff --git a/docs/original-game-migration-matrix.md b/docs/original-game-migration-matrix.md index 2214e9fa6..07bbd9145 100644 --- a/docs/original-game-migration-matrix.md +++ b/docs/original-game-migration-matrix.md @@ -18,7 +18,7 @@ validation proves contract shape, not wiring, exclusivity, lowering, or parity. | Run/session state | `ServerShared`, `ActionGameManager` | Aetheria daemon/CultCache | provider/session advertisement | all clients | owner-exists; wired; projected; not proven | restart and multi-client convergence | | Entity identity/loadout | `ServerShared/Entity*` | daemon | typed entity and inventory surfaces | EveUnity/Electron | owner-exists; wired; projected; not proven | loadout round trip and reconnect | | Loadout generation | map/faction availability, item cost, hull hardpoints and role constraints | daemon using canonical galaxy, faction knowledge/economy and typed catalog | generated loadout plus provenance/availability facts | Eve inspection and refit surfaces | daemon now uses the fossil candidate filter and seeded weighted selection: manufacturer must be present and allied, ally weight decays by home-zone graph distance, price uses the authored exponent, and hardpoints require matching semantic type, rotated footprint containment, and controller role; the exact placement rotation used by hardpoint/free-space/cargo fitting now survives generated state, durable loadouts, runtime commits, viewport snapshots, cloning, and reconnect instead of disappearing after occupancy reservation; generation fills the largest compatible footprint before applying economic weighting, so small gear remains a valid large-mount fallback without displacing available station-scale gear; cargo/capacitor plus station docking equipment must fit remaining hull space; stations draw up to sixteen faction-available equipment rows and pack largest-first into the selected cargo bay's actual interior shape; ordinary ships begin without generated cargo, and the deleted scenario-string path can no longer silently invent non-catalog item identities; station cargo slots and receipts preserve the same canonical keys; zone generation derives one continuing deterministic RNG stream per availability corporation, so cross-faction calls cannot perturb another faction; every generated entity persists an immutable source/selection receipt that reaches Eve as `loadout.item` semantics; Terminus explicitly maps combat-role factions to catalog availability corporations | multi-zone generated-world parity and exact root-to-zone stream sequencing against the fossil | -| Flight intent | `Ship`, `Thruster`, `AetherDrive`, input paths | daemon intent + Ymir physics | analog movement/look/tractor | EveUnity input driver | movement intents feed Ymir-owned body integration; authored thrust allocation, torque, energy and heat remain simplified | prove original drive/equipment behavior ordering and runtime interpolation | +| Flight intent | `Ship`, `Thruster`, `AetherDrive`, input paths | daemon actuator simulation + Ymir integration | analog local helm/look/tractor plus actuator state | generic Eve input and scene lowerers | direct faction-speed velocity ownership is deleted; daemon persists local strafe/forward helm and desired look, allocates ordinary directional thruster banks by authored rotation, derives torque from hull/item placement, compensates lateral torque, gates execution through the shared energy ledger, deposits equipment-cell heat, publishes plume visibility and actuator state, applies hull drag, and gives resulting velocity/direction to Ymir. Autonomous tasks translate world travel into the same local helm axes and issue look commands instead of mutating heading. AetherDrive rotor/coupling simulation is additive and explicitly non-default: the canonical catalog has one expensive `Traction` drive and one compatible rare `LonginusX` modified hull, while ordinary smoke flight contains no drive behavior | hardpoint-transform direction parity, exact behavior execution ordering, CultMath/float32 parity harness, production loadout-frequency witness, generic thrust/turn feedback lowering, and live handling screenshots | | Collision | Unity physics and entity handlers | Ymir | collision/result facts | visual interpolation only | Ymir.Core world stepping wired for entity bodies, radial fields and contacts; missing-owner negative proof passes | publish authoritative collision events and prove Unity cannot write transforms back | | Targeting/contacts | sensors + `ActionGameManager` | daemon | contact/target semantics | target HUD and indicators | simplified owner wired/projected; every authored instant lock behavior now evaluates on every daemon step independently of trigger/burst selection, so an idle weapon cannot retain a stale completed lock; acquisition and decay derive from facing, elapsed time, and observer-local contact confidence instead of granting an immediate perfect lock; target changes and invalid targets clear the daemon state; `weapon.lock.started`, `weapon.lock.acquired`, and `weapon.lock.lost` publish stable one-time chronology with target, weapon identity, reason, and prior/current progress through the generic feedback stream; the provider cockpit and generic combat reticle consume the same continuous selected-target lock without client smoothing or reconstruction | angular loss fixture, visibility/nearest/explicit targeting cases, provider audio/effect roles, and authored reticle parity | | Projectile flight | weapon/projectile classes | Eve presentation for ordinary tracers; Ymir for persistent physical payloads | receipt trajectory/effect facts or persistent payload state | native projectile visual | ordinary instant, charged, and constant execution creates no projectile body; each weapon state owns a stable shot sequence and receipts carry origin, endpoint, nominal duration, and effect identity for Eve presentation; `SpawnProjectile` and its alternate writer are deleted; Ymir projectile contacts are feedback-only for explicitly persisted payload rows and cannot write damage; Ymir.Core remains embedded for world integration, radial fields, circle contacts, pickups, and genuinely persistent/interceptable payloads | split/rename the remaining physical-payload interface and remove ordinary projectile terminology from runtime contracts |