Inventory grid, parked: UI/Inventory Grid shader, InventoryGrid graphic, atlas and thermal parity harness against the Nodes8 sheets

The shader draws a panel's cells from one RGBA32 record texture as texel-box shapes through the nine-slice remap (map IG-B3, IG-G).
The harness renders every mask 0..511 through the sprite cells and through the grid at 1920 and 2560 and compares them.
The background sheet is 100 pixels per unit, not 66 (IG-B1 states 66 for both): BgTexel is 1 canvas unit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-29 22:24:57 +01:00
commit 872b4bd3c4
6 changed files with 988 additions and 0 deletions

View file

@ -0,0 +1,488 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
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>] -logFile <log>
//
// 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.
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;
private static string _mutant = "";
private static string _pngOut;
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"
};
private static void Log(string line) => Debug.Log("[InventoryGridParity] " + line);
public static void Run()
{
try
{
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");
_mutant = Arg("-mutant") ?? "";
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);
if (Breaches.Count > 0)
{
foreach (var breach in Breaches) Log("BOUND BREACHED " + breach);
EditorApplication.Exit(1);
return;
}
Log("PASS");
EditorApplication.Exit(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
EditorApplication.Exit(1);
}
}
// A camera canvas at the real CanvasScaler settings, drawn to a texture of (width, height) pixels.
private sealed class Rig : IDisposable
{
public readonly int Width, Height;
public readonly float Scale;
public readonly RectTransform Page;
private readonly GameObject _root, _cameraObject;
private readonly Camera _camera;
private readonly RenderTexture _target;
private readonly Canvas _canvas;
public Rig(int width)
{
Width = width;
Height = width * 9 / 16;
Scale = width / 1920f;
_root = new GameObject("Parity canvas", typeof(RectTransform)) { layer = LayerMask.NameToLayer("UI") };
_cameraObject = new GameObject("Parity camera");
_camera = _cameraObject.AddComponent<Camera>();
_camera.orthographic = true;
_camera.orthographicSize = 5;
_camera.clearFlags = CameraClearFlags.SolidColor;
_camera.backgroundColor = new Color(0, 0, 0, 0);
_camera.cullingMask = 1 << LayerMask.NameToLayer("UI");
_target = new RenderTexture(Width, Height, 24, RenderTextureFormat.ARGB32);
_camera.targetTexture = _target;
_canvas = _root.AddComponent<Canvas>();
_canvas.renderMode = RenderMode.ScreenSpaceCamera;
_canvas.worldCamera = _camera;
_canvas.planeDistance = 10;
_canvas.vertexColorAlwaysGammaSpace = false;
var scaler = _root.AddComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1920, 1080);
scaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
scaler.matchWidthOrHeight = 0;
scaler.referencePixelsPerUnit = 100;
typeof(CanvasScaler).GetMethod("Handle", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(scaler, null);
Canvas.ForceUpdateCanvases();
var rect = ((RectTransform) _root.transform).rect;
if (Mathf.Abs(rect.width - 1920) > .01f || Mathf.Abs(_canvas.scaleFactor - Scale) > .001f)
throw new InvalidOperationException($"Canvas {rect.size} scale {_canvas.scaleFactor}, want 1920 wide at {Scale}.");
var page = new GameObject("Page", typeof(RectTransform)) { layer = _root.layer };
Page = (RectTransform) page.transform;
Page.SetParent(_root.transform, false);
Page.anchorMin = Vector2.zero;
Page.anchorMax = Vector2.one;
Page.offsetMin = Page.offsetMax = Vector2.zero;
}
public Color32[] Render()
{
Canvas.ForceUpdateCanvases();
foreach (var grid in Page.GetComponentsInChildren<InventoryGrid>()) grid.Flush();
_camera.Render();
var previous = RenderTexture.active;
RenderTexture.active = _target;
var read = new Texture2D(Width, Height, TextureFormat.RGBA32, false);
read.ReadPixels(new Rect(0, 0, Width, Height), 0, 0);
RenderTexture.active = previous;
var pixels = read.GetPixels32();
UnityEngine.Object.DestroyImmediate(read);
return pixels;
}
public void Dispose()
{
UnityEngine.Object.DestroyImmediate(_root);
UnityEngine.Object.DestroyImmediate(_cameraObject);
UnityEngine.Object.DestroyImmediate(_target);
}
}
private sealed class Oracle : IDisposable
{
public readonly GameObject PanelObject;
public readonly InventoryPanel Panel;
public Oracle()
{
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(PrefabPath) ?? throw new InvalidOperationException("No " + PrefabPath);
PanelObject = (GameObject) PrefabUtility.InstantiatePrefab(prefab);
Panel = PanelObject.GetComponent<InventoryPanel>() ?? PanelObject.GetComponentInChildren<InventoryPanel>(true);
}
public void Dispose() => UnityEngine.Object.DestroyImmediate(PanelObject);
}
private static Shader GridShader() => AssetDatabase.LoadAssetAtPath<Shader>(ShaderPath) ?? throw new InvalidOperationException("No " + ShaderPath);
// The look of the new path with the named mutant applied.
private static void Look(InventoryGrid grid, float iconMultiplier)
{
grid.Shader = GridShader();
grid.IconTexel = InventoryGrid.TexelOf(66f, _mutant == "icon-multiplier-1" ? 1f : iconMultiplier);
grid.BgTexel = InventoryGrid.TexelOf(100f, 1f);
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;
}
}
private static GameObject NewObject(string name, RectTransform parent, float x, float y, float size)
{
var go = new GameObject(name, typeof(RectTransform)) { layer = parent.gameObject.layer };
var rect = (RectTransform) go.transform;
rect.SetParent(parent, false);
rect.anchorMin = rect.anchorMax = Vector2.zero;
rect.pivot = Vector2.zero;
rect.anchoredPosition = new Vector2(x, y);
rect.sizeDelta = new Vector2(size, size);
return go;
}
private struct Regime
{
public string Name;
public float Size, IconMultiplier;
}
private static readonly Regime[] Regimes =
{
new Regime { Name = "S32m1", Size = 32, IconMultiplier = 1f },
new Regime { Name = "S16m1.5", Size = 16, IconMultiplier = 1.5f },
new Regime { Name = "S10m1.5", Size = 10, IconMultiplier = 1.5f },
new Regime { Name = "S6m1.5", Size = 6, IconMultiplier = 1.5f },
};
// Icon and background colour of the three passes: white over the menu's background, a hardpoint tint times .7071 over the
// HUD's, grey .25 over a non-black pulse colour.
private static readonly (Color icon, Color bg)[] Passes =
{
(Color.white, new Color(0, 0, 0, .902f)),
(new Color(.9f, .45f, .15f) * .7071f, new Color(0, 0, 0, .949f)),
(new Color(.25f, .25f, .25f), new Color(.6f, .2f, .1f, .8f)),
};
private static int MaxDifference(Color32 a, Color32 b) => Mathf.Max(Mathf.Abs(a.r - b.r), Mathf.Abs(a.g - b.g), Mathf.Abs(a.b - b.b));
private static void Atlas()
{
using var oracle = new Oracle();
var panel = oracle.Panel;
// The texel constants rest on the sheets' pixels per unit (map IG-B1 states 66 for both; the background sheet is 100).
var iconPpu = panel.NodeTextures[0].pixelsPerUnit;
var bgPpu = panel.NodeBackgroundTextures[0].pixelsPerUnit;
Log($"sheets pixelsPerUnit icon={iconPpu} background={bgPpu}");
if (iconPpu != 66f || bgPpu != 100f) Breaches.Add($"sheet pixels per unit {iconPpu} / {bgPpu}, want 66 / 100");
foreach (var width in new[] { 1920, 2560 })
using (var rig = new Rig(width))
foreach (var regime in Regimes)
{
var stride = regime.Size + 8f;
const int columns = 32;
for (var pass = 0; pass < Passes.Length; pass++)
{
var (iconColor, bgColor) = Passes[pass];
// Old: one two-image cell per mask, the sheet's own sprites.
ClearPage(rig);
var cells = new List<GameObject>();
for (var m = 0; m < 512; m++)
{
var cell = UnityEngine.Object.Instantiate(panel.NodePrototype.gameObject, rig.Page, false);
cell.SetActive(true);
var rect = (RectTransform) cell.transform;
rect.anchorMin = rect.anchorMax = Vector2.zero;
rect.pivot = Vector2.zero;
rect.anchoredPosition = new Vector2(8 + m % columns * stride, 8 + m / columns * stride);
rect.sizeDelta = new Vector2(regime.Size, regime.Size);
var node = cell.GetComponent<InventoryCell>();
node.Background.sprite = panel.NodeBackgroundTextures[m & 255];
node.Background.color = bgColor;
node.Icon.sprite = panel.NodeTextures[m];
node.Icon.pixelsPerUnitMultiplier = regime.IconMultiplier;
node.Icon.color = iconColor;
cells.Add(cell);
}
var old = rig.Render();
ClearPage(rig);
// New: one grid per mask at the same rects, fed the same record.
for (var m = 0; m < 512; m++)
{
var go = NewObject("Grid " + m, rig.Page, 8 + m % columns * stride, 8 + m / columns * stride, regime.Size);
var grid = go.AddComponent<InventoryGrid>();
Look(grid, regime.IconMultiplier);
grid.Resize(1, 1, regime.Size, new RectOffset(), GridOrientation.LowerLeft);
grid.SetCell(new int2(0, 0), new CellRecord
{
Mask = (byte) (m & 255), Present = true, Item = m >= 256, Icon = iconColor, Background = bgColor
});
}
var fresh = rig.Render();
// Judge each cell's pixels; masks 33 and 289 are judged outside their authoring-slip footprint (IG-B3).
var worst = 0;
var worstMask = -1;
var slip = 0;
var pad = 0;
for (var m = 0; m < 512; m++)
{
var x0 = Mathf.Max(0, Mathf.FloorToInt((8 + m % columns * stride) * rig.Scale) - 2);
var y0 = Mathf.Max(0, Mathf.FloorToInt((8 + m / columns * stride) * rig.Scale) - 2);
var x1 = Mathf.CeilToInt((8 + m % columns * stride + regime.Size) * rig.Scale) + 2;
var y1 = Mathf.CeilToInt((8 + m / columns * stride + regime.Size) * rig.Scale) + 2;
var cellTop = (8 + m / columns * stride + regime.Size) * rig.Scale;
var tMin = Mathf.Min(InventoryGrid.TexelOf(66f, regime.IconMultiplier), InventoryGrid.TexelOf(100f, 1f));
var tMax = Mathf.Max(InventoryGrid.TexelOf(66f, regime.IconMultiplier), InventoryGrid.TexelOf(100f, 1f));
var isSlip = m == 33 || m == 289;
// Nodes8_392 and Nodes8BG_136 carry a wrong pad on their top and bottom edge (columns 5 to 8 read 0 where the
// sprite's own edge is filled), so the oracle itself bleeds there; half a texel and a pixel of each edge is not judged.
var isPad = m == 136 || m == 392;
var cellBottom = (8 + m / columns * stride) * rig.Scale;
for (var y = y0; y < y1; y++)
for (var x = x0; x < x1; x++)
{
var i = y * rig.Width + x;
var diff = MaxDifference(old[i], fresh[i]);
if (isPad)
{
var edge = Mathf.Min(cellTop - (y + .5f), y + .5f - cellBottom) / rig.Scale;
if (edge < .5f * tMax + 1.5f) { pad = Mathf.Max(pad, diff); continue; }
}
if (isSlip)
{
var fromTop = (cellTop - (y + .5f)) / rig.Scale;
if (fromTop > 1.5f * tMin - 1.5f && fromTop < 3.5f * tMax + 1.5f) { slip = Mathf.Max(slip, diff); continue; }
}
if (diff > worst) { worst = diff; worstMask = m; }
}
}
Log($"atlas {regime.Name} w={width} pass={pass} max8bitDiff={worst} (mask {worstMask}) slipFootprintMax={slip} padSlipMax={pad}");
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)));
_ = cells;
}
}
}
private static void ClearPage(Rig rig)
{
for (var i = rig.Page.childCount - 1; i >= 0; i--) UnityEngine.Object.DestroyImmediate(rig.Page.GetChild(i).gameObject);
}
// Thermal pipes: the 16 pipe sprites against the grid's blob and capsules, icon layer only. With -fitThermal the four look
// parameters are first fitted to the sprites by least squares (Nelder-Mead on the squared difference of both sizes) and printed.
private static void Thermal(bool fit)
{
using var oracle = new Oracle();
var panel = oracle.Panel;
const float stride = 48;
var sizes = new[] { 32f, 16f };
var rigs = sizes.Select(_ => new Rig(1920)).ToArray();
var olds = new Color32[sizes.Length][];
for (var k = 0; k < sizes.Length; k++)
{
var rig = rigs[k];
ClearPage(rig);
for (var m = 0; m < 16; m++)
{
var cell = UnityEngine.Object.Instantiate(panel.NodePrototype.gameObject, rig.Page, false);
cell.SetActive(true);
var rect = (RectTransform) cell.transform;
rect.anchorMin = rect.anchorMax = Vector2.zero;
rect.pivot = Vector2.zero;
rect.anchoredPosition = new Vector2(8 + m * stride, 8);
rect.sizeDelta = new Vector2(sizes[k], sizes[k]);
var node = cell.GetComponent<InventoryCell>();
node.Background.color = new Color(0, 0, 0, 0);
node.Icon.sprite = panel.ThermalTextures[m];
node.Icon.color = Color.white;
}
olds[k] = rig.Render();
ClearPage(rig);
}
var grids = new InventoryGrid[sizes.Length][];
for (var k = 0; k < sizes.Length; k++)
{
grids[k] = new InventoryGrid[16];
for (var m = 0; m < 16; m++)
{
var grid = NewObject("Pipes " + m, rigs[k].Page, 8 + m * stride, 8, sizes[k]).AddComponent<InventoryGrid>();
Look(grid, 1f);
grid.Thermal = true;
grid.Resize(1, 1, sizes[k], new RectOffset(), GridOrientation.LowerLeft);
grid.SetCell(new int2(0, 0), new CellRecord
{
Mask = 0, Present = true, Item = false, Conductivity = (byte) m, Icon = Color.white, Background = new Color(0, 0, 0, 0)
});
grids[k][m] = grid;
}
}
double[] Rms(int k, Color32[] fresh)
{
var result = new double[16];
for (var m = 0; m < 16; m++)
{
double sum = 0;
var n = 0;
for (var y = 6; y < 8 + sizes[k] + 2; y++)
for (var x = 8 + m * (int) stride - 2; x < 8 + m * (int) stride + sizes[k] + 2; x++)
{
var i = y * rigs[k].Width + x;
var d = (olds[k][i].r - fresh[i].r) / 255.0;
sum += d * d;
n++;
}
result[m] = Math.Sqrt(sum / n);
}
return result;
}
void Apply(double[] p)
{
foreach (var row in grids)
foreach (var grid in row)
{
grid.BlobRadius = (float) p[0];
grid.PipeHalfWidth = (float) p[1];
grid.Fillet = (float) p[2];
grid.PipeSoft = (float) p[3];
grid.SetMaterialDirty();
}
}
double Cost(double[] p)
{
Apply(p);
double total = 0;
for (var k = 0; k < sizes.Length; k++) total += Rms(k, rigs[k].Render()).Sum(r => r * r);
return total;
}
var best = new double[] { grids[0][0].BlobRadius, grids[0][0].PipeHalfWidth, grids[0][0].Fillet, grids[0][0].PipeSoft };
if (fit)
{
var simplex = new double[5][];
var cost = new double[5];
for (var i = 0; i < 5; i++)
{
simplex[i] = (double[]) best.Clone();
if (i > 0) simplex[i][i - 1] *= 1.15;
cost[i] = Cost(simplex[i]);
}
for (var iteration = 0; iteration < 120; iteration++)
{
var order = Enumerable.Range(0, 5).OrderBy(i => cost[i]).ToArray();
simplex = order.Select(i => simplex[i]).ToArray();
cost = order.Select(i => cost[i]).ToArray();
var centroid = new double[4];
for (var i = 0; i < 4; i++) for (var d = 0; d < 4; d++) centroid[d] += simplex[i][d] / 4;
double[] Along(double t) => Enumerable.Range(0, 4).Select(d => Math.Max(1e-3, centroid[d] + t * (simplex[4][d] - centroid[d]))).ToArray();
var reflected = Along(-1);
var reflectedCost = Cost(reflected);
if (reflectedCost < cost[0])
{
var expanded = Along(-2);
var expandedCost = Cost(expanded);
if (expandedCost < reflectedCost) { simplex[4] = expanded; cost[4] = expandedCost; }
else { simplex[4] = reflected; cost[4] = reflectedCost; }
}
else if (reflectedCost < cost[3]) { simplex[4] = reflected; cost[4] = reflectedCost; }
else
{
var contracted = Along(.5);
var contractedCost = Cost(contracted);
if (contractedCost < cost[4]) { simplex[4] = contracted; cost[4] = contractedCost; }
else
for (var i = 1; i < 5; i++)
{
for (var d = 0; d < 4; d++) simplex[i][d] = simplex[0][d] + .5 * (simplex[i][d] - simplex[0][d]);
cost[i] = Cost(simplex[i]);
}
}
}
var bestIndex = Enumerable.Range(0, 5).OrderBy(i => cost[i]).First();
best = simplex[bestIndex];
Log($"thermal fit BlobRadius={best[0]:F4} PipeHalfWidth={best[1]:F4} Fillet={best[2]:F4} PipeSoft={best[3]:F4} cost={cost[bestIndex]:F5}");
}
Apply(best);
for (var k = 0; k < sizes.Length; k++)
{
var fresh = rigs[k].Render();
var rms = Rms(k, fresh);
var worst = rms.Max();
Log($"thermal S{sizes[k]} worstRms={worst:F4} (mask {Array.IndexOf(rms, 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();
}
// 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 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++)
for (var x = 0; x < region.width; x++)
{
var i = (region.y + y) * rig.Width + region.x + x;
Color32 Over(Color32 c) => new Color32(c.r, c.g, c.b, 255);
pixels[y * region.width * 3 + x] = Over(old[i]);
pixels[y * region.width * 3 + region.width + x] = Over(fresh[i]);
pixels[y * region.width * 3 + 2 * region.width + x] = new Color32(
(byte) Mathf.Min(255, 8 * Mathf.Abs(old[i].r - fresh[i].r)), (byte) Mathf.Min(255, 8 * Mathf.Abs(old[i].g - fresh[i].g)),
(byte) Mathf.Min(255, 8 * Mathf.Abs(old[i].b - fresh[i].b)), 255);
}
output.SetPixels32(pixels);
File.WriteAllBytes(Path.Combine(_pngOut, name), output.EncodeToPNG());
UnityEngine.Object.DestroyImmediate(output);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: dd00afc599e4d704696448c5fec05990