From 872b4bd3c45f9713afdee069b44bf40e7b4e8255 Mon Sep 17 00:00:00 2001 From: soul Date: Sun, 29 Nov 2026 22:24:57 +0100 Subject: [PATCH] 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 --- .../Editor/InventoryGridParityCapture.cs | 488 ++++++++++++++++++ .../Editor/InventoryGridParityCapture.cs.meta | 2 + Assets/Scripts/UI/Menu/InventoryGrid.cs | 238 +++++++++ Assets/Scripts/UI/Menu/InventoryGrid.cs.meta | 12 + Assets/Shaders/InventoryGrid.shader | 239 +++++++++ Assets/Shaders/InventoryGrid.shader.meta | 9 + 6 files changed, 988 insertions(+) create mode 100644 Assets/Scripts/Editor/InventoryGridParityCapture.cs create mode 100644 Assets/Scripts/Editor/InventoryGridParityCapture.cs.meta create mode 100644 Assets/Scripts/UI/Menu/InventoryGrid.cs create mode 100644 Assets/Scripts/UI/Menu/InventoryGrid.cs.meta create mode 100644 Assets/Shaders/InventoryGrid.shader create mode 100644 Assets/Shaders/InventoryGrid.shader.meta diff --git a/Assets/Scripts/Editor/InventoryGridParityCapture.cs b/Assets/Scripts/Editor/InventoryGridParityCapture.cs new file mode 100644 index 000000000..26f2fdba7 --- /dev/null +++ b/Assets/Scripts/Editor/InventoryGridParityCapture.cs @@ -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 -executeMethod InventoryGridParityCapture.Run [-pngOut ] [-mutant ] -logFile +// +// 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 Breaches = new List(); + + 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.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.renderMode = RenderMode.ScreenSpaceCamera; + _canvas.worldCamera = _camera; + _canvas.planeDistance = 10; + _canvas.vertexColorAlwaysGammaSpace = false; + var scaler = _root.AddComponent(); + 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()) 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(PrefabPath) ?? throw new InvalidOperationException("No " + PrefabPath); + PanelObject = (GameObject) PrefabUtility.InstantiatePrefab(prefab); + Panel = PanelObject.GetComponent() ?? PanelObject.GetComponentInChildren(true); + } + public void Dispose() => UnityEngine.Object.DestroyImmediate(PanelObject); + } + + private static Shader GridShader() => AssetDatabase.LoadAssetAtPath(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(); + 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(); + 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(); + 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(); + 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(); + 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); + } +} diff --git a/Assets/Scripts/Editor/InventoryGridParityCapture.cs.meta b/Assets/Scripts/Editor/InventoryGridParityCapture.cs.meta new file mode 100644 index 000000000..7fa26f97e --- /dev/null +++ b/Assets/Scripts/Editor/InventoryGridParityCapture.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: dd00afc599e4d704696448c5fec05990 \ No newline at end of file diff --git a/Assets/Scripts/UI/Menu/InventoryGrid.cs b/Assets/Scripts/UI/Menu/InventoryGrid.cs new file mode 100644 index 000000000..a018910b3 --- /dev/null +++ b/Assets/Scripts/UI/Menu/InventoryGrid.cs @@ -0,0 +1,238 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using UnityEngine; +using UnityEngine.UI; +using int2 = CultMath.int2; + +// What one cell of an inventory panel draws: the 8-bit edge mask in InventoryPanel's _offsets order (bit 0 up, 1 right, 2 down, +// 3 left, then the four diagonals), whether the cell exists, whether an item sits in it, the 4 conductivity bits of the thermal +// view (up, right, down, left), and the two layer colours as a Graphic's vertex colour (gamma bytes). The panel's match rules +// produce these; the grid only draws them. +public struct CellRecord +{ + public byte Mask; + public bool Present; + public bool Item; + public byte Conductivity; + public Color32 Icon; + public Color32 Background; +} + +public enum GridOrientation { LowerLeft, UpperRight } + +// One quad that draws a whole inventory panel's cells through UI/Inventory Grid (map section IG). It owns the layout of the +// cells, their pixels and the point-to-cell mapping, and decides nothing about a panel: SetCell is the one write path. +// The record texture is a cache of what SetCell was given and is never read back as truth. +[RequireComponent(typeof(CanvasRenderer))] +public class InventoryGrid : MaskableGraphic, ILayoutElement, ICanvasRaycastFilter +{ + public Shader Shader; + + // Look, in texels of the sheet sprite; the shader's constants (IG-G). + public float RuleInset = 1.5f, RuleWidth = 1f, ArmTexels = 1f, FillInset = 3f, Softness = 1f; + public float RuleAlpha = .2f, BracketAlpha = 1f, FillAlpha = 13f / 255f; + // Thermal pipes as fractions of the cell, fitted to the 16 pipe sprites by the parity harness (-fitThermal; IG-B4). + public float BlobRadius = .1157f, PipeHalfWidth = .1257f, Fillet = .0245f, PipeSoft = .0697f; + // One texel of the sheet sprite in canvas units, per layer. The icon sheet is 66 pixels per unit: 1.51515 at multiplier 1, + // 1.01010 at 1.5. The background sheet is 100: 1 at multiplier 1. + public float IconTexel = TexelOf(66f, 1f), BgTexel = TexelOf(100f, 1f); + public bool Thermal; + + private int _width, _height; + private float _cellSize = 32; + private RectOffset _padding = new RectOffset(); + private GridOrientation _orientation; + private Color32[] _records = new Color32[0]; + private Texture2D _texture; + private bool _dirty; + private Material _material; + + // A texel of a sliced sprite in canvas units, as Image computes it: the canvas reference is 100 pixels per unit. + public static float TexelOf(float spritePixelsPerUnit, float multiplier) => 100f / (spritePixelsPerUnit * multiplier); + + public int Width => _width; + public int Height => _height; + public float CellSize => _cellSize; + public GridOrientation Orientation => _orientation; + public override Texture mainTexture => _texture; + + public void Resize(int width, int height, float cellSize, RectOffset padding, GridOrientation orientation) + { + _cellSize = cellSize; + _padding = padding; + _orientation = orientation; + if (width != _width || height != _height || !_texture) + { + _width = width; + _height = height; + if (_texture) DestroyTexture(); + _texture = new Texture2D(Mathf.Max(3 * width, 1), Mathf.Max(height, 1), TextureFormat.RGBA32, false, true) + { + filterMode = FilterMode.Point, wrapMode = TextureWrapMode.Clamp, hideFlags = HideFlags.HideAndDontSave + }; + _records = new Color32[_texture.width * _texture.height]; + } + else System.Array.Clear(_records, 0, _records.Length); + _dirty = true; + SetAllDirty(); + } + + public void Clear() + { + System.Array.Clear(_records, 0, _records.Length); + _dirty = true; + } + + public void SetCell(int2 cell, CellRecord record) + { + if (cell.x < 0 || cell.y < 0 || cell.x >= _width || cell.y >= _height) return; + var at = cell.y * 3 * _width + 3 * cell.x; + _records[at] = record.Icon; + _records[at + 1] = record.Background; + _records[at + 2] = new Color32(record.Mask, (byte) ((record.Present ? 1 : 0) | (record.Item ? 2 : 0)), (byte) (record.Conductivity & 15), 0); + _dirty = true; + } + + // Uploads the records when any changed. Once per frame is the contract; edit-mode callers flush by hand. + public void Flush() + { + if (!_dirty || !_texture) return; + _texture.SetPixelData(_records, 0); + _texture.Apply(false); + _dirty = false; + } + + private void LateUpdate() => Flush(); + + // The block of cells inside this rect as GridLayoutGroup places a middle-centre block with this padding. + private Rect Block() + { + var rect = rectTransform.rect; + var size = new Vector2(_width, _height) * _cellSize; + var x = rect.xMin + _padding.left + (rect.width - _padding.horizontal - size.x) * .5f; + var top = rect.yMax - _padding.top - (rect.height - _padding.vertical - size.y) * .5f; + return new Rect(x, top - size.y, size.x, size.y); + } + + protected override void OnPopulateMesh(VertexHelper vh) + { + vh.Clear(); + if (_width == 0 || _height == 0) return; + var b = Block(); + var extent = new Vector2(b.width, b.height); + var flip = _orientation == GridOrientation.UpperRight; + UIVertex Vertex(float x, float y) + { + var u = new Vector2(x - b.xMin, y - b.yMin); + if (flip) u = extent - u; + return new UIVertex { position = new Vector3(x, y), color = color, uv0 = u }; + } + vh.AddVert(Vertex(b.xMin, b.yMin)); + vh.AddVert(Vertex(b.xMin, b.yMax)); + vh.AddVert(Vertex(b.xMax, b.yMax)); + vh.AddVert(Vertex(b.xMax, b.yMin)); + vh.AddTriangle(0, 1, 2); + vh.AddTriangle(2, 3, 0); + } + + public override void SetMaterialDirty() + { + PushUniforms(); + base.SetMaterialDirty(); + } + + protected override void UpdateMaterial() + { + PushUniforms(); + base.UpdateMaterial(); + } + + private void PushUniforms() + { + if (!Shader) return; + if (!_material || _material.shader != Shader) + { + if (_material) DestroyImmediate(_material); + _material = new Material(Shader) { hideFlags = HideFlags.HideAndDontSave }; + } + if (m_Material != _material) m_Material = _material; + var m = _material; + m.SetVector("_GridCells", new Vector4(_width, _height, 0, 0)); + m.SetFloat("_CellSize", _cellSize); + m.SetFloat("_Flip", _orientation == GridOrientation.UpperRight ? 1 : 0); + m.SetFloat("_Thermal", Thermal ? 1 : 0); + m.SetFloat("_IconTexel", IconTexel); + m.SetFloat("_BgTexel", BgTexel); + m.SetFloat("_RuleInset", RuleInset); + m.SetFloat("_RuleWidth", RuleWidth); + m.SetFloat("_ArmTexels", ArmTexels); + m.SetFloat("_FillInset", FillInset); + m.SetFloat("_Softness", Softness); + m.SetFloat("_RuleAlpha", RuleAlpha); + m.SetFloat("_BracketAlpha", BracketAlpha); + m.SetFloat("_FillAlpha", FillAlpha); + m.SetFloat("_BlobRadius", BlobRadius); + m.SetFloat("_PipeHalfWidth", PipeHalfWidth); + m.SetFloat("_Fillet", Fillet); + m.SetFloat("_PipeSoft", PipeSoft); + } + + // The cell under a screen point and where in it (0..1, screen-aligned, y up), or false outside the block. + public bool CellAt(Vector2 screen, Camera camera, out int2 cell, out Vector2 inCell01) + { + cell = default; + inCell01 = default; + if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screen, camera, out var local)) return false; + var b = Block(); + var g = local - b.min; + if (_orientation == GridOrientation.UpperRight) g = new Vector2(b.width, b.height) - g; + var f = g / _cellSize; + var c = new int2(Mathf.FloorToInt(f.x), Mathf.FloorToInt(f.y)); + if (c.x < 0 || c.y < 0 || c.x >= _width || c.y >= _height) return false; + cell = c; + var within = new Vector2(f.x - c.x, f.y - c.y); + inCell01 = _orientation == GridOrientation.UpperRight ? Vector2.one - within : within; + return true; + } + + // The cell's rect in this rect's local space; defined for cells outside the grid too (the temperature display sits at (-1, -1)). + public Rect CellRect(int2 cell) + { + var b = Block(); + return _orientation == GridOrientation.UpperRight + ? new Rect(b.xMax - (cell.x + 1) * _cellSize, b.yMax - (cell.y + 1) * _cellSize, _cellSize, _cellSize) + : new Rect(b.xMin + cell.x * _cellSize, b.yMin + cell.y * _cellSize, _cellSize, _cellSize); + } + + // Empty cells pass the click through to whatever lies behind, as the panel background does today. + public bool IsRaycastLocationValid(Vector2 screen, Camera camera) + { + if (!CellAt(screen, camera, out var cell, out _)) return false; + return (_records[cell.y * 3 * _width + 3 * cell.x + 2].g & 1) != 0; + } + + public float minWidth => _padding.horizontal + _width * _cellSize; + public float preferredWidth => minWidth; + public float flexibleWidth => -1; + public float minHeight => _padding.vertical + _height * _cellSize; + public float preferredHeight => minHeight; + public float flexibleHeight => -1; + public int layoutPriority => 1; + public void CalculateLayoutInputHorizontal() { } + public void CalculateLayoutInputVertical() { } + + private void DestroyTexture() + { + if (Application.isPlaying) Destroy(_texture); else DestroyImmediate(_texture); + _texture = null; + } + + protected override void OnDestroy() + { + if (_texture) DestroyTexture(); + if (_material) DestroyImmediate(_material); + base.OnDestroy(); + } +} diff --git a/Assets/Scripts/UI/Menu/InventoryGrid.cs.meta b/Assets/Scripts/UI/Menu/InventoryGrid.cs.meta new file mode 100644 index 000000000..7ae982fbb --- /dev/null +++ b/Assets/Scripts/UI/Menu/InventoryGrid.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3b9e6d41c7a24f08b15d2e9a60c4f7a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: + - Shader: {fileID: 4800000, guid: 7d1f3c0a5b2e4f6a9c8d0e1f2a3b4c5d, type: 3} + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Shaders/InventoryGrid.shader b/Assets/Shaders/InventoryGrid.shader new file mode 100644 index 000000000..491186e6f --- /dev/null +++ b/Assets/Shaders/InventoryGrid.shader @@ -0,0 +1,239 @@ +// The inventory grid as one shader. One quad covers a panel's cells; each fragment finds its cell, reads the cell's three +// record texels from _MainTex, and evaluates the cell's two layers (the background and the icon) as signed shapes. +// +// The shapes are the grammar of the old nine-sliced cell sheets (docs/aetheria-release-map.md IG-B3), evaluated as texel boxes +// through Unity's nine-slice remap (IG-G). A texel box [lo, hi] of texel centres, sampled at texel coordinate u by a bilinear +// filter, weighs saturate(1 - dist(u, [lo, hi]) / soft) with soft = 1 texel; a pixel is the product of one such profile per axis, +// summed over the grammar's boxes. The shader owns no match rule: the 8-bit edge mask arrives in the record (IG-R). +// +// Record texels, per cell x: 3x icon colour (gamma bytes, as a Graphic's vertex colour), 3x+1 background colour (same), +// 3x+2 R = edge mask (_offsets order), G = flags (bit 0 present, bit 1 item), B = conductivity bits (up, right, down, left). +Shader "UI/Inventory Grid" +{ + Properties + { + [PerRendererData] _MainTex ("Cell records", 2D) = "black" {} + _Color ("Tint", Color) = (1,1,1,1) + + _StencilComp ("Stencil Comparison", Float) = 8 + _Stencil ("Stencil ID", Float) = 0 + _StencilOp ("Stencil Operation", Float) = 0 + _StencilWriteMask ("Stencil Write Mask", Float) = 255 + _StencilReadMask ("Stencil Read Mask", Float) = 255 + _ColorMask ("Color Mask", Float) = 15 + [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0 + + // Layout: (columns, rows), the cell edge in canvas units, 1 when the grid starts UpperRight, 1 in thermal mode. + _GridCells ("Grid cells", Vector) = (1,1,0,0) + _CellSize ("Cell size", Float) = 32 + _Flip ("Flip", Float) = 0 + _Thermal ("Thermal", Float) = 0 + // One texel of the sheet sprite in canvas units, per layer: 100 / (the sheet's pixels per unit x the layer's multiplier). + _IconTexel ("Icon texel", Float) = 1.51515 + _BgTexel ("Background texel", Float) = 1 + + // Look, in texels of the sheet sprite. + _RuleInset ("Rule inset", Float) = 1.5 + _RuleWidth ("Rule width", Float) = 1 + _ArmTexels ("Bracket arm", Float) = 1 + _FillInset ("Fill inset", Float) = 3 + _Softness ("Softness", Float) = 1 + _RuleAlpha ("Rule alpha", Float) = 0.2 + _BracketAlpha ("Bracket alpha", Float) = 1 + _FillAlpha ("Fill alpha", Float) = 0.050980392 + // Look of the thermal pipes, as fractions of the cell. + _BlobRadius ("Blob radius", Float) = 0.1157 + _PipeHalfWidth ("Pipe half width", Float) = 0.1257 + _Fillet ("Fillet", Float) = 0.0245 + _PipeSoft ("Pipe softness", Float) = 0.0697 + } + + SubShader + { + Tags + { + "Queue"="Transparent" + "IgnoreProjector"="True" + "RenderType"="Transparent" + "PreviewType"="Plane" + } + + Stencil + { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull Off + Lighting Off + ZWrite Off + ZTest [unity_GUIZTestMode] + Blend One OneMinusSrcAlpha + ColorMask [_ColorMask] + + Pass + { + Name "Default" + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma target 3.0 + + #include "UnityCG.cginc" + #include "UnityUI.cginc" + + #pragma multi_compile_local _ UNITY_UI_CLIP_RECT + #pragma multi_compile_local _ UNITY_UI_ALPHACLIP + + struct appdata_t + { + float4 vertex : POSITION; + float4 color : COLOR; + float2 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID + }; + + struct v2f + { + float4 vertex : SV_POSITION; + fixed4 color : COLOR; + float2 texcoord : TEXCOORD0; + float4 worldPosition : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO + }; + + fixed4 _Color; + float4 _ClipRect; + sampler2D _MainTex; + float4 _GridCells; + float _CellSize, _Flip, _Thermal, _IconTexel, _BgTexel; + float _RuleInset, _RuleWidth, _ArmTexels, _FillInset, _Softness, _RuleAlpha, _BracketAlpha, _FillAlpha; + float _BlobRadius, _PipeHalfWidth, _Fillet, _PipeSoft; + + v2f vert(appdata_t IN) + { + v2f OUT; + UNITY_SETUP_INSTANCE_ID(IN); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT); + OUT.worldPosition = IN.vertex; + OUT.vertex = UnityObjectToClipPos(OUT.worldPosition); + OUT.texcoord = IN.texcoord; + OUT.color = IN.color * _Color; + return OUT; + } + + static const float Far = 1000.0; + + // The profile of a texel box [lo, hi] (texel centres) at texel coordinate x. An empty box (hi < lo) weighs nothing. + float Box(float x, float lo, float hi) + { + float outside = max(max(lo - x, x - hi), 0.0); + return hi < lo ? 0.0 : saturate(1.0 - outside / _Softness); + } + + // What a Graphic's vertex colour goes through in a linear project: bytes read as sRGB (probe P1). The exact curve, + // not UnityCG's polynomial, which reads 2 to 3 levels away from the Graphic's vertex path. + float3 Decode(float3 c) + { + return c <= 0.04045 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4); + } + + // One layer of one cell: alpha in 0..1. p is the position in the cell, screen-aligned, y up, canvas units. + // The quadrant is the one nearest the point; x and y count texels from that quadrant's outer corner (IG-B3, IG-G). + float Layer(float2 p, float texel, uint mask, bool item, bool icon) + { + float S = _CellSize; + float t = min(texel, S / 8.0); + bool left = p.x < S * 0.5; + bool top = p.y >= S * 0.5; + float x = max(min((left ? p.x : S - p.x) / t, 4.0), 0.5); + float y = max(min((top ? S - p.y : p.y) / t, 4.0), 0.5); + bool v = (mask >> (top ? 0 : 2)) & 1u; + bool h = (mask >> (left ? 3 : 1)) & 1u; + bool d = (mask >> (top ? (left ? 7 : 4) : (left ? 6 : 5))) & 1u; + bool concave = !v && !h && d; + + float fillLo = _FillInset + 0.5; + float Fx = h ? Box(x, fillLo, Far) : 1.0; + float Fy = v ? Box(y, fillLo, Far) : 1.0; + float F = Fx * Fy; + if (concave) F -= Box(x, -Far, _FillInset - 0.5) * Box(y, -Far, _FillInset - 0.5); + if (!icon) return F; + + float a = item ? _FillAlpha * F : 0.0; + float ri = _RuleInset; + float rlo = ri - (_RuleWidth - 1.0) * 0.5, rhi = ri + (_RuleWidth - 1.0) * 0.5; + float Rx = Box(x, rlo, rhi); + float Ry = Box(y, rlo, rhi); + float arms = _ArmTexels >= 1.0 ? 1.0 : 0.0; + if (v) a += _RuleAlpha * Ry * (h ? Box(x, ri, Far) : 1.0); + if (h) a += _RuleAlpha * Rx * (v ? Box(y, ri + 1.0, Far) : 1.0); + if (v && h) + a += (_BracketAlpha - _RuleAlpha) * (Ry * Box(x, ri, ri + _ArmTexels) + arms * Rx * Box(y, ri + 1.0, ri + _ArmTexels)); + else if (concave) + a += _BracketAlpha * (Ry * Box(x, ri - _ArmTexels, ri) + arms * Rx * Box(y, ri - _ArmTexels, ri - 1.0)); + return a; + } + + float SmoothMin(float a, float b, float k) + { + float h = saturate(0.5 + 0.5 * (b - a) / max(k, 1e-5)); + return lerp(b, a, h) - k * h * (1.0 - h); + } + + // The pipes of the thermal view (IG-B4): a blob, and a capsule from the centre to each conducting edge, in cell fractions. + float Pipes(float2 p, uint cond) + { + float2 q = p / _CellSize - 0.5; + float d = length(q) - _BlobRadius; + float2 dirs[4] = { float2(0, 1), float2(1, 0), float2(0, -1), float2(-1, 0) }; + [unroll] for (int b = 0; b < 4; b++) + { + if (((cond >> b) & 1u) == 0u) continue; + float along = dot(q, dirs[b]); + float perp = abs(dot(q, float2(dirs[b].y, -dirs[b].x))); + float d2 = along >= 0.0 ? perp - _PipeHalfWidth : length(float2(perp, along)) - _PipeHalfWidth; + d = SmoothMin(d, d2, _Fillet); + } + return saturate(0.5 - d / _PipeSoft); + } + + fixed4 frag(v2f IN) : SV_Target + { + float S = _CellSize; + float2 cellf = floor(IN.texcoord / S); + if (any(cellf < 0.0) || any(cellf >= _GridCells.xy)) return 0; + float2 p = IN.texcoord - cellf * S; + if (_Flip > 0.5) p = S - p; + + float3 grid = float3(_GridCells.x * 3.0, _GridCells.y, 0); + float ty = (cellf.y + 0.5) / grid.y; + float4 icon = tex2Dlod(_MainTex, float4((cellf.x * 3.0 + 0.5) / grid.x, ty, 0, 0)); + float4 bg = tex2Dlod(_MainTex, float4((cellf.x * 3.0 + 1.5) / grid.x, ty, 0, 0)); + float4 data = tex2Dlod(_MainTex, float4((cellf.x * 3.0 + 2.5) / grid.x, ty, 0, 0)); + uint mask = (uint)round(data.r * 255.0); + uint flags = (uint)round(data.g * 255.0); + uint cond = (uint)round(data.b * 255.0); + if ((flags & 1u) == 0u) return 0; + + float aBg = Layer(p, _BgTexel, mask, false, false) * bg.a; + float aIcon = _Thermal > 0.5 ? Pipes(p, cond) : Layer(p, _IconTexel, mask, (flags & 2u) != 0u, true); + aIcon *= icon.a; + float4 color = float4(Decode(bg.rgb) * aBg + Decode(icon.rgb) * aIcon, aBg); + color *= IN.color.a; + + #ifdef UNITY_UI_CLIP_RECT + color *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect); + #endif + #ifdef UNITY_UI_ALPHACLIP + clip(color.a + max(color.r, max(color.g, color.b)) - 0.001); + #endif + return color; + } + ENDCG + } + } +} diff --git a/Assets/Shaders/InventoryGrid.shader.meta b/Assets/Shaders/InventoryGrid.shader.meta new file mode 100644 index 000000000..8d55f11d9 --- /dev/null +++ b/Assets/Shaders/InventoryGrid.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 7d1f3c0a5b2e4f6a9c8d0e1f2a3b4c5d +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: