From 05b5a209db74e45396a32bf9ffb593cbdc614980 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 18 Sep 2026 17:18:06 +0200 Subject: [PATCH] Cut 1: terms replace the four fixed exponents; R-heat PerformanceStat's four fixed fields (HeatExponentMultiplier, DurabilityExponentMultiplier, QualityExponent, FromRole) tombstone into a declared List (source + exponent + role), walked by the one evaluation path Cut 0 unified. A stat with no terms resolves to Max (the same identity a stat with all-zero exponents already produced), so the migration is exact: a zero multiplier becomes no term, not a term with exponent 0. R-heat (operator, docs/stats-and-power-cut.md): EquippableItemData's HeatPerformanceCurve (a BezierCurve, plus the 100-sample scan that inferred OptimalTemperature and its cache) is retired in favor of an authored minimum, maximum, optimum and plateau width, with linear falloff outside the plateau. StatValidation refuses an optimum outside its bounds or a negative plateau width, loudly, at catalog load. The plateau's consequence rides along for free: Wear's thermal term is pow(ThermalPerformance, ...), and Performance() now returns exactly 1 across the plateau, so a well-managed item takes wear only from deltaTemp there -- the operational-lifespan lever the operator asked for. ConsumableItemEffect's progress-through-duration substitution for "heat" becomes its own StatSource (ConsumableProgress) rather than an unconditional override applied regardless of what a stat declares. Tests: LoadoutTests' four PerformanceStat-shaped fixtures rebuilt against Terms/authored heat fields; HeatResponseTests.cs (new) pins load validation, the plateau shape, and the three wear-lever claims (held inside takes no thermal wear, held outside does, a fast swing across still wears) each under its own mutation in tests/mutation_tests_stats_power_cut1.py (new, 10 rules including a no-op control; all pass). 64 pre-Cut-1 tests still pass unmodified; 71 total with the 7 new ones. Unity batchmode: 0 error CS. ShieldPanelCut1Verify and Cut2Verify pass; Cut3Verify fails with an unrelated pre-existing "Kernel 'KInit' not found" compute-shader error, reproduced against Cut 0's own landing state with no shader/compute file in this diff -- flagged for Soul, not fixed here. Co-Authored-By: Claude Opus 5 --- Assets/Scripts/ServerShared/AetheriaStores.cs | 4 + Assets/Scripts/ServerShared/Entity.cs | 18 +- Assets/Scripts/ServerShared/ItemData.cs | 156 ++++++++----- Assets/Scripts/ServerShared/ItemManager.cs | 8 +- .../UI/Properties Panel/PropertiesPanel.cs | 21 +- .../HeatResponseTests.cs | 181 +++++++++++++++ tests/Aetheria.Shared.Tests/LoadoutTests.cs | 80 +++---- tests/mutation_tests_stats_power_cut1.py | 218 ++++++++++++++++++ 8 files changed, 566 insertions(+), 120 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/HeatResponseTests.cs create mode 100644 tests/mutation_tests_stats_power_cut1.py diff --git a/Assets/Scripts/ServerShared/AetheriaStores.cs b/Assets/Scripts/ServerShared/AetheriaStores.cs index 0a702a7b8..99b740698 100644 --- a/Assets/Scripts/ServerShared/AetheriaStores.cs +++ b/Assets/Scripts/ServerShared/AetheriaStores.cs @@ -29,6 +29,10 @@ public static class AetheriaStores cache.AllStoredDocuments.All(stored => stored.Descriptor != descriptor)); if (missing != null) throw new InvalidOperationException($"Catalog {catalogPath} has no {missing.SchemaName} record; catalog globals are authored, never invented."); + // R-heat (docs/stats-and-power-cut.md): every equippable design's heat response must describe a + // coherent range before anything reads it. Fails loudly, naming the item. + foreach (var data in cache.GetAll()) + StatValidation.ValidateHeatResponse(data); return cache; } catch diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 12e4d420b..f83268f82 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -1183,9 +1183,15 @@ public class ConsumableItemEffect : IStatContext return float.IsNaN(result) ? stat.Min : result; } - public float HeatFactor(PerformanceStat stat) => - Data.Effectiveness.Evaluate((Data.Duration - RemainingDuration) / Data.Duration); - public float DurabilityFactor(PerformanceStat stat) => 1f; + // Cut 1 (docs/stats-and-power-cut.md): progress-through-duration is now its own StatSource + // (ConsumableProgress) rather than a hard-coded override of "heat" that applied to every stat regardless of + // its declared terms. A consumable stat that wants this must declare a ConsumableProgress term; one that + // does not gets the identity (1), same as any other context reading a term it has no source for. + public float HeatFactor(float exponent) => 1f; + public float DurabilityFactor(float exponent) => 1f; + public float ConsumableProgressFactor(float exponent) => + pow(Data.Effectiveness.Evaluate((Data.Duration - RemainingDuration) / Data.Duration), exponent); + public float PowerSupplyFactor(float exponent) => 1f; public float ScaleModifier(PerformanceStat stat) => 1f; public float ConstantModifier(PerformanceStat stat) => 0f; } @@ -1362,8 +1368,10 @@ public class EquippedItem : IStatContext return float.IsNaN(result) ? stat.Min : result; } - public float HeatFactor(PerformanceStat stat) => pow(ThermalPerformance, ThermalExponent * stat.HeatExponentMultiplier); - public float DurabilityFactor(PerformanceStat stat) => pow(DurabilityPerformance, DurabilityExponent * stat.DurabilityExponentMultiplier); + public float HeatFactor(float exponent) => pow(ThermalPerformance, ThermalExponent * exponent); + public float DurabilityFactor(float exponent) => pow(DurabilityPerformance, DurabilityExponent * exponent); + public float ConsumableProgressFactor(float exponent) => 1f; + public float PowerSupplyFactor(float exponent) => 1f; public float ScaleModifier(PerformanceStat stat) { diff --git a/Assets/Scripts/ServerShared/ItemData.cs b/Assets/Scripts/ServerShared/ItemData.cs index c21115290..1324023f7 100644 --- a/Assets/Scripts/ServerShared/ItemData.cs +++ b/Assets/Scripts/ServerShared/ItemData.cs @@ -380,8 +380,8 @@ public abstract class EquippableItemData : CraftedItemData // [InspectableField, JsonProperty("heatExponent"), Key(16), SimplePerformanceStat] // public PerformanceStat HeatExponent = new PerformanceStat(); - [InspectableAnimationCurve, JsonProperty("heatCurve"), Key(17)] - public BezierCurve HeatPerformanceCurve; + // MessagePack key 17 belonged to HeatPerformanceCurve, a BezierCurve; R-heat (docs/stats-and-power-cut.md) + // replaced the authored shape with minimum, maximum, optimum and plateau width. Do not reuse. [Inspectable, JsonProperty("resilience"), Key(18)] public float ThermalResilience = 1; @@ -400,39 +400,33 @@ public abstract class EquippableItemData : CraftedItemData [IgnoreMember] public abstract HardpointType HardpointType { get; } - - [IgnoreMember] private const int STEPS = 64; - [IgnoreMember] private float? _optimum; - - [IgnoreMember] - public float OptimalTemperature - { - get - { - if (_optimum==null) - { - var samples = Enumerable.Range(0, STEPS).Select(i => (float) i / STEPS).ToArray(); - float max = 0; - _optimum = 0; - foreach (var f in samples) - { - var p = HeatPerformanceCurve?.Evaluate(f)??0; - if (p > max) - { - max = p; - _optimum = f; - } - } - } + // R-heat (docs/stats-and-power-cut.md): the authored shape is minimum, maximum (both above), optimum and + // plateau width. Where the part likes to be, and how forgiving it is. Authored, not derived -- the 100-sample + // bezier scan that used to infer this from HeatPerformanceCurve is gone, and so is its cache. + [InspectableTemperature, JsonProperty("optimalTemperature"), Key(30)] + public float OptimalTemperature; - return (float) (MinimumTemperature + _optimum * (MaximumTemperature - MinimumTemperature)); - } - } + // The band, centered on OptimalTemperature, across which performance is 1. Plateau width is the + // operational-lifespan lever: inside it, Wear's thermal term is zero (Performance() returns exactly 1), so a + // well-managed item takes wear only from deltaTemp (Entity.cs UpdatePerformance). + [Inspectable, JsonProperty("plateauWidth"), Key(31)] + public float PlateauWidth; + // Performance is 1 across the plateau and falls linearly to 0 at each bound -- asymmetric whenever the + // optimum is off-centre, which is how most gear behaves and how negent gear inverts. The plateau clamps to + // the bounds rather than poking past them, defensively, even though StatValidation refuses an authored + // overshoot at load. public float Performance(float temperature) { - return saturate(HeatPerformanceCurve?.Evaluate(unlerp(MinimumTemperature, MaximumTemperature, temperature))??1); + if (temperature <= MinimumTemperature || temperature >= MaximumTemperature) return 0f; + var halfPlateau = PlateauWidth * 0.5f; + var plateauLow = max(MinimumTemperature, OptimalTemperature - halfPlateau); + var plateauHigh = min(MaximumTemperature, OptimalTemperature + halfPlateau); + if (temperature >= plateauLow && temperature <= plateauHigh) return 1f; + if (temperature < plateauLow) + return saturate(unlerp(MinimumTemperature, plateauLow, temperature)); + return saturate(unlerp(MaximumTemperature, plateauHigh, temperature)); } } @@ -572,19 +566,51 @@ public class HardpointData private static Dictionary _tintColors; } -// What a PerformanceStat reads to resolve one number: the lot it prices quality against, and the three -// per-context factors that used to be three separate Evaluate bodies. EquippedItem, ConsumableItemEffect and the +// What a PerformanceStat reads to resolve one number: the lot it prices quality against, and the per-context +// factors that used to be three separate Evaluate bodies. EquippedItem, ConsumableItemEffect and the // unequipped case (ItemManager's own private context) are the three implementations; each supplies only the // sources it has, and says so through what it returns rather than through a second, quietly different formula. +// Cut 1 (docs/stats-and-power-cut.md): each factor now takes the declaring term's own exponent rather than +// reading a fixed field off the stat, because the stat no longer carries one fixed field per source. public interface IStatContext { Lot Lot { get; } - float HeatFactor(PerformanceStat stat); - float DurabilityFactor(PerformanceStat stat); + float HeatFactor(float exponent); + float DurabilityFactor(float exponent); + // Progress through a consumable effect's duration, standing in for "condition" on a consumable the way heat + // does for equipped gear. Only ConsumableItemEffect has one; every other context is the identity (1). + float ConsumableProgressFactor(float exponent); + // Cut 6 (the power bus) wires this to a real brownout curve. Until then no catalog stat declares a + // PowerSupply term, and every context answers the identity so the enum member can exist now without a + // resolver to back it. + float PowerSupplyFactor(float exponent); float ScaleModifier(PerformanceStat stat); float ConstantModifier(PerformanceStat stat); } +// The declared sources a stat term can read. Closed: adding a member is a schema change with a census +// (docs/stats-and-power-cut.md ยง2). +public enum StatSource +{ + Heat, + Durability, + Quality, + PowerSupply, + ConsumableProgress +} + +// One declared dependency of a stat: a source and the exponent it is raised to inside the stat's Min/Max +// interpolation. Role is meaningful only for Quality; PerformanceStat.Evaluate refuses it elsewhere. +[MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class StatTerm +{ + [JsonProperty("source"), Key(0)] public StatSource Source; + [JsonProperty("exponent"), Key(1)] public float Exponent; + // The design role whose part quality this term reads; unset reads the item's own workmanship quality. + // Njordr states the same rule as a derivation over dimensions; this is that rule with one dimension. + [Inspectable, JsonProperty("role"), Key(2)] public string Role; +} + [MessagePackObject, JsonObject(MemberSerialization.OptIn)] public class PerformanceStat { @@ -592,20 +618,13 @@ public class PerformanceStat [JsonProperty("max"), Key(1)] public float Max; - [JsonProperty("heatExponentMultiplier"), Key(2)] - public float HeatExponentMultiplier; + // MessagePack keys 2, 3, 4 and 5 belonged to fixed exponent fields (HeatExponentMultiplier, + // DurabilityExponentMultiplier, QualityExponent, FromRole) now expressed as declared Terms below; do not + // reuse them. - [JsonProperty("durabilityExponentMultiplier"), Key(3)] - public float DurabilityExponentMultiplier; + [Inspectable, JsonProperty("terms"), Key(6)] + public List Terms = new List(); - [JsonProperty("qualityExponent"), Key(4)] - public float QualityExponent; - - // The design role whose part quality this stat reads; unset reads the item's own workmanship quality. - // Njordr states the same rule as a derivation over dimensions; this is that rule with one dimension. - [Inspectable, JsonProperty("fromRole"), Key(5)] - public string FromRole; - [IgnoreMember] private Dictionary> _scaleModifiers; [IgnoreMember] private Dictionary> _constantModifiers; @@ -633,17 +652,44 @@ public class PerformanceStat return ConstantModifiers[entity]; } - // The one evaluation path. Quality is read from the context's Lot the same way for everyone; heat, - // durability and modifiers are whatever the context has, and a context with none of those returns the - // identity for that term (1 for a multiplied factor, 0 for an added one) instead of a bespoke formula. - // Callers keep their own NaN handling: an unequipped read throws with diagnostic detail, an equipped or - // consumable read falls back to Min. That disagreement is not named as a defect, so it is not touched here. + // The one evaluation path. A stat with no terms resolves to Max (the identity factor, 1, times Min/Max + // interpolation lands on the top) -- that is the same number a stat with all-zero exponents produced before + // this cut, because pow(x, 0) == 1 regardless of x. Callers keep their own NaN handling: an unequipped read + // throws with diagnostic detail, an equipped or consumable read falls back to Min. That disagreement is not + // named as a defect, so it is not touched here. public float Evaluate(IStatContext context) { - var quality = pow(context.Lot.QualityForRole(FromRole), QualityExponent); - var durability = context.DurabilityFactor(this); - var heat = context.HeatFactor(this); - return lerp(Min, Max, quality * durability * heat) * context.ScaleModifier(this) + context.ConstantModifier(this); + var factor = 1f; + foreach (var term in Terms) + { + factor *= term.Source switch + { + StatSource.Quality => pow(context.Lot.QualityForRole(term.Role), term.Exponent), + StatSource.Heat => context.HeatFactor(term.Exponent), + StatSource.Durability => context.DurabilityFactor(term.Exponent), + StatSource.ConsumableProgress => context.ConsumableProgressFactor(term.Exponent), + StatSource.PowerSupply => context.PowerSupplyFactor(term.Exponent), + _ => throw new ArgumentOutOfRangeException(nameof(term.Source), term.Source, $"Unknown StatSource on {Min}-{Max} stat") + }; + } + return lerp(Min, Max, factor) * context.ScaleModifier(this) + context.ConstantModifier(this); + } +} + +// Cut 1's loud refusal: the heat-response shape (min, max, optimum, plateau width) must describe a coherent +// range. Runs at catalog load (AetheriaStores.Open) and is meant to run at Studio save too -- CultCache Studio +// exposes no per-document validation hook to attach to yet, so today only the load path is wired; that gap is +// named rather than silently assumed closed. +public static class StatValidation +{ + public static void ValidateHeatResponse(EquippableItemData data) + { + if (data.OptimalTemperature < data.MinimumTemperature || data.OptimalTemperature > data.MaximumTemperature) + throw new InvalidOperationException( + $"{data.Name}: OptimalTemperature {data.OptimalTemperature} lies outside its bounds " + + $"[{data.MinimumTemperature}, {data.MaximumTemperature}]"); + if (data.PlateauWidth < 0) + throw new InvalidOperationException($"{data.Name}: PlateauWidth {data.PlateauWidth} is negative"); } } diff --git a/Assets/Scripts/ServerShared/ItemManager.cs b/Assets/Scripts/ServerShared/ItemManager.cs index 38a4b015a..281228165 100644 --- a/Assets/Scripts/ServerShared/ItemManager.cs +++ b/Assets/Scripts/ServerShared/ItemManager.cs @@ -102,9 +102,11 @@ public class ItemManager pow(Lot.Quality, items.GameplaySettings.DurabilityQualityExponent)); } - public float HeatFactor(PerformanceStat stat) => 1f; - public float DurabilityFactor(PerformanceStat stat) => - pow(_item.Durability / _data.Durability, _durabilityExponent * stat.DurabilityExponentMultiplier); + public float HeatFactor(float exponent) => 1f; + public float DurabilityFactor(float exponent) => + pow(_item.Durability / _data.Durability, _durabilityExponent * exponent); + public float ConsumableProgressFactor(float exponent) => 1f; + public float PowerSupplyFactor(float exponent) => 1f; public float ScaleModifier(PerformanceStat stat) => 1f; public float ConstantModifier(PerformanceStat stat) => 0f; } diff --git a/Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs b/Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs index 06c406eb6..3e8a3c5ae 100644 --- a/Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs +++ b/Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs @@ -479,14 +479,11 @@ public class PropertiesPanel : MonoBehaviour statusSheet.AddStat("Durability", () => "Item Destroyed!"); else statusSheet.AddStat("Durability", () => $"{(int)(item.EquippableItem.Durability / gearData.Durability * 100)}%"); statusSheet.AddStat("Temperature", () => ActionGameManager.PlayerSettings.FormatTemperature(item.Temperature)); - - var heatCurve = AddCurveField(); - heatCurve.Show( - "Thermal Performance", - gearData.HeatPerformanceCurve, - t => ActionGameManager.PlayerSettings.FormatTemperature(lerp(gearData.MinimumTemperature, gearData.MaximumTemperature, t)), - true); - RefreshPropertyValues += () => heatCurve.SetCurrent(unlerp(gearData.MinimumTemperature, gearData.MaximumTemperature, item.Temperature)); + // R-heat (docs/stats-and-power-cut.md): the authored shape is min/max/optimum/plateau width, not a + // curve, so the thermal performance panel reads those directly rather than sampling a BezierCurve. + // Cut 8 owns the real UI reconciliation pass; this keeps the panel legible and compiling in the interim. + statusSheet.AddStat("Optimal Temp", () => ActionGameManager.PlayerSettings.FormatTemperature(gearData.OptimalTemperature)); + statusSheet.AddStat("Thermal Performance", () => $"{(int)(gearData.Performance(item.Temperature) * 100)}%"); AddEquippableItemProperties(item.EquippableItem, item.Evaluate); AddSpacer(); @@ -520,12 +517,8 @@ public class PropertiesPanel : MonoBehaviour var gearData = GameManager.ItemManager.GetData(gear); var statusSheet = AddStatSheet(); statusSheet.AddStat("Durability", () => $"{(int)(gear.Durability / gearData.Durability * 100)}%"); - var heatCurve = AddCurveField(); - heatCurve.Show( - "Thermal Performance", - gearData.HeatPerformanceCurve, - t => ActionGameManager.PlayerSettings.FormatTemperature(lerp(gearData.MinimumTemperature, gearData.MaximumTemperature, t)), - true); + // R-heat: see the equipped Inspect() overload above for why this is stats, not a curve field. + statusSheet.AddStat("Optimal Temp", () => ActionGameManager.PlayerSettings.FormatTemperature(gearData.OptimalTemperature)); AddEquippableItemProperties(gear, stat => GameManager.ItemManager.Evaluate(stat, gear)); } diff --git a/tests/Aetheria.Shared.Tests/HeatResponseTests.cs b/tests/Aetheria.Shared.Tests/HeatResponseTests.cs new file mode 100644 index 000000000..219156c99 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/HeatResponseTests.cs @@ -0,0 +1,181 @@ +using System; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; + +// Cut 1 (docs/stats-and-power-cut.md), R-heat: the authored heat-response shape (minimum, maximum, optimum, +// plateau width), its load-time validation, and the wear-lever consequence (the plateau is where Wear's thermal +// term goes to zero). Each rule here has a matching mutation in tests/mutation_tests_stats_power_cut1.py. +public sealed class HeatResponseTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-heatresponse-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + private static readonly int2 HardpointCell = new int2(0, 0); + + public HeatResponseTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + private GameplaySettings Settings() => new GameplaySettings + { + DefaultEntitySettings = new EntitySettings(), + Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } }, + QualityPriceModifier = new ExponentialLerp() + }; + + // A hull plus one thermal gear design, equipped and settled at the given start temperature (two + // UpdatePerformance calls so deltaTemp reads 0 before the test drives its own change). + private EquippedItem BuildEquippedAt(CultCache cache, ItemManager items, float startTemperature, out Ship ship) + { + var maker = cache.RefOf(cache.GetByName("Maker")); + var hullData = cache.GetByName("Skiff"); + var thermalData = cache.GetByName("Thermal"); + var hullItem = (EquippableItem) items.CreateInstance(items.CreateLot(hullData, maker, .5f)); + ship = new Ship(items, null, hullItem, new EntitySettings()); + var gearItem = (EquippableItem) items.CreateInstance(items.CreateLot(thermalData, maker, .5f)); + Assert.True(ship.TryEquip(gearItem, HardpointCell)); + var equipped = ship.Equipment.Single(e => e.Data is GearData); + foreach (var cell in equipped.InsetShape.Coordinates) ship.Temperature[cell.x, cell.y] = startTemperature; + equipped.UpdatePerformance(); + equipped.UpdatePerformance(); // settle: oldTemperature now equals startTemperature, deltaTemp reads 0 + return equipped; + } + + private void SetTemperature(EquippedItem equipped, Ship ship, float temperature) + { + foreach (var cell in equipped.InsetShape.Coordinates) ship.Temperature[cell.x, cell.y] = temperature; + } + + private CultCache OpenCatalogWithThermalGear() + { + var cache = AetheriaStores.Open(Catalog, catalogWritable: true); + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + cache.Upsert(new Faction { Name = "Maker", ShortName = "MKR" }); + var hullShape = new Shape(3, 3); + foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true; + cache.Upsert(new HullData + { + Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Price = 100, + Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = HardpointCell, Shape = new Shape() } } + }); + // Plateau 40-60 of a 0-100 range: full performance across it, linear falloff to the bounds outside it. + cache.Upsert(new GearData + { + Name = "Thermal", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10, + Durability = 100, MinimumTemperature = 0, MaximumTemperature = 100, + OptimalTemperature = 50, PlateauWidth = 20 + }); + cache.FlushAsync().Wait(); + return cache; + } + + // --- R-heat shape: Performance() is 1 across the plateau and falls linearly to 0 at the bounds --- + + [Fact] + public void PerformanceIsFullAcrossThePlateau() + { + using var cache = OpenCatalogWithThermalGear(); + var data = cache.GetByName("Thermal"); + Assert.Equal(1f, data.Performance(40), 5); + Assert.Equal(1f, data.Performance(50), 5); + Assert.Equal(1f, data.Performance(60), 5); + } + + [Fact] + public void PerformanceFallsLinearlyOutsideThePlateau() + { + using var cache = OpenCatalogWithThermalGear(); + var data = cache.GetByName("Thermal"); + // Halfway from the plateau's low edge (40) down to the minimum (0) -> halfway performance. + Assert.Equal(.5f, data.Performance(20), 5); + Assert.Equal(0f, data.Performance(0), 5); + Assert.Equal(0f, data.Performance(100), 5); + } + + // --- Validation: fails loudly at catalog load, naming the item --- + + [Fact] + public void LoadRefusesAnOptimumOutsideItsBounds() + { + var root = Path.Combine(Path.GetTempPath(), "aetheria-heatresponse-invalid-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var catalog = Path.Combine(root, "Aetheria.cc"); + using (var cache = AetheriaStores.Open(catalog, catalogWritable: true)) + { + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + cache.Upsert(new GearData + { + Name = "BadOptimum", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 1, + MinimumTemperature = 0, MaximumTemperature = 100, OptimalTemperature = 150, PlateauWidth = 0 + }); + cache.FlushAsync().Wait(); + } + var ex = Assert.Throws(() => AetheriaStores.Open(catalog)); + Assert.Contains("BadOptimum", ex.Message); + } + finally { Directory.Delete(root, true); } + } + + [Fact] + public void LoadRefusesANegativePlateauWidth() + { + var root = Path.Combine(Path.GetTempPath(), "aetheria-heatresponse-invalid-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var catalog = Path.Combine(root, "Aetheria.cc"); + using (var cache = AetheriaStores.Open(catalog, catalogWritable: true)) + { + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + cache.Upsert(new GearData + { + Name = "BadPlateau", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 1, + MinimumTemperature = 0, MaximumTemperature = 100, OptimalTemperature = 50, PlateauWidth = -1 + }); + cache.FlushAsync().Wait(); + } + var ex = Assert.Throws(() => AetheriaStores.Open(catalog)); + Assert.Contains("BadPlateau", ex.Message); + } + finally { Directory.Delete(root, true); } + } + + // --- The wear lever (Entity.cs UpdatePerformance): inside the plateau the thermal term is zero --- + + [Fact] + public void HeldInsidePlateauTakesNoThermalWear() + { + using var cache = OpenCatalogWithThermalGear(); + var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); + var equipped = BuildEquippedAt(cache, items, 50f, out var ship); + Assert.Equal(1f, equipped.ThermalPerformance, 5); + Assert.Equal(0f, equipped.Wear, 5); // no thermal term (Performance == 1) and no deltaTemp (settled) + } + + [Fact] + public void HeldOutsidePlateauTakesThermalWear() + { + using var cache = OpenCatalogWithThermalGear(); + var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); + var equipped = BuildEquippedAt(cache, items, 10f, out var ship); // outside 40-60, inside 0-100 + Assert.True(equipped.ThermalPerformance < 1f); + Assert.True(equipped.Wear > 0f); + } + + [Fact] + public void AFastSwingAcrossThePlateauStillWears() + { + using var cache = OpenCatalogWithThermalGear(); + var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); + var equipped = BuildEquippedAt(cache, items, 10f, out var ship); + // Jump straight into the plateau in one tick: ThermalPerformance ends at 1 (no thermal term), but the + // swing itself (deltaTemp) still costs. + SetTemperature(equipped, ship, 50f); + equipped.UpdatePerformance(); + Assert.Equal(1f, equipped.ThermalPerformance, 5); + Assert.True(equipped.Wear > 0f); + } +} diff --git a/tests/Aetheria.Shared.Tests/LoadoutTests.cs b/tests/Aetheria.Shared.Tests/LoadoutTests.cs index cd6f246be..d2ed39e82 100644 --- a/tests/Aetheria.Shared.Tests/LoadoutTests.cs +++ b/tests/Aetheria.Shared.Tests/LoadoutTests.cs @@ -519,8 +519,8 @@ public sealed class LoadoutTests : IDisposable var instance = (EquippableItem) items.CreateInstance(commonLot); var rareInstance = (EquippableItem) items.CreateInstance(rareLot); - var withRole = new PerformanceStat { FromRole = "lens", Min = 0, Max = 1, QualityExponent = 1 }; - var noRole = new PerformanceStat { Min = 0, Max = 1, QualityExponent = 1 }; + var withRole = new PerformanceStat { Min = 0, Max = 1, Terms = { new StatTerm { Source = StatSource.Quality, Exponent = 1, Role = "lens" } } }; + var noRole = new PerformanceStat { Min = 0, Max = 1, Terms = { new StatTerm { Source = StatSource.Quality, Exponent = 1 } } }; Assert.Equal(.9f, items.Evaluate(withRole, instance), 3); Assert.Equal(.2f, items.Evaluate(noRole, instance), 3); Assert.Equal(.2f, items.GetTier(instance).tier.Quality, 3); @@ -549,8 +549,8 @@ public sealed class LoadoutTests : IDisposable } // F4: the durability exponent path in ItemManager.Evaluate reads the lot's quality (GameplaySettings. - // DurabilityQuality{Min,Max,Exponent}), independently of the quality-for-role term (zeroed here via - // QualityExponent 0). + // DurabilityQuality{Min,Max,Exponent}), independently of the quality-for-role term (absent here -- the + // stat declares only a Durability term). [Fact] public void EvaluateDurabilityExponentReadsLotQuality() { @@ -566,7 +566,7 @@ public sealed class LoadoutTests : IDisposable low.Durability = items.GetData(low).Durability / 2; high.Durability = items.GetData(high).Durability / 2; - var stat = new PerformanceStat { Min = 0, Max = 1, QualityExponent = 0, DurabilityExponentMultiplier = 1 }; + var stat = new PerformanceStat { Min = 0, Max = 1, Terms = { new StatTerm { Source = StatSource.Durability, Exponent = 1 } } }; Assert.NotEqual(items.Evaluate(stat, low), items.Evaluate(stat, high)); } @@ -604,13 +604,11 @@ public sealed class LoadoutTests : IDisposable // EquippedItem.Evaluate) with no shared entry point to assert against. It is expressible now because both // resolve through the one function via an IStatContext, which is the structural point of the cut. // - // Real catalog curves rarely land on exactly 1.0 at their reported OptimalTemperature (64-sample search over - // an authored Bezier) -- a probe against GameData/Aetheria.cc found 12 of 30 heat-bearing stats disagreeing - // between the unequipped and full-health/optimal-temperature equipped reads, by up to ~100 units on a - // Min/Max=0/1e6 stat. That is real, current, and *not* fixed here: heat curve semantics are Cut 1's R-heat - // ruling, not Cut 0's. This test pins the design contract with a controlled fixture (a flat-topped curve - // whose plateau samples to exactly 1.0) rather than live data, so it is not a claim that every real item - // agrees today. + // Cut 1 (docs/stats-and-power-cut.md), R-heat: the authored shape is minimum, maximum, optimum and plateau + // width, with linear falloffs -- no curve. This fixture authors a plateau (40-60 out of a 0-100 range) that + // reaches exactly 1.0 across it, the R-heat equivalent of the old flat-topped bezier fixture, so the + // equality this test pins (unequipped agrees with equipped-at-optimum) is expressible the same way Cut 0 + // left it. [Fact] public void UnequippedAgreesWithEquippedAtFullHealthAndOptimalTemperature() { @@ -618,20 +616,11 @@ public sealed class LoadoutTests : IDisposable var maker = cache.RefOf(cache.GetByName("Maker")); var hullData = cache.GetByName("Skiff"); - var flatCurve = new BezierCurve - { - Keys = new[] - { - new float4(0f, 0f, 0f, 0f), - new float4(.4f, 1f, 0f, 0f), - new float4(.6f, 1f, 0f, 0f), - new float4(1f, 0f, 0f, 0f), - } - }; var thermalGear = cache.Upsert(new GearData { Name = "Thermal", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10, - Durability = 100, MinimumTemperature = 0, MaximumTemperature = 100, HeatPerformanceCurve = flatCurve + Durability = 100, MinimumTemperature = 0, MaximumTemperature = 100, + OptimalTemperature = 50, PlateauWidth = 20 }); cache.FlushAsync().Wait(); var thermalData = cache.Get(thermalGear); @@ -650,16 +639,20 @@ public sealed class LoadoutTests : IDisposable Assert.Equal(1f, equipped.ThermalPerformance, 4); Assert.Equal(1f, equipped.DurabilityPerformance, 4); - var stat = new PerformanceStat { Min = 0, Max = 1, QualityExponent = 0, HeatExponentMultiplier = 1, DurabilityExponentMultiplier = 1 }; + var stat = new PerformanceStat + { + Min = 0, Max = 1, + Terms = { new StatTerm { Source = StatSource.Heat, Exponent = 1 }, new StatTerm { Source = StatSource.Durability, Exponent = 1 } } + }; var equippedResult = equipped.Evaluate(stat); var unequippedResult = items.Evaluate(stat, gearItem); Assert.Equal(unequippedResult, equippedResult, 5); } // Cut 0: the unequipped context has no heat, by name (UnequippedStatContext.HeatFactor is a fixed 1), - // regardless of the item's actual temperature or the stat's HeatExponentMultiplier. This is one of the two - // named disagreements the cut preserves rather than resolves -- the trade menu shows the un-discounted value - // on purpose. Mutation: have HeatFactor read a real thermal performance instead of the constant 1; this goes + // regardless of the item's actual temperature or the term's exponent. This is one of the two named + // disagreements the cut preserves rather than resolves -- the trade menu shows the un-discounted value on + // purpose. Mutation: have HeatFactor read a real thermal performance instead of the constant 1; this goes // red because the item is equipped far off its optimal temperature while unequipped stays unchanged. [Fact] public void UnequippedIgnoresHeatRegardlessOfTemperature() @@ -667,14 +660,13 @@ public sealed class LoadoutTests : IDisposable using var cache = AetheriaStores.Open(Catalog, catalogWritable: true); var maker = cache.RefOf(cache.GetByName("Maker")); var hullData = cache.GetByName("Skiff"); - var curve = new BezierCurve - { - Keys = new[] { new float4(0f, 0f, 0f, 0f), new float4(.5f, 1f, 0f, 0f), new float4(1f, 0f, 0f, 0f) } - }; + // A peak with zero plateau width: performance reaches 1.0 only exactly at the optimum, matching the old + // curve fixture's single-point peak at .5 of its range. var thermalGear = cache.Upsert(new GearData { Name = "ColdThermal", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10, - Durability = 100, MinimumTemperature = 0, MaximumTemperature = 100, HeatPerformanceCurve = curve + Durability = 100, MinimumTemperature = 0, MaximumTemperature = 100, + OptimalTemperature = 50, PlateauWidth = 0 }); cache.FlushAsync().Wait(); var thermalData = cache.Get(thermalGear); @@ -692,20 +684,20 @@ public sealed class LoadoutTests : IDisposable equipped.UpdatePerformance(); Assert.True(equipped.ThermalPerformance < 0.01f); - var stat = new PerformanceStat { Min = 0, Max = 1, QualityExponent = 0, HeatExponentMultiplier = 1 }; + var stat = new PerformanceStat { Min = 0, Max = 1, Terms = { new StatTerm { Source = StatSource.Heat, Exponent = 1 } } }; var equippedResult = equipped.Evaluate(stat); var unequippedResult = items.Evaluate(stat, gearItem); Assert.True(equippedResult < 0.01f); // heat tanks the equipped read Assert.Equal(1f, unequippedResult, 3); // unequipped never reads heat at all } - // Cut 0: ConsumableItemEffect.Evaluate substitutes progress-through-duration for heat -- applied - // unconditionally, not exponentiated by the stat's HeatExponentMultiplier the way EquippedItem's real heat - // performance is. That is the named "consumable substitutes progress for heat" disagreement, preserved - // exactly. Mutation: route consumable heat through pow(effectiveness, HeatExponentMultiplier) like the - // equipped path; this goes red because HeatExponentMultiplier is 0 here on purpose. + // Cut 1: ConsumableItemEffect's progress-through-duration is now its own declared term (ConsumableProgress) + // rather than a hard override of "heat" applied to every stat regardless of what it declares. A stat that + // declares the term reads progress; one that does not is unaffected by it, the same as any other source a + // context has no reader for. Mutation: apply ConsumableProgressFactor unconditionally instead of gating it + // on a declared term; the "undeclared" assertion goes red because Undeclared would then also read .5. [Fact] - public void ConsumableEvaluateSubstitutesProgressForHeatUnconditionally() + public void ConsumableProgressAppliesOnlyWhenDeclared() { using var cache = AetheriaStores.Open(Catalog, catalogWritable: true); var maker = cache.RefOf(cache.GetByName("Maker")); @@ -726,10 +718,12 @@ public sealed class LoadoutTests : IDisposable var effect = new ConsumableItemEffect(consumableItem, ship); effect.Update(5f); // half the duration elapsed -> progress .5 -> effectiveness .5 on a linear ramp - // HeatExponentMultiplier = 0: if consumable heat were exponentiated like the equipped path, progress - // would have no effect (pow(x, 0) == 1) and the result would be 1, not .5. - var stat = new PerformanceStat { Min = 0, Max = 1, QualityExponent = 0, HeatExponentMultiplier = 0 }; - Assert.Equal(.5f, effect.Evaluate(stat), 3); + // Exponent 2, not 1: pow(.5, 2) == .25 differs from the raw progress .5, so a mutation that dropped the + // term's own exponent (using the raw effectiveness value unexponentiated) is distinguishable from this. + var declared = new PerformanceStat { Min = 0, Max = 1, Terms = { new StatTerm { Source = StatSource.ConsumableProgress, Exponent = 2 } } }; + var undeclared = new PerformanceStat { Min = 0, Max = 1 }; + Assert.Equal(.25f, effect.Evaluate(declared), 3); + Assert.Equal(1f, effect.Evaluate(undeclared), 3); } // F4: CreateLot(product) fills each of the design's roles from the product's own per-role spread diff --git a/tests/mutation_tests_stats_power_cut1.py b/tests/mutation_tests_stats_power_cut1.py new file mode 100644 index 000000000..e552d5e8d --- /dev/null +++ b/tests/mutation_tests_stats_power_cut1.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +"""Mutation tests for docs/stats-and-power-cut.md Cut 1 (terms replace the four fixed exponents; R-heat). + +Cut 1 replaces PerformanceStat's four fixed exponent fields with a declared list of StatTerm (source + +exponent + role), and replaces EquippableItemData.HeatPerformanceCurve with an authored minimum, maximum, +optimum and plateau width. This script mutates each rule's own line of code and asserts the named test goes +red for exactly that reason. A no-op control mutation proves the read/replace/restore path is transparent. + +Usage: + python tests/mutation_tests_stats_power_cut1.py --cultlib-root + +Only touches files under this repository; every mutation is reversed before the script exits, including on +failure. +""" +from __future__ import annotations + +import argparse +import subprocess +import sys +from dataclasses import dataclass +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +TEST_PROJECT = REPO_ROOT / "tests" / "Aetheria.Shared.Tests" + + +@dataclass +class Mutation: + rule: str + file: str + anchor: str + mutated: str + test: str + expect: str # "red" (mutant must be killed) or "green" (the no-op control) + + +MUTATIONS: list[Mutation] = [ + # --- No-op control: proves the anchor/replace/restore mechanism is transparent --- + Mutation( + rule="control (no-op round trip)", + file="Assets/Scripts/ServerShared/ItemData.cs", + anchor=" StatSource.Quality => pow(context.Lot.QualityForRole(term.Role), term.Exponent),", + mutated=" StatSource.Quality => pow(context.Lot.QualityForRole(term.Role), term.Exponent),", + test="LoadoutTests.StatsReadTheLot", + expect="green", + ), + # --- A term's Role must actually route the quality read; Quality is not one universal reader --- + Mutation( + rule="a Quality term must read its own Role, not always the item's workmanship (unrolled)", + file="Assets/Scripts/ServerShared/ItemData.cs", + anchor=" StatSource.Quality => pow(context.Lot.QualityForRole(term.Role), term.Exponent),", + mutated=" StatSource.Quality => pow(context.Lot.QualityForRole(null), term.Exponent),", + test="LoadoutTests.StatsReadTheLot", + expect="red", + ), + # --- A Durability term must resolve through DurabilityFactor, not some other source's factor --- + Mutation( + rule="a Durability term must call DurabilityFactor, not HeatFactor", + file="Assets/Scripts/ServerShared/ItemData.cs", + anchor=" StatSource.Durability => context.DurabilityFactor(term.Exponent),", + mutated=" StatSource.Durability => context.HeatFactor(term.Exponent),", + test="LoadoutTests.EvaluateDurabilityExponentReadsLotQuality", + expect="red", + ), + # --- A stat with no declared terms is the identity (factor 1, i.e. Max) -- the zero-multiplier equivalence + # --- the migration depends on (docs/stats-and-power-cut.md Cut 1's "a zero multiplier becomes no term") --- + Mutation( + rule="an undeclared term set must resolve to the identity factor (1), not 0", + file="Assets/Scripts/ServerShared/ItemData.cs", + anchor=" var factor = 1f;", + mutated=" var factor = 0f;", + test="LoadoutTests.ConsumableProgressAppliesOnlyWhenDeclared", + expect="red", + ), + # --- ConsumableProgress must apply the term's own exponent, not a fixed pass-through --- + Mutation( + rule="a ConsumableProgress term must apply its own exponent", + file="Assets/Scripts/ServerShared/Entity.cs", + anchor=( + " public float ConsumableProgressFactor(float exponent) =>\n" + " pow(Data.Effectiveness.Evaluate((Data.Duration - RemainingDuration) / Data.Duration), exponent);" + ), + mutated=( + " public float ConsumableProgressFactor(float exponent) =>\n" + " Data.Effectiveness.Evaluate((Data.Duration - RemainingDuration) / Data.Duration);" + ), + test="LoadoutTests.ConsumableProgressAppliesOnlyWhenDeclared", + expect="red", + ), + # --- R-heat validation: an optimum outside its own bounds must be refused at load, naming the item --- + Mutation( + rule="StatValidation must refuse an OptimalTemperature outside its bounds", + file="Assets/Scripts/ServerShared/ItemData.cs", + anchor=( + " if (data.OptimalTemperature < data.MinimumTemperature || data.OptimalTemperature > data.MaximumTemperature)" + ), + mutated=" if (false)", + test="HeatResponseTests.LoadRefusesAnOptimumOutsideItsBounds", + expect="red", + ), + # --- R-heat validation: a negative plateau width must be refused at load, naming the item --- + Mutation( + rule="StatValidation must refuse a negative PlateauWidth", + file="Assets/Scripts/ServerShared/ItemData.cs", + anchor=" if (data.PlateauWidth < 0)", + mutated=" if (false)", + test="HeatResponseTests.LoadRefusesANegativePlateauWidth", + expect="red", + ), + # --- R-heat shape: performance must be full across the whole authored plateau, not only at the optimum --- + Mutation( + rule="Performance() must be 1 across the whole plateau, not only exactly at the optimum", + file="Assets/Scripts/ServerShared/ItemData.cs", + anchor=" var halfPlateau = PlateauWidth * 0.5f;", + mutated=" var halfPlateau = 0f;", + test="HeatResponseTests.PerformanceIsFullAcrossThePlateau", + expect="red", + ), + # --- The wear lever: inside the plateau, Wear's thermal term must be zero (Performance == 1 there) --- + Mutation( + rule="held inside the plateau must take no thermal wear (the operational-lifespan lever)", + file="Assets/Scripts/ServerShared/Entity.cs", + anchor=( + " Wear = (1 - pow(ThermalPerformance,\n" + " (1 - pow(Lot.Quality, ItemManager.GameplaySettings.QualityWearExponent)) *\n" + " ItemManager.GameplaySettings.ThermalWearExponent) +\n" + " deltaTemp * ItemManager.GameplaySettings.DeltaTempWearExponent \n" + " ) * Data.Durability / Data.ThermalResilience;" + ), + mutated=( + " Wear = (0.05f - pow(ThermalPerformance,\n" + " (1 - pow(Lot.Quality, ItemManager.GameplaySettings.QualityWearExponent)) *\n" + " ItemManager.GameplaySettings.ThermalWearExponent) +\n" + " deltaTemp * ItemManager.GameplaySettings.DeltaTempWearExponent \n" + " ) * Data.Durability / Data.ThermalResilience;" + ), + test="HeatResponseTests.HeldInsidePlateauTakesNoThermalWear", + expect="red", + ), + # --- The wear lever's other half: a fast swing across the plateau must still wear, from deltaTemp alone --- + Mutation( + rule="deltaTemp must still cost wear even when the swing lands back inside the plateau", + file="Assets/Scripts/ServerShared/Entity.cs", + anchor=" var deltaTemp = math.abs(temp - oldTemperature);", + mutated=" var deltaTemp = 0f;", + test="HeatResponseTests.AFastSwingAcrossThePlateauStillWears", + expect="red", + ), +] + + +def replace_unique(path: Path, anchor: str, mutated: str) -> None: + original = path.read_text(encoding="utf-8") + count = original.count(anchor) + if count != 1: + raise SystemExit(f"{path}: anchor must occur exactly once, found {count}\n---\n{anchor}") + path.write_text(original.replace(anchor, mutated), encoding="utf-8") + + +def run_test(cultlib_root: str, test: str) -> tuple[int, str]: + proc = subprocess.run( + ["dotnet", "test", str(TEST_PROJECT), f"-p:CultLibRoot={cultlib_root}", + "--filter", f"FullyQualifiedName~{test}"], + capture_output=True, text=True, timeout=300, + ) + return proc.returncode, proc.stdout + proc.stderr + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--cultlib-root", required=True) + args = parser.parse_args() + + failures: list[str] = [] + originals: dict[str, str] = {} + for m in MUTATIONS: + path = REPO_ROOT / m.file + if m.file not in originals: + originals[m.file] = path.read_text(encoding="utf-8") + + def restore_all() -> None: + for file, text in originals.items(): + (REPO_ROOT / file).write_text(text, encoding="utf-8") + + try: + for m in MUTATIONS: + print(f"\n=== {m.rule} (expect {m.expect}) ===") + path = REPO_ROOT / m.file + replace_unique(path, m.anchor, m.mutated) + code, output = run_test(args.cultlib_root, m.test) + passed = "Passed!" in output and code == 0 + if m.expect == "green": + if not passed: + failures.append(f"{m.rule}: expected green (test passing), got failure\n{output[-2000:]}") + else: + print(f"OK: {m.test} passed under a no-op mutation, as expected") + else: + if passed: + failures.append(f"{m.rule}: expected red (mutant killed), but {m.test} still passed") + else: + print(f"OK: {m.test} went red under the mutation, as expected") + # Restore this file immediately so the next mutation starts from a clean tree. + path.write_text(originals[m.file], encoding="utf-8") + finally: + restore_all() + + if failures: + print("\n=== FAILURES ===") + for f in failures: + print(f) + return 1 + + print("\nAll mutation cases behaved as Cut 1's verification section demands.") + return 0 + + +if __name__ == "__main__": + sys.exit(main())