diff --git a/Assets/Scripts/Editor/IsolinePlayCheck.cs b/Assets/Scripts/Editor/IsolinePlayCheck.cs new file mode 100644 index 000000000..5735f2a88 --- /dev/null +++ b/Assets/Scripts/Editor/IsolinePlayCheck.cs @@ -0,0 +1,281 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Aetheria.EditorTools; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.UI; + +// Batchmode play check for campaign aetheria-release, cut isoline-wiring (ported from the soul pass's IsolinePlayProbe): the only check that +// runs IsolineView.LateUpdate. It boots a Duel through MainMenu.Launch and asserts that both views draw (target, wiring, coverage), that +// the map screen releases on close and draws again on reopen, that a pan moves no contour on the live pose cameras (the bound of +// IsolineRenderSmoke's anchor check, many poses, the live terms), and that an overflow logs one warning per view. +// +// Needs a graphics device: run WITHOUT -nographics and without -quit; it exits the Editor itself, 0 on success. +// Unity -batchmode -projectPath -executeMethod IsolinePlayCheck.Run -logFile +[InitializeOnLoad] +public static class IsolinePlayCheck +{ + const string Tag = "[IsolinePlayCheck]"; + const string Flag = "IsolinePlayCheck.running"; + const double Budget = 540; + const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + static readonly Stack Steps = new Stack(); + static readonly List Fails = new List(); + static readonly List Warnings = new List(); + static double _started; + static int _errors; + + static IsolinePlayCheck() + { + if (SessionState.GetBool(Flag, false)) EditorApplication.playModeStateChanged += OnPlayMode; + } + + static void Log(string line) => Debug.Log($"{Tag} {line}"); + + public static void Run() + { + try + { + EditorSceneManager.playModeStartScene = AssetDatabase.LoadAssetAtPath("Assets/Scenes/Main Menu.unity") + ?? throw new InvalidOperationException("No Main Menu scene."); + SessionState.SetBool(Flag, true); + EditorApplication.EnterPlaymode(); + } + catch (Exception exception) { Debug.LogException(exception); EditorApplication.Exit(1); } + } + + static void OnPlayMode(PlayModeStateChange change) + { + if (change != PlayModeStateChange.EnteredPlayMode) return; + _started = Time.realtimeSinceStartupAsDouble; + Application.logMessageReceived += OnLog; + Steps.Push(Play()); + EditorApplication.update += Step; + } + + static void OnLog(string condition, string stack, LogType type) + { + // Other systems' errors (the console view, the editor's indexer) are counted, not failed: only an isoline error fails the check. + if (type == LogType.Error || type == LogType.Exception || type == LogType.Assert) + { + _errors++; + if (stack.Contains("Isoline") || condition.Contains("Isoline")) Fails.Add($"logged {type}: {condition}"); + } + else if (type == LogType.Warning) Warnings.Add(condition); + } + + static void Step() + { + try + { + if (Time.realtimeSinceStartupAsDouble - _started > Budget) throw new InvalidOperationException($"did not finish in {Budget} s"); + while (Steps.Count > 0) + { + var top = Steps.Peek(); + if (!top.MoveNext()) { Steps.Pop(); continue; } + if (top.Current is IEnumerator nested) { Steps.Push(nested); continue; } + return; + } + Finish(); + } + catch (Exception exception) { Debug.LogException(exception); Fails.Add(exception.Message); Finish(); } + } + + static void Finish() + { + EditorApplication.update -= Step; + Application.logMessageReceived -= OnLog; + SessionState.SetBool(Flag, false); + EditorSceneManager.playModeStartScene = null; + Log($"errors logged during the run: {_errors}; failures: {Fails.Count}"); + foreach (var f in Fails) Log(" FAIL " + f); + Log(Fails.Count == 0 ? "PASS" : "FAILED"); + EditorApplication.Exit(Fails.Count == 0 ? 0 : 1); + } + + static void Check(bool condition, string what) + { + if (!condition) Fails.Add(what); + Log((condition ? "ok: " : "FAIL: ") + what); + } + + static T Get(object o, string field) => (T)o.GetType().GetField(field, Any).GetValue(o); + + static int Covered(RenderTexture rt) + { + var previous = RenderTexture.active; + RenderTexture.active = rt; + var tex = new Texture2D(rt.width, rt.height, TextureFormat.RGBAHalf, false); + tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); + RenderTexture.active = previous; + var covered = tex.GetPixels().Count(p => p.a > .05f); + UnityEngine.Object.Destroy(tex); + return covered; + } + + static GameSettings.IsolineViewSettings SettingsOf(IsolineView view) => + view.View == IsolineView.Kind.Map ? view.ZoneRenderer.Settings.MapIsolines : view.ZoneRenderer.Settings.MinimapIsolines; + + static Vector2Int TargetSizeOf(IsolineView view) => (Vector2Int)typeof(IsolineView).GetMethod("TargetSize", Any).Invoke(view, null); + + struct Frame { public Vector2 origin, perTexel; public Vector2Int size; public IsolineExtractor.IsoSegment[] segments; } + + // The grid of the live pose camera extracted in this frame from the live terms: every pose reads the same field, so only the grid moves. + static Frame ExtractNow(IsolineView view) + { + var renderer = Get(view, "_renderer"); + IsolineView.Grid(view.PoseCamera, TargetSizeOf(view), Mathf.Max(SettingsOf(view).CellPixels, 1), out var o, out var p, out var s); + var levels = new IsolineExtractor.IsolineLevels(0f, view.ZoneRenderer.Map.ContourRange, 1e-3f); + var command = new CommandBuffer { name = "IsolinePlayCheck" }; + renderer.Extractor.Extract(command, view.ZoneRenderer.Terms, o, p, s, levels); + Graphics.ExecuteCommandBuffer(command); + command.Release(); + var count = new uint[2]; + renderer.Extractor.Count.GetData(count); + var n = (int)Mathf.Min(count[0], renderer.Extractor.Capacity); + var segments = new IsolineExtractor.IsoSegment[n]; + renderer.Extractor.Segments.GetData(segments, 0, 0, n); + return new Frame { origin = o, perTexel = p, size = s, segments = segments }; + } + + static (Vector2 lo, Vector2 hi) Reach(Frame f) + { + var end = f.origin + new Vector2((f.size.x - 1) * f.perTexel.x, (f.size.y - 1) * f.perTexel.y); + return (Vector2.Min(f.origin, end), Vector2.Max(f.origin, end)); + } + + static float Distance(Vector2 p, Vector2 a, Vector2 b) + { + var ab = b - a; + var t = ab.sqrMagnitude < 1e-20f ? 0f : Mathf.Clamp01(Vector2.Dot(p - a, ab) / ab.sqrMagnitude); + return (p - (a + ab * t)).magnitude; + } + + // Worst distance, in steps, of the moved grid's interior vertices (every 6th) from the first grid's polyline of the same key. + static double Deviation(Frame a, Frame b, double step, out int vertices) + { + var ra = Reach(a); var rb = Reach(b); + var margin = new Vector2((float)step, (float)step) * 2; + var lo = Vector2.Max(ra.lo, rb.lo) + margin; + var hi = Vector2.Min(ra.hi, rb.hi) - margin; + bool In(Vector2 q) => q.x >= lo.x && q.x <= hi.x && q.y >= lo.y && q.y <= hi.y; + var byKey = a.segments.Where(s => In(s.a) || In(s.b)).GroupBy(s => s.key).ToDictionary(g => g.Key, g => g.ToArray()); + var sample = b.segments.Where(s => In(s.a) && In(s.b)).Where((_, k) => k % 6 == 0).ToArray(); + vertices = sample.Length; + double worst = 0; + foreach (var s in sample) + { + if (!byKey.TryGetValue(s.key, out var list)) { worst = Math.Max(worst, 1e3); continue; } + var best = float.MaxValue; + foreach (var t in list) best = Mathf.Min(best, Distance(s.a, t.a, t.b)); + worst = Math.Max(worst, best / step); + } + return worst; + } + + // Grids of the live pose camera at poses around its home and at that pose moved by (0.37, 0.61) of a step, from the live terms. + static IEnumerator Pan(IsolineView view, string label, float radius, int poses) + { + yield return null; + var camera = view.PoseCamera; + var home = camera.transform.position; + Frame At(Vector2 p) { camera.transform.position = new Vector3(p.x, home.y, p.y); return ExtractNow(view); } + var rng = new System.Random(5); + var usable = 0; + double worst = 0; + for (var i = 0; i < poses; i++) + { + var p = new Vector2(home.x, home.z) + new Vector2((float)(rng.NextDouble() * 2 - 1) * radius, (float)(rng.NextDouble() * 2 - 1) * radius); + var a = At(p); + var b = At(p + new Vector2(.37f * Mathf.Abs(a.perTexel.x), .61f * Mathf.Abs(a.perTexel.y))); + var d = Deviation(a, b, Mathf.Abs(a.perTexel.x), out var vertices); + if (vertices < 30) continue; + usable++; + worst = Math.Max(worst, d); + } + camera.transform.position = home; + Log($"{label} pan: {usable} usable poses of {poses} within +-{radius} u, worst vertex deviation {worst:G3} step (bound {IsolineRenderSmoke.AnchorBound})"); + Check(usable >= poses / 2, $"{label}: the pan test is not vacuous ({usable} usable poses)"); + Check(worst <= IsolineRenderSmoke.AnchorBound, $"{label}: a pan by a fraction of a step moves no vertex off its contour ({worst:G3} step)"); + yield return null; + } + + static IEnumerator Play() + { + MainMenu menu = null; + while (!(menu = UnityEngine.Object.FindFirstObjectByType())) yield return null; + for (var i = 0; i < 30; i++) yield return null; + var scenario = Scenarios.Tests.First(s => s.Id == "duel"); + Log($"Screen {Screen.width}x{Screen.height}; device {SystemInfo.graphicsDeviceName}; launching {scenario.Name}"); + menu.Launch(scenario); + + ActionGameManager game = null; + while (!((game = ActionGameManager.Instance) && game.CurrentEntity != null && game.ShipPanel && game.ShipPanel.Grid.Width > 0)) yield return null; + for (var i = 0; i < 90; i++) yield return null; + Check(ActionGameManager.RunLive, "the game is live"); + + var views = UnityEngine.Object.FindObjectsByType(FindObjectsInactive.Include, FindObjectsSortMode.None); + var mini = views.First(v => v.View == IsolineView.Kind.Minimap); + var map = views.First(v => v.View == IsolineView.Kind.Map); + + // minimap: LateUpdate ran, the RawImage shows the target, the target carries contours + var miniTarget = Get(mini, "_target"); + Check(miniTarget != null, "the minimap view's target exists: LateUpdate ran in play"); + Check(miniTarget != null && ((RawImage)mini.GetComponent()).texture == miniTarget, "RawImage.texture is the minimap target"); + Check(miniTarget != null && Covered(miniTarget) > 200, "the minimap target carries contours"); + var follow = mini.PoseCamera.GetComponent(); + if (follow != null) follow.enabled = false; + yield return Pan(mini, "minimap", 1500f, 20); + if (follow != null) follow.enabled = true; + + // map screen: an instance of the template carries the target; the template is never written. The zone fills the screen at + // this scale whatever the Screen size (a batchmode Game view is 640 x 480). + game.Menu.ShowTab(MenuTab.Map); + var mapRenderer = UnityEngine.Object.FindFirstObjectByType(); + mapRenderer.Scale = 4000f / Screen.height; + var enough = Screen.width * Screen.height / 400; + for (var i = 0; i < 30; i++) yield return null; + var mapTarget = Get(map, "_target"); + Check(mapTarget != null, "the map view's target exists: LateUpdate ran in play"); + var instance = Get(map, "_instance"); + var template = Get(map, "_template"); + var image = map.GetComponent(); + Check(instance != null && image.material == instance && instance.GetTexture("_DetailTex") == mapTarget, "the Image draws a material instance whose _DetailTex is the target"); + Check(template != null && template != instance && template.GetTexture("_DetailTex") != mapTarget, "the shared template material was never written"); + Check(mapTarget != null && mapTarget.width == Screen.width && mapTarget.height == Screen.height, "the map target is Screen-sized"); + Check(mapTarget != null && Covered(mapTarget) > enough, "the map target carries contours"); + yield return Pan(map, "map", 1500f, 31); + + // closing the map releases, reopening draws again + game.Menu.ShowTab(MenuTab.Inventory); + for (var i = 0; i < 20; i++) yield return null; + Check(Get(map, "_target") == null && Get(map, "_instance") == null, "closing the map releases the target and the instance"); + Check(image.material == template, "closing the map puts the template material back on the Image"); + game.Menu.ShowTab(MenuTab.Map); + for (var i = 0; i < 20; i++) yield return null; + var again = Get(map, "_target"); + Check(again != null && Covered(again) > enough, "reopening the map draws again"); + + // overflow: one warning per view, then no second + var settings = mini.ZoneRenderer.Settings; + var saveMini = settings.MinimapIsolines; + var saveMap = settings.MapIsolines; + Warnings.Clear(); + var m = saveMini; m.SegmentCapacity = 100; settings.MinimapIsolines = m; + for (var i = 0; i < 800; i++) yield return null; + var miniWarnings = Warnings.Where(w => w.Contains("isolines overflowed")).ToList(); + Check(miniWarnings.Count == 1 && miniWarnings[0].StartsWith("Minimap"), $"the minimap view logs exactly one overflow warning in 800 frames ({miniWarnings.Count})"); + settings.MinimapIsolines = saveMini; + Warnings.Clear(); + var mm = saveMap; mm.PoolCapacity = 100; settings.MapIsolines = mm; + for (var i = 0; i < 400; i++) yield return null; + var mapWarnings = Warnings.Where(w => w.Contains("isolines overflowed")).ToList(); + Check(mapWarnings.Count == 1 && mapWarnings[0].StartsWith("Map"), $"the map view logs exactly one overflow warning ({mapWarnings.Count})"); + settings.MapIsolines = saveMap; + } +} diff --git a/Assets/Scripts/Editor/IsolinePlayCheck.cs.meta b/Assets/Scripts/Editor/IsolinePlayCheck.cs.meta new file mode 100644 index 000000000..00e73f023 --- /dev/null +++ b/Assets/Scripts/Editor/IsolinePlayCheck.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e50d7fff7160807408e7ea2ddbe3f02a \ No newline at end of file diff --git a/Assets/Scripts/Editor/IsolineRenderSmoke.cs b/Assets/Scripts/Editor/IsolineRenderSmoke.cs index c8abd3b68..3b5ef2acc 100644 --- a/Assets/Scripts/Editor/IsolineRenderSmoke.cs +++ b/Assets/Scripts/Editor/IsolineRenderSmoke.cs @@ -44,9 +44,19 @@ namespace Aetheria.EditorTools const float PerspectiveSBound = 33.5f; const float WrongWayBound = 0.045f; const float FlowLagBound = 3.5f; - // Cost gate (cut isoline-wiring): Extract plus Draw per view at its shipped settings, 1.2 x the readings of 08b1a13cd - // (map 1920 x 1080 2.289 ms, minimap 0.329 ms; F:/aeth-wt/isoline-chain-g.IsolineRenderSmoke.log, GTX 1070 D3D11). - const double MapCostBound = 2.75, MinimapCostBound = 0.40; + // Cost gate (cut isoline-wiring), Extract plus Draw per view at its shipped settings. Map: the median of 7 warm runs of 31 x 8 reps + // (the first Cost of a session is cold and discarded), shipped 2.237 to 2.400 over four sessions (baseline of 08b1a13cd 2.289), + // bound 2.75 = 1.2 x baseline. The minimap's absolute reading drifts with the GPU's load, clock and the session (medians 0.347, + // 0.383, 0.446, 0.487; single runs 0.29 to 0.76), so it is gated on a ratio from one interleaved loop, which cancels the load: the + // view over the same view at CellPixels 1 (double the sampling density, the regression claimed), paired per iteration. Shipped + // 0.684 (pairs 0.620 to 0.810; unpaired sessions 0.62 to 0.68, one 0.90 from a clock ramp), the regression 1.0: margin rule + // sqrt(0.684 x 1.0) = 0.83, taken as 0.82, separation 1.20 and 1.22. Its absolute reading is reported. + const double MapCostBound = 2.75, MinimapCostRatioBound = 0.82; + // Pan bound, in steps (margin rule, lodur:ruling:deterministic-bound-margin): shipped worst 0.0024 (the live duel's 31 map poses, + // the soul pass; this smoke's 31 map poses read 0.0014, the minimap's 0), least claimed mutant 0.934 (the step differenced from two + // projected points, run on this smoke's map poses; the soul pass read 1.3 live; the no-snap origin reads 27.3); + // sqrt(0.0024 x 0.934) = 0.047, taken as 0.05: separation 21 and 19. + internal const double AnchorBound = 0.05; static bool _ok = true; static string _out; @@ -1440,62 +1450,80 @@ namespace Aetheria.EditorTools if (!poolMessage.Contains(number.ToString())) Fail("overflow message", $"the pool message does not name {number}: {poolMessage}"); } - // The grid is anchored to the world lattice of its step, so a pan moves no contour: the same pose and the pose moved by - // (0.37, 0.61) of a step give the same segments wherever both grids reach, compared bit for bit on a, b, depths, slopes and - // key (s is a chain property and cell a grid index: both depend on where a grid ends). Shipped reads 0 differing; the mutant - // takes its origin from the camera frame's first pixel centre without the snap and must read more. - static void GridIsWorldAnchored(GameSettings settings, GravityLowering.GravityTerms terms, IsolineExtractor.IsolineLevels levels) + // A pan moves no contour: over many poses of each pose camera, the grid at a pose and at the pose moved by (0.37, 0.61) of a + // step give vertices that lie on the same contours. Bit-equality cannot hold (origin + n x step rounds differently per n), so + // the pin is geometric: the worst distance, in steps, of a moved grid's interior vertex from the first grid's polyline of the + // same key. The mutant takes its origin from the camera frame's first pixel centre without the snap and reads far more. + static double PanDeviation(Camera camera, Vector2Int target, int cellPixels, GravityLowering.GravityTerms terms, IsolineExtractor.IsolineLevels levels, + int poses, bool snap, int seed, out int usable) { - var view = settings.MapIsolines; - var target = new Vector2Int(1920, 1080); - var camera = MapPoseCamera(); var extractor = new IsolineExtractor(ExtractShader, FixtureSegments); + var rng = new System.Random(seed); + var aspect = target.x / (float)target.y; + var halfHeight = camera.orthographicSize; + usable = 0; + double worst = 0; try { - void GridAt(Vector2 centre, bool snap, out Vector2 origin, out Vector2 perTexel, out Vector2Int size) + (Seg[] segments, Vector2 origin, Vector2 perTexel, Vector2Int size) Frame(Vector2 centre) { - Pose(camera, centre, 1100f, 16f / 9f); - IsolineView.Grid(camera, target, view.CellPixels, out origin, out perTexel, out size); - if (snap) return; - var first = camera.ViewportToWorldPoint(new Vector3(.5f / target.x, .5f / target.y, 100f)); - origin = new Vector2(first.x, first.z); - } - (Vector2 lo, Vector2 hi) Reach(Vector2 o, Vector2 p, Vector2Int n) - { - var end = o + new Vector2((n.x - 1) * p.x, (n.y - 1) * p.y); - return (Vector2.Min(o, end), Vector2.Max(o, end)); - } - HashSet<(Vector4, Vector4, uint)> Inside(Vector2 o, Vector2 p, Vector2Int n, Vector2 lo, Vector2 hi) - { - var command = new CommandBuffer { name = "IsolineAnchored" }; + Pose(camera, centre, halfHeight, aspect); + IsolineView.Grid(camera, target, cellPixels, out var o, out var p, out var n); + if (!snap) + { + var first = camera.ViewportToWorldPoint(new Vector3(.5f / target.x, .5f / target.y, 100f)); + o = new Vector2(first.x, first.z); + } + var command = new CommandBuffer { name = "IsolinePan" }; extractor.Extract(command, terms, o, p, n, levels); Graphics.ExecuteCommandBuffer(command); command.Release(); - var (segments, _) = ReadExtraction(extractor); - bool In(Vector2 q) => q.x >= lo.x && q.x <= hi.x && q.y >= lo.y && q.y <= hi.y; - return new HashSet<(Vector4, Vector4, uint)>(segments.Where(s => In(s.a) && In(s.b)) - .Select(s => (new Vector4(s.a.x, s.a.y, s.b.x, s.b.y), new Vector4(s.depthA, s.depthB, s.slopeA, s.slopeB), s.key))); + return (ReadExtraction(extractor).segments, o, p, n); } - int Differing(bool snap) + for (var i = 0; i < poses; i++) { - GridAt(ZoneCentre, snap, out var o1, out var p1, out var n1); - GridAt(ZoneCentre + new Vector2(.37f * Mathf.Abs(p1.x), .61f * Mathf.Abs(p1.y)), snap, out var o2, out var p2, out var n2); - var r1 = Reach(o1, p1, n1); - var r2 = Reach(o2, p2, n2); - var lo = Vector2.Max(r1.lo, r2.lo); - var hi = Vector2.Min(r1.hi, r2.hi); - var a = Inside(o1, p1, n1, lo, hi); - var b = Inside(o2, p2, n2, lo, hi); - var differing = a.Count(x => !b.Contains(x)) + b.Count(x => !a.Contains(x)); - Info($"grid anchor ({(snap ? "shipped" : "no-snap mutant")}): {a.Count} and {b.Count} segments inside both grids, {differing} differing"); - if (a.Count < 1000) Fail("grid is world-anchored", $"only {a.Count} segments lie inside both grids: the fixture is vacuous"); - return differing; + var at = ZoneCentre + new Vector2((float)(rng.NextDouble() * 2 - 1) * 1500f, (float)(rng.NextDouble() * 2 - 1) * 1500f); + var a = Frame(at); + var b = Frame(at + new Vector2(.37f * Mathf.Abs(a.perTexel.x), .61f * Mathf.Abs(a.perTexel.y))); + var step = Mathf.Abs(a.perTexel.x); + Vector2 End(Vector2 o, Vector2 p, Vector2Int n) => o + new Vector2((n.x - 1) * p.x, (n.y - 1) * p.y); + var lo = Vector2.Max(Vector2.Min(a.origin, End(a.origin, a.perTexel, a.size)), Vector2.Min(b.origin, End(b.origin, b.perTexel, b.size))) + Vector2.one * (2 * step); + var hi = Vector2.Min(Vector2.Max(a.origin, End(a.origin, a.perTexel, a.size)), Vector2.Max(b.origin, End(b.origin, b.perTexel, b.size))) - Vector2.one * (2 * step); + bool In(Vector2 q) => q.x >= lo.x && q.x <= hi.x && q.y >= lo.y && q.y <= hi.y; + var byKey = a.segments.Where(s => In(s.a) || In(s.b)).GroupBy(s => s.key).ToDictionary(g => g.Key, g => g.ToArray()); + var vertices = b.segments.Where(s => In(s.a) && In(s.b)).Where((_, k) => k % 6 == 0).ToArray(); + if (vertices.Length < 30) continue; + usable++; + foreach (var s in vertices) + { + if (!byKey.TryGetValue(s.key, out var list)) { worst = Math.Max(worst, 1e3); continue; } + var best = float.MaxValue; + foreach (var t in list) best = Mathf.Min(best, DistanceToSegment(s.a, t.a, t.b)); + worst = Math.Max(worst, best / step); + } } - var shipped = Differing(true); - if (shipped != 0) Fail("grid is world-anchored", $"{shipped} segments differ between a pose and the pose moved by a fraction of a step"); - if (Differing(false) == 0) Fail("grid is world-anchored", "the no-snap mutant reads 0 differing: the fixture does not separate it"); } finally { extractor.Release(); } + return worst; + } + + static void GridIsWorldAnchored(GameSettings settings, GravityLowering.GravityTerms terms, IsolineExtractor.IsolineLevels levels) + { + foreach (var (name, camera, target, view, poses) in new[] + { + ("map", MapPoseCamera(), new Vector2Int(1920, 1080), settings.MapIsolines, 31), + ("minimap", MinimapPoseCamera(), new Vector2Int(256, 256), settings.MinimapIsolines, 20), + }) + { + var half = name == "map" ? 1100f : 1000f; + Pose(camera, ZoneCentre, half, target.x / (float)target.y); + var shipped = PanDeviation(camera, target, view.CellPixels, terms, levels, poses, true, 5, out var usable); + var mutant = PanDeviation(camera, target, view.CellPixels, terms, levels, poses, false, 5, out _); + Info($"grid anchor {name}: {usable} usable poses of {poses}; worst vertex deviation of a 0.37-step pan {shipped:G3} step (bound {AnchorBound}); no-snap mutant {mutant:G3}"); + if (usable < poses / 2) Fail("grid is world-anchored", $"{name}: only {usable} of {poses} poses hold enough segments: the fixture is vacuous"); + if (shipped > AnchorBound) Fail("grid is world-anchored", $"{name}: a pan moved a vertex {shipped:G3} step off its contour (> {AnchorBound})"); + if (mutant <= AnchorBound) Fail("grid is world-anchored", $"{name}: the no-snap mutant reads {mutant:G3}, inside the bound: the fixture does not separate it"); + } } static void CapturesAndCost(Zone zone, Orbit[] orbits, GravityLowering.GravityTerms terms, GameSettings settings) @@ -1544,10 +1572,21 @@ namespace Aetheria.EditorTools RecordAndSave(fixture, terms, fOrigin, fPerTexel, new Vector2Int(512, 512), levels, flowView.ViewProjection, flowTarget, flowLook, $"flow-{phase}.png", phase / 6f); Info("old path at 08b1a13cd (F:\\aeth-wt\\isoline-chain-g.IsolineRenderSmoke.log, GTX 1070 D3D11): map camera field 1.188 + blit 0.378 = 1.566 ms; minimap 0.383 + 0.079 = 0.462 ms; new path at that commit: map Extract 1.234 + renderer 1.055 = 2.289 ms, minimap 0.167 + 0.162 = 0.329 ms"); - var miniCost = Cost("256 x 256 (minimap)", miniRenderer, terms, miniFrame, levels, miniTarget, mini.Look); - var mapCost = Cost("1920 x 1080 (map)", mapRenderer, terms, mapFrame, levels, mapTarget, map.Look); + // The first Cost of a session is cold (the GPU clock ramps: 0.4 to 0.8 ms on the minimap), so each view is warmed by one + // logged Cost and gated on the median of CostRepeats further ones; the distribution is reported. The minimap's claimed + // regression is double the sampling density (CellPixels 1), timed the same way in the same process: the gate is the ratio. + Cost("256 x 256 (minimap, warm-up)", miniRenderer, terms, miniFrame, levels, miniTarget, mini.Look); + var denseFrame = FrameOf(MinimapPoseCamera(), new Vector2Int(256, 256), 1); + var denseRenderer = new IsolineRenderer(ExtractShader, RenderShader, mini.SegmentCapacity, mini.PoolCapacity); + var denseTarget = HalfTarget(256, 256); + var miniRatio = PairedRatio("minimap 256 x 256 over the same view at CellPixels 1", miniRenderer, miniFrame, mini.Look, miniTarget, denseRenderer, denseFrame, denseTarget, terms, levels); + Cost("1920 x 1080 (map, warm-up)", mapRenderer, terms, mapFrame, levels, mapTarget, map.Look); + var mapCost = CostRepeats("map 1920 x 1080", mapRenderer, terms, mapFrame, levels, mapTarget, map.Look); if (mapCost > MapCostBound) Fail("cost gate", $"map Extract plus Draw {mapCost:F3} ms > {MapCostBound} ms"); - if (miniCost > MinimapCostBound) Fail("cost gate", $"minimap Extract plus Draw {miniCost:F3} ms > {MinimapCostBound} ms"); + if (miniRatio > MinimapCostRatioBound) Fail("cost gate", $"minimap Extract plus Draw is {miniRatio:F3} of the same view at CellPixels 1, over {MinimapCostRatioBound}"); + denseRenderer.Release(); + denseTarget.Release(); + UnityEngine.Object.DestroyImmediate(denseTarget); var stressTerms = IsolineExtractSmoke.WellsFrom(StressWells(out var stressRange)); var stressView = Ortho(new Vector2(960f, 540f), 540f, 1920, 1080); var stressFrame = new ViewFrame { Origin = new Vector2(.5f, .5f), PerTexel = Vector2.one, Size = new Vector2Int(1920, 1080), ViewProjection = stressView.ViewProjection }; @@ -1580,6 +1619,55 @@ namespace Aetheria.EditorTools // difference of two neighbouring prefixes in the same iteration. Median of 31 interleaved iterations, ms per pass. Returns the // Extract median plus the renderer total, the definition of the 08b1a13cd readings the gate is set from (each one fenced); // the same two recorded in one pass (renderer.Record, one fence) are reported beside it. + const int CostRepeats_ = 7; + + // Extract plus Draw of view A over view B, paired and interleaved in one loop so the GPU's clock and load are the same for both: + // per iteration one run of 8 passes of each (A then B, B then A on odd iterations), the ratio of the pair, the median of 31 pair + // ratios after 5 discarded. Reports both medians and the ratio's spread. + static double PairedRatio(string label, IsolineRenderer a, ViewFrame frameA, IsolineLook lookA, RenderTexture targetA, IsolineRenderer b, ViewFrame frameB, + RenderTexture targetB, GravityLowering.GravityTerms terms, IsolineExtractor.IsolineLevels levels) + { + const int Reps = 8, Iterations = 31, Discard = 5; + var scratch = new uint[6]; + double Time(IsolineRenderer renderer, ViewFrame frame, RenderTexture target) + { + var command = new CommandBuffer { name = "IsolinePaired" }; + for (var i = 0; i < Reps; i++) renderer.Record(command, terms, frame.Origin, frame.PerTexel, frame.Size, levels, frame.ViewProjection, target, lookA, 0f); + var clock = Stopwatch.StartNew(); + Graphics.ExecuteCommandBuffer(command); + renderer.Stats.GetData(scratch); + clock.Stop(); + command.Release(); + return clock.Elapsed.TotalMilliseconds / Reps; + } + var ratios = new List(); + var timesA = new List(); + var timesB = new List(); + for (var i = -Discard; i < Iterations; i++) + { + double ta, tb; + if (i % 2 == 0) { ta = Time(a, frameA, targetA); tb = Time(b, frameB, targetB); } + else { tb = Time(b, frameB, targetB); ta = Time(a, frameA, targetA); } + if (i < 0) continue; + ratios.Add(ta / tb); timesA.Add(ta); timesB.Add(tb); + } + var median = Median(ratios); + Info($"cost gate {label}: paired interleaved ratio median {median:F3} (min {ratios.Min():F3}, max {ratios.Max():F3}) of {Iterations} pairs x {Reps} reps; A median {Median(timesA):F3} ms, B median {Median(timesB):F3} ms"); + return median; + } + + // Median of CostRepeats_ further Cost runs (each its own median of 31), after a warm-up the caller ran; reports the spread. + static double CostRepeats(string label, IsolineRenderer renderer, GravityLowering.GravityTerms terms, ViewFrame frame, IsolineExtractor.IsolineLevels levels, + RenderTexture target, IsolineLook look) + { + var readings = new List(); + for (var i = 0; i < CostRepeats_; i++) readings.Add(Cost(null, renderer, terms, frame, levels, target, look)); + var text = string.Join(" ", readings.Select(v => v.ToString("F3"))); + var median = Median(readings); + Info($"cost gate {label}: Extract plus Draw median of {CostRepeats_} runs {median:F3} ms (min {readings.Min():F3}, max {readings.Max():F3}); runs {text}"); + return median; + } + static double Cost(string label, IsolineRenderer renderer, GravityLowering.GravityTerms terms, ViewFrame frame, IsolineExtractor.IsolineLevels levels, RenderTexture target, IsolineLook look) { @@ -1636,7 +1724,7 @@ namespace Aetheria.EditorTools var total = Median(prefixes[6].Select((v, i) => v - prefixes[0][i]).ToList()); var recordMs = Median(full); var extractMs = Median(extract); - Info($"cost {label}: ms per pass, median of {Iterations} interleaved iterations x {Reps} reps, wall clock to a fence, kernel = paired difference of prefixes: {string.Join(", ", parts)}; renderer total {total:F3} (kernel sum {sum:F3}); Extract {Median(extract):F3} (Sample alone {Median(sampleAlone):F3}); Extract plus Draw {extractMs + total:F3} (sum of the two medians, the definition of the 08b1a13cd readings), recorded in one pass {recordMs:F3}; fence alone {Median(prefixes[0]):F3}; recorder {(recorder.isValid ? recorder.gpuElapsedNanoseconds / 1e6 + " ms" : "unmeasured (no frame loop)")}"); + if (label != null) Info($"cost {label}: ms per pass, median of {Iterations} interleaved iterations x {Reps} reps, wall clock to a fence, kernel = paired difference of prefixes: {string.Join(", ", parts)}; renderer total {total:F3} (kernel sum {sum:F3}); Extract {Median(extract):F3} (Sample alone {Median(sampleAlone):F3}); Extract plus Draw {extractMs + total:F3} (sum of the two medians, the definition of the 08b1a13cd readings), recorded in one pass {recordMs:F3}; fence alone {Median(prefixes[0]):F3}; recorder {(recorder.isValid ? recorder.gpuElapsedNanoseconds / 1e6 + " ms" : "unmeasured (no frame loop)")}"); recorder.enabled = false; return extractMs + total; } diff --git a/Assets/Scripts/Zone Display/IsolineView.cs b/Assets/Scripts/Zone Display/IsolineView.cs index 82ca19808..e76123d02 100644 --- a/Assets/Scripts/Zone Display/IsolineView.cs +++ b/Assets/Scripts/Zone Display/IsolineView.cs @@ -40,8 +40,10 @@ public sealed class IsolineView : MonoBehaviour /// /// The sample grid of a view: cellPixels target pixels per sample, the origin snapped down (against the step's sign) to the /// world lattice of that step per axis, and two samples more than the target spans so the view stays covered wherever the - /// snap lands. Panning therefore never moves a contour, and the grid's size is fixed for a target size. The frame is read - /// through ViewportToWorldPoint at pixel centres, as the smokes' field renders were. + /// snap lands. The step is exact, 2 x orthographicSize (x aspect) / target pixels, never a difference of two projected points + /// (that carries the rounding of the camera's position, so the lattice would shift as the camera moves); only the direction of + /// each axis and the first pixel's edge are read through ViewportToWorldPoint. A pan therefore moves a contour's vertices by + /// rounding only (origin + n x step rounds differently per n), and the grid's size is fixed for a target size. /// public static void Grid(Camera camera, Vector2Int target, int cellPixels, out Vector2 origin, out Vector2 perTexel, out Vector2Int size) { @@ -51,7 +53,10 @@ public sealed class IsolineView : MonoBehaviour return new Vector2(p.x, p.z); } var first = At(0, 0); - var perPixel = new Vector2(At(1, 0).x - first.x, At(0, 1).y - first.y); + var next = new Vector2(At(1, 0).x, At(0, 1).y); + var perPixel = new Vector2( + (next.x < first.x ? -1f : 1f) * (float)(2.0 * camera.orthographicSize * camera.aspect / target.x), + (next.y < first.y ? -1f : 1f) * (float)(2.0 * camera.orthographicSize / target.y)); perTexel = perPixel * cellPixels; // the view's edge (the first pixel's outer edge) is where the first sample must not lie past var edge = first - perPixel * .5f;