diff --git a/Assets/Scripts/Editor/InventoryGridParityCapture.cs b/Assets/Scripts/Editor/InventoryGridParityCapture.cs index 26f2fdba7..55bf4762a 100644 --- a/Assets/Scripts/Editor/InventoryGridParityCapture.cs +++ b/Assets/Scripts/Editor/InventoryGridParityCapture.cs @@ -6,6 +6,8 @@ using System.Reflection; using UnityEditor; using UnityEngine; using UnityEngine.UI; +using UniRx.Triggers; +using GameCult.Caching; using int2 = CultMath.int2; // The parity harness of the inventory grid (map IG): the sheet sprites are the oracle and InventoryGrid is judged against them. @@ -20,11 +22,15 @@ public static class InventoryGridParityCapture private const string PrefabPath = "Assets/Prefabs/UI/Inventory.prefab"; private const string ShaderPath = "Assets/Shaders/InventoryGrid.shader"; - // The bound on the largest 8-bit channel difference of any pixel of the atlas, outside the mask-33 footprint. It is - // the geometric mean of the shipped worst reading and the least claimed mutant's reading (lodur:ruling:deterministic-bound-margin). - private const int AtlasBound = 4; - // The bound on a thermal mask's rms difference, 0..1 channel units, after the fit. - private const double ThermalBound = 0.1; + // The bound on the largest 8-bit channel difference of any pixel of the atlas and of the real hull, outside the footprints of the + // oracle's own slips. lodur:ruling:deterministic-bound-margin: the geometric mean of the shipped worst reading (4) and the least + // claimed mutant's reading (122, fill-inset-2.5), sqrt(4 x 122) = 22.1, a separation of 5.5 on each side. The other mutants read 170 to 255. + private static int AtlasBound = 22; + // The bound on a thermal mask's rms difference in the atlas, 0..1 channel units, after the fit: the geometric mean of the shipped + // worst reading (0.0577, S32 mask 15) and the pipe-width-minus mutant's (0.1363, S16 mask 15), a separation of 1.53 on each side. + private static double ThermalBound = 0.089; + private static int _atlasWorst, _hullWorst; + private static double _thermalWorst; private static string _mutant = ""; private static string _pngOut; @@ -32,7 +38,7 @@ public static class InventoryGridParityCapture public static readonly string[] Mutants = { - "rule-inset-2", "softness-1.25", "fill-inset-2.5", "arms-0", "icon-multiplier-1" + "rule-inset-2", "softness-1.25", "fill-inset-2.5", "arms-0", "icon-multiplier-1", "flip-ignored", "pipe-width-minus" }; private static void Log(string line) => Debug.Log("[InventoryGridParity] " + line); @@ -45,13 +51,18 @@ public static class InventoryGridParityCapture string Arg(string name) { var i = Array.IndexOf(args, name); return i >= 0 && i + 1 < args.Length ? args[i + 1] : null; } _pngOut = Arg("-pngOut"); _mutant = Arg("-mutant") ?? ""; + if (Arg("-atlasBound") != null) AtlasBound = int.Parse(Arg("-atlasBound")); + if (Arg("-thermalBound") != null) ThermalBound = double.Parse(Arg("-thermalBound"), System.Globalization.CultureInfo.InvariantCulture); if (_mutant != "" && !Mutants.Contains(_mutant)) throw new InvalidOperationException("Unknown mutant " + _mutant); if (_pngOut != null) Directory.CreateDirectory(_pngOut); Log("mutant=" + (_mutant == "" ? "none" : _mutant)); - Atlas(); - Thermal(Array.IndexOf(args, "-fitThermal") >= 0); + var hullOnly = Array.IndexOf(args, "-hullOnly") >= 0; + if (!hullOnly) Atlas(); + if (!hullOnly) Thermal(Array.IndexOf(args, "-fitThermal") >= 0); + if (Array.IndexOf(args, "-noHull") < 0) Hull(); + Log($"SUMMARY atlasWorst={_atlasWorst} hullWorst={_hullWorst} thermalWorstRms={_thermalWorst:F4} bounds atlas={AtlasBound} thermal={ThermalBound}"); if (Breaches.Count > 0) { foreach (var breach in Breaches) Log("BOUND BREACHED " + breach); @@ -74,6 +85,7 @@ public static class InventoryGridParityCapture public readonly int Width, Height; public readonly float Scale; public readonly RectTransform Page; + public Camera Camera => _camera; private readonly GameObject _root, _cameraObject; private readonly Camera _camera; private readonly RenderTexture _target; @@ -168,6 +180,7 @@ public static class InventoryGridParityCapture case "softness-1.25": grid.Softness = 1.25f; break; case "fill-inset-2.5": grid.FillInset = 2.5f; break; case "arms-0": grid.ArmTexels = 0f; break; + case "pipe-width-minus": grid.PipeHalfWidth -= .5f / 32f; break; } } @@ -301,6 +314,7 @@ public static class InventoryGridParityCapture } } Log($"atlas {regime.Name} w={width} pass={pass} max8bitDiff={worst} (mask {worstMask}) slipFootprintMax={slip} padSlipMax={pad}"); + _atlasWorst = Math.Max(_atlasWorst, worst); if (worst > AtlasBound) Breaches.Add($"atlas {regime.Name} w={width} pass={pass}: {worst} > {AtlasBound}"); if (pass == 0 || pass == 2) SaveSideBySide($"atlas-{regime.Name}-{width}-pass{pass}.png", rig, old, fresh, new RectInt(0, 0, Mathf.CeilToInt((8 + columns * stride) * rig.Scale), Mathf.CeilToInt((8 + 16 * stride) * rig.Scale))); @@ -458,12 +472,461 @@ public static class InventoryGridParityCapture var rms = Rms(k, fresh); var worst = rms.Max(); Log($"thermal S{sizes[k]} worstRms={worst:F4} (mask {Array.IndexOf(rms, worst)})"); + _thermalWorst = Math.Max(_thermalWorst, worst); if (worst > ThermalBound) Breaches.Add($"thermal S{sizes[k]}: rms {worst:F4} > {ThermalBound}"); SaveSideBySide($"thermal-S{sizes[k]}.png", rigs[k], olds[k], fresh, new RectInt(0, 0, Mathf.CeilToInt(8 + 16 * stride), Mathf.CeilToInt(8 + sizes[k] + 8))); } foreach (var rig in rigs) rig.Dispose(); } + + // ---- Real hull ------------------------------------------------------------------------------------------------------ + + private sealed class Fixture : IDisposable + { + public ItemManager Items; + public Zone Zone; + public Entity Ship; + public HullData Hull; + public ActionGameManager Manager; + private readonly List _objects = new List(); + + public static Fixture Build() + { + var fixture = new Fixture(); + var root = Directory.GetParent(Application.dataPath)!.FullName; + // The catalog is a package stack: the shipped catalog plus the ship packages under GameData/Mods, composed the way the game does. + var derived = Path.Combine(Path.GetTempPath(), $"inventory-grid-parity-{Guid.NewGuid():N}.cc"); + var composition = ShipModCatalog.Compose(Path.Combine(root, "GameData", "Aetheria.cc"), derived, Path.Combine(root, "GameData", "Mods")); + Log($"packages composed: {string.Join(", ", composition.Included)}; excluded {composition.Excluded.Length}"); + var cache = AetheriaStores.Open(derived); + var settings = AssetDatabase.LoadAssetAtPath("Assets/Resources/Settings.asset")?.GameplaySettings + ?? throw new InvalidOperationException("No Settings.asset."); + fixture.Items = new ItemManager(1u, cache, new ProvenanceLedger(), settings, _ => { }); + fixture.Zone = new Zone(fixture.Items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Parity", Owner = null }, null); + + // The hull whose hardpoints carry the most distinct types, among those a Loadout fits: a faction's boss loadout + // first, else any Loadout naming the hull. + var loadouts = new Dictionary(); + foreach (var faction in cache.GetAll()) + if (Loadouts.BossOf(cache, faction, out _) is { } boss && cache.Get(boss.Hull) is { } bossHull) + loadouts.TryAdd(bossHull.Name, boss); + foreach (var loadout in cache.GetAll()) + if (cache.Get(loadout.Hull) is { } hull) loadouts.TryAdd(hull.Name, loadout); + Log($"catalog: {cache.GetAll().Count()} factions, {cache.GetAll().Count()} loadouts ({loadouts.Count} by hull), {cache.GetAll().OfType().Count()} hulls"); + foreach (var l in cache.GetAll()) Log($"loadout {l.Name}: hull key {l.Hull.Key.Value} resolves {cache.Get(l.Hull)?.Name ?? "null"}"); + foreach (var h in cache.GetAll().OfType()) Log($"hull {h.Name} {h.HullType} key {cache.RefOf(h).Key.Value} types {h.Hardpoints.Select(x => x.Type).Distinct().Count()}"); + var candidate = cache.GetAll().OfType() + .Where(hull => hull.HullType == HullType.Ship && loadouts.ContainsKey(hull.Name)) + .OrderByDescending(hull => hull.Hardpoints.Select(h => h.Type).Distinct().Count()) + .ThenBy(hull => hull.Name, StringComparer.Ordinal) + .FirstOrDefault() ?? throw new InvalidOperationException("No ship hull has a Loadout."); + var chosen = loadouts[candidate.Name]; + FactionProductData Choose(CraftedItemData design) + { + var key = cache.RefOf(design).Key; + return cache.GetAll().Where(product => product.Design.Key.Equals(key)) + .OrderBy(product => product.Name, StringComparer.Ordinal).FirstOrDefault(); + } + var failures = new List(); + fixture.Ship = Loadouts.Materialize(fixture.Items, fixture.Zone, chosen, Choose, failures) + ?? throw new InvalidOperationException($"Cannot build {candidate.Name}: {string.Join("; ", failures)}"); + fixture.Hull = candidate; + + // The loadout carries no cargo bay: fit the smallest bay design the hull takes, and store three distinct commodities in it. + if (!fixture.Ship.CargoBays.Any()) + foreach (var bay in cache.GetAll().OfType().OrderBy(b => b.InteriorShape.Width * b.InteriorShape.Height)) + { + var unit = (EquippableItem) fixture.Items.CreateInstance(fixture.Items.CreateLot(bay, default, Loadouts.UnbrandedQuality)); + if (fixture.Ship.TryFindSpace(unit, out var spot) && fixture.Ship.TryEquip(unit, spot)) break; + } + var cargo = fixture.Ship.CargoBays.FirstOrDefault() ?? throw new InvalidOperationException("No cargo bay design fits the hull."); + foreach (var commodity in cache.GetAll().OfType().Take(8)) + { + var stack = new SimpleCommodity { Data = cache.RefOf(commodity), Quantity = 1 }; + cargo.TryStore(stack); + } + var stored = cargo.Occupancy.Cast().Where(i => i != null).Distinct().Count(); + Log($"cargo bay {cargo.Data.Name}: {stored} distinct stored items"); + if (stored < 3) throw new InvalidOperationException($"The cargo bay holds {stored} items, want at least 3."); + Log($"hull {candidate.Name}: {candidate.Hardpoints.Select(h => h.Type).Distinct().Count()} hardpoint types, {candidate.Shape.Width}x{candidate.Shape.Height} cells, {fixture.Ship.Equipment.Count} items fitted, {fixture.Ship.CargoBays.Count()} cargo bays"); + + var managerObject = new GameObject("Parity game manager"); + fixture._objects.Add(managerObject); + fixture.Manager = managerObject.AddComponent(); + const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + typeof(ActionGameManager).GetProperty("Instance", Any).SetValue(null, fixture.Manager); + typeof(ActionGameManager).GetProperty("ItemManager", Any).GetSetMethod(true).Invoke(fixture.Manager, new object[] { fixture.Items }); + typeof(ActionGameManager).GetProperty("Zone", Any).GetSetMethod(true).Invoke(fixture.Manager, new object[] { fixture.Zone }); + fixture.Manager.CurrentEntity = fixture.Ship as Ship; + return fixture; + } + + public void Dispose() + { + foreach (var o in _objects) if (o) UnityEngine.Object.DestroyImmediate(o); + } + } + + private struct HullState + { + public string Name; + public bool Hud, Enemy, Thermal, Cargo; + public Action Setup; + } + + private static void Hull() + { + using var fixture = Fixture.Build(); + var states = new[] + { + new HullState { Name = "menu" }, + new HullState { Name = "hud", Hud = true }, + new HullState { Name = "enemy", Hud = true, Enemy = true }, + new HullState + { + Name = "hover", + Setup = (panel, f) => + { + var item = f.Ship.Equipment.First(e => e.EquippableItem != null).EquippableItem; + var occupancy = new Shape(f.Hull.Shape.Width, f.Hull.Shape.Height); + foreach (var v in f.Hull.Shape.AllCoordinates.Where(c => f.Hull.Shape[c]).Take(5)) occupancy[v] = true; + panel.FakeItem = item; + panel.FakeOccupancy = occupancy; + } + }, + new HullState + { + Name = "drag", + Setup = (panel, f) => + { + var item = f.Ship.Equipment.First(e => e.EquippableItem != null); + panel.IgnoreOccupancy = f.Hull.Shape.Inset(item.Data.Shape, item.Position, item.EquippableItem.Rotation); + } + }, + new HullState { Name = "thermal", Thermal = true }, + new HullState { Name = "cargo", Cargo = true }, + }; + + foreach (var width in new[] { 1920, 2560 }) + using (var rig = new Rig(width)) + foreach (var state in states) + HullStateCheck(rig, fixture, state, width, width == 1920 && state.Name == "menu" ? FrameTime : (Action>) null); + } + + // A reading, not a gate: 101 paired, interleaved iterations of the menu real-hull state. Each times a full refresh with changed content + // (RefreshCells for the sprite cells; SetCell for every cell plus the texture Apply for the grid) plus Canvas.ForceUpdateCanvases plus + // camera.Render plus a 1-pixel ReadPixels sync. + private static void FrameTime(Rig rig, InventoryPanel panel, InventoryGrid grid, Dictionary recordsA) + { + var fixtureShip = (Entity) panel.GameManager.CurrentEntity; + var hull = (HullData) panel.GameManager.ItemManager.GetData(fixtureShip.Hull); + var item = fixtureShip.Equipment.First(e => e.EquippableItem != null); + var shape = hull.Shape.Inset(item.Data.Shape, item.Position, item.EquippableItem.Rotation); + foreach (var cell in panel.CellInstances.Values) cell.gameObject.SetActive(true); + panel.IgnoreOccupancy = shape; + panel.RefreshCells(); + var recordsB = ReadRecords(panel, false); + panel.IgnoreOccupancy = null; + panel.RefreshCells(); + var one = new Texture2D(1, 1, TextureFormat.RGBA32, false); + void Sync() + { + Canvas.ForceUpdateCanvases(); + rig.Camera.Render(); + var previous = RenderTexture.active; + RenderTexture.active = rig.Camera.targetTexture; + one.ReadPixels(new Rect(0, 0, 1, 1), 0, 0); + RenderTexture.active = previous; + } + double OldIteration(int i) + { + foreach (var cell in panel.CellInstances.Values) cell.gameObject.SetActive(true); + grid.gameObject.SetActive(false); + Sync(); + var watch = System.Diagnostics.Stopwatch.StartNew(); + panel.IgnoreOccupancy = i % 2 == 0 ? shape : null; + panel.RefreshCells(); + Sync(); + return watch.Elapsed.TotalMilliseconds; + } + double NewIteration(int i) + { + foreach (var cell in panel.CellInstances.Values) cell.gameObject.SetActive(false); + grid.gameObject.SetActive(true); + Sync(); + var watch = System.Diagnostics.Stopwatch.StartNew(); + foreach (var (v, record) in i % 2 == 0 ? recordsB : recordsA) grid.SetCell(v, record); + grid.Flush(); + Sync(); + return watch.Elapsed.TotalMilliseconds; + } + for (var i = 0; i < 5; i++) { OldIteration(i); NewIteration(i); } + var olds = new List(); + var news = new List(); + for (var i = 0; i < 101; i++) { olds.Add(OldIteration(i)); news.Add(NewIteration(i)); } + double Percentile(List values, double q) { var sorted = values.OrderBy(v => v).ToList(); return sorted[(int) Math.Round(q * (sorted.Count - 1))]; } + Log($"frame time (ms, 101 paired iterations, menu real hull, {panel.CellInstances.Count} cells) old median {Percentile(olds, .5):F2} [p25 {Percentile(olds, .25):F2}, p75 {Percentile(olds, .75):F2}], new median {Percentile(news, .5):F2} [p25 {Percentile(news, .25):F2}, p75 {Percentile(news, .75):F2}]"); + UnityEngine.Object.DestroyImmediate(one); + } + + // Every cell's record, read back from the sprite cells: the mask from the sprite name's index, plus the two colours. + private static Dictionary ReadRecords(InventoryPanel panel, bool thermal) + { + var records = new Dictionary(); + foreach (var (v, cell) in panel.CellInstances) + { + var iconName = cell.Icon.sprite.name; + var iconIndex = int.Parse(iconName.Substring(iconName.LastIndexOf('_') + 1)); + var bgName = cell.Background.sprite.name; + var bgIndex = int.Parse(bgName.Substring(bgName.LastIndexOf('_') + 1)); + records[v] = new CellRecord + { + Mask = (byte) (bgIndex & 255), Present = true, + Item = !thermal && iconIndex >= 256, Conductivity = thermal ? (byte) (iconIndex & 15) : (byte) 0, + Icon = cell.Icon.color, Background = cell.Background.color + }; + } + return records; + } + + private static void HullStateCheck(Rig rig, Fixture fixture, HullState state, int width, Action> afterwards = null) + { + ClearPage(rig); + var prefab = AssetDatabase.LoadAssetAtPath(PrefabPath); + var panelObject = (GameObject) PrefabUtility.InstantiatePrefab(prefab, rig.Page); + var panel = panelObject.GetComponent() ?? panelObject.GetComponentInChildren(true); + panel.GameManager = fixture.Manager; + if (!panel.Settings) panel.Settings = AssetDatabase.LoadAssetAtPath("Assets/Resources/Settings.asset"); + panel.NodePrototype.gameObject.SetActive(false); + var panelRect = (RectTransform) panel.transform; + panelRect.anchorMin = panelRect.anchorMax = new Vector2(.5f, .5f); + panelRect.pivot = new Vector2(.5f, .5f); + panelRect.anchoredPosition = Vector2.zero; + panelRect.sizeDelta = new Vector2(1200, 900); + var content = (RectTransform) panel.Grid.transform; + var fitter = content.GetComponent(); + var iconMultiplier = state.Hud ? 1.5f : 1f; + panel.NodePrototype.GetComponent().Icon.pixelsPerUnitMultiplier = iconMultiplier; + panel.Flip = state.Enemy; + panel.Grid.startCorner = state.Enemy ? GridLayoutGroup.Corner.UpperRight : GridLayoutGroup.Corner.LowerLeft; + panel.FitToContent = state.Hud; + if (state.Hud) + { + // The HUD's schematic rect: no fitter, a fixed rect the cells are sized to. + if (fitter) fitter.enabled = false; + content.anchorMin = content.anchorMax = new Vector2(.5f, .5f); + content.pivot = new Vector2(.5f, .5f); + content.sizeDelta = state.Enemy ? new Vector2(260, 260) : new Vector2(254, 260); + content.anchoredPosition = Vector2.zero; + } + // The thermal branch subscribes to a click trigger the edit-mode instance of the prefab does not carry. + var prototypeCell = panel.NodePrototype.GetComponent(); + if ((state.Thermal || state.Cargo) && !prototypeCell.PointerClickTrigger) prototypeCell.PointerClickTrigger = prototypeCell.gameObject.AddComponent(); + if (state.Cargo) + { + if (!prototypeCell.BeginDragTrigger) prototypeCell.BeginDragTrigger = prototypeCell.gameObject.AddComponent(); + if (!prototypeCell.DragTrigger) prototypeCell.DragTrigger = prototypeCell.gameObject.AddComponent(); + if (!prototypeCell.EndDragTrigger) prototypeCell.EndDragTrigger = prototypeCell.gameObject.AddComponent(); + if (!prototypeCell.PointerEnterTrigger) prototypeCell.PointerEnterTrigger = prototypeCell.gameObject.AddComponent(); + if (!prototypeCell.PointerExitTrigger) prototypeCell.PointerExitTrigger = prototypeCell.gameObject.AddComponent(); + } + state.Setup?.Invoke(panel, fixture); + if (state.Cargo) panel.Display(fixture.Ship.CargoBays.First()); + else panel.Display(fixture.Ship, state.Hud, state.Thermal); + LayoutRebuilder.ForceRebuildLayoutImmediate(content); + Canvas.ForceUpdateCanvases(); + + var records = ReadRecords(panel, state.Thermal); + var columns = panel.Grid.constraintCount; + var rows = (panel.CellInstances.Count + panel.EmptyCells.Count) / columns; + var cellSize = panel.Grid.cellSize.x; + var padding = panel.Grid.padding; + var orientation = panel.Grid.startCorner == GridLayoutGroup.Corner.UpperRight ? GridOrientation.UpperRight : GridOrientation.LowerLeft; + var cellRects = panel.CellInstances.ToDictionary(pair => pair.Key, pair => (RectTransform) pair.Value.transform); + + var old = rig.Render(); + + // New: the grid in the content's place over the same rect; the cells off. + foreach (var cell in panel.CellInstances.Values) cell.gameObject.SetActive(false); + if (fitter) fitter.enabled = false; + panel.Grid.enabled = false; + var gridObject = new GameObject("Parity grid", typeof(RectTransform), typeof(CanvasRenderer)) { layer = panelObject.layer }; + var gridRect = (RectTransform) gridObject.transform; + gridRect.SetParent(content.parent, false); + gridRect.SetSiblingIndex(content.GetSiblingIndex()); + gridRect.anchorMin = content.anchorMin; + gridRect.anchorMax = content.anchorMax; + gridRect.pivot = content.pivot; + gridRect.anchoredPosition = content.anchoredPosition; + gridRect.sizeDelta = content.sizeDelta; + gridRect.localScale = content.localScale; + var grid = gridObject.AddComponent(); + Look(grid, iconMultiplier); + grid.Thermal = state.Thermal; + grid.Resize(columns, rows, cellSize, padding, state.Enemy && _mutant == "flip-ignored" ? GridOrientation.LowerLeft : orientation); + foreach (var (v, record) in records) grid.SetCell(v, record); + var fresh = rig.Render(); + + // Judge the whole panel's pixels; cells whose sprite has a known authoring slip are judged outside its footprint. + var camera = rig.Camera; + Rect PixelRect(RectTransform rect) + { + var corners = new Vector3[4]; + rect.GetWorldCorners(corners); + var a = RectTransformUtility.WorldToScreenPoint(camera, corners[0]); + var b = RectTransformUtility.WorldToScreenPoint(camera, corners[2]); + return Rect.MinMaxRect(Mathf.Min(a.x, b.x), Mathf.Min(a.y, b.y), Mathf.Max(a.x, b.x), Mathf.Max(a.y, b.y)); + } + var excluded = new bool[rig.Width * rig.Height]; + var ties = 0; + var minX = int.MaxValue; + var minY = int.MaxValue; + var maxX = 0; + var maxY = 0; + foreach (var (v, record) in records) + { + var pixels = PixelRect(cellRects[v]); + minX = Mathf.Min(minX, Mathf.FloorToInt(pixels.xMin)); + minY = Mathf.Min(minY, Mathf.FloorToInt(pixels.yMin)); + maxX = Mathf.Max(maxX, Mathf.CeilToInt(pixels.xMax)); + maxY = Mathf.Max(maxY, Mathf.CeilToInt(pixels.yMax)); + // A pixel centre exactly on a cell boundary is drawn by both neighbouring cells of the oracle, so its additive icon + // layer counts twice: a tie of the rasteriser, not of the look. Such a pixel is not judged. + for (var y = Mathf.Max(0, Mathf.FloorToInt(pixels.yMin) - 1); y < Mathf.Min(rig.Height, Mathf.CeilToInt(pixels.yMax) + 1); y++) + for (var x = Mathf.Max(0, Mathf.FloorToInt(pixels.xMin) - 1); x < Mathf.Min(rig.Width, Mathf.CeilToInt(pixels.xMax) + 1); x++) + if (Mathf.Abs(x + .5f - pixels.xMin) < .01f || Mathf.Abs(x + .5f - pixels.xMax) < .01f || + Mathf.Abs(y + .5f - pixels.yMin) < .01f || Mathf.Abs(y + .5f - pixels.yMax) < .01f) + { + if (!excluded[y * rig.Width + x]) ties++; + excluded[y * rig.Width + x] = true; + } + var iconMask = record.Mask | (record.Item ? 256 : 0); + var slip = (!state.Thermal && (iconMask == 33 || iconMask == 289)) || record.Mask == 33; + var padSlip = record.Mask == 136 || (!state.Thermal && iconMask == 392); + if (!slip && !padSlip) continue; + var texelMin = Mathf.Min(InventoryGrid.TexelOf(66f, iconMultiplier), InventoryGrid.TexelOf(100f, 1f)) * rig.Scale; + var texelMax = Mathf.Max(InventoryGrid.TexelOf(66f, iconMultiplier), InventoryGrid.TexelOf(100f, 1f)) * rig.Scale; + for (var y = Mathf.Max(0, Mathf.FloorToInt(pixels.yMin) - 2); y < Mathf.Min(rig.Height, Mathf.CeilToInt(pixels.yMax) + 2); y++) + for (var x = Mathf.Max(0, Mathf.FloorToInt(pixels.xMin) - 2); x < Mathf.Min(rig.Width, Mathf.CeilToInt(pixels.xMax) + 2); x++) + { + var fromTop = pixels.yMax - (y + .5f); + var fromBottom = y + .5f - pixels.yMin; + if (slip && fromTop > 1.5f * texelMin - 1.5f && fromTop < 3.5f * texelMax + 1.5f) excluded[y * rig.Width + x] = true; + if (padSlip && Mathf.Min(fromTop, fromBottom) < .5f * texelMax + 1.5f) excluded[y * rig.Width + x] = true; + } + } + var worst = 0; + var worstAt = (0, 0); + for (var y = Mathf.Max(0, minY - 2); y < Mathf.Min(rig.Height, maxY + 2); y++) + for (var x = Mathf.Max(0, minX - 2); x < Mathf.Min(rig.Width, maxX + 2); x++) + { + var i = y * rig.Width + x; + var diff = MaxDifference(old[i], fresh[i]); + if (!excluded[i] && diff > worst) { worst = diff; worstAt = (x, y); } + } + if (worst > AtlasBound) + { + var perCell = new List<(int diff, int2 v, string at)>(); + foreach (var (v, record) in records) + { + var pixels = PixelRect(cellRects[v]); + var cellWorst = 0; + var at = ""; + for (var y = Mathf.Max(0, Mathf.FloorToInt(pixels.yMin)); y < Mathf.Min(rig.Height, Mathf.CeilToInt(pixels.yMax)); y++) + for (var x = Mathf.Max(0, Mathf.FloorToInt(pixels.xMin)); x < Mathf.Min(rig.Width, Mathf.CeilToInt(pixels.xMax)); x++) + if (!excluded[y * rig.Width + x]) + { + var d = MaxDifference(old[y * rig.Width + x], fresh[y * rig.Width + x]); + if (d > cellWorst) { cellWorst = d; at = $"px {x},{y} cell px [{pixels.xMin:F2},{pixels.xMax:F2}]x[{pixels.yMin:F2},{pixels.yMax:F2}] old {old[y * rig.Width + x]} new {fresh[y * rig.Width + x]}"; } + } + if (cellWorst > AtlasBound) perCell.Add((cellWorst, v, at)); + } + foreach (var (diff, v, where) in perCell.OrderByDescending(c => c.diff).Take(8)) + { + var r = records[v]; + Log($" worst cell {v.x},{v.y} {where}: diff {diff} mask {r.Mask} ({Convert.ToString(r.Mask, 2).PadLeft(8, '0')}) item {r.Item} icon {r.Icon} bg {r.Background} sprite {panel.CellInstances[v].Icon.sprite.name}/{panel.CellInstances[v].Background.sprite.name}"); + } + } + Log($"hull {state.Name} w={width} cells={records.Count} max8bitDiff={worst} at {worstAt} tiePixelsNotJudged={ties}" + (state.Thermal ? " (thermal: the pipes are a fit, judged by cell rms)" : "")); + if (!state.Thermal) _hullWorst = Math.Max(_hullWorst, worst); + if (!state.Thermal && worst > AtlasBound) Breaches.Add($"hull {state.Name} w={width}: {worst} > {AtlasBound}"); + if (state.Thermal) + { + var worstRms = 0.0; + foreach (var (v, _) in records) + { + var pixels = PixelRect(cellRects[v]); + double sum = 0; + var n = 0; + for (var y = Mathf.Max(0, Mathf.FloorToInt(pixels.yMin)); y < Mathf.Min(rig.Height, Mathf.CeilToInt(pixels.yMax)); y++) + for (var x = Mathf.Max(0, Mathf.FloorToInt(pixels.xMin)); x < Mathf.Min(rig.Width, Mathf.CeilToInt(pixels.xMax)); x++) + { + var d = (old[y * rig.Width + x].r - fresh[y * rig.Width + x].r) / 255.0; + sum += d * d; + n++; + } + if (n > 0) worstRms = Math.Max(worstRms, Math.Sqrt(sum / n)); + } + Log($"hull thermal w={width} worst cell rms={worstRms:F4} (a reading; the pipe fit is gated by the atlas thermal section)"); + + // The background layer of every thermal cell, icons hidden in both paths, judged by the atlas bound. + foreach (var cell in panel.CellInstances.Values) + { + cell.gameObject.SetActive(true); + var hidden = cell.Icon.color; + hidden.a = 0; + cell.Icon.color = hidden; + } + grid.gameObject.SetActive(false); + var old2 = rig.Render(); + foreach (var cell in panel.CellInstances.Values) cell.gameObject.SetActive(false); + grid.gameObject.SetActive(true); + foreach (var (v, record) in records) + { + var hiddenRecord = record; + hiddenRecord.Icon.a = 0; + grid.SetCell(v, hiddenRecord); + } + var fresh2 = rig.Render(); + var worstBackground = 0; + for (var y = Mathf.Max(0, minY - 2); y < Mathf.Min(rig.Height, maxY + 2); y++) + for (var x = Mathf.Max(0, minX - 2); x < Mathf.Min(rig.Width, maxX + 2); x++) + if (!excluded[y * rig.Width + x]) worstBackground = Mathf.Max(worstBackground, MaxDifference(old2[y * rig.Width + x], fresh2[y * rig.Width + x])); + Log($"hull thermal w={width} background layer max8bitDiff={worstBackground}"); + _hullWorst = Math.Max(_hullWorst, worstBackground); + if (worstBackground > AtlasBound) Breaches.Add($"hull thermal background w={width}: {worstBackground} > {AtlasBound}"); + // A reading: the pipes are a fit, gated by the atlas section. The cells' background layer is judged below. + } + + // Hit-testing: CellAt returns the cell at every cell centre and nothing over an absent cell; empty cells pass clicks through. + var misses = 0; + var centres = 0; + for (var y = 0; y < rows; y++) + for (var x = 0; x < columns; x++) + { + var cell = new int2(x, y); + var world = gridRect.TransformPoint(grid.CellRect(cell).center); + var screen = RectTransformUtility.WorldToScreenPoint(camera, world); + var hit = grid.CellAt(screen, camera, out var found, out _); + var valid = grid.IsRaycastLocationValid(screen, camera); + centres++; + if (records.ContainsKey(cell) ? !(hit && found.Equals(cell) && valid) : valid) misses++; + } + Log($"hull {state.Name} w={width} hit-test centres={centres} wrong={misses}"); + if (misses > 0) Breaches.Add($"hull {state.Name} w={width}: {misses} hit-test centres wrong"); + + if (_pngOut != null && minX < int.MaxValue) + { + var x0 = Mathf.Max(0, minX - 8); + var y0 = Mathf.Max(0, minY - 8); + var region = new RectInt(x0, y0, Mathf.Min(rig.Width, maxX + 8) - x0, Mathf.Min(rig.Height, maxY + 8) - y0); + SaveSideBySide($"hull-{state.Name}-{width}.png", rig, old, fresh, region); + } + afterwards?.Invoke(rig, panel, grid, records); + ClearPage(rig); + } + // old | new | abs difference x 8, cropped to the region. private static void SaveSideBySide(string name, Rig rig, Color32[] old, Color32[] fresh, RectInt region) { diff --git a/tests/mutation_tests_inventory_grid.py b/tests/mutation_tests_inventory_grid.py new file mode 100644 index 000000000..9d7f8b095 --- /dev/null +++ b/tests/mutation_tests_inventory_grid.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +"""Mutation tests for the inventory grid (docs/aetheria-release-map.md section IG, cut inventory-grid-shader). + +Assets/Scripts/Editor/InventoryGridParityCapture.cs renders every cell mask through the sheet sprites and through InventoryGrid and +exits 1 when a bound is breached. This script proves the bounds bite: it runs the harness once unmutated (the control must exit 0 and +log PASS), then once per mutant, and requires exit 1 with a "BOUND BREACHED" line. + +A mutant is one named perturbation of the look the grid claims: either a harness argument (-mutant , which perturbs the new path +in the harness) or a one-line edit of the shader that is restored afterwards. The bound follows lodur:ruling:deterministic-bound-margin: +it sits at the geometric mean of the shipped reading and the least claimed mutant's reading, with a separation of at least 1.2 on each +side. A mutant whose reading is not 1.2 above the bound is recorded as UNCLAIMED and the bound is never loosened to meet it. + +One Unity batch instance runs on Starfire at a time, so each launch takes the lock directory F:/aeth-wt/unity.lock.d first. + +Run from the repo root: python tests/mutation_tests_inventory_grid.py +Exit code 0 only if the control passes, every claimed mutant is killed, and the bound sits where the margin rule puts it. +""" +from __future__ import annotations + +import math +import os +import re +import subprocess +import sys +import time +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +UNITY_EXE = r"C:\Program Files\Unity\Hub\Editor\6000.3.24f1\Editor\Unity.exe" +LOCK = Path("F:/aeth-wt/unity.lock.d") +HARNESS = REPO_ROOT / "Assets" / "Scripts" / "Editor" / "InventoryGridParityCapture.cs" +SHADER = REPO_ROOT / "Assets" / "Shaders" / "InventoryGrid.shader" +SCRATCH = REPO_ROOT / "tests" / "_scratch_inventory_grid" + +# name -> (harness argument or None, (file, anchor, mutated) or None, which bound kills it) +MUTANTS = { + "rule-inset-2": ("rule-inset-2", None, "atlas"), + "softness-1.25": ("softness-1.25", None, "atlas"), + "fill-inset-2.5": ("fill-inset-2.5", None, "atlas"), + "arms-0": ("arms-0", None, "atlas"), + "icon-multiplier-1": ("icon-multiplier-1", None, "atlas"), + "flip-ignored": ("flip-ignored", None, "atlas"), + "no-border-clamp": (None, (SHADER, "float t = min(texel, S / 8.0);", "float t = texel;"), "atlas"), + "concave-bracket-dropped": (None, (SHADER, "else if (concave)", "else if (false)"), "atlas"), + "pipe-width-minus": ("pipe-width-minus", None, "thermal"), +} + + +def pid_alive(pid: int) -> bool: + out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output=True, text=True).stdout + return str(pid) in out + + +def take_lock() -> None: + while True: + try: + os.mkdir(LOCK) + (LOCK / "holder.txt").write_text(f"nibu-hands-invgrid-mutation {os.getpid()}\n") + return + except FileExistsError: + holder = LOCK / "holder.txt" + if holder.exists(): + m = re.search(r"(\d+)\s*$", holder.read_text()) + if m and not pid_alive(int(m.group(1))): + for child in LOCK.iterdir(): + child.unlink() + LOCK.rmdir() + continue + time.sleep(60) + + +def release_lock() -> None: + try: + for child in LOCK.iterdir(): + child.unlink() + LOCK.rmdir() + except OSError: + pass + + +def run_harness(log: Path, extra: list[str]) -> tuple[int, str]: + take_lock() + try: + proc = subprocess.Popen( + [UNITY_EXE, "-batchmode", "-projectPath", str(REPO_ROOT), "-executeMethod", "InventoryGridParityCapture.Run", + "-logFile", str(log), *extra]) + (LOCK / "holder.txt").write_text(f"nibu-hands-invgrid-mutation {proc.pid}\n") + code = proc.wait(timeout=1500) + finally: + release_lock() + return code, log.read_text(encoding="utf-8", errors="replace") + + +def summary(text: str) -> tuple[int, int, float]: + m = re.search(r"SUMMARY atlasWorst=(\d+) hullWorst=(\d+) thermalWorstRms=([0-9.]+)", text) + if not m: + raise SystemExit("no SUMMARY line in the harness log") + return int(m.group(1)), int(m.group(2)), float(m.group(3)) + + +def replace_unique(path: Path, anchor: str, mutated: str) -> str: + original = path.read_bytes().decode("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_bytes(original.replace(anchor, mutated).encode("utf-8")) + return original + + +def main() -> int: + SCRATCH.mkdir(parents=True, exist_ok=True) + failures: list[str] = [] + readings: dict[str, tuple[int, float]] = {} + + print("\n=== control: unmutated tree ===") + code, text = run_harness(SCRATCH / "control.log", []) + if code != 0 or "[InventoryGridParity] PASS" not in text: + failures.append("control: expected exit 0 and PASS on the unmutated tree") + print("control FAILED") + else: + print("control OK: exit 0, PASS") + atlas_c, hull_c, thermal_c = summary(text) + shipped = max(atlas_c, hull_c) + bound_atlas = int(re.search(r"private static int AtlasBound = (\d+);", HARNESS.read_text(encoding="utf-8")).group(1)) + bound_thermal = float(re.search(r"private static double ThermalBound = ([0-9.]+);", HARNESS.read_text(encoding="utf-8")).group(1)) + print(f"shipped worst: {shipped} (atlas {atlas_c}, hull {hull_c}), thermal rms {thermal_c}; bounds {bound_atlas}, {bound_thermal}") + + for name, (arg, edit, kind) in MUTANTS.items(): + print(f"\n=== mutant {name} ===") + original = replace_unique(*edit[:1], edit[1], edit[2]) if edit else None + try: + code, text = run_harness(SCRATCH / f"{name}.log", ["-mutant", arg] if arg else []) + finally: + if edit: + edit[0].write_bytes(original.encode("utf-8")) + atlas_m, hull_m, thermal_m = summary(text) + reading = max(atlas_m, hull_m) if kind == "atlas" else thermal_m + readings[name] = (kind, reading) + killed = code == 1 and "BOUND BREACHED" in text + claimed = kind == "thermal" or reading >= 1.2 * bound_atlas + print(f"{name}: exit {code}, reading {reading} ({kind}), killed={killed}, claimed={claimed}") + if claimed and not killed: + failures.append(f"{name}: claimed but not killed by the bound (exit {code}, reading {reading})") + + # The margin rule: separation at least 1.2 on each side of each bound; an unseparated mutant is unclaimed. + atlas_least = min((r for k, r in readings.values() if k == "atlas" and r >= 1.2 * bound_atlas), default=None) + thermal_least = min((r for k, r in readings.values() if k == "thermal"), default=None) + print(f"\natlas: shipped {shipped}, bound {bound_atlas}, least claimed mutant {atlas_least}, " + f"geometric mean {math.sqrt(shipped * atlas_least):.2f}" if atlas_least else "\natlas: no claimed mutant") + if bound_atlas < 1.2 * shipped: + failures.append(f"atlas bound {bound_atlas} is under 1.2 x the shipped reading {shipped}") + if thermal_least is not None: + print(f"thermal: shipped {thermal_c}, bound {bound_thermal}, mutant {thermal_least:.4f}, geometric mean {math.sqrt(thermal_c * thermal_least):.4f}") + if bound_thermal < 1.2 * thermal_c or thermal_least < 1.2 * bound_thermal: + failures.append("thermal bound is not separated by 1.2 on each side") + for name, (kind, reading) in readings.items(): + if kind == "atlas" and reading < 1.2 * bound_atlas: + print(f"UNCLAIMED: {name} reads {reading}, under 1.2 x the bound {bound_atlas}") + + if failures: + print("\nFAILURES:\n " + "\n ".join(failures)) + return 1 + print("\nAll inventory grid mutation checks behaved as the cut demands.") + return 0 + + +if __name__ == "__main__": + sys.exit(main())