diff --git a/Assets/Scripts/Gameplay/EntityInstance.cs b/Assets/Scripts/Gameplay/EntityInstance.cs index 296457912..e07ba3135 100644 --- a/Assets/Scripts/Gameplay/EntityInstance.cs +++ b/Assets/Scripts/Gameplay/EntityInstance.cs @@ -511,11 +511,6 @@ public class EntityInstance : MonoBehaviour x.Value.material.SetFloat("_Emission", Entity.ItemManager.GameplaySettings.TemperatureEmissionCurve.Evaluate(x.Key.RadiatorTemperature)); } - foreach (var x in Barrels) - { - Entity.HardpointTransforms[x.Key] = (x.Value[0].position.ToCultMath(), x.Value[0].forward.ToCultMath()); - } - LookAtPoint.position = transform.position + Entity.LookDirection.ToUnity() * (Entity.Target.Value != null ? max(Entity.TargetRange,Entity.ItemManager.GameplaySettings.ConvergenceMinimumDistance) : 10000); LocalSpace.localPosition = transform.position = Entity.Position.ToUnity(); diff --git a/Assets/Scripts/ServerShared/Agents/States/Combat.cs b/Assets/Scripts/ServerShared/Agents/States/Combat.cs index f63d49553..6feeed610 100644 --- a/Assets/Scripts/ServerShared/Agents/States/Combat.cs +++ b/Assets/Scripts/ServerShared/Agents/States/Combat.cs @@ -97,9 +97,7 @@ public class CombatState : BaseState toTarget = normalize(predictedPosition - _agent.Ship.Position); } - var shouldFire = dot( - _agent.Ship.HardpointTransforms[_agent.Ship.Hardpoints[testWeapon.Item.Position.x, testWeapon.Item.Position.y]].direction, - toTarget) > .99f; + var shouldFire = FireControl.InArc(testWeapon.Item, toTarget); foreach (var weapon in _agent.Ship.WeaponGroups[selectedGroup].weapons) { if (shouldFire) diff --git a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs index dd72122f4..7e44c96e0 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs @@ -27,16 +27,8 @@ public abstract class Behavior { if(Item != null) { - var hardpoint = Entity.Hardpoints[Item.Position.x, Item.Position.y]; - if (hardpoint != null && Entity.HardpointTransforms.ContainsKey(hardpoint)) - { - return normalize(Entity.HardpointTransforms[hardpoint].direction); - } - else - { - var itemDirection = Entity.Direction.Rotate(Item.EquippableItem.Rotation); - return float3(itemDirection.x, 0, itemDirection.y); - } + var itemDirection = Entity.Direction.Rotate(Item.EquippableItem.Rotation); + return float3(itemDirection.x, 0, itemDirection.y); } return float3(Entity.Direction.x, 0, Entity.Direction.y); diff --git a/Assets/Scripts/ServerShared/Behaviors/TurretController.cs b/Assets/Scripts/ServerShared/Behaviors/TurretController.cs index 6e39f94e0..6b67cc26b 100644 --- a/Assets/Scripts/ServerShared/Behaviors/TurretController.cs +++ b/Assets/Scripts/ServerShared/Behaviors/TurretController.cs @@ -78,9 +78,7 @@ public class TurretController : Behavior, IInitializableBehavior foreach (var x in _weapons) { var data = x.Data as WeaponData; - var fire = dot( - x.Direction, - Entity.LookDirection) > .99f; + var fire = FireControl.InArc(x.Item, Entity.LookDirection); if (x.Evaluate(data.Range) > dist && fire) { x.Activate(); diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 2dcf90601..585c5e534 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -54,10 +54,8 @@ public abstract class Entity public readonly Dictionary Messages = new Dictionary(); public readonly Dictionary VisibilitySources = new Dictionary(); - public readonly ReactiveDictionary EntityInfoGathered = new ReactiveDictionary(); - public readonly Dictionary HardpointTransforms = - new Dictionary(); - + public readonly ReactiveDictionary EntityInfoGathered = new ReactiveDictionary(); + public (List weapons, List items)[] WeaponGroups; public List PopulationAssignments = new List(); diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs new file mode 100644 index 000000000..a19bf5838 --- /dev/null +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -0,0 +1,43 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using CultMath; +using static CultMath.math; + +// Cut 1 (docs/fire-control-cut.md): geometry only. Whether a weapon bears on a point is decided here and +// nowhere else -- no prefab, transform, ArticulationPoint or renderer may influence it (R6, R7). Mount +// direction and arc are both derived per read from catalog data and the item's authored rotation; neither +// is ever stored on the entity. +public static class FireControl +{ + // The planar unit vector a hardpoint's weapon points along, derived solely from the item's authored + // rotation (R6, the same convention reaction thrusters already use) -- never from a live Unity + // transform. This is the item-rotation path Behavior.Direction now uses unconditionally, after the + // HardpointTransforms readback branch is deleted. + public static float3 MountDirection(EquippedItem item) + { + var itemDirection = item.Entity.Direction.Rotate(item.EquippableItem.Rotation); + return normalize(float3(itemDirection.x, 0, itemDirection.y)); + } + + // Full arc width in degrees: the per-hardpoint override when authored (nonzero), else + // GameplaySettings.FiringArc. Zero on the hardpoint means "use the default," not "no arc." + public static float ArcFor(EquippedItem item) + { + var hardpoint = item.Entity.Hardpoints[item.Position.x, item.Position.y]; + var arc = hardpoint?.FiringArc ?? 0f; + return arc > 0 ? arc : item.ItemManager.GameplaySettings.FiringArc; + } + + // Planar bearing test (R7: the simulation is 2D, the 3D is set dressing -- target height never enters + // this). An arc of 360 degrees or more passes unconditionally, which is how a turret hardpoint + // (authored FiringArc: 360, Q1) tracks all the way around without a second type. + public static bool InArc(EquippedItem weapon, float3 toTarget) + { + var arc = ArcFor(weapon); + if (arc >= 360f) return true; + var planarTarget = normalize(float3(toTarget.x, 0, toTarget.z)); + return dot(MountDirection(weapon), planarTarget) >= cos(radians(arc / 2f)); + } +} diff --git a/Assets/Scripts/ServerShared/FireControl.cs.meta b/Assets/Scripts/ServerShared/FireControl.cs.meta new file mode 100644 index 000000000..0c35816a2 --- /dev/null +++ b/Assets/Scripts/ServerShared/FireControl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e84f481f2a2e9fdc572e40e239eacc92 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/ItemData.cs b/Assets/Scripts/ServerShared/ItemData.cs index f40179acc..5e82ea6d7 100644 --- a/Assets/Scripts/ServerShared/ItemData.cs +++ b/Assets/Scripts/ServerShared/ItemData.cs @@ -543,6 +543,9 @@ public class HardpointData [Inspectable, JsonProperty("transform"), Key(3)] public string Transform; [Inspectable, JsonProperty("rotation"), Key(4)] public ItemRotation Rotation; [Inspectable, JsonProperty("armor"), Key(5)] public float Armor; + // Full arc width in degrees a weapon on this hardpoint may bear across; 0 means "use + // GameplaySettings.FiringArc" (docs/fire-control-cut.md R6). Turrets author 360 (Q1). + [Inspectable, JsonProperty("firingArc"), Key(6)] public float FiringArc; public override string ToString() { diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index ff5980109..41126bc79 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -212,10 +212,10 @@ public class GameplaySettings public float TargetArmorInfoThreshold; public float TargetGearInfoThreshold; public float ConvergenceMinimumDistance; + public float FiringArc = 120; public float AgentRangeExponent = .25f; public float AgentForwardLerp = .5f; public float AgentMaxForwardDistance = 50; - public float AgentFiringMinDot = .99f; } [Serializable, MessagePackObject(keyAsPropertyName: true), JsonObject] diff --git a/tests/Aetheria.Shared.Tests/FireControlTests.cs b/tests/Aetheria.Shared.Tests/FireControlTests.cs new file mode 100644 index 000000000..4c9f059cf --- /dev/null +++ b/tests/Aetheria.Shared.Tests/FireControlTests.cs @@ -0,0 +1,221 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; +using static CultMath.math; +using float3 = CultMath.float3; + +// Cut 1 (docs/fire-control-cut.md): pins mount direction, arc authoring/defaulting and the headless +// engagement this cut exists to unbreak. Builds its own hull/catalog (the IffAndCombatTests Skiff/Gun +// fixture is fixed to one hardpoint) rather than reusing those private helpers. +public sealed class FireControlTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-firecontrol-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + + public FireControlTests() => Directory.CreateDirectory(_root); + + private CultCache _openCache; + + public void Dispose() + { + _openCache?.Dispose(); + Directory.Delete(_root, true); + } + + private static GameplaySettings TestSettings() => new GameplaySettings + { + DefaultEntitySettings = new EntitySettings(), + Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } }, + QualityPriceModifier = new ExponentialLerp(), + TargetDetectionInfoThreshold = .5f, + FiringArc = 120 + }; + + // A hull with one weapon hardpoint per (rotation, firingArc) pair, laid out along the X axis of a 1xN + // shape so each gets its own cell. FiringArc 0 on a hardpoint means "use GameplaySettings.FiringArc". + private (ItemManager items, Ship ship, EquippedItem[] weapons) BuildShipWithHardpoints( + params (ItemRotation rotation, float firingArc)[] hardpoints) + { + var hullShape = new Shape(Math.Max(hardpoints.Length, 3), 3); + foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true; + // Mass defaults to 0 (ItemData.cs:285), which zeroes ThermalMass (Entity.cs MapEntity) and NaNs + // UpdateTemperature -- author a real mass so the entity's own temperature stays a real number. + var hullData = new HullData { Name = "TestHull", HullType = HullType.Ship, Shape = hullShape, Durability = 1, Mass = 1000 }; + for (var i = 0; i < hardpoints.Length; i++) + hullData.Hardpoints.Add(new HardpointData + { + Type = HardpointType.Sensors, Position = new int2(i, 0), Shape = new Shape(), + Rotation = hardpoints[i].rotation, FiringArc = hardpoints[i].firingArc + }); + + using (var buildCache = AetheriaStores.Open(Catalog, catalogWritable: true)) + { + buildCache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + buildCache.Upsert(hullData); + buildCache.Upsert(new GearData + { + // The default [0,100] temperature bounds (ItemData.cs:379-382) don't necessarily cover + // wherever this hull's heat model settles after a tick: author a wide plateau so + // EquippableItemData.Performance stays 1 and the item actually comes Online. + Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new InstantWeaponData() } + }); + buildCache.FlushAsync().Wait(); + } + + _openCache = AetheriaStores.Open(Catalog, catalogWritable: true); + var ledger = new ProvenanceLedger(); + ledger.Lots[1] = new Lot { Origin = new Attributed(), Quality = 1 }; // hull + for (var i = 0; i < hardpoints.Length; i++) + ledger.Lots[2 + i] = new Lot { Origin = new Attributed(), Quality = 1 }; // guns + var items = new ItemManager(_openCache, ledger, TestSettings(), _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + + var hullRef = items.ItemData.RefOf(items.ItemData.GetByName("TestHull")); + var hull = new EquippableItem { Data = hullRef, Durability = 1, Lot = 1 }; + var ship = new Ship(items, zone, hull, new EntitySettings()); + + // Entity.MapEntity equips the hull itself into Equipment at int2.zero, so hardpoint 0 (also at + // (0,0) here) shares a cell with the hull's own equipped-item entry: match guns by identity, not + // position. + var gunRef = items.ItemData.RefOf(items.ItemData.GetByName("Gun")); + var weapons = new EquippedItem[hardpoints.Length]; + for (var i = 0; i < hardpoints.Length; i++) + { + var gun = new EquippableItem { Data = gunRef, Durability = 1, Lot = 2 + i }; + Assert.True(ship.TryEquip(gun, new int2(i, 0))); + weapons[i] = ship.Equipment.Single(e => e.EquippableItem == gun); + } + + zone.Entities.Add(ship); + ship.Activate(); + + return (items, ship, weapons); + } + + // R6: mount direction is the item's authored rotation, not the hull's facing. A target 90 degrees to + // starboard bears on the Clockwise hardpoint's weapon and not the None hardpoint's, and vice versa dead + // ahead. Mutation: make InArc read Entity.Direction instead of the item's rotation, or swap Rotate's + // Clockwise/CounterClockwise cases -- either breaks one of the four assertions below. + [Fact] + public void ArcFollowsMountRotation() + { + var (_, _, weapons) = BuildShipWithHardpoints((ItemRotation.None, 0f), (ItemRotation.Clockwise, 0f)); + var forward = weapons[0]; + var starboardMounted = weapons[1]; + + var deadAhead = float3(0, 0, 1); + var abeamStarboard = float3(1, 0, 0); + + Assert.True(FireControl.InArc(forward, deadAhead)); + Assert.False(FireControl.InArc(forward, abeamStarboard)); + Assert.True(FireControl.InArc(starboardMounted, abeamStarboard)); + Assert.False(FireControl.InArc(starboardMounted, deadAhead)); + } + + // FiringArc is full width: at the default 120, a target 59 degrees off the mount bears and one at 61 + // does not. Mutation: compare against cos(radians(arc)) instead of cos(radians(arc/2)). + [Fact] + public void ArcBoundaryIsHalfWidth() + { + var (_, _, weapons) = BuildShipWithHardpoints((ItemRotation.None, 0f)); + var weapon = weapons[0]; + + float3 AtAngle(float degrees) + { + var r = radians(degrees); + return float3(sin(r), 0, cos(r)); + } + + Assert.True(FireControl.InArc(weapon, AtAngle(59))); + Assert.False(FireControl.InArc(weapon, AtAngle(61))); + } + + // R7: the simulation is 2D. A target inside the arc horizontally but far above the firer still bears. + // Mutation: normalize and dot the full 3D vector instead of zeroing height first. + [Fact] + public void ArcIsPlanar() + { + var (_, _, weapons) = BuildShipWithHardpoints((ItemRotation.None, 0f)); + var weapon = weapons[0]; + + var highButAhead = float3(0, 1000, 1); + + Assert.True(FireControl.InArc(weapon, highButAhead)); + } + + // The per-hardpoint override wins over the default, and an authored 0 means "use the default," not + // "zero-degree arc." A hardpoint authored FiringArc: 360 bears 170 degrees off; a hardpoint left at 0 + // falls back to GameplaySettings.FiringArc (120) and fails there, but still bears a target only 5 + // degrees off. Mutation: ignore HardpointData.FiringArc entirely (both hardpoints fail at 170), or + // treat an authored 0 as a literal zero-width arc (the second hardpoint then fails even at 5 degrees). + [Fact] + public void HardpointOverrideBeatsDefault() + { + var (_, _, weapons) = BuildShipWithHardpoints((ItemRotation.None, 360f), (ItemRotation.None, 0f)); + var turret = weapons[0]; + var defaultArc = weapons[1]; + + float3 AtAngle(float degrees) + { + var r = radians(degrees); + return float3(sin(r), 0, cos(r)); + } + + Assert.True(FireControl.InArc(turret, AtAngle(170))); + Assert.False(FireControl.InArc(defaultArc, AtAngle(170))); + Assert.True(FireControl.InArc(defaultArc, AtAngle(5))); + } + + // The cut's real deliverable: Entity.HardpointTransforms is gone, so a Minion can step through a full + // Zone.Update tick and reach the fire decision without Unity ever having run. Before this cut, + // Combat.cs:100-102 threw KeyNotFoundException on the first combat tick headless, because the AI's aim + // direction was a readback from a renderer that never ran. Mutation: restore the HardpointTransforms + // read in Behavior.Direction / Combat.cs -- this throws again outside Unity. + [Fact] + public void CombatStateStepsHeadless() + { + var (items, shooter, weapons) = BuildShipWithHardpoints((ItemRotation.None, 0f)); + var weaponData = (InstantWeaponData) weapons[0].Data.Behaviors.Single(b => b is InstantWeaponData); + weaponData.Damage = new PerformanceStat { Min = 10, Max = 10 }; + weaponData.Cooldown = new PerformanceStat { Min = 1, Max = 1 }; + weaponData.Range = new PerformanceStat { Min = 1000, Max = 1000 }; + weaponData.MinRange = new PerformanceStat { Min = 0, Max = 0 }; + weaponData.DamageCurve = new BezierCurve { Keys = new[] { float4(0, 1, 0, 0), float4(1, 1, 0, 0) } }; + + var zone = shooter.Zone; + var targetHullRef = items.ItemData.RefOf(items.ItemData.GetByName("TestHull")); + var target = new Ship(items, zone, new EquippableItem { Data = targetHullRef, Durability = 1, Lot = 1 }, new EntitySettings()); + // Entity._orderedEquipment is populated only by TryEquip (Entity.cs:813); a ship that never equips + // anything leaves it null, and Entity.Update (:932) throws on that regardless of this cut. Equip a + // gun so the target is a real, ordinarily-constructed ship rather than a workaround-shaped one. + var targetGunRef = items.ItemData.RefOf(items.ItemData.GetByName("Gun")); + Assert.True(target.TryEquip(new EquippableItem { Data = targetGunRef, Durability = 1, Lot = 1 }, new int2(0, 0))); + zone.Entities.Add(target); + target.Activate(); + + shooter.Position = float3.zero; + target.Position = float3(0, 0, 10); // dead ahead of the None-rotation hardpoint, well within range and arc + + shooter.Target.Value = target; + zone.Agents.Add(new Minion(shooter)); + + var ex = Record.Exception(() => + { + zone.Update(1f); // tick 1: transitions the Minion into CombatState and evaluates weapon stats for the first time + zone.Update(1f); // tick 2: CombatState.Update reaches FireControl.InArc -- the line that used to throw headless + }); + + Assert.Null(ex); + var weapon = shooter.Weapons.Single(); + Assert.True(weapon.Firing); // arc + range satisfied: the fight actually decided to fire, not just avoided a crash + } +} diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 8f69161b2..2ee6c4dc1 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -32,8 +32,9 @@ public static class Program case "shield-migrate": return ShieldMigrate(args.Contains("apply")); case "brownout-migrate": return BrownoutMigrate(args.Contains("apply")); case "roles-migrate": return RolesMigrate(args.Contains("apply")); + case "firing-arc-migrate": return FiringArcMigrate(args.Contains("apply")); default: - Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply]"); + Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply]"); return 1; } } @@ -974,4 +975,60 @@ public static class Program Console.WriteLine($"Landed {changed.Count} changed records in Aetheria.cc"); return 0; } + + // Cut 1 (docs/fire-control-cut.md, "Catalog" under Cut 1 / Q1): a turret hardpoint authors + // FiringArc: 360 -- no new type for what a number already says (R6 already gives every other hardpoint + // the GameplaySettings.FiringArc default via 0). Scoped to the Turret hull's own hardpoints, the only + // ones the cut names; other hulls' hardpoints are left at 0 (default arc) until a design pass says + // otherwise. Dry run unless passed "apply", same contract as ShieldMigrate/BrownoutMigrate. + private static int FiringArcMigrate(bool apply) + { + var db = AetherDb.Open(catalogWritable: apply); + + var hulls = db.Cache.GetAll().Where(h => h.Name == "Turret").ToArray(); + if (hulls.Length == 0) + { + Console.WriteLine("No hull named \"Turret\" found."); + return 1; + } + + Console.WriteLine($"{"hull",-16} {"hardpoint",-10} {"position",-10} {"was",5} {"now",5}"); + var changed = new List<(object Document, CultRecordKey Key)>(); + foreach (var hull in hulls) + { + var key = db.Cache.RefOf(hull).Key; + var touchedThisHull = false; + foreach (var hardpoint in hull.Hardpoints) + { + if (hardpoint.Type != HardpointType.Ballistic) continue; + var position = $"({hardpoint.Position.x},{hardpoint.Position.y})"; + var was = hardpoint.FiringArc; + if (was >= 360f) + { + Console.WriteLine($"{hull.Name,-16} {hardpoint.Type,-10} {position,-10} {was,5:0} {was,5:0} (already authored, left alone)"); + continue; + } + hardpoint.FiringArc = 360f; + Console.WriteLine($"{hull.Name,-16} {hardpoint.Type,-10} {position,-10} {was,5:0} {360,5:0}"); + touchedThisHull = true; + } + if (touchedThisHull) changed.Add((hull, key)); + } + + Console.WriteLine($"\n{changed.Count} hull records migrated"); + if (changed.Count == 0) return 0; + if (!apply) + { + Console.WriteLine($"Dry run. Pass \"apply\" to land {changed.Count} changed records."); + return 0; + } + + foreach (var (document, _) in changed) CultRecordRefs.Validate(document); + db.Cache.Commit(batch => + { + foreach (var (document, key) in changed) batch.Upsert(document.GetType(), document, key); + }); + Console.WriteLine($"Landed {changed.Count} changed records in Aetheria.cc"); + return 0; + } }