Inventory panel: cells draw and hit-test through the panel's InventoryGrid, RefreshCells the only record writer; harness switch half and Interact
InventoryPanel composes each cell's record only in RefreshCells(cells, highlight) (match predicates and GetColor unchanged), reads pointer input from the grid (Interactive authored), hover from HoveredCellChanged, draws the drag ghost as a second grid from RecordAt copies and the pulse as a per-cell background override. Flip derives from Grid.Orientation, TemperatureDisplay follows CellRect(-1,-1), InventoryMenu's selection goes through SetHighlight. CargoBackgroundColor carries the cargo cells' own background (the prototype's colour, .85, which the sprite cells never overwrote), so the golden's cargo records stay exact. The harness compares the live panels' records exactly and their cell and temperature rects by a bound against the golden (-recordsIn), judges the live grid against oracle sprite cells built from the same records, counts the RefreshCells branches each state reaches, and Interact() sends pointer events through the grids. This commit needs the next one (the migration's prefab and scene) to run. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
7f9880f2e4
commit
c2070e9fe3
3 changed files with 743 additions and 462 deletions
|
|
@ -6,7 +6,9 @@ using System.Reflection;
|
|||
using UnityEditor;
|
||||
using UnityEditor.SceneManagement;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.UI;
|
||||
using UniRx;
|
||||
using UniRx.Triggers;
|
||||
using GameCult.Caching;
|
||||
using int2 = CultMath.int2;
|
||||
|
|
@ -14,10 +16,11 @@ 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.
|
||||
// Every check logs one "[InventoryGridParity]" line, and the run exits 0 when every bound holds, 1 otherwise.
|
||||
//
|
||||
// Unity -batchmode -projectPath <project> -executeMethod InventoryGridParityCapture.Run [-pngOut <dir>] [-mutant <name>] [-hullOnly] [-recordsOut <file>] -logFile <log>
|
||||
// Unity -batchmode -projectPath <project> -executeMethod InventoryGridParityCapture.Run [-pngOut <dir>] [-mutant <name>] [-hullOnly] [-recordsIn <golden>] -logFile <log>
|
||||
//
|
||||
// -recordsOut writes the golden of the real-hull states (every cell's record and rect in page canvas units, and the temperature display's
|
||||
// rect), read off the panel as it stands. The golden is a run output, kept outside git; Soul regenerates it from the first commit of the cut.
|
||||
// -recordsIn is the golden of the real-hull states (every cell's record and rect in page canvas units, and the temperature display's
|
||||
// rect) that the first commit of the switch cut wrote from the sprite panels (`-recordsOut`, which exists only at that commit); the live
|
||||
// panels must equal it. The golden is a run output, kept outside git; Soul regenerates it from that commit.
|
||||
//
|
||||
// Needs a GPU device; do not pass -nographics or -quit. A mutant is one named perturbation of the new path (see Mutants); the
|
||||
// run must then fail a bound.
|
||||
|
|
@ -41,12 +44,12 @@ public static class InventoryGridParityCapture
|
|||
private static double _thermalWorst, _thermalHullWorst;
|
||||
|
||||
private static string _mutant = "";
|
||||
private static string _pngOut, _recordsOut;
|
||||
private static string _pngOut, _recordsIn;
|
||||
private static readonly List<string> Breaches = new List<string>();
|
||||
|
||||
public static readonly string[] Mutants =
|
||||
{
|
||||
"rule-inset-2", "softness-1.25", "fill-inset-2.5", "arms-0", "icon-multiplier-1", "flip-ignored", "pipe-width-minus"
|
||||
"rule-inset-2", "softness-1.25", "fill-inset-2.5", "arms-0", "icon-multiplier-1", "flip-ignored", "pipe-width-minus", "ghost-full-alpha"
|
||||
};
|
||||
|
||||
private static void Log(string line) => Debug.Log("[InventoryGridParity] " + line);
|
||||
|
|
@ -58,7 +61,8 @@ public static class InventoryGridParityCapture
|
|||
var args = Environment.GetCommandLineArgs();
|
||||
string Arg(string name) { var i = Array.IndexOf(args, name); return i >= 0 && i + 1 < args.Length ? args[i + 1] : null; }
|
||||
_pngOut = Arg("-pngOut");
|
||||
_recordsOut = Arg("-recordsOut");
|
||||
_recordsIn = Arg("-recordsIn");
|
||||
if (Arg("-recordsOut") != null) throw new InvalidOperationException("-recordsOut writes the golden from the sprite panels and exists only at the first commit of the switch cut.");
|
||||
_mutant = Arg("-mutant") ?? "";
|
||||
if (Arg("-atlasBound") != null) AtlasBound = int.Parse(Arg("-atlasBound"));
|
||||
if (Arg("-thermalBound") != null) ThermalHullBound = ThermalBound = double.Parse(Arg("-thermalBound"), System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
|
@ -73,8 +77,8 @@ public static class InventoryGridParityCapture
|
|||
if (!hullOnly) Masked();
|
||||
if (!hullOnly) LateLook();
|
||||
if (!hullOnly) AlphaAndClip();
|
||||
if (Array.IndexOf(args, "-noHull") < 0) Hull();
|
||||
if (_recordsOut != null) WriteGolden();
|
||||
if (Array.IndexOf(args, "-noHull") < 0) { Hull(); Interact(); }
|
||||
if (Array.IndexOf(args, "-noHull") < 0) CheckBranchCounts();
|
||||
|
||||
Log($"SUMMARY atlasWorst={_atlasWorst} hullWorst={_hullWorst} thermalWorstRms={_thermalWorst:F4} thermalHullRms={_thermalHullWorst:F4} maskedWorst={_maskedWorst} alphaClipWorst={_alphaClipWorst} bounds atlas={AtlasBound} thermal={ThermalBound} thermalHull={ThermalHullBound}");
|
||||
if (Breaches.Count > 0)
|
||||
|
|
@ -871,26 +875,6 @@ public static class InventoryGridParityCapture
|
|||
HullStateCheck(rig, fixture, state, width);
|
||||
}
|
||||
|
||||
// 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<int2, CellRecord> ReadRecords(InventoryPanel panel, bool thermal)
|
||||
{
|
||||
var records = new Dictionary<int2, CellRecord>();
|
||||
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;
|
||||
}
|
||||
|
||||
// The scene's own panel, copied into the rig page as it is authored: nothing about its rect, cell size, start corner, Flip or
|
||||
// multiplier is set here. The scene is opened additively for the copy and closed.
|
||||
private static GameObject SceneClone(string path, RectTransform page)
|
||||
|
|
@ -927,24 +911,14 @@ public static class InventoryGridParityCapture
|
|||
panelRect.anchoredPosition = Vector2.zero;
|
||||
panelRect.sizeDelta = new Vector2(1200, 900);
|
||||
}
|
||||
var content = (RectTransform) panel.Grid.transform;
|
||||
var fitter = content.GetComponent<ContentSizeFitter>();
|
||||
var iconMultiplier = panel.NodePrototype.GetComponent<InventoryCell>().Icon.pixelsPerUnitMultiplier;
|
||||
// The thermal branch subscribes to a click trigger the edit-mode instance of the prefab does not carry.
|
||||
var prototypeCell = panel.NodePrototype.GetComponent<InventoryCell>();
|
||||
if ((state.Thermal || state.Cargo) && !prototypeCell.PointerClickTrigger) prototypeCell.PointerClickTrigger = prototypeCell.gameObject.AddComponent<ObservablePointerClickTrigger>();
|
||||
if (state.Cargo)
|
||||
{
|
||||
if (!prototypeCell.BeginDragTrigger) prototypeCell.BeginDragTrigger = prototypeCell.gameObject.AddComponent<ObservableBeginDragTrigger>();
|
||||
if (!prototypeCell.DragTrigger) prototypeCell.DragTrigger = prototypeCell.gameObject.AddComponent<ObservableDragTrigger>();
|
||||
if (!prototypeCell.EndDragTrigger) prototypeCell.EndDragTrigger = prototypeCell.gameObject.AddComponent<ObservableEndDragTrigger>();
|
||||
if (!prototypeCell.PointerEnterTrigger) prototypeCell.PointerEnterTrigger = prototypeCell.gameObject.AddComponent<ObservablePointerEnterTrigger>();
|
||||
if (!prototypeCell.PointerExitTrigger) prototypeCell.PointerExitTrigger = prototypeCell.gameObject.AddComponent<ObservablePointerExitTrigger>();
|
||||
}
|
||||
var grid = panel.Grid;
|
||||
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);
|
||||
MutateLook(panel, state);
|
||||
// The container of the cells lays them out (the menu's Content sizes itself to them).
|
||||
LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform) grid.transform.parent);
|
||||
Canvas.ForceUpdateCanvases();
|
||||
|
||||
// The temperature display follows the first cell in Update, which edit mode never runs: run it once, without the labels, which
|
||||
|
|
@ -954,38 +928,44 @@ public static class InventoryGridParityCapture
|
|||
panel.MinTempLabel = panel.MaxTempLabel = null;
|
||||
typeof(InventoryPanel).GetMethod("Update", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(panel, null);
|
||||
}
|
||||
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 records = LiveRecords(grid);
|
||||
var columns = grid.Width;
|
||||
var rows = grid.Height;
|
||||
var gridRect = grid.rectTransform;
|
||||
CountBranches(fixture, panel, state, records);
|
||||
CompareGolden(rig, state, panel, records, width);
|
||||
|
||||
if (width == 1920) RecordGolden(rig, state.Name, records, cellRects, panel.TemperatureDisplay && state.Name != "cargo" ? (RectTransform) panel.TemperatureDisplay.transform : null);
|
||||
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<InventoryGrid>();
|
||||
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);
|
||||
// The live panel as it draws.
|
||||
var fresh = rig.Render();
|
||||
|
||||
// The oracle: the sheets' own sprite cells of the same records at the live cell rects, the grid hidden.
|
||||
var cellRects = new Dictionary<int2, RectTransform>();
|
||||
var oracle = new Dictionary<int2, InventoryCell>();
|
||||
foreach (var (v, record) in records)
|
||||
{
|
||||
var cell = panel.NodePrototype.Instantiate<InventoryCell>();
|
||||
// Under the grid's own object: in the same mask as the grid and outside the container's layout group (the menu's), which would
|
||||
// move them. The grid is hidden by a clear vertex colour, not by disabling it: a disabled grid leaves the layout and the
|
||||
// container collapses.
|
||||
cell.transform.SetParent(grid.transform, false);
|
||||
var rect = (RectTransform) cell.transform;
|
||||
var at = grid.CellRect(v);
|
||||
rect.anchorMin = rect.anchorMax = Vector2.zero;
|
||||
rect.pivot = Vector2.zero;
|
||||
rect.sizeDelta = at.size;
|
||||
rect.position = gridRect.TransformPoint(at.min);
|
||||
cell.Background.sprite = panel.NodeBackgroundTextures[record.Mask];
|
||||
cell.Background.color = record.Background;
|
||||
cell.Icon.sprite = state.Thermal ? panel.ThermalTextures[record.Conductivity] : panel.NodeTextures[record.Mask + (record.Item ? 256 : 0)];
|
||||
cell.Icon.color = record.Icon;
|
||||
oracle.Add(v, cell);
|
||||
cellRects.Add(v, rect);
|
||||
}
|
||||
grid.color = Color.clear;
|
||||
var old = rig.Render();
|
||||
grid.color = Color.white;
|
||||
foreach (var cell in oracle.Values) cell.gameObject.SetActive(false);
|
||||
|
||||
// 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)
|
||||
|
|
@ -1067,7 +1047,7 @@ public static class InventoryGridParityCapture
|
|||
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($" 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 {oracle[v].Icon.sprite.name}/{oracle[v].Background.sprite.name}");
|
||||
}
|
||||
}
|
||||
Log($"hull {state.Name} w={width} cells={records.Count} max8bitDiff={worst} at {worstAt} boundaryPixelsNotJudged={ties}" + (state.Thermal ? " (thermal: the pipes are a fit, judged by cell rms)" : ""));
|
||||
|
|
@ -1093,17 +1073,17 @@ public static class InventoryGridParityCapture
|
|||
Log($"hull thermal w={width} worst cell rms={worstRms:F4}");
|
||||
|
||||
// The background layer of every thermal cell, icons hidden in both paths, judged by the atlas bound.
|
||||
foreach (var cell in panel.CellInstances.Values)
|
||||
foreach (var cell in oracle.Values)
|
||||
{
|
||||
cell.gameObject.SetActive(true);
|
||||
var hidden = cell.Icon.color;
|
||||
hidden.a = 0;
|
||||
cell.Icon.color = hidden;
|
||||
}
|
||||
grid.gameObject.SetActive(false);
|
||||
grid.color = Color.clear;
|
||||
var old2 = rig.Render();
|
||||
foreach (var cell in panel.CellInstances.Values) cell.gameObject.SetActive(false);
|
||||
grid.gameObject.SetActive(true);
|
||||
foreach (var cell in oracle.Values) cell.gameObject.SetActive(false);
|
||||
grid.color = Color.white;
|
||||
foreach (var (v, record) in records)
|
||||
{
|
||||
var hiddenRecord = record;
|
||||
|
|
@ -1149,7 +1129,247 @@ public static class InventoryGridParityCapture
|
|||
ClearPage(rig);
|
||||
}
|
||||
|
||||
// ---- The golden ------------------------------------------------------------------------------------------------------
|
||||
// ---- Interaction: pointer events through the grid ----------------------------------------------------------------------
|
||||
|
||||
private static void Check(bool holds, string what)
|
||||
{
|
||||
Log((holds ? "ok " : "FAILED ") + "interact: " + what);
|
||||
if (!holds) Breaches.Add("interact: " + what);
|
||||
}
|
||||
|
||||
private static Rect ScreenRect(Camera camera, 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));
|
||||
}
|
||||
|
||||
// Two prefab panels (equipment and cargo) and a drag parent on one page, an event system, and events sent to the grids with
|
||||
// ExecuteEvents at cell centres: what the input module would send, with the canvas' raycaster as the event module.
|
||||
private static void Interact()
|
||||
{
|
||||
using var fixture = Fixture.Build();
|
||||
using var rig = new Rig(2560);
|
||||
var canvas = rig.Page.GetComponentInParent<Canvas>();
|
||||
var raycaster = canvas.gameObject.AddComponent<GraphicRaycaster>();
|
||||
var eventSystem = new GameObject("Parity event system", typeof(EventSystem)).GetComponent<EventSystem>();
|
||||
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(PrefabPath);
|
||||
var settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset");
|
||||
var dragParent = (RectTransform) new GameObject("Drag parent", typeof(RectTransform)) { layer = rig.Page.gameObject.layer }.transform;
|
||||
dragParent.SetParent(rig.Page, false);
|
||||
|
||||
InventoryPanel MakePanel(float x)
|
||||
{
|
||||
var go = (GameObject) PrefabUtility.InstantiatePrefab(prefab, rig.Page);
|
||||
// Edit mode refuses to reparent a prefab instance's child, which the drag ghost does.
|
||||
PrefabUtility.UnpackPrefabInstance(go, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);
|
||||
var panel = go.GetComponent<InventoryPanel>() ?? go.GetComponentInChildren<InventoryPanel>(true);
|
||||
panel.GameManager = fixture.Manager;
|
||||
if (!panel.Settings) panel.Settings = settings;
|
||||
panel.DragParent = dragParent;
|
||||
panel.NodePrototype.gameObject.SetActive(false);
|
||||
var rect = (RectTransform) panel.transform;
|
||||
rect.anchorMin = rect.anchorMax = new Vector2(.5f, .5f);
|
||||
rect.pivot = new Vector2(.5f, .5f);
|
||||
rect.anchoredPosition = new Vector2(x, 0);
|
||||
rect.sizeDelta = new Vector2(800, 900);
|
||||
dragParent.SetAsLastSibling();
|
||||
return panel;
|
||||
}
|
||||
|
||||
PointerEventData Pointer(GameObject target, Vector2 position, Vector2? press = null)
|
||||
{
|
||||
var hit = new RaycastResult { gameObject = target, module = raycaster };
|
||||
return new PointerEventData(eventSystem)
|
||||
{
|
||||
position = position, pressPosition = press ?? position, button = PointerEventData.InputButton.Left,
|
||||
pointerCurrentRaycast = hit, pointerPressRaycast = hit, pointerEnter = target, pointerPress = target, pointerDrag = target
|
||||
};
|
||||
}
|
||||
Vector2 ScreenOf(InventoryGrid grid, Vector2 gridLocal) => RectTransformUtility.WorldToScreenPoint(rig.Camera, grid.rectTransform.TransformPoint(gridLocal));
|
||||
Vector2 Centre(InventoryGrid grid, int2 v) => ScreenOf(grid, grid.CellRect(v).center);
|
||||
void Layout(InventoryPanel panel)
|
||||
{
|
||||
LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform) panel.Grid.transform.parent);
|
||||
Canvas.ForceUpdateCanvases();
|
||||
}
|
||||
Color32[] RenderAll() => rig.Render();
|
||||
|
||||
try
|
||||
{
|
||||
var ship = fixture.Ship;
|
||||
var hull = fixture.Hull;
|
||||
var equipment = MakePanel(-400);
|
||||
var cargoPanel = MakePanel(500);
|
||||
equipment.Display(ship);
|
||||
Layout(equipment);
|
||||
var grid = equipment.Grid;
|
||||
// The smallest equipped item whose cells are all on the screen with a margin (the hull is taller than the page).
|
||||
bool OnScreen(int2 v)
|
||||
{
|
||||
var r = grid.CellRect(v);
|
||||
var a = ScreenOf(grid, r.min);
|
||||
var b = ScreenOf(grid, r.max);
|
||||
return Mathf.Min(a.x, b.x) > 40 && Mathf.Max(a.x, b.x) < rig.Width - 40 && Mathf.Min(a.y, b.y) > 40 && Mathf.Max(a.y, b.y) < rig.Height - 40;
|
||||
}
|
||||
var equipped = ship.Equipment.Where(e => e.EquippableItem != null)
|
||||
.Where(e => hull.Shape.Inset(e.Data.Shape, e.Position, e.EquippableItem.Rotation).Coordinates.All(OnScreen))
|
||||
.OrderBy(e => e.Data.Shape.Coordinates.Length).First();
|
||||
var item = equipped.EquippableItem;
|
||||
var occupancy = hull.Shape.Inset(equipped.Data.Shape, equipped.Position, item.Rotation);
|
||||
var itemCells = occupancy.Coordinates.ToArray();
|
||||
var other = hull.Shape.AllCoordinates.First(c => hull.Shape[c] && !itemCells.Any(i => i.Equals(c)));
|
||||
Check(grid.GetComponent<ObservablePointerClickTrigger>() && grid.GetComponent<ObservableBeginDragTrigger>(), "an interactive panel's grid carries the triggers its subscriptions added");
|
||||
|
||||
// Clicks: (v, 1), then (v, 2); a press on one cell released on another gives none.
|
||||
var clicks = new List<(int2 cell, int count)>();
|
||||
using (equipment.OnClickAsObservable().Subscribe(e => clicks.Add((e.data.Position, e.clickCount))))
|
||||
{
|
||||
var a = itemCells[0];
|
||||
ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, Centre(grid, a)), ExecuteEvents.pointerClickHandler);
|
||||
Check(clicks.Count == 1 && clicks[0].cell.Equals(a) && clicks[0].count == 1, $"a click on cell {a.x},{a.y} gives ({a.x},{a.y}), 1");
|
||||
ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, Centre(grid, a)), ExecuteEvents.pointerClickHandler);
|
||||
Check(clicks.Count == 2 && clicks[1].cell.Equals(a) && clicks[1].count == 2, "a second click on it gives its count 2");
|
||||
ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, Centre(grid, other), Centre(grid, a)), ExecuteEvents.pointerClickHandler);
|
||||
Check(clicks.Count == 2, "a press on one cell released on another gives no click");
|
||||
}
|
||||
|
||||
// The selection highlight: every item cell draws GetColor(v, true), and the next refresh clears it.
|
||||
equipment.SetHighlight(item, true);
|
||||
var highlighted = itemCells.All(v => Pack(grid.RecordAt(v).Icon) == Pack(equipment.GetColor(v, true)));
|
||||
var distinct = itemCells.All(v => Pack(equipment.GetColor(v, true)) != Pack(equipment.GetColor(v)));
|
||||
Check(highlighted && distinct, "SetHighlight(item, true) draws GetColor(v, true) on each of the item's cells, which differs from GetColor(v)");
|
||||
equipment.RefreshCells();
|
||||
Check(itemCells.All(v => Pack(grid.RecordAt(v).Icon) == Pack(equipment.GetColor(v))), "the next RefreshCells clears the highlight");
|
||||
|
||||
// The panel whose item is dragged over the other panel: a begin drag on an item cell shows the ghost; the pointer moving over a
|
||||
// fitting cell of the cargo panel sets its FakeOccupancy, and leaving clears it.
|
||||
var bay = ship.CargoBays.First();
|
||||
foreach (var stored in bay.Occupancy.Cast<ItemInstance>().Where(i => i != null).Distinct().ToArray()) bay.Remove(stored);
|
||||
cargoPanel.Display(bay);
|
||||
Layout(cargoPanel);
|
||||
var cargoGrid = cargoPanel.Grid;
|
||||
var offset = equipped.Position - itemCells[0];
|
||||
var target = bay.Data.InteriorShape.AllCoordinates.FirstOrDefault(h => bay.Data.InteriorShape[h] && bay.ItemFits(item, h + offset));
|
||||
var fits = bay.Data.InteriorShape[target] && bay.ItemFits(item, target + offset);
|
||||
Check(fits, $"an equipped item fits the emptied bay (item {equipped.Data.Name}, shape {equipped.Data.Shape.Width}x{equipped.Data.Shape.Height}, bay {bay.Data.InteriorShape.Width}x{bay.Data.InteriorShape.Height})");
|
||||
|
||||
if (_mutant == "ghost-full-alpha") equipment.DragGhost.color = Color.white;
|
||||
var press = Centre(grid, itemCells[0]);
|
||||
ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, press), ExecuteEvents.beginDragHandler);
|
||||
var ghost = equipment.DragGhost;
|
||||
Check(ghost.gameObject.activeSelf && ghost.transform.parent == dragParent, $"a begin drag on an item cell activates DragGhost under DragParent (active {ghost.gameObject.activeSelf}, parent {ghost.transform.parent?.name}, DragParent {dragParent.name})");
|
||||
var min = new int2(itemCells.Min(c => c.x), itemCells.Min(c => c.y));
|
||||
var present = Enumerable.Range(0, ghost.Height).SelectMany(y => Enumerable.Range(0, ghost.Width).Select(x => new int2(x, y))).Count(c => ghost.RecordAt(c).Present);
|
||||
Check(itemCells.All(v => ghost.RecordAt(v - min).Present) && present == itemCells.Length, $"the ghost holds the item's {itemCells.Length} cells and no other");
|
||||
Check(itemCells.All(v => equipment.IgnoreOccupancy?[v] ?? false), "the dragged item's cells are ignored (IgnoreOccupancy)");
|
||||
Check(fixture.Manager.DragObject is EquippedItemDragObject, "the drag protocol began with the item");
|
||||
|
||||
// Its rect is the union of the item cells' rects.
|
||||
var union = itemCells.Select(v => PageRect(rig, grid.rectTransform.TransformPoint(grid.CellRect(v).min), grid.rectTransform.TransformPoint(grid.CellRect(v).max))).ToArray();
|
||||
var want = new[] { union.Min(r => r[0]), union.Min(r => r[1]), 0f, 0f };
|
||||
want[2] = union.Max(r => r[0] + r[2]) - want[0];
|
||||
want[3] = union.Max(r => r[1] + r[3]) - want[1];
|
||||
var rectGap = Worst(PageRect(rig, ghost.rectTransform), want);
|
||||
Check(rectGap <= RectBound, $"the ghost's rect is the union of the item's cell rects (worst {rectGap:F5}, bound {RectBound}; ghost {string.Join(",", PageRect(rig, ghost.rectTransform))}, union {string.Join(",", want)})");
|
||||
|
||||
// Its pixels against the sprite cells of the same records at half alpha.
|
||||
Canvas.ForceUpdateCanvases();
|
||||
var withGhost = RenderAll();
|
||||
ghost.gameObject.SetActive(false);
|
||||
var excluded = new List<Rect>();
|
||||
var oracle = new List<GameObject>();
|
||||
foreach (var v in itemCells)
|
||||
{
|
||||
var record = ghost.RecordAt(v - min);
|
||||
var cell = equipment.NodePrototype.Instantiate<InventoryCell>();
|
||||
cell.transform.SetParent(rig.Page, false);
|
||||
var rect = (RectTransform) cell.transform;
|
||||
var at = ghost.CellRect(v - min);
|
||||
rect.anchorMin = rect.anchorMax = Vector2.zero;
|
||||
rect.pivot = Vector2.zero;
|
||||
rect.sizeDelta = at.size;
|
||||
rect.position = ghost.rectTransform.TransformPoint(at.min);
|
||||
cell.Background.sprite = equipment.NodeBackgroundTextures[record.Mask];
|
||||
cell.Icon.sprite = equipment.NodeTextures[record.Mask + (record.Item ? 256 : 0)];
|
||||
Color Half(Color32 c) => new Color(c.r / 255f, c.g / 255f, c.b / 255f, c.a / 255f * .5f);
|
||||
cell.Background.color = Half(record.Background);
|
||||
cell.Icon.color = Half(record.Icon);
|
||||
oracle.Add(cell.gameObject);
|
||||
var iconMask = record.Mask + (record.Item ? 256 : 0);
|
||||
if (record.Mask == 33 || iconMask == 33 || iconMask == 289 || record.Mask == 136 || iconMask == 392) excluded.Add(ScreenRect(rig.Camera, rect));
|
||||
}
|
||||
var withOracle = RenderAll();
|
||||
foreach (var cell in oracle) UnityEngine.Object.DestroyImmediate(cell);
|
||||
var ghostPixels = ScreenRect(rig.Camera, ghost.rectTransform);
|
||||
var worstGhost = 0;
|
||||
var litGhost = 0;
|
||||
for (var y = Mathf.Max(0, Mathf.FloorToInt(ghostPixels.yMin) - 2); y < Mathf.Min(rig.Height, Mathf.CeilToInt(ghostPixels.yMax) + 2); y++)
|
||||
for (var x = Mathf.Max(0, Mathf.FloorToInt(ghostPixels.xMin) - 2); x < Mathf.Min(rig.Width, Mathf.CeilToInt(ghostPixels.xMax) + 2); x++)
|
||||
{
|
||||
if (excluded.Any(r => x + .5f > r.xMin - 2 && x + .5f < r.xMax + 2 && y + .5f > r.yMin - 2 && y + .5f < r.yMax + 2)) continue;
|
||||
worstGhost = Mathf.Max(worstGhost, MaxDifference(withGhost[y * rig.Width + x], withOracle[y * rig.Width + x]));
|
||||
if (withOracle[y * rig.Width + x].r > 20) litGhost++;
|
||||
}
|
||||
Check(worstGhost <= AtlasBound && litGhost > 100, $"the ghost's pixels equal the oracle cells at half alpha (max channel diff {worstGhost}, bound {AtlasBound}, {litGhost} lit pixels judged, {excluded.Count} slip cells not judged, ghost px {ghostPixels})");
|
||||
if (_pngOut != null)
|
||||
SaveSideBySide("interact-ghost.png", rig, withOracle, withGhost, new RectInt(Mathf.Max(0, (int) ghostPixels.xMin - 16), Mathf.Max(0, (int) ghostPixels.yMin - 16), (int) ghostPixels.width + 32, (int) ghostPixels.height + 32));
|
||||
ghost.gameObject.SetActive(true);
|
||||
|
||||
// A drag moves the ghost by the pointer's delta.
|
||||
var before = ghost.rectTransform.position;
|
||||
ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, press + new Vector2(40, -25), press), ExecuteEvents.dragHandler);
|
||||
var moved = ghost.rectTransform.position - before;
|
||||
Check(Vector2.Distance(moved, new Vector2(40, -25)) < .01f && Mathf.Abs(moved.z) < 1e-4f, $"a drag moves the ghost by the pointer's delta (moved {moved})");
|
||||
|
||||
// Over a fitting cell of the other panel: FakeOccupancy; leaving it clears.
|
||||
if (fits)
|
||||
{
|
||||
ExecuteEvents.Execute(cargoGrid.gameObject, Pointer(cargoGrid.gameObject, Centre(cargoGrid, target)), ExecuteEvents.pointerMoveHandler);
|
||||
Check(cargoPanel.FakeItem == item && cargoPanel.FakeOccupancy != null && cargoPanel.FakeOccupancy.Coordinates.Any(), "the pointer moving onto a fitting cell of the other panel sets its FakeOccupancy");
|
||||
ExecuteEvents.Execute(cargoGrid.gameObject, Pointer(cargoGrid.gameObject, Centre(cargoGrid, target)), ExecuteEvents.pointerExitHandler);
|
||||
Check(cargoPanel.FakeItem == null && cargoPanel.FakeOccupancy == null, "the pointer leaving it clears the FakeOccupancy");
|
||||
}
|
||||
ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, press + new Vector2(40, -25), press), ExecuteEvents.endDragHandler);
|
||||
Check(!ghost.gameObject.activeSelf && equipment.IgnoreOccupancy == null && fixture.Manager.DragObject == null, "an end drag deactivates the ghost and ends the drag");
|
||||
|
||||
// The thermal view: a click in the left toggle region of a cell toggles the left conductivity.
|
||||
equipment.Display(ship, false, true);
|
||||
Layout(equipment);
|
||||
var thermal = hull.Shape.AllCoordinates.First(c => hull.Shape[c] && hull.Shape[new int2(c.x - 1, c.y)]);
|
||||
var left = new int2(thermal.x - 1, thermal.y);
|
||||
var wasOn = ship.HullConductivity[left.x, left.y].x;
|
||||
var cell01 = grid.CellRect(thermal);
|
||||
var inRegion = ScreenOf(grid, cell01.min + new Vector2(cell01.width * equipment.ThermalToggleRegionSize * .25f, cell01.height * .5f));
|
||||
ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, inRegion), ExecuteEvents.pointerClickHandler);
|
||||
var toggled = ship.HullConductivity[left.x, left.y].x != wasOn;
|
||||
var drawn = ((grid.RecordAt(thermal).Conductivity & 8) != 0) == ship.HullConductivity[left.x, left.y].x;
|
||||
Check(toggled && drawn, $"a thermal click at the left of cell {thermal.x},{thermal.y} toggles the left conductivity and draws it");
|
||||
ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, inRegion), ExecuteEvents.pointerClickHandler);
|
||||
Check(ship.HullConductivity[left.x, left.y].x == wasOn, "a second thermal click restores it");
|
||||
|
||||
// A HUD panel is not interactive: its grid gets no trigger component.
|
||||
var hud = SceneClone("Canvas/Gameplay/Hud Schematic/Inventory", rig.Page).GetComponent<InventoryPanel>();
|
||||
hud.GameManager = fixture.Manager;
|
||||
if (!hud.Settings) hud.Settings = settings;
|
||||
hud.Display(ship, true);
|
||||
Check(!hud.Interactive && hud.Grid.GetComponents<ObservableTriggerBase>().Length == 0, "a HUD panel (Interactive false) adds no trigger component to its grid");
|
||||
}
|
||||
finally
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(eventSystem.gameObject);
|
||||
UnityEngine.Object.DestroyImmediate(raycaster);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- The live panel against the golden -----------------------------------------------------------------------------
|
||||
|
||||
// The bound on a cell rect or the temperature display's rect against the golden, in page canvas units. The shipped reading is 0 (rects
|
||||
// are the same floats as the sprite panels', or within the float spacing near 1000, 6e-5), taken as 1e-4; mutant temperature-anchor-0
|
||||
// moves the display one cell, 8 units at the HUD's smallest cell. lodur:ruling:deterministic-bound-margin: sqrt(1e-4 x 8) = 0.028.
|
||||
private const float RectBound = .028f;
|
||||
|
||||
[Serializable] private sealed class GoldenCell
|
||||
{
|
||||
|
|
@ -1168,44 +1388,129 @@ public static class InventoryGridParityCapture
|
|||
|
||||
[Serializable] private sealed class Golden { public GoldenState[] states; }
|
||||
|
||||
private static readonly List<GoldenState> GoldenStates = new List<GoldenState>();
|
||||
private static Golden _golden;
|
||||
|
||||
private static Dictionary<int2, CellRecord> LiveRecords(InventoryGrid grid)
|
||||
{
|
||||
var records = new Dictionary<int2, CellRecord>();
|
||||
for (var y = 0; y < grid.Height; y++)
|
||||
for (var x = 0; x < grid.Width; x++)
|
||||
if (grid.RecordAt(new int2(x, y)) is { Present: true } record) records[new int2(x, y)] = record;
|
||||
return records;
|
||||
}
|
||||
|
||||
private static float[] PageRect(Rig rig, Vector3 a, Vector3 b)
|
||||
{
|
||||
var low = rig.Page.InverseTransformPoint(a);
|
||||
var high = rig.Page.InverseTransformPoint(b);
|
||||
return new[] { low.x, low.y, high.x - low.x, high.y - low.y };
|
||||
}
|
||||
|
||||
private static float[] PageRect(Rig rig, RectTransform rect)
|
||||
{
|
||||
var corners = new Vector3[4];
|
||||
rect.GetWorldCorners(corners);
|
||||
var a = rig.Page.InverseTransformPoint(corners[0]);
|
||||
var b = rig.Page.InverseTransformPoint(corners[2]);
|
||||
return new[] { a.x, a.y, b.x - a.x, b.y - a.y };
|
||||
return PageRect(rig, corners[0], corners[2]);
|
||||
}
|
||||
|
||||
private static uint Pack(Color32 c) => (uint) c.r << 24 | (uint) c.g << 16 | (uint) c.b << 8 | c.a;
|
||||
|
||||
private static void RecordGolden(Rig rig, string name, Dictionary<int2, CellRecord> records, Dictionary<int2, RectTransform> rects, RectTransform temperature)
|
||||
private static float Worst(float[] a, float[] b) => a.Zip(b, (p, q) => Mathf.Abs(p - q)).Max();
|
||||
|
||||
// Every live record equals the golden's exactly (mask, present, item, conductivity, icon and background bytes), no other cell is
|
||||
// present, and each cell rect and the temperature display's rect sit within RectBound.
|
||||
private static void CompareGolden(Rig rig, HullState state, InventoryPanel panel, Dictionary<int2, CellRecord> records, int width)
|
||||
{
|
||||
GoldenStates.Add(new GoldenState
|
||||
if (_recordsIn == null) return;
|
||||
_golden ??= JsonUtility.FromJson<Golden>(File.ReadAllText(_recordsIn));
|
||||
var golden = _golden.states.FirstOrDefault(s => s.name == state.Name) ?? throw new InvalidOperationException("No golden state " + state.Name);
|
||||
var grid = panel.Grid;
|
||||
var expected = golden.cells.ToDictionary(c => new int2(c.x, c.y));
|
||||
var wrong = 0;
|
||||
var worstRect = 0f;
|
||||
foreach (var (v, cell) in expected)
|
||||
{
|
||||
name = name,
|
||||
cells = records.OrderBy(p => p.Key.y).ThenBy(p => p.Key.x).Select(p => new GoldenCell
|
||||
var live = records.TryGetValue(v, out var found) ? found : default;
|
||||
var same = records.ContainsKey(v) && live.Mask == cell.mask && live.Present == cell.present && live.Item == cell.item &&
|
||||
live.Conductivity == cell.conductivity && Pack(live.Icon) == cell.icon && Pack(live.Background) == cell.background;
|
||||
if (!same && wrong++ < 6) Log($" golden {state.Name} cell {v.x},{v.y}: live mask {live.Mask} item {live.Item} cond {live.Conductivity} icon {Pack(live.Icon):x8} bg {Pack(live.Background):x8}, golden mask {cell.mask} item {cell.item} cond {cell.conductivity} icon {cell.icon:x8} bg {cell.background:x8}");
|
||||
var rect = grid.CellRect(v);
|
||||
worstRect = Mathf.Max(worstRect, Worst(PageRect(rig, grid.rectTransform.TransformPoint(rect.min), grid.rectTransform.TransformPoint(rect.max)), cell.rect));
|
||||
}
|
||||
var extra = records.Keys.Count(v => !expected.ContainsKey(v));
|
||||
var worstTemperature = 0f;
|
||||
var temperature = "none";
|
||||
if (golden.temperature != null && golden.temperature.Length > 0)
|
||||
{
|
||||
if (!panel.TemperatureDisplay) { worstTemperature = float.PositiveInfinity; temperature = "missing"; }
|
||||
else
|
||||
{
|
||||
x = p.Key.x, y = p.Key.y, mask = p.Value.Mask, conductivity = p.Value.Conductivity, present = p.Value.Present, item = p.Value.Item,
|
||||
icon = Pack(p.Value.Icon), background = Pack(p.Value.Background), rect = PageRect(rig, rects[p.Key])
|
||||
}).ToArray(),
|
||||
temperature = temperature ? PageRect(rig, temperature) : null
|
||||
});
|
||||
worstTemperature = Worst(PageRect(rig, panel.TemperatureDisplay.rectTransform), golden.temperature);
|
||||
temperature = worstTemperature.ToString("F5");
|
||||
}
|
||||
}
|
||||
Log($"golden {state.Name} w={width} cells={records.Count}/{expected.Count} wrongRecords={wrong} extraCells={extra} worstRect={worstRect:F5} temperatureRect={temperature} (bound {RectBound})");
|
||||
if (wrong > 0 || extra > 0) Breaches.Add($"golden {state.Name} w={width}: {wrong} records differ, {extra} extra cells");
|
||||
if (worstRect > RectBound) Breaches.Add($"golden {state.Name} w={width}: cell rect {worstRect:F5} > {RectBound}");
|
||||
if (worstTemperature > RectBound) Breaches.Add($"golden {state.Name} w={width}: temperature rect {temperature} > {RectBound}");
|
||||
}
|
||||
|
||||
private static void WriteGolden()
|
||||
// The look mutants of the new path, applied to the live panel's grid; flip-ignored lays the enemy grid out unflipped.
|
||||
private static void MutateLook(InventoryPanel panel, HullState state)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(_recordsOut))!);
|
||||
File.WriteAllText(_recordsOut, JsonUtility.ToJson(new Golden { states = GoldenStates.ToArray() }, true));
|
||||
Log($"golden written to {_recordsOut}: {GoldenStates.Count} states, {GoldenStates.Sum(s => s.cells.Length)} cells");
|
||||
var grid = panel.Grid;
|
||||
switch (_mutant)
|
||||
{
|
||||
case "rule-inset-2": grid.RuleInset = 2f; break;
|
||||
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;
|
||||
case "icon-multiplier-1": grid.IconTexel = InventoryGrid.TexelOf(66f, 1f); break;
|
||||
case "flip-ignored" when state.Enemy:
|
||||
grid.Resize(grid.Width, grid.Height, grid.CellSize, grid.Padding, GridOrientation.LowerLeft);
|
||||
panel.RefreshCells();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// The branches of RefreshCells the states reach: a hardpoint cell, an interior cell with an item, an empty interior cell, an exterior
|
||||
// cell, a cell shown as the fake occupancy, a cell ignored as the drag's source. Each must be reached by some state.
|
||||
private static readonly Dictionary<string, int> Branches = new[] { "hardpoint", "interior with item", "interior empty", "exterior", "fake", "ignored" }.ToDictionary(n => n, _ => 0);
|
||||
|
||||
private static void CountBranches(Fixture fixture, InventoryPanel panel, HullState state, Dictionary<int2, CellRecord> records)
|
||||
{
|
||||
var counts = Branches.Keys.ToDictionary(n => n, _ => 0);
|
||||
void Count(string branch) { counts[branch]++; Branches[branch]++; }
|
||||
foreach (var (v, record) in records)
|
||||
{
|
||||
if (state.Cargo)
|
||||
{
|
||||
Count(record.Item ? "interior with item" : "interior empty");
|
||||
}
|
||||
else if (fixture.Ship.Hardpoints[v.x, v.y] != null) Count("hardpoint");
|
||||
else if (fixture.Hull.InteriorCells[v]) Count(record.Item ? "interior with item" : "interior empty");
|
||||
else Count("exterior");
|
||||
if (panel.FakeOccupancy?[v] ?? false) Count("fake");
|
||||
if (panel.IgnoreOccupancy?[v] ?? false) Count("ignored");
|
||||
}
|
||||
Log($"branches {state.Name}: " + string.Join(", ", counts.Select(c => $"{c.Key} {c.Value}")));
|
||||
}
|
||||
|
||||
private static void CheckBranchCounts()
|
||||
{
|
||||
foreach (var (branch, count) in Branches)
|
||||
if (count == 0) Breaches.Add($"no state reached the {branch} branch of RefreshCells");
|
||||
}
|
||||
|
||||
// old | new | abs difference x 8, cropped to the region.
|
||||
private static void SaveSideBySide(string name, Rig rig, Color32[] old, Color32[] fresh, RectInt region)
|
||||
{
|
||||
if (_pngOut == null) return;
|
||||
var x1 = Mathf.Min(rig.Width, region.x + region.width);
|
||||
var y1 = Mathf.Min(rig.Height, region.y + region.height);
|
||||
region = new RectInt(Mathf.Max(0, region.x), Mathf.Max(0, region.y), x1 - Mathf.Max(0, region.x), y1 - Mathf.Max(0, region.y));
|
||||
if (region.width <= 0 || region.height <= 0) throw new InvalidOperationException($"{name}: the region {region} lies outside the {rig.Width}x{rig.Height} frame.");
|
||||
var output = new Texture2D(region.width * 3, region.height, TextureFormat.RGBA32, false);
|
||||
var pixels = new Color32[region.width * 3 * region.height];
|
||||
for (var y = 0; y < region.height; y++)
|
||||
|
|
|
|||
Loading…
Reference in a new issue