diff --git a/Assets/Scripts/ServerShared/Behaviors/TargetingSystem.cs b/Assets/Scripts/ServerShared/Behaviors/TargetingSystem.cs index 44658d332..96d9f3703 100644 --- a/Assets/Scripts/ServerShared/Behaviors/TargetingSystem.cs +++ b/Assets/Scripts/ServerShared/Behaviors/TargetingSystem.cs @@ -29,8 +29,11 @@ public class TargetingSystemData : BehaviorData [Inspectable, JsonProperty("resolution"), Key(2), RuntimeInspectable] public PerformanceStat Resolution = new PerformanceStat(); - // The chance a hit lands on the item actually aimed at (Entity.TargetItem) rather than a random cell. - // Consumed by Cut 3's roll. + // Cut 6d (docs/fire-control-cut.md): grouping tightness, not a probability. FireControl.Sigma derives a + // Gaussian kernel's sigma as 1/Precision, in hull-schematic cell units -- a higher number groups tighter + // around whatever is aimed at (Entity.TargetItem's cells, or the hull's own centre of mass unaimed). + // Consumed by Cut 3's roll (folded into HitProbability as pOnHull) and by Commit's cell draw, both through + // the one kernel function -- never re-derived separately. [Inspectable, JsonProperty("precision"), Key(3), RuntimeInspectable] public PerformanceStat Precision = new PerformanceStat(); diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index e9cc2829f..714a7c515 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -2,6 +2,7 @@ * 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.Collections.Generic; using System.Linq; using CultMath; @@ -9,6 +10,7 @@ using static CultMath.math; using float2 = CultMath.float2; using float3 = CultMath.float3; using int2 = CultMath.int2; +using Random = CultMath.Random; // Cut 1 (docs/fire-control-cut.md): geometry -- 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 @@ -102,10 +104,15 @@ public static class FireControl return system != null && system.Item.Active.Value ? system.Resolution : 1f; } + // Cut 6d (docs/fire-control-cut.md): falls back to GameplaySettings.UnaidedPrecision, the same shape + // Accuracy/Tracking already fall back to their own Unaided* floors. The old coin-flip rule could get away + // with a bare 0 here (0 meant "never draw the aimed-item branch," a legitimate value under that rule); the + // dart-throw kernel reads Precision as a grouping tightness, and 0 would ask Sigma for an infinite, division- + // guarded group -- not the authored "spraying at the silhouette" floor the spec asks for. public static float Precision(Entity entity) { var system = entity.GetBehavior(); - return system != null && system.Item.Active.Value ? system.Precision : 0f; + return system != null && system.Item.Active.Value ? system.Precision : entity.ItemManager.GameplaySettings.UnaidedPrecision; } // Cut 5, 5.1 (Soul finding 3): falls back to GameplaySettings.UnaidedTracking, exactly the shape Accuracy @@ -157,17 +164,28 @@ public static class FireControl (1f - settings.TargetDetectionInfoThreshold) / max(Resolution(source), 1e-3f); var pSensor = saturate(unlerp(settings.TargetDetectionInfoThreshold, demandCeiling, info)); + var targetHull = source.ItemManager.GetData(target.Hull) as HullData; + float pSpread; if (weapon.Spread > 0) { - var targetHull = source.ItemManager.GetData(target.Hull) as HullData; var halfExtent = .5f * max(targetHull.Shape.Width, targetHull.Shape.Height) * settings.SchematicCellSize; var angularRadius = degrees(atan(halfExtent / range)); pSpread = saturate(angularRadius / (weapon.Spread / 2f)); } else pSpread = 1f; - return Accuracy(source) * pSensor * pSpread; + // Cut 6d (docs/fire-control-cut.md): the dart-throw kernel's other half. pSpread above prices whether + // the weapon's own barrel-dispersion cone even reaches the ship's silhouette at this range (weapon + // hardware, whole-hull bounding size, range-dependent, aim-point-blind). pOnHull prices whether the + // targeting system's own aim scatter, centred on whatever is actually aimed at, lands on the hull's + // real schematic footprint rather than open grid around it (targeting hardware, per-cell shape, + // range-blind, aim-point-aware). Different inputs, different failure modes; see Cut(0's report for the + // double-charging call). Aim point is source.ResolvedTargetItem, exactly what Fire freezes below -- + // HitProbability and Fire read the same reveal-gated aim point, never two. + var pOnHull = HullKernel(targetHull, ResolveAimPoint(target, targetHull, source.ResolvedTargetItem).AimPoint, Precision(source)).POnHull; + + return Accuracy(source) * pSensor * pSpread * pOnHull; } // Cut 3, R1: called once per burst step from InstantWeapon.Execute. Computes flight time, freezes the @@ -328,18 +346,16 @@ public static class FireControl if (hit) { + // Cut 6d: the same kernel HitProbability's pOnHull drew its mass from -- same aim point (the + // frozen Aimed, or the hull's own centre of mass), same sigma (the frozen Precision). A shot that + // passed the roll always lands on metal (R3: one roll decides damage; the off-hull share was + // already priced into that roll, not resolved here as a second stage), so the draw is unconditional + // and always returns an occupied cell -- no fallback branch, uniform or otherwise. var hullData = shot.Source.ItemManager.GetData(shot.Target.Hull) as HullData; - var aimedCells = shot.Aimed != null ? CellsOf(shot.Target, shot.Aimed) : null; - if (aimedCells != null && aimedCells.Length > 0 && random.NextFloat() < shot.Precision) - { - aimed = shot.Aimed; - cell = aimedCells[random.NextInt(aimedCells.Length)]; - } - else - { - var coords = hullData.Shape.Coordinates; - cell = coords[random.NextInt(coords.Length)]; - } + var (aimPoint, aimedCells) = ResolveAimPoint(shot.Target, hullData, shot.Aimed); + var (cells, weights, totalWeight, _) = HullKernel(hullData, aimPoint, shot.Precision); + cell = WeightedPick(cells, weights, totalWeight, random); + if (aimedCells != null && Array.IndexOf(aimedCells, cell) >= 0) aimed = shot.Aimed; var shield = shot.Target.Shield; var shieldActive = shield != null && shield.Item.Active.Value; @@ -435,6 +451,74 @@ public static class FireControl } } + // Cut 6d (docs/fire-control-cut.md): the one kernel. HitProbability multiplies pOnHull; Commit draws the + // landing cell from the same per-cell weights. Nowhere else may compute a sigma or a weight -- this is the + // named risk from Cut 3 (two functions answering "where will this shot go" and eventually disagreeing), + // applied to placement instead of authority. + // + // Sigma is the frozen Precision's reciprocal, in hull-schematic cell units -- the same units + // Shape.CenterOfMass and GearOccupancy already use, so a sigma of 1 means "one cell's width of spread." + // Higher Precision (a tighter group) gives a smaller sigma; the 1e-3 floor only guards a stray zero or + // negative authored value; no authored Precision should ever reach it (GameplaySettings.UnaidedPrecision + // is the deliberately-bad floor Precision(Entity) itself falls back to, same shape as UnaidedAccuracy). + private static float Sigma(float precision) => 1f / max(precision, 1e-3f); + + // w(cell) = exp(-d^2 / 2*sigma^2) over every occupied hull cell, `d` the planar cell-space distance from + // the aim point, plus pOnHull = (sum of those weights) / (2*pi*sigma^2) -- the share of the full continuous + // kernel's mass (a 2D Gaussian integrates to 2*pi*sigma^2 over the infinite plane) that a discrete sum over + // occupied cells actually captures. The off-hull share -- outside the schematic's bounding box, or on an + // unoccupied cell inside it (a hole, a thin limb's missing neighbour) -- is exactly 1 - pOnHull, and it + // never gets a second roll (see Commit below): pOnHull already told HitProbability the price. + private static (int2[] Cells, float[] Weights, float TotalWeight, float POnHull) HullKernel(HullData hullData, float2 aimPoint, float precision) + { + var sigma = Sigma(precision); + var coords = hullData.Shape.Coordinates; + var weights = new float[coords.Length]; + var total = 0f; + for (var i = 0; i < coords.Length; i++) + { + var w = exp(-lengthsq((float2) coords[i] - aimPoint) / (2f * sigma * sigma)); + weights[i] = w; + total += w; + } + // saturate: the discrete sum only approximates the continuous kernel's integral, and undershoots badly + // once sigma drops below about one cell (an extremely tight, well-authored Precision) -- the aim cell + // alone can then carry a weight whose share of the (now tiny) 2*pi*sigma^2 denominator exceeds 1. A + // share of a kernel's mass cannot exceed the whole kernel; clamped here so every other reader of + // pOnHull (HitProbability's product of factors, this cut's own tests) can keep treating it as a + // probability rather than re-deriving the same guard at every call site. + var pOnHull = saturate(total / (2f * PI * sigma * sigma)); + return (coords, weights, total, pOnHull); + } + + // The aim point the kernel is centred on (R10/Q6: the same frozen Aimed both HitProbability and Fire read) + // -- the aimed item's own cell centroid when it currently occupies cells on the target, else the hull's + // own centre of mass. One path; the uniform-random branch this replaces is deleted, not demoted (Cut 6d). + private static (float2 AimPoint, int2[] AimedCells) ResolveAimPoint(Entity target, HullData hullData, EquippedItem aimed) + { + var aimedCells = aimed != null ? CellsOf(target, aimed) : null; + if (aimedCells != null && aimedCells.Length > 0) + return (aimedCells.Aggregate(float2.zero, (total, c) => total + (float2) c) / aimedCells.Length, aimedCells); + return (hullData.Shape.CenterOfMass, null); + } + + // A single weighted draw over the kernel's own occupied-cell weights -- the only way Commit picks a cell + // once a shot has already passed the roll (R3: one roll decides damage). totalWeight is passed in rather + // than resummed so this reads the identical mass HullKernel just computed. The trailing return guards only + // floating-point rounding at the very end of the accumulation; it can never fall through for a shot that + // reaches here, because the roll already established this hull has nonzero on-hull mass. + private static int2 WeightedPick(int2[] cells, float[] weights, float totalWeight, Random random) + { + var roll = random.NextFloat() * totalWeight; + var accumulated = 0f; + for (var i = 0; i < cells.Length; i++) + { + accumulated += weights[i]; + if (roll < accumulated) return cells[i]; + } + return cells[cells.Length - 1]; + } + // The cells of the target's hull schematic actually occupied by `item` -- GearOccupancy is the one source // of truth for where an equipped item's footprint lands, the same table Entity.DamageSchematic reads. private static int2[] CellsOf(Entity target, EquippedItem item) diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 52949f04d..ffd369b01 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -227,6 +227,18 @@ public class GameplaySettings // fire-time-projection deviation forgiveness is the first guess and the operator's knob, the same shape // as UnaidedAccuracy: authored deliberately bad, not authored broken. public float UnaidedTracking = 10f; + // Cut 6d (docs/fire-control-cut.md): the unaided fallback for Precision, alongside UnaidedAccuracy and + // UnaidedTracking above -- FireControl.Precision falls back to this the same way it already falls back to + // UnaidedAccuracy/UnaidedTracking. Precision is now a grouping tightness (FireControl.Sigma = 1/Precision, + // in hull-schematic cell units), not the old coin-flip probability, so the unaided floor has to be + // authored on that scale. .3 -> sigma 3.33 cells: against the live catalog's own hulls (LonginusX 6x17, + // Zenith 12x12, Turret 8x8) that puts pOnHull at the hull's own centre of mass around .5-.84 -- broadly + // sprayed across the whole silhouette (sigma is a large fraction of the hull's own width) while still + // landing on the ship more often than not. A tighter floor (e.g. .1, sigma 10) was tried first and + // rejected: it drove pOnHull for the same hulls down to .08-.18, reading as "can't hit the broad side of a + // barn" rather than "sprays the silhouette." First guess, the same deliberately-bad shape as its two + // siblings; the operator rules the real figure in play. + public float UnaidedPrecision = .3f; public float AgentRangeExponent = .25f; public float AgentForwardLerp = .5f; public float AgentMaxForwardDistance = 50; diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index d9cd1bedf..d2a0b4982 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:566407075ba92e82e1e1cd3c2658656ac7710c265e1a3577d569e94feed30b44 -size 12691318 +oid sha256:1862ddc46be55e3ae574d214afd1be5aa917d3e9ff5c13d6c38d48a1652e13c1 +size 12691535 diff --git a/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs b/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs index 3f65f24d8..ad9aaa2d1 100644 --- a/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs +++ b/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs @@ -44,6 +44,11 @@ public sealed class FireAuthorityTests : IDisposable CommitHorizon = .5f, SchematicCellSize = 1f, UnaidedAccuracy = .05f, + // Cut 6d (docs/fire-control-cut.md): high enough that pOnHull saturates to 1 at this fixture's 5x5 + // hull's own centre of mass -- these tests pin the Accuracy cap and hit/miss timing, not the dart- + // throw kernel, so the unaided floor here is authored to stay out of their way, the same reason + // Spread is authored 0 in most of these fixtures to keep pSpread pinned at 1. + UnaidedPrecision = 2f, AgentMinHitProbability = 0f }; @@ -67,7 +72,13 @@ public sealed class FireAuthorityTests : IDisposable GameplaySettings settings, float damage = 10, float range = 1000, float minRange = 0, float velocity = 0, float spread = 0, float damageSpread = 0, float penetration = 0, - float accuracy = 1, float resolution = 1, float precision = 0, float tracking = 1000, + // Cut 6d (docs/fire-control-cut.md): Precision now feeds HitProbability's pOnHull for every shot, aimed + // or not (the dart-throw kernel's sigma), where it used to matter only for the coin-flip aimed-item + // branch this cut deletes. The old default of 0 -- harmless when Precision only gated that branch -- + // would now flatten pOnHull to nearly nothing against this fixture's 5x5 hull (sigma = 1/Precision + // balloons), starving every test in this file that doesn't care about aim placement. 1 keeps pOnHull + // close to its ceiling for an unaimed shot at this hull's centre of mass without pinning it exactly. + float accuracy = 1, float resolution = 1, float precision = 1, float tracking = 1000, float targetRange = 100, bool equipTargeting = true, float hullDurability = 1000, float armor = 0, Action beforeActivate = null) { @@ -430,13 +441,15 @@ public sealed class FireAuthorityTests : IDisposable Assert.True(dealt < 100f); // nowhere near the inflated 99999 value -- the original 10 landed } - // R5's payoff: with Precision 1 and p 1, only the aimed item's durability falls. - // Mutation: the roll ignores Aimed and always picks a uniform random hull cell. + // R5's payoff: with Precision authored extremely tight (Cut 6d: a sigma a tiny fraction of one cell) and + // p 1, only the aimed item's durability falls -- the dart-throw kernel still converges on a deterministic + // single-cell pick when the group is that tight, so this stays a same-cell-every-time assertion rather + // than a statistical one. Mutation: the draw ignores Aimed and always picks a uniform random hull cell. [Fact] public void AimedHitLandsOnSelectedItem() { EquippableItem aimedGear = null; - var e = Build(TestSettings(), damage: 50, velocity: 0, accuracy: 1, resolution: 1, spread: 0, precision: 1, armor: 0, + var e = Build(TestSettings(), damage: 50, velocity: 0, accuracy: 1, resolution: 1, spread: 0, precision: 1000, armor: 0, beforeActivate: (items, shooter, target) => { // A second, distinct interior item on the target to aim at, equipped before Activate() (Entity. @@ -509,10 +522,20 @@ public sealed class FireAuthorityTests : IDisposable // The absorb rule now exists once, in FireControl: an active shield that CanTakeHit absorbs, and the // schematic is untouched. Mutation: remove the shield branch (the hit always reaches the hull). + // + // Cut 6d (docs/fire-control-cut.md): damage raised from 10 to 50, well above the Reactor/Shield gear's own + // Durability of 10. Unaimed fire now lands via the dart-throw kernel instead of a uniform pick over the + // whole hull, and Build's own default Precision groups shots tightly enough around this fixture's small + // hull's centre of mass that the deterministic draw for this exact seed lands on one of the two equipped + // Tool items. At damage 10 that coincidentally consumed the item's own durability with zero remainder, + // which left the hull's durability unchanged with or without the shield mutation applied -- the shield + // branch could be deleted outright and this test would not have noticed. Damage well past what any single + // item on this hull could fully absorb makes the assertion mean what it says regardless of which cell the + // kernel happens to land on. [Fact] public void ShieldTakesHit() { - var e = Build(TestSettings(), damage: 10, velocity: 0, accuracy: 1, resolution: 1, spread: 0, armor: 0, + var e = Build(TestSettings(), damage: 50, velocity: 0, accuracy: 1, resolution: 1, spread: 0, armor: 0, beforeActivate: (items, shooter, target) => { // The Reactor/Shield catalog entries are authored in Build's own upsert batch (see its @@ -530,7 +553,7 @@ public sealed class FireAuthorityTests : IDisposable e.Target.Shield.Item.Enabled.Value = true; for (var i = 0; i < 20; i++) e.Zone.Update(.1f); // charge the reserve - Assert.True(e.Target.Shield.CanTakeHit(DamageType.Kinetic, 10)); + Assert.True(e.Target.Shield.CanTakeHit(DamageType.Kinetic, 50)); var beforeHull = e.Target.Hull.Durability; FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter); diff --git a/tests/Aetheria.Shared.Tests/FireControlCut4Tests.cs b/tests/Aetheria.Shared.Tests/FireControlCut4Tests.cs index cc30e415c..efb66b5f2 100644 --- a/tests/Aetheria.Shared.Tests/FireControlCut4Tests.cs +++ b/tests/Aetheria.Shared.Tests/FireControlCut4Tests.cs @@ -99,9 +99,12 @@ public sealed class FireControlCut4Tests : IDisposable { Name = "Targeting", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + // Cut 6d (docs/fire-control-cut.md): Precision now feeds pOnHull (the dart-throw kernel's sigma) + // for every shot, aimed or not -- 0 would balloon sigma and starve this fixture's rolls, which + // don't care about aim placement. See FireAuthorityTests.Build's own comment on this same change. Behaviors = { new TargetingSystemData { - Accuracy = Constant(1), Resolution = Constant(1), Precision = Constant(0), Tracking = Constant(1000) + Accuracy = Constant(1), Resolution = Constant(1), Precision = Constant(2), Tracking = Constant(1000) } } }); // Powers the beam: with no Reactor, PowerBus grants nothing and ConstantWeapon.Execute safes itself diff --git a/tests/Aetheria.Shared.Tests/FireControlCut5Tests.cs b/tests/Aetheria.Shared.Tests/FireControlCut5Tests.cs index c294b59fe..48dccca21 100644 --- a/tests/Aetheria.Shared.Tests/FireControlCut5Tests.cs +++ b/tests/Aetheria.Shared.Tests/FireControlCut5Tests.cs @@ -47,6 +47,9 @@ public sealed class FireControlCut5Tests : IDisposable SchematicCellSize = 1f, UnaidedAccuracy = .05f, UnaidedTracking = 10f, + // Cut 6d (docs/fire-control-cut.md): high enough that pOnHull saturates to 1 at this fixture's 5x5 + // hull's own centre of mass -- see FireAuthorityTests.TestSettings' own comment on this same value. + UnaidedPrecision = 2f, AgentMinHitProbability = 0f, BeamResolveInterval = .1f }; @@ -77,7 +80,10 @@ public sealed class FireControlCut5Tests : IDisposable GameplaySettings settings, float damage = 10, float range = 1000, float minRange = 0, float velocity = 0, float spread = 0, float damageSpread = 0, float penetration = 0, - float accuracy = 1, float resolution = 1, float precision = 0, float tracking = 1000, + // Cut 6d (docs/fire-control-cut.md): Precision now feeds every shot's pOnHull (the dart-throw kernel's + // sigma), aimed or not -- see FireAuthorityTests.Build's own comment on this same default change. 0 + // would balloon sigma and starve this fixture's hit tests, which don't care about aim placement. + float accuracy = 1, float resolution = 1, float precision = 1, float tracking = 1000, float targetRange = 100, bool equipTargeting = true, float hullDurability = 1000, float armor = 0, bool equipShield = false, float shieldCapacity = 1000, Action beforeActivate = null) diff --git a/tests/Aetheria.Shared.Tests/FireControlCut6Tests.cs b/tests/Aetheria.Shared.Tests/FireControlCut6Tests.cs index 1054c25a3..72421af4e 100644 --- a/tests/Aetheria.Shared.Tests/FireControlCut6Tests.cs +++ b/tests/Aetheria.Shared.Tests/FireControlCut6Tests.cs @@ -113,7 +113,10 @@ public sealed class FireControlCut6Tests : IDisposable MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, Behaviors = { new TargetingSystemData { - Accuracy = Constant(accuracy), Resolution = Constant(resolution), Precision = Constant(0), Tracking = Constant(tracking) + // Cut 6d (docs/fire-control-cut.md): Precision now feeds pOnHull (the dart-throw kernel's + // sigma) for every shot, aimed or not -- 0 would balloon sigma and starve this fixture's hit + // tests, none of which care about aim placement. See FireAuthorityTests.Build's own comment. + Accuracy = Constant(accuracy), Resolution = Constant(resolution), Precision = Constant(1), Tracking = Constant(tracking) } } }); cache.FlushAsync().Wait(); diff --git a/tests/Aetheria.Shared.Tests/FireControlCut6dTests.cs b/tests/Aetheria.Shared.Tests/FireControlCut6dTests.cs new file mode 100644 index 000000000..326e7c378 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/FireControlCut6dTests.cs @@ -0,0 +1,377 @@ +/* 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.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using UniRx; +using Xunit; +using static CultMath.math; +using float2 = CultMath.float2; +using float3 = CultMath.float3; +using int2 = CultMath.int2; +using Random = CultMath.Random; + +// Cut 6d (docs/fire-control-cut.md, "where a hit lands is a dart throw, not a coin flip"): pins the Gaussian +// kernel that replaces FireControl.Commit's coin flip -- one function, w(cell) = exp(-d^2/2*sigma^2), that +// HitProbability's pOnHull and Commit's cell draw both read. Builds its own fixtures, the same convention +// every earlier cut's test file establishes. +public sealed class FireControlCut6dTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-firecontrolcut6d-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + + public FireControlCut6dTests() => Directory.CreateDirectory(_root); + + private readonly List _openCaches = new List(); + + public void Dispose() + { + foreach (var c in _openCaches) c.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 = .1f, + TargetArmorInfoThreshold = .2f, + TargetGearInfoThreshold = .8f, + FiringArc = 170, + CommitHorizon = .5f, + SchematicCellSize = 1f, + UnaidedAccuracy = .05f, + UnaidedTracking = 10f, + UnaidedPrecision = .3f, + AgentMinHitProbability = 0f, + BeamResolveInterval = .1f + }; + + private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; + + private sealed class Engagement + { + public ItemManager Items; + public Zone Zone; + public Ship Shooter; + public Ship Target; + public EquippedItem WeaponItem; + public InstantWeapon Weapon; + public HullData HullData; + } + + // A shooter/target engagement over a caller-supplied hull shape, with a full-strength (Accuracy 1, + // Resolution huge, Tracking huge, zero weapon Spread) targeting system so HitProbability collapses to + // Accuracy * pSensor * pSpread * pOnHull = 1 * 1 * 1 * pOnHull at full info and zero deviation -- the one + // factor this cut's tests care about isolated from the other three (the same "neutralise everything but + // the term under test" convention FireControlCut6cTests.Build uses for Resolution). + // markerCell, when given, equips the catalog's bare "Marker" Tool stub at that exact interior cell on the + // target and selects it as the shooter's aim point -- done here, before Activate(), because Entity.TryEquip + // refuses once an entity is active (the same reason every earlier cut's fixture equips extra items through + // a beforeActivate hook rather than after Build returns). + private Engagement Build(GameplaySettings settings, Shape hullShape, float precision, float targetRange = 100, int2? markerCell = null) + { + var hullData = new HullData + { + Name = "Hull", HullType = HullType.Ship, Shape = hullShape, Durability = 100000, Mass = 1000, + Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } } + }; + + var cache = AetheriaStores.Open(Catalog + Guid.NewGuid().ToString("N"), catalogWritable: true); + _openCaches.Add(cache); + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + cache.Upsert(hullData); + cache.Upsert(new GearData + { + Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new InstantWeaponData + { + Damage = Constant(10), Range = Constant(1000), MinRange = Constant(0), + Velocity = Constant(0), Spread = Constant(0), DamageSpread = Constant(0), + Penetration = Constant(0), Count = Constant(1), BurstTime = Constant(0), Cooldown = Constant(1000), + DamageCurve = new BezierCurve { Keys = new[] { float4(0, 1, 0, 0), float4(1, 1, 0, 0) } } + } } + }); + cache.Upsert(new GearData + { + Name = "Targeting", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new TargetingSystemData + { + Accuracy = Constant(1f), Resolution = Constant(1000f), Precision = Constant(precision), Tracking = Constant(100000f) + } } + }); + // Durability far above anything a single shot deals: an aim point this cut's tests fire hundreds or + // thousands of rounds at must survive being hit directly for the whole run, or Cut 5.5's "a destroyed + // item drops out of the reveal ranking" rule pulls the aim out from under later shots mid-sample and + // silently corrupts the landing distribution for everything fired after that point. + cache.Upsert(new GearData + { + Name = "Marker", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1000000, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000 + }); + cache.FlushAsync().Wait(); + + var ledger = new ProvenanceLedger(); + for (var i = 1; i <= 20; i++) ledger.Lots[i] = new Lot { Origin = new Attributed(), Quality = 1 }; + var items = new ItemManager(cache, ledger, settings, _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test", Owner = null }, null); + + // Durability high enough to survive thousands of direct 10-damage hits over a test's whole sample -- + // several of this cut's tests fire that many shots to get a stable landing distribution, and an entity + // whose hull dies partway through would both stop taking further hits and bias the remaining sample. + var hullRef = items.ItemData.RefOf(items.ItemData.GetByName("Hull")); + var shooterHull = new EquippableItem { Data = hullRef, Durability = 1000000, Lot = 1 }; + var shooter = new Ship(items, zone, shooterHull, new EntitySettings()); + + var gunRef = items.ItemData.RefOf(items.ItemData.GetByName("Gun")); + var gun = new EquippableItem { Data = gunRef, Durability = 1, Lot = 2 }; + Assert.True(shooter.TryEquip(gun, new int2(0, 0))); + var weaponItem = shooter.Equipment.Single(x => x.EquippableItem == gun); + var weapon = (InstantWeapon) weaponItem.Behaviors.Single(b => b is Weapon); + + var targetingRef = items.ItemData.RefOf(items.ItemData.GetByName("Targeting")); + var targeting = new EquippableItem { Data = targetingRef, Durability = 1, Lot = 3 }; + Assert.True(shooter.TryFindSpace(targeting, out var tpos)); + Assert.True(shooter.TryEquip(targeting, tpos)); + + var targetHull = new EquippableItem { Data = hullRef, Durability = 1000000, Lot = 4 }; + var target = new Ship(items, zone, targetHull, new EntitySettings()); + var targetGunRef = items.ItemData.RefOf(items.ItemData.GetByName("Gun")); + var targetGun = new EquippableItem { Data = targetGunRef, Durability = 1, Lot = 5 }; + Assert.True(target.TryEquip(targetGun, new int2(0, 0))); + + EquippableItem marker = null; + if (markerCell != null) + { + var markerRef = items.ItemData.RefOf(items.ItemData.GetByName("Marker")); + marker = new EquippableItem { Data = markerRef, Durability = 1000000, Lot = 6 }; + Assert.True(target.TryEquip(marker, markerCell.Value)); + } + + zone.Entities.Add(shooter); + zone.Entities.Add(target); + shooter.Activate(); + target.Activate(); + + shooter.Position = float3.zero; + target.Position = float3(0, 0, targetRange); + shooter.Target.Value = target; + shooter.SetIff(target, true); + shooter.EntityInfoGathered[target] = 1f; // full reveal: pSensor = 1 + + zone.Update(0f); // warm-up: resolves weapon/targeting stats before HitProbability/Fire read them + + if (marker != null) + { + var markerItem = target.Equipment.Single(x => x.EquippableItem == marker); + Assert.True(shooter.TrySelectTargetItem(markerItem)); + Assert.Same(markerItem, shooter.ResolvedTargetItem); + } + + return new Engagement { Items = items, Zone = zone, Shooter = shooter, Target = target, WeaponItem = weaponItem, Weapon = weapon, HullData = hullData }; + } + + // Fires `count` shots and returns the resolved outcomes. Velocity 0 (the weapon fixture's own Constant(0)) + // gives every shot a zero flight time, so one small zone.Update both commits and resolves it -- no + // deviation-over-time noise to control for, matching FireControlCut6cTests' own "commits and resolves in + // this one call" convention. + private List FireMany(Engagement e, int count) + { + var outcomes = new List(); + e.Zone.ShotResolved.Subscribe(o => outcomes.Add(o)); + for (var i = 0; i < count; i++) + { + FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter); + e.Zone.Update(.01f); + } + return outcomes; + } + + // A solid 3-wide, 11-tall hull: a "Stern Marker" item sits at (1,1), near one end. y < 5.5 is the stern + // half, y >= 5.5 the bow half -- neither half is the aim point itself, so the split is a genuine + // spatial-spread question and not just "did it land on the exact aimed cell." + private static Shape SolidShape(int w, int h) + { + var shape = new Shape(w, h); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + return shape; + } + + // AimingAtTheSternHitsTheStern: with a mid-range Precision, hits aimed at a stern item land in the stern + // half far more often than the bow half. Mutation: restore the uniform-random branch. Must die -- this is + // the assertion the shipped coin flip would fail (a coin flip's "miss the item" branch is uniform over the + // whole hull, so roughly half of it lands in either half regardless of aim). + [Fact] + public void AimingAtTheSternHitsTheStern() + { + var e = Build(TestSettings(), SolidShape(3, 11), precision: .5f, markerCell: new int2(1, 1)); + + var outcomes = FireMany(e, 300); + var hits = outcomes.Where(o => o.Hit).ToList(); + Assert.True(hits.Count > 50, $"expected a healthy number of hits to measure a distribution from, got {hits.Count}"); + + var stern = hits.Count(o => o.Cell.y < 5.5f); + var sternFraction = (float) stern / hits.Count; + Assert.True(sternFraction > .8f, $"expected the large majority of hits aimed at (1,1) to land in the stern half (y<5.5), got sternFraction={sternFraction} over {hits.Count} hits"); + } + + // A 5x5 blob (x:0-4, y:0-4) plus a 3x3 "pod" (x:6-8, y:1-3) joined to it by a single-cell neck at (5,2) -- + // an appendage connected to the main mass at only one point, the schematic shape of a thin limb. The pod's + // own centre (7,2) is technically an interior cell (Shape.Shrink needs a full 8-neighbour ring, which a + // bare single isolated cell -- tried first -- can never satisfy: Tool gear can only equip to a cell fully + // enclosed by the schematic, so a true one-cell-wide extremity can never itself carry an aimable item). The + // pod supplies that ring locally while still being almost entirely surrounded by open space one ring + // further out, so the kernel still prices it far worse than the blob's own, much better-supported centre. + private static Shape BlobWithLimb(out int2 limb) + { + var shape = new Shape(9, 5); + for (var x = 0; x < 5; x++) + for (var y = 0; y < 5; y++) + shape[new int2(x, y)] = true; + shape[new int2(5, 2)] = true; // neck + for (var x = 6; x < 9; x++) + for (var y = 1; y < 4; y++) + shape[new int2(x, y)] = true; // pod + limb = new int2(7, 2); // pod centre -- the aim point + return shape; + } + + // ThinLimbCostsHitChance: HitProbability against an aim point on a single-cell extremity is strictly lower + // than against the centre of mass, at the same Precision -- and the gap widens as Precision falls (within + // the well-tuned band this campaign's catalog designs live in; both probabilities collapse toward each + // other again at the extreme where sigma dwarfs the whole hull, which is not the regime any authored + // design occupies). Mutation: drop pOnHull from the probability. Must die -- with pOnHull gone, aiming at + // the limb and aiming at the centre of mass score identically (Accuracy * pSensor * pSpread, no spatial + // term at all). + [Fact] + public void ThinLimbCostsHitChance() + { + var hullShape = BlobWithLimb(out var limb); + + float CenterProbability(float precision) + { + var e = Build(TestSettings(), hullShape, precision); + return FireControl.HitProbability(e.Weapon, e.Shooter, e.Target); // unaimed: hull's own centre of mass + } + + float LimbProbability(float precision) + { + var e = Build(TestSettings(), hullShape, precision, markerCell: limb); + return FireControl.HitProbability(e.Weapon, e.Shooter, e.Target); + } + + var gaps = new List<(float Precision, float Gap)>(); + foreach (var precision in new[] { 1.5f, 1f, .6f }) + { + var center = CenterProbability(precision); + var onLimb = LimbProbability(precision); + Assert.True(onLimb < center, $"at precision {precision}: expected aiming at the limb ({onLimb}) to score lower than the centre of mass ({center})"); + gaps.Add((precision, center - onLimb)); + } + + for (var i = 1; i < gaps.Count; i++) + Assert.True(gaps[i].Gap > gaps[i - 1].Gap, + $"expected the centre-vs-limb gap to widen as Precision falls from {gaps[i - 1].Precision} to {gaps[i].Precision}, " + + $"got {gaps[i - 1].Gap} then {gaps[i].Gap}"); + } + + // The one kernel, replicated independently here (not by calling FireControl's private helpers) from the + // spec's own formula: w(cell) = exp(-d^2 / 2*sigma^2), sigma = 1/Precision, pOnHull = sum(w) / (2*pi*sigma^2). + // Used to compute an expected value from public inputs (the hull's own Shape and the authored Precision) + // and check production against it, rather than trusting production to grade its own homework. + private static (int2[] Cells, float[] Weights, float Total) ExpectedKernel(HullData hull, float2 aim, float precision) + { + var sigma = 1f / precision; + var coords = hull.Shape.Coordinates; + var weights = new float[coords.Length]; + var total = 0f; + for (var i = 0; i < coords.Length; i++) + { + var w = MathF.Exp(-CultMath.math.lengthsq((float2) coords[i] - aim) / (2f * sigma * sigma)); + weights[i] = w; + total += w; + } + return (coords, weights, total); + } + + // PlacementAndProbabilityShareOneKernel: the empirical on-hull rate over many seeded draws matches the + // pOnHull the probability reported, within tolerance. Mutation: perturb sigma in one of the two call sites + // only. Must die -- this is the test that would catch the two functions drifting apart. + // + // Two independent checks against one independently-recomputed expectation: + // 1. HitProbability's reported number (== pOnHull exactly, every other factor neutralised to 1 by Build) + // must match the analytic pOnHull this test computes from the documented formula. A sigma perturbed + // only in HitProbability's own call to the kernel shows up here. + // 2. The empirical distribution of landing cells, over many seeded shots, must match the analytic + // per-cell weight shares this test computes from the same formula. A sigma perturbed only in Commit's + // call to the kernel (placement) leaves check 1 untouched but shows up here -- placement, not the roll, + // is what it drives. + [Fact] + public void PlacementAndProbabilityShareOneKernel() + { + var hullShape = BlobWithLimb(out var limb); + const float precision = 1f; + var e = Build(TestSettings(), hullShape, precision, markerCell: limb); + + var (cells, weights, total) = ExpectedKernel(e.HullData, limb, precision); + var expectedPOnHull = Math.Min(1f, total / (2f * MathF.PI * (1f / precision) * (1f / precision))); + + var reportedPBase = FireControl.HitProbability(e.Weapon, e.Shooter, e.Target); + Assert.Equal(expectedPOnHull, reportedPBase, 3); + + const int shots = 2500; + var outcomes = FireMany(e, shots); + var hits = outcomes.Where(o => o.Hit).ToList(); + Assert.True(hits.Count > shots * expectedPOnHull * .5f, $"expected roughly {shots * expectedPOnHull:0} hits, got {hits.Count}"); + + // Check the two heaviest cells (the limb itself, and its one blob-side neighbour) -- together they + // carry most of the kernel's mass at this sigma, so their empirical share is the most sensitive, + // least noisy signal a perturbed placement sigma would move. + var byWeightDesc = Enumerable.Range(0, cells.Length).OrderByDescending(i => weights[i]).Take(2).ToArray(); + foreach (var i in byWeightDesc) + { + var expectedFraction = weights[i] / total; + var empiricalFraction = (float) hits.Count(o => o.Cell.Equals(cells[i])) / hits.Count; + Assert.True(Math.Abs(expectedFraction - empiricalFraction) < .07f, + $"cell {cells[i]}: expected fraction {expectedFraction:0.0000}, empirical {empiricalFraction:0.0000} over {hits.Count} hits"); + } + } + + // A 7x7 hull with a hole at its own centre (3,3) -- the bounding box has 49 cells, the schematic only 48. + // The aim point (1,1) is chosen far enough from the hole that it is still a valid interior cell (Shrink + // excludes not just the border but every cell touching the hole itself, which rules out the whole 3x3 + // block around it). EveryHitLandsOnMetal: no committed hit ever resolves to an unoccupied cell, across + // seeds and aim points including extremities. Mutation: draw from the hull's full bounding box + // (Shape.AllCoordinates) instead of its occupied cells (Shape.Coordinates) -- with a real hole to fall + // into, that mutant lands on the missing centre cell often enough over many draws to be caught, where a + // solid rectangle never would be. + [Fact] + public void EveryHitLandsOnMetal() + { + var shape = new Shape(7, 7); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + shape[new int2(3, 3)] = false; // the hole + + var aimPoint = new int2(1, 1); + // .Loose grouping (low Precision -> wide sigma): plenty of mass would spill toward the hole. + var e = Build(TestSettings(), shape, precision: .3f, markerCell: aimPoint); + + // 2000 shots at pOnHull ~.38 (~760 expected hits): the bounding-box-instead-of-Coordinates mutation + // would expect ~15 of those to land on the missing (3,3) specifically (1/49 uniform chance per hit), + // reliably enough to die even though the correct kernel puts exactly zero weight there. + var outcomes = FireMany(e, 2000); + var hits = outcomes.Where(o => o.Hit).ToList(); + Assert.True(hits.Count > 100, $"expected a healthy number of hits to check, got {hits.Count}"); + + foreach (var outcome in hits) + Assert.True(shape[outcome.Cell], $"hit landed on {outcome.Cell}, which is not part of the hull's own schematic"); + } +} diff --git a/tests/Aetheria.Shared.Tests/TargetingSystemTests.cs b/tests/Aetheria.Shared.Tests/TargetingSystemTests.cs index d3a436340..478bc93c2 100644 --- a/tests/Aetheria.Shared.Tests/TargetingSystemTests.cs +++ b/tests/Aetheria.Shared.Tests/TargetingSystemTests.cs @@ -264,7 +264,11 @@ public sealed class TargetingSystemTests : IDisposable // handle stays open per test -- BuildTarget is not called twice). var bareShip = BuildObserver(items, target.Zone); Assert.Equal(settings.UnaidedAccuracy, FireControl.Accuracy(bareShip), 4); - Assert.Equal(0f, FireControl.Precision(bareShip), 4); + // Cut 6d (docs/fire-control-cut.md): Precision now falls back to UnaidedPrecision, the same shape as + // Accuracy/Tracking above -- it used to fall back to a bare 0, which was fine when Precision only fed + // the old coin-flip's aimed-item branch and meant nothing to a shot with no aim point. Now it derives + // every shot's sigma, aimed or not, so the unaided floor has to be an authored number, not a bare zero. + Assert.Equal(settings.UnaidedPrecision, FireControl.Precision(bareShip), 4); Assert.Equal(1f, FireControl.Resolution(bareShip), 4); // Bring it online to prove the fixture can actually supply its own stats... @@ -278,7 +282,7 @@ public sealed class TargetingSystemTests : IDisposable equippedTargeting.UpdatePerformance(); Assert.False(equippedTargeting.Active.Value); Assert.Equal(settings.UnaidedAccuracy, FireControl.Accuracy(target), 4); - Assert.Equal(0f, FireControl.Precision(target), 4); + Assert.Equal(settings.UnaidedPrecision, FireControl.Precision(target), 4); Assert.Equal(1f, FireControl.Resolution(target), 4); // Repair it, then disable it directly instead: same fallback. @@ -288,7 +292,7 @@ public sealed class TargetingSystemTests : IDisposable equippedTargeting.Enabled.Value = false; Assert.False(equippedTargeting.Active.Value); Assert.Equal(settings.UnaidedAccuracy, FireControl.Accuracy(target), 4); - Assert.Equal(0f, FireControl.Precision(target), 4); + Assert.Equal(settings.UnaidedPrecision, FireControl.Precision(target), 4); } // The brownout ruling (docs/stats-and-power-cut.md) applies to Accuracy same as any other stat: a diff --git a/tests/mutation_tests_fire_control_cut3.sh b/tests/mutation_tests_fire_control_cut3.sh index b47255d12..edd97eb24 100644 --- a/tests/mutation_tests_fire_control_cut3.sh +++ b/tests/mutation_tests_fire_control_cut3.sh @@ -3,22 +3,20 @@ # # Fourteen check_mutation calls covering the cut's own thirteen declared tests (one, ProbabilityFollowsInputs, # carries three sub-mutations from its own declared list, so fifteen mutations run in total) against -# tests/Aetheria.Shared.Tests/FireAuthorityTests.cs -- plus one test the harness deliberately does NOT attempt -# a mutation for, documented below rather than silently skipped: +# tests/Aetheria.Shared.Tests/FireAuthorityTests.cs, plus one more against the test Cut 7 rewrote in its place: # -# OutOfArcConsumesNoDraw -- NOT YET REACHED. The test asserts against ItemManager.Random (`e.Items.Random`), -# but Cut 6b (6.1) moved every shot's roll onto its own freshly-seeded, immediately-discarded +# OutOfArcConsumesNoDraw no longer exists. It asserted against ItemManager.Random (`e.Items.Random`), but +# Cut 6b (6.1) moved every shot's roll onto its own freshly-seeded, immediately-discarded # `new Random((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u)` local to Commit -- a deliberate, -# good change (reproducibility independent of unrelated draws elsewhere) that also means Commit never reads -# or writes ItemManager.Random at all, on any path, arc or no arc. Confirmed empirically: applying the -# declared mutation ("roll first and multiply by zero" -- `var hit = random.NextFloat() < p;` in place of -# `var hit = p > 0f && random.NextFloat() < p;`) leaves this test green, because the local generator that -# mutation actually touches is discarded before anything outside Commit could observe it, and nothing else -# in the Fire/Step path ever touches ItemManager.Random (Zone.NextShotId is a plain counter). This is not a -# fixable fixture defect -- there is no external observation point for "did Commit's own local generator -# draw" under the current per-shot-seeded design, short of instrumenting FireControl itself (an injectable -# call-counting random source, or reverting 6.1's shared-stream removal) -- a production-code seam change, -# not a test change, and out of this cut's scope. Reaching it takes that seam. +# good change (reproducibility independent of unrelated draws elsewhere) that also meant Commit stopped +# reading or writing ItemManager.Random on any path, arc or no arc, which made the old test's own declared +# mutation ("roll first and multiply by zero") pass for a reason that had nothing to do with arcs. Cut 7 +# (fire-control-cut.md, 7.2's own header comment, and FireAuthorityTests.cs's comment on the replacement) +# rewrote it as CombatNeverDrawsFromTheSharedStream: no combat path draws from the shared stream, in arc or +# out. That rule IS externally observable (Commit has no reference to ItemManager to draw from at all under +# the current design, so the only way to make it "touch the shared stream" is to add a read that was not +# there before) -- this harness's own mutation below does exactly that, through the one handle Commit does +# hold (`shot.Source.ItemManager`, already read elsewhere in this same function for hull data). # # A no-op control (a byte-identical rewrite of one target file through this script's own read/write path) # proves the mechanism itself is transparent before any real mutation is trusted. Modelled on @@ -205,11 +203,14 @@ check_mutation \ "red" # --- ProbabilityFollowsInputs, variant 1/3: drop pSensor -- probability stops depending on detection info. --- +# Cut 6d (docs/fire-control-cut.md) added a fourth factor, pOnHull, to this same return line -- the anchor +# below tracks the current line so this still targets the pSensor drop specifically, not a byte-exact copy of +# the pre-Cut-6d line, which no longer exists. check_mutation \ "ProbabilityFollowsInputs (1/3): HitProbability must scale with pSensor, not drop it" \ "$FIRE_CONTROL_CS" \ - 'return Accuracy(source) * pSensor * pSpread;' \ - 'return Accuracy(source) * pSpread;' \ + 'return Accuracy(source) * pSensor * pSpread * pOnHull;' \ + 'return Accuracy(source) * pSpread * pOnHull;' \ "FireAuthorityTests.ProbabilityFollowsInputs" \ "red" @@ -296,13 +297,17 @@ check_mutation \ "FireAuthorityTests.OutcomeIsSnapshotNotReread" \ "red" -# --- AimedHitLandsOnSelectedItem (R5's payoff): with Precision 1, a hit must land on the aimed item's own -# cells, not a uniform-random hull cell. --- +# --- AimedHitLandsOnSelectedItem (R5's payoff): with Precision authored extremely tight (Cut 6d: the test now +# passes precision: 1000, a sigma a tiny fraction of one cell), a hit must land on the aimed item's own cell, +# not the hull's centre of mass. Cut 6d deleted the coin-flip branch this mutation used to sabotage +# (`random.NextFloat() < shot.Precision` picking between the aimed cell and a uniform-random one); the +# equivalent sabotage under the dart-throw kernel is feeding Commit's aim-point resolver a null Aimed, so it +# falls back to the centre-of-mass path unconditionally -- the same "aim is ignored" defect, on the new code. --- check_mutation \ - "AimedHitLandsOnSelectedItem: the roll must respect Aimed, not always pick a uniform random hull cell" \ + "AimedHitLandsOnSelectedItem: the kernel's aim point must respect Aimed, not fall back to centre of mass" \ "$FIRE_CONTROL_CS" \ - 'if (aimedCells != null && aimedCells.Length > 0 && random.NextFloat() < shot.Precision)' \ - 'if (false)' \ + 'var (aimPoint, aimedCells) = ResolveAimPoint(shot.Target, hullData, shot.Aimed);' \ + 'var (aimPoint, aimedCells) = ResolveAimPoint(shot.Target, hullData, null);' \ "FireAuthorityTests.AimedHitLandsOnSelectedItem" \ "red" @@ -336,14 +341,17 @@ check_mutation \ "FireAuthorityTests.ShieldTakesHit" \ "red" -echo "" -echo "=== OutOfArcConsumesNoDraw: NOT YET REACHED (see header comment) -- confirming the test itself is still green with no mutation applied ===" -if run_test "FireAuthorityTests.OutOfArcConsumesNoDraw"; then - echo "OK: FireAuthorityTests.OutOfArcConsumesNoDraw passes on the unmutated tree" -else - FAILURES+=("OutOfArcConsumesNoDraw: the unmutated test itself failed -- that is a real regression, not a not-yet-reached mutation") - echo "$LAST_OUTPUT" | tail -40 -fi +# --- Cut 7's replacement for OutOfArcConsumesNoDraw: CombatNeverDrawsFromTheSharedStream. Mutation: Commit +# reads shot.Source.ItemManager.Random (the shared stream FireAuthorityTests.cs's own Build exposes as +# e.Items.Random) once per call, restoring exactly the kind of shared-stream touch Cut 6b (6.1) removed -- +# unconditionally, so both the theory's in-arc and out-of-arc cases go red. --- +check_mutation \ + "CombatNeverDrawsFromTheSharedStream: Commit must never read ItemManager's shared stream, on any path" \ + "$FIRE_CONTROL_CS" \ + 'var random = new Random((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u);' \ + 'var random = new Random((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u); shot.Source.ItemManager.Random.NextFloat();' \ + "FireAuthorityTests.CombatNeverDrawsFromTheSharedStream" \ + "red" echo "" verify_tree_clean @@ -362,5 +370,5 @@ if [ "${#FAILURES[@]}" -gt 0 ] || [ "$TREE_CLEAN_OK" != "1" ]; then exit 1 fi -echo "RESULT: All attempted mutations behaved as declared (OutOfArcConsumesNoDraw: not yet reached, see header). tree-clean: PASS" +echo "RESULT: All mutations behaved as declared. tree-clean: PASS" exit 0 diff --git a/tests/mutation_tests_fire_control_cut6d.sh b/tests/mutation_tests_fire_control_cut6d.sh new file mode 100644 index 000000000..0f843983a --- /dev/null +++ b/tests/mutation_tests_fire_control_cut6d.sh @@ -0,0 +1,278 @@ +#!/usr/bin/env bash +# Mutation tests for docs/fire-control-cut.md's Cut 6d ("where a hit lands is a dart throw, not a coin flip"). +# +# Four mutations, each from the spec's own Verification block, against +# tests/Aetheria.Shared.Tests/FireControlCut6dTests.cs: +# +# 1. AimingAtTheSternHitsTheStern -- restore the uniform-random branch (ignore the kernel's weights when +# drawing a landing cell). +# 2. ThinLimbCostsHitChance -- drop pOnHull from HitProbability's return. +# 3. PlacementAndProbabilityShareOneKernel -- perturb sigma in one of the kernel's two call sites only +# (HitProbability's, leaving Commit's placement call untouched). +# 4. EveryHitLandsOnMetal -- draw the kernel's weights over the hull's full bounding box +# (Shape.AllCoordinates) instead of its occupied cells (Shape.Coordinates). Not named in the spec's own +# Verification block, but declared in this cut's own test file as the mutation that invariant is pinned +# against, so it is included here rather than left unrun. +# +# A no-op control (a byte-identical rewrite of the target file through this script's own read/write path) +# proves the mechanism itself is transparent before any real mutation is trusted. +# +# Usage: +# tests/mutation_tests_fire_control_cut6d.sh +# +# Every mutation is reversed (byte-exact, from an on-disk copy) before the script exits, including on failure +# or interrupt, and every restore is verified against a sha256 recorded before any mutation ran: the tree- +# clean verdict at the end states PASS/FAIL explicitly rather than leaving a reader to infer it. A SIGKILL of +# the whole process group is the one termination bash cannot trap at all -- verify the tree independently +# after a run that was killed that hard. +# +# Run only one mutation harness at a time against this tree -- concurrent harnesses corrupt each other's +# snapshots (docs/fire-control-cut.md's own campaign has hit this). + +set -u + +if [ $# -lt 1 ]; then + echo "Usage: $0 " >&2 + exit 2 +fi +CULTLIB_ROOT="$1" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +TEST_PROJECT="$REPO_ROOT/tests/Aetheria.Shared.Tests" + +FIRE_CONTROL_CS="$REPO_ROOT/Assets/Scripts/ServerShared/FireControl.cs" + +# --- byte-exact backup/restore: preserves line endings exactly, no text-mode translation. --- +declare -A ORIGINALS +declare -A ORIGINAL_HASH +FILES=("$FIRE_CONTROL_CS") +BACKUP_DIR="$(mktemp -d)" + +hash_file() { + sha256sum "$1" 2>/dev/null | awk '{print $1}' +} + +for f in "${FILES[@]}"; do + base="$(basename "$f")" + cp -p "$f" "$BACKUP_DIR/$base.orig" + ORIGINALS["$f"]="$BACKUP_DIR/$base.orig" + ORIGINAL_HASH["$f"]="$(hash_file "$f")" +done + +# restore_and_verify FILE -- restores one file from its recorded backup, then re-hashes it and aborts the +# whole script (not just this mutation) if the restore did not reproduce the pre-mutation hash exactly. A +# mismatch here means continuing would judge every later mutation against an already-contaminated baseline, +# which is strictly worse than stopping. +restore_and_verify() { + local file="$1" + cp -p "${ORIGINALS[$file]}" "$file" + local actual + actual="$(hash_file "$file")" + if [ "$actual" != "${ORIGINAL_HASH[$file]}" ]; then + echo "" >&2 + echo "FATAL: restoring $file did not reproduce its pre-mutation hash -- aborting." >&2 + echo " expected sha256: ${ORIGINAL_HASH[$file]}" >&2 + echo " actual sha256: $actual" >&2 + exit 1 + fi +} + +TREE_CLEAN_OK=1 +TREE_VERDICT_DONE=0 + +# verify_tree_clean -- re-hashes every target file against its pre-mutation baseline and prints an explicit +# PASS/FAIL verdict. Called once explicitly at the bottom of a normal run (so the verdict is part of that +# run's own summary, not something a reader has to infer from silence) and again from the EXIT/INT/TERM trap +# as the safety net for every abnormal exit -- interrupted, failed, or killed in a way bash can still trap. +# (A SIGKILL of the whole process group is the one termination this cannot see at all; nothing running inside +# the killed process can run afterward, trap or not -- that gap is closed by re-checking independently after +# the fact, not by this function.) +verify_tree_clean() { + if [ "$TREE_VERDICT_DONE" = "1" ]; then return; fi + local f actual + for f in "${FILES[@]}"; do + cp -p "${ORIGINALS[$f]}" "$f" 2>/dev/null + actual="$(hash_file "$f")" + if [ "$actual" != "${ORIGINAL_HASH[$f]}" ]; then + echo "FATAL: $f is NOT byte-identical to how this script found it." >&2 + echo " expected sha256: ${ORIGINAL_HASH[$f]}" >&2 + echo " actual sha256: $actual" >&2 + TREE_CLEAN_OK=0 + fi + done + echo "" + if [ "$TREE_CLEAN_OK" = "1" ]; then + echo "=== tree-clean verdict: PASS -- every target file is byte-identical to how this script found it ===" + else + echo "=== tree-clean verdict: FAIL -- see FATAL lines above; the working tree is contaminated ===" + fi + TREE_VERDICT_DONE=1 +} +trap verify_tree_clean EXIT INT TERM + +FAILURES=() + +# replace_unique FILE ANCHOR REPLACEMENT +# Anchor must occur exactly once (byte-exact match via awk/perl, not sed's line-oriented rewriting, so a +# multi-line anchor is matched as literal text). Writes the mutated content back byte-exact. +replace_unique() { + local file="$1" anchor="$2" replacement="$3" + local count + count=$(perl -0777 -e ' + my ($anchor, $file) = @ARGV; + local $/; open(my $fh, "<:raw", $file) or die $!; + my $text = <$fh>; close $fh; + my $n = () = $text =~ /\Q$anchor\E/g; + print $n; + ' "$anchor" "$file") + if [ "$count" != "1" ]; then + echo "ERROR: $file: anchor must occur exactly once, found $count" >&2 + echo "--- anchor ---" >&2 + echo "$anchor" >&2 + return 1 + fi + # No -i: on this filesystem perl's in-place-edit extension parsing has mangled a literal ":raw" suffix + # into stray sibling files before. Read, substitute once, write back byte-exact instead. + perl -0777 -e ' + my ($file, $anchor, $replacement) = @ARGV; + local $/; open(my $fh, "<:raw", $file) or die $!; + my $text = <$fh>; close $fh; + my $qa = quotemeta($anchor); + $text =~ s/$qa/$replacement/; + open(my $out, ">:raw", $file) or die $!; + print $out $text; close $out; + ' "$file" "$anchor" "$replacement" +} + +# A dedicated, isolated artifacts path -- the default tests/Aetheria.Shared.Tests/bin,obj can carry stale +# prebuilt CultLib assemblies from an unrelated earlier session's default-path build, and mixing those with a +# freshly compiled Aetheria.Shared.Tests.dll produced one observed spurious failure of a control (no-op) +# mutation elsewhere in this campaign. A private --artifacts-path sidesteps that shared, unowned build state +# entirely. +ARTIFACTS_PATH="$(mktemp -d)" + +# run_test TEST_FQN -> 0 (passed) or 1 (failed/errored) +run_test() { + local test="$1" + local out + out=$(dotnet test "$TEST_PROJECT" -p:CultLibRoot="$CULTLIB_ROOT" --artifacts-path "$ARTIFACTS_PATH" --filter "FullyQualifiedName~$test" 2>&1) + if echo "$out" | grep -q "Passed!" && ! echo "$out" | grep -q "Failed: [1-9]"; then + return 0 + fi + LAST_OUTPUT="$out" + return 1 +} + +# check_mutation NAME FILE ANCHOR MUTATED TEST EXPECT("red"|"green") +check_mutation() { + local name="$1" file="$2" anchor="$3" mutated="$4" test="$5" expect="$6" + echo "" + echo "=== $name (expect $expect) ===" + if ! replace_unique "$file" "$anchor" "$mutated"; then + FAILURES+=("$name: anchor replacement failed") + restore_and_verify "$file" + return + fi + if run_test "$test"; then + passed=1 + else + passed=0 + fi + restore_and_verify "$file" # restore this file immediately, before judging, so a crash still leaves a clean tree + + if [ "$expect" = "green" ]; then + if [ "$passed" = "1" ]; then + echo "OK: $test passed under a no-op mutation, as expected" + else + FAILURES+=("$name: expected green (test passing), got failure") + echo "$LAST_OUTPUT" | tail -40 + fi + else + if [ "$passed" = "0" ]; then + echo "OK: $test went red under the mutation, as expected" + else + FAILURES+=("$name: expected red (mutant killed), but $test still passed") + fi + fi +} + +# --- No-op control: a byte-identical round trip through this script's own replace_unique path, proving the +# anchor/replace/restore mechanism is transparent before any real mutation is trusted. --- +check_mutation \ + "control (no-op round trip)" \ + "$FIRE_CONTROL_CS" \ + 'var sigma = Sigma(precision);' \ + 'var sigma = Sigma(precision);' \ + "FireControlCut6dTests.AimingAtTheSternHitsTheStern" \ + "green" + +# --- AimingAtTheSternHitsTheStern: restore the uniform-random branch. Mutation: Commit's weighted draw +# ignores the kernel's own weights and picks uniformly over the hull's occupied cells instead -- the shipped +# coin flip's "miss the aimed item" behaviour, which spreads evenly over the whole hull regardless of aim. --- +check_mutation \ + "AimingAtTheSternHitsTheStern: Commit must draw from the kernel's weights, not uniformly" \ + "$FIRE_CONTROL_CS" \ + 'cell = WeightedPick(cells, weights, totalWeight, random);' \ + 'cell = cells[random.NextInt(cells.Length)];' \ + "FireControlCut6dTests.AimingAtTheSternHitsTheStern" \ + "red" + +# --- ThinLimbCostsHitChance: drop pOnHull from the probability. Mutation: HitProbability's return loses its +# fourth factor -- aiming at a thin limb and aiming at the centre of mass then score identically, since +# nothing left in the product carries a spatial term at all. --- +check_mutation \ + "ThinLimbCostsHitChance: HitProbability must carry pOnHull, not drop it" \ + "$FIRE_CONTROL_CS" \ + 'return Accuracy(source) * pSensor * pSpread * pOnHull;' \ + 'return Accuracy(source) * pSensor * pSpread;' \ + "FireControlCut6dTests.ThinLimbCostsHitChance" \ + "red" + +# --- PlacementAndProbabilityShareOneKernel: perturb sigma in one of the two call sites only. Mutation: +# HitProbability's own call into the kernel reads a Precision inflated by 1.5x, while Commit's placement call +# (WeightedPick's own kernel read, a few hundred lines below) is untouched -- the two functions answering +# "where will this shot go" now disagree, which is exactly the named risk this cut's own comments call out +# One kernel, computed by one function" no longer holds once a caller perturbs its own input. --- +check_mutation \ + "PlacementAndProbabilityShareOneKernel: HitProbability and Commit must read the same Precision into the kernel" \ + "$FIRE_CONTROL_CS" \ + 'var pOnHull = HullKernel(targetHull, ResolveAimPoint(target, targetHull, source.ResolvedTargetItem).AimPoint, Precision(source)).POnHull;' \ + 'var pOnHull = HullKernel(targetHull, ResolveAimPoint(target, targetHull, source.ResolvedTargetItem).AimPoint, Precision(source) * 1.5f).POnHull;' \ + "FireControlCut6dTests.PlacementAndProbabilityShareOneKernel" \ + "red" + +# --- EveryHitLandsOnMetal: draw the kernel's weights over the hull's full bounding box instead of its +# occupied cells. Mutation: HullKernel reads Shape.AllCoordinates (every grid cell in the bounding box, +# occupied or not) instead of Shape.Coordinates (only the cells actually part of the schematic) -- a hull with +# a hole in it can then have a hit resolve onto the hole. Not one of the spec's own four named mutations, but +# the one this cut's own test file declares against this invariant. --- +check_mutation \ + "EveryHitLandsOnMetal: the kernel must draw from the hull's occupied cells, not its full bounding box" \ + "$FIRE_CONTROL_CS" \ + 'var coords = hullData.Shape.Coordinates;' \ + 'var coords = hullData.Shape.AllCoordinates;' \ + "FireControlCut6dTests.EveryHitLandsOnMetal" \ + "red" + +echo "" +verify_tree_clean # explicit call: the tree-clean verdict is part of THIS run's own summary, not only + # something printed later at exit (the trap's own call is a no-op after this one runs -- + # see TREE_VERDICT_DONE above -- and remains the safety net for an interrupted run). + +if [ "${#FAILURES[@]}" -gt 0 ]; then + echo "" + echo "=== FAILURES ===" + for f in "${FAILURES[@]}"; do + echo "- $f" + done +fi + +if [ "${#FAILURES[@]}" -gt 0 ] || [ "$TREE_CLEAN_OK" != "1" ]; then + echo "" + echo "RESULT: FAILED -- mutations: $([ "${#FAILURES[@]}" -gt 0 ] && echo "${#FAILURES[@]} failure(s)" || echo "all behaved as declared"), tree-clean: $([ "$TREE_CLEAN_OK" = "1" ] && echo PASS || echo FAIL)" + exit 1 +fi + +echo "RESULT: All mutations behaved as declared. tree-clean: PASS" +exit 0 diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index f0d22306a..46aae9575 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -35,8 +35,9 @@ public static class Program case "firing-arc-migrate": return FiringArcMigrate(args.Contains("apply")); case "targeting-catalog": return TargetingCatalog(args.Contains("apply")); case "targeting-catalog-6c": return TargetingCatalog6c(args.Contains("apply")); + case "targeting-catalog-6d": return TargetingCatalog6d(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], firing-arc-migrate [apply], targeting-catalog [apply], targeting-catalog-6c [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], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply]"); return 1; } } @@ -1396,4 +1397,81 @@ public static class Program Console.WriteLine($"\nLanded {resolutionChanges.Length} Resolution changes and {newProducts.Length} new products in Aetheria.cc"); return 0; } + + // Fire control Cut 6d (docs/fire-control-cut.md, "where a hit lands is a dart throw, not a coin flip"). + // + // Precision stops being a probability (the old coin flip's "chance the hit lands exactly on the aimed + // item") and becomes a grouping tightness on FireControl.Sigma's own scale (sigma = 1/Precision, in hull- + // schematic cell units -- the same units Shape.CenterOfMass and GearOccupancy already use). The two + // designs' authored ranges (Cut 6a: 1-cell .05-.2, 2-cell .35-.55) were probabilities under the old rule + // and are meaningless as written under the new one -- re-authored here on the sigma-reciprocal scale + // instead, same convention as 6c.1's Resolution fix. + // + // Both ranges are chosen against real hull scale (GameData/Aetheria.cc's own hulls: LonginusX 6x17, + // Zenith 12x12, Turret 8x8) and the unaided floor this cut adds alongside them + // (GameplaySettings.UnaidedPrecision, .3 -> sigma 3.33 cells): a design that did not clear the unaided + // floor by a wide margin would make the required Tool item pointless to equip. + // + // 1-cell Targeting Computer: .5-.8 (sigma 2.0-1.25 cells) -- tight enough that aiming at a named subsystem + // meaningfully concentrates fire on it and its immediate neighbours, well past the unaided floor. + // 2-cell Fire Control Array: .9-1.3 (sigma 1.11-0.77 cells) -- strictly tighter than the 1-cell design at + // every point along both authored ranges, the same "premium item unambiguously ahead" shape 6c.1 restored + // for Resolution. + // + // Dry run unless passed "apply", same contract as the other *-migrate commands. + private static int TargetingCatalog6d(bool apply) + { + var db = AetherDb.Open(catalogWritable: apply); + + GearData DesignByName(string name) + { + var design = db.Cache.GetAll().FirstOrDefault(i => i.Name == name); + if (design == null) throw new InvalidOperationException($"No design named \"{name}\"."); + return design; + } + + var targetingComputer = DesignByName("Targeting Computer"); + var fireControlArray = DesignByName("Fire Control Array"); + + var precisionChanges = new (GearData Design, (float Min, float Max) Old, (float Min, float Max) New)[] + { + (targetingComputer, + (targetingComputer.Behaviors.OfType().Single().Precision.Min, + targetingComputer.Behaviors.OfType().Single().Precision.Max), + (.5f, .8f)), + (fireControlArray, + (fireControlArray.Behaviors.OfType().Single().Precision.Min, + fireControlArray.Behaviors.OfType().Single().Precision.Max), + (.9f, 1.3f)), + }; + + Console.WriteLine("Precision re-authored from a coin-flip probability to a grouping-tightness scale (Cut 6d):"); + foreach (var (design, old, @new) in precisionChanges) + Console.WriteLine($" {design.Name,-20} {old.Min,4:0.##}-{old.Max,-4:0.##} -> {@new.Min,4:0.##}-{@new.Max,-4:0.##}"); + + if (!apply) + { + Console.WriteLine($"\nDry run. Pass \"apply\" to land {precisionChanges.Length} Precision changes."); + return 0; + } + + foreach (var (design, _, @new) in precisionChanges) + { + var behavior = design.Behaviors.OfType().Single(); + var terms = behavior.Precision.Terms; + behavior.Precision = new PerformanceStat { Min = @new.Min, Max = @new.Max, Terms = terms }; + } + + // Validate before staging, same contract as ShieldMigrate/TargetingCatalog/TargetingCatalog6c above. + foreach (var (design, _, _) in precisionChanges) CultRecordRefs.Validate(design); + + db.Cache.Commit(batch => + { + foreach (var (design, _, _) in precisionChanges) + batch.Upsert(typeof(GearData), design, db.Cache.RefOf(design).Key); + }); + + Console.WriteLine($"\nLanded {precisionChanges.Length} Precision changes in Aetheria.cc"); + return 0; + } }