diff --git a/Assets/Scripts/Editor/IsolineRenderSmoke.cs b/Assets/Scripts/Editor/IsolineRenderSmoke.cs new file mode 100644 index 000000000..a5b6563e7 --- /dev/null +++ b/Assets/Scripts/Editor/IsolineRenderSmoke.cs @@ -0,0 +1,1095 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using float2 = CultMath.float2; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.Profiling; +using UnityEngine.Rendering; +using Debug = UnityEngine.Debug; +using Seg = IsolineExtractor.IsoSegment; + +namespace Aetheria.EditorTools +{ + /// + /// Batchmode check for campaign aetheria-release, cut isoline-renderer: IsolineRender.compute draws a segment buffer. + /// Hand-made segments and orthographic or tactical views for the geometry checks (the smoke's raw variant writes + /// float4(D, h, s, dir) of one family), the real zone for the flow check, captures for the operator and a cost report. + /// + /// Needs a graphics device: run WITHOUT -nographics. + /// Unity -batchmode -projectPath <repo> -executeMethod Aetheria.EditorTools.IsolineRenderSmoke.Run -logFile <path> + /// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure. Captures go to ISOLINE_SMOKE_OUT when + /// it is set, else to a fresh directory under the temp path; the paths are logged. + /// + public static class IsolineRenderSmoke + { + const string Tag = "[IsolineRenderSmoke]"; + const float RhoMax = 500f; + const float SlopeEpsilon = 1e-3f; + // The shipped sizes: segments the extractor and the screen scratch hold, and tile-list entries the pool holds. + const int ShippedSegments = 1 << 20; + const int ShippedPool = 1 << 22; + + // Margin rule (lodur:ruling:deterministic-bound-margin): a bound sits at the geometric mean of the shipped reading and + // the least claimed mutant's reading, at least 1.2 apart on each side. Each constant's comment gives both readings + // from the run that set it; mutants are emulated on the CPU from the same inputs. + const float DistanceBound = 0.0049f; + const float SplitBound = 0.0314f; + const float SeamBound = 0.0278f; + const float DensityBound = 0.0053f; + const float PerspectiveHBound = 3.8f; + const float PerspectiveSBound = 33.5f; + const float WrongWayBound = 0.045f; + const float FlowLagBound = 3.5f; + + static bool _ok = true; + static string _out; + static string _wrote = ""; + + static void Fail(string check, string detail) + { + Debug.LogError($"{Tag} FAIL {check}: {detail}"); + _ok = false; + } + + static void Info(string message) => Debug.Log($"{Tag} {message}"); + + static ComputeShader Load(string name) => AssetDatabase.LoadAssetAtPath("Assets/Shaders/" + name) + ?? throw new InvalidOperationException("No " + name); + + static ComputeShader ExtractShader => Load("IsolineExtract.compute"); + static ComputeShader RenderShader => Load("IsolineRender.compute"); + + // ---- views and plumbing ------------------------------------------------------------------------------------------- + + sealed class View + { + public Camera Camera; + public GameObject Owner; + public int W, H; + public Matrix4x4 ViewProjection => GL.GetGPUProjectionMatrix(Camera.projectionMatrix, true) * Camera.worldToCameraMatrix; + public void Dispose() => UnityEngine.Object.DestroyImmediate(Owner); + } + + // A downward orthographic view: world (x, z) lands at pixel ((x - cx) / pp + W / 2, (z - cz) / pp + H / 2), row 0 at the bottom. + static View Ortho(Vector2 centre, float halfHeight, int w, int h) + { + var owner = new GameObject("Isoline Render Smoke View") { hideFlags = HideFlags.HideAndDontSave }; + var camera = owner.AddComponent(); + camera.orthographic = true; + camera.orthographicSize = halfHeight; + camera.aspect = w / (float)h; + camera.nearClipPlane = .3f; + camera.farClipPlane = 1000f; + owner.transform.SetPositionAndRotation(new Vector3(centre.x, 100f, centre.y), Quaternion.Euler(90f, 0f, 0f)); + return new View { Camera = camera, Owner = owner, W = w, H = h }; + } + + // The tactical pose (ActionGameManager.PoseTactical): pitch GameSettings.TacticalPitch, the chase camera's 60 degree lens. + static View Tactical(Vector2 target, float distance, float pitch, float yaw, int w, int h) + { + var owner = new GameObject("Isoline Render Smoke Tactical") { hideFlags = HideFlags.HideAndDontSave }; + var camera = owner.AddComponent(); + camera.orthographic = false; + camera.fieldOfView = 60f; + camera.aspect = w / (float)h; + camera.nearClipPlane = .3f; + camera.farClipPlane = 6000f; + var rotation = Quaternion.Euler(pitch, yaw, 0f); + owner.transform.SetPositionAndRotation(new Vector3(target.x, 0f, target.y) - rotation * Vector3.forward * distance, rotation); + return new View { Camera = camera, Owner = owner, W = w, H = h }; + } + + static Seg Segment(Vector2 a, Vector2 b, float sA, float sB, float depthA, float depthB, bool ray = false, uint level = 0, float slope = .32f) => new Seg + { + a = a, b = b, sA = sA, sB = sB, slopeA = slope, slopeB = slope, depthA = depthA, depthB = depthB, + key = (level & 0xFFu) | (ray ? 1u << 8 : 0u), cell = 0 + }; + + static Seg Contour(Vector2 a, Vector2 b) => Segment(a, b, 0f, (b - a).magnitude, .1f, .1f); + + static IsolineExtractor.IsolineLevels Levels => new IsolineExtractor.IsolineLevels(0f, 1f, RhoMax, SlopeEpsilon); + + sealed class Frame + { + public int W, H; + public Vector4[] Px; + public uint[] Stats; + public Vector4 At(int x, int y) => Px[y * W + x]; + } + + // Draws hand-made segments through the renderer's own Draw: raw writes float4(D, h, s, dir) of one family into a float + // target; otherwise the composite lands in an ARGBHalf target, as in the shipped path. + static Frame Draw(View view, Seg[] segments, IsolineLook look, bool raw, int family = 0, float time = 0f, int count = -1, + int pool = 1 << 20, float dilation = -1f, int bufferLength = 0, Action prepare = null, Action inspect = null) + { + var capacity = Math.Max(Math.Max(segments.Length, bufferLength), 16); + var renderer = new IsolineRenderer(ExtractShader, RenderShader, capacity, pool) { DilationOverride = dilation }; + var buffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, capacity, 48); + var counts = new GraphicsBuffer(GraphicsBuffer.Target.Structured, 2, sizeof(uint)); + var target = new RenderTexture(view.W, view.H, 0, raw ? RenderTextureFormat.ARGBFloat : RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear) + { enableRandomWrite = true, filterMode = FilterMode.Point }; + target.Create(); + var command = new CommandBuffer { name = "IsolineRenderSmoke" }; + try + { + var padded = new Seg[capacity]; + Array.Copy(segments, padded, segments.Length); + buffer.SetData(padded); + var written = (uint)(count < 0 ? segments.Length : count); + counts.SetData(new[] { written, written }); + prepare?.Invoke(renderer); + renderer.Draw(command, buffer, counts, Levels, view.ViewProjection, target, look, time, raw, family); + Graphics.ExecuteCommandBuffer(command); + var frame = new Frame { W = view.W, H = view.H, Px = Read(target), Stats = new uint[6] }; + renderer.Stats.GetData(frame.Stats); + inspect?.Invoke(renderer); + return frame; + } + finally + { + command.Release(); + target.Release(); + UnityEngine.Object.DestroyImmediate(target); + buffer.Release(); + counts.Release(); + renderer.Release(); + } + } + + static Vector4[] Read(RenderTexture target) + { + var format = target.format == RenderTextureFormat.ARGBFloat ? TextureFormat.RGBAFloat : TextureFormat.RGBAHalf; + var texture = new Texture2D(target.width, target.height, format, false, true); + var previous = RenderTexture.active; + RenderTexture.active = target; + texture.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0); + texture.Apply(); + RenderTexture.active = previous; + var colours = texture.GetPixels(); + UnityEngine.Object.DestroyImmediate(texture); + return colours.Select(c => new Vector4(c.r, c.g, c.b, c.a)).ToArray(); + } + + static double Median(List values) + { + values.Sort(); + return values[values.Count / 2]; + } + + // Straight alpha cannot be compared where alpha is near zero: ink over black. + static Vector4 Premultiplied(Vector4 p) => new Vector4(p.x * p.w, p.y * p.w, p.z * p.w, p.w); + + static float Sgn(float v) => v > 0f ? 1f : v < 0f ? -1f : 0f; + + static float DistanceToSegment(Vector2 p, Vector2 a, Vector2 b) + { + var d = b - a; + var l2 = Vector2.Dot(d, d); + var u = l2 > 1e-12f ? Mathf.Clamp01(Vector2.Dot(p - a, d) / l2) : 0f; + return (p - (a + d * u)).magnitude; + } + + // The CPU projection the checks judge by: the camera's own view and projection matrices, the world segment clipped + // to clip w >= IsolineRenderer.NearW, pixels with row 0 at the bottom. Independent of the shader's matrix handling. + static bool Project(View view, Vector2 a, Vector2 b, out Vector2 pa, out Vector2 pb, out float t0, out float t1) + { + var viewM = view.Camera.worldToCameraMatrix; + var projM = view.Camera.projectionMatrix; + Vector4 Clip(Vector2 p) => projM * (viewM * new Vector4(p.x, 0f, p.y, 1f)); + var cA = Clip(a); + var cB = Clip(b); + var dA = cA.w - IsolineRenderer.NearW; + var dB = cB.w - IsolineRenderer.NearW; + t0 = 0f; t1 = 1f; pa = pb = default; + if (dA < 0f && dB < 0f) return false; + if (dA < 0f) t0 = dA / (dA - dB); + else if (dB < 0f) t1 = dA / (dA - dB); + Vector2 Pixel(Vector4 c) => new Vector2((c.x / c.w * .5f + .5f) * view.W, (c.y / c.w * .5f + .5f) * view.H); + pa = Pixel(Vector4.Lerp(cA, cB, t0)); + pb = Pixel(Vector4.Lerp(cA, cB, t1)); + return true; + } + + static (Vector2, Vector2) UnclippedPixels(View view, Vector2 a, Vector2 b) + { + var m = view.Camera.projectionMatrix * view.Camera.worldToCameraMatrix; + Vector2 Pixel(Vector2 p) + { + var c = m * new Vector4(p.x, 0f, p.y, 1f); + return new Vector2((c.x / c.w * .5f + .5f) * view.W, (c.y / c.w * .5f + .5f) * view.H); + } + return (Pixel(a), Pixel(b)); + } + + // The world point on the ground plane under a pixel (bottom-up, fractional), from the camera's matrices. + static Vector2 Unproject(View view, Vector2 pixel) + { + var inverse = (view.Camera.projectionMatrix * view.Camera.worldToCameraMatrix).inverse; + var ndc = new Vector2(pixel.x / view.W * 2f - 1f, pixel.y / view.H * 2f - 1f); + var near = inverse.MultiplyPoint(new Vector3(ndc.x, ndc.y, -1f)); + var far = inverse.MultiplyPoint(new Vector3(ndc.x, ndc.y, 1f)); + var k = near.y / (near.y - far.y); + var hit = Vector3.Lerp(near, far, k); + return new Vector2(hit.x, hit.z); + } + + // ---- entry ------------------------------------------------------------------------------------------------------- + + public static void Run() + { + if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null) + { + Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics."); + EditorApplication.Exit(1); + return; + } + _out = Environment.GetEnvironmentVariable("ISOLINE_SMOKE_OUT"); + if (string.IsNullOrEmpty(_out)) _out = Path.Combine(Path.GetTempPath(), "isoline-render-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_out); + Info($"captures go to {_out}; device {SystemInfo.graphicsDeviceName} ({SystemInfo.graphicsDeviceType})"); + + var work = Path.Combine(Path.GetTempPath(), "isoline-render-work-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(work); + ComputeBuffer wells = null; + GameObject field = null; + try + { + Guarded("distance is exact", DistanceExact); + Guarded("split invariance", SplitInvariance); + Guarded("union, not sum", UnionNotSum); + Guarded("density counts lines", DensityCountsLines); + Guarded("tiles leave no seams", NoSeams); + Guarded("perspective", Perspective); + Guarded("composite moves the way raw dir says", CompositeFlow); + Guarded("count guard", CountGuard); + Guarded("pool guard", PoolGuard); + + EditorSceneManager.OpenScene("Assets/Scenes/ARPG.unity", OpenSceneMode.Single); + var settings = AssetDatabase.LoadAssetAtPath("Assets/Resources/Settings.asset") + ?? throw new InvalidOperationException("No Settings.asset."); + var material = AssetDatabase.LoadAssetAtPath("Assets/Materials/Brushes/Gravity Field.mat") + ?? throw new InvalidOperationException("No Gravity Field.mat."); + var zone = GravityFieldParityVerify.BuildZone(settings, work, out var orbits, multiRoot: true); + GravityLowering.Lower(zone, 0f, ref wells); + field = GravityLowering.CreateField(material); + Guarded("flow follows depth near the real-zone saddle", () => FlowOnRealZone(zone, orbits)); + Guarded("stress field and the shipped pool", () => StressAndPool(zone, orbits)); + Guarded("captures and cost", () => CapturesAndCost(zone, orbits)); + Info(_ok ? "PASS" : "FAIL: see errors above"); + } + catch (Exception e) + { + Debug.LogError($"{Tag} FAIL exception: {e}"); + _ok = false; + } + finally + { + if (field != null) UnityEngine.Object.DestroyImmediate(field); + wells?.Release(); + try { Directory.Delete(work, true); } catch { } + } + EditorApplication.Exit(_ok ? 0 : 1); + } + + static void Guarded(string name, Action check) + { + try { check(); } + catch (Exception e) { Fail(name, e.ToString()); } + } + + // ---- geometry checks --------------------------------------------------------------------------------------------- + + static readonly Seg[] ExactSet = + { + Contour(new Vector2(20.3f, 30.7f), new Vector2(200.1f, 60.2f)), + Contour(new Vector2(40f, 200f), new Vector2(41.5f, 120f)), + Contour(new Vector2(100f, 100f), new Vector2(180f, 180f)), + Contour(new Vector2(10f, 10f), new Vector2(246f, 12f)), + Contour(new Vector2(128f, 128f), new Vector2(129f, 128.5f)), + Contour(new Vector2(220f, 230f), new Vector2(150.7f, 210.3f)), + }; + + static IsolineLook PlainLook() + { + var look = IsolineLook.Default; + look.Contour.Bloom = 0f; + look.Ray.Bloom = 0f; + return look; + } + + // The view at one world unit per pixel: world (x, z) is pixel (x, z) up to the half-pixel centre. + static View Unit256() => Ortho(new Vector2(128f, 128f), 128f, 256, 256); + + // Raw h at every pixel within R of a segment matches the CPU distance from the pixel centre to the projected segment. + // Mutant: pixel positions without the half-pixel centre offset. + static void DistanceExact() + { + var view = Unit256(); + try + { + var look = PlainLook(); + var frame = Draw(view, ExactSet, look, true); + var r = look.Dilation; + float shipped = 0f, mutant = 0f; var checkedPixels = 0; + var pixels = ExactSet.Select(s => { Project(view, s.a, s.b, out var pa, out var pb, out _, out _); return (pa, pb); }).ToArray(); + for (var y = 0; y < view.H; y++) + for (var x = 0; x < view.W; x++) + { + var p = new Vector2(x + .5f, y + .5f); + var truth = pixels.Min(q => DistanceToSegment(p, q.pa, q.pb)); + if (truth > r) continue; + checkedPixels++; + shipped = Mathf.Max(shipped, Mathf.Abs(frame.At(x, y).y - truth)); + var wrong = pixels.Min(q => DistanceToSegment(new Vector2(x, y), q.pa, q.pb)); + mutant = Mathf.Max(mutant, Mathf.Abs(frame.At(x, y).y - wrong)); + } + Info($"distance is exact: {checkedPixels} pixels within R {r:G3} px; worst |h - cpu| {shipped:G3} px (mutant without the half-pixel centre {mutant:G3}, ratio {mutant / Mathf.Max(shipped, 1e-9f):G3})"); + if (checkedPixels < 1000) Fail("distance is exact", $"only {checkedPixels} pixels checked"); + if (shipped > DistanceBound) Fail("distance is exact", $"worst {shipped:G4} px > {DistanceBound:G4}"); + } + finally { view.Dispose(); } + } + + // One straight line as 1 segment and as 64 collinear segments agree on raw D and raw h. + static void SplitInvariance() + { + var view = Unit256(); + try + { + var a = new Vector2(20.2f, 40.4f); + var b = new Vector2(220.6f, 200.2f); + var whole = new[] { Contour(a, b) }; + var pieces = Enumerable.Range(0, 64).Select(i => Contour(Vector2.Lerp(a, b, i / 64f), Vector2.Lerp(a, b, (i + 1) / 64f))).ToArray(); + var look = PlainLook(); + var one = Draw(view, whole, look, true); + var many = Draw(view, pieces, look, true); + float dD = 0f, dH = 0f, mutantD = 0f; var counted = 0; + var sigmaD = look.Contour.SigmaD; + for (var y = 0; y < view.H; y++) + for (var x = 0; x < view.W; x++) + { + var p = new Vector2(x + .5f, y + .5f); + if (DistanceToSegment(p, a, b) > 4f) continue; + counted++; + dD = Mathf.Max(dD, Mathf.Abs(one.At(x, y).x - many.At(x, y).x)); + dH = Mathf.Max(dH, Mathf.Abs(one.At(x, y).y - many.At(x, y).y)); + // the mutant counts segments: each piece adds its own kernel with no share-of-line weight + var sumPieces = 0f; + for (var i = 0; i < 64; i++) + { + var h = DistanceToSegment(p, Vector2.Lerp(a, b, i / 64f), Vector2.Lerp(a, b, (i + 1) / 64f)); + sumPieces += Mathf.Exp(-h * h / (2f * sigmaD * sigmaD)); + } + var single = Mathf.Exp(-DistanceToSegment(p, a, b) * DistanceToSegment(p, a, b) / (2f * sigmaD * sigmaD)); + mutantD = Mathf.Max(mutantD, Mathf.Abs(sumPieces - single)); + } + Info($"split invariance: {counted} pixels; worst |D1 - D64| {dD:G3}, |h1 - h64| {dH:G3} (mutant counting segments {mutantD:G3}, ratio {mutantD / Mathf.Max(dD, 1e-9f):G3}); D on the line {one.At(120, 90).x:F4}"); + if (dD > SplitBound || dH > SplitBound) Fail("split invariance", $"D {dD:G4} h {dH:G4} > {SplitBound:G4}"); + } + finally { view.Dispose(); } + } + + // Every segment duplicated: raw h and the composite with Bloom 0 equal the single set. + static void UnionNotSum() + { + var view = Unit256(); + try + { + var look = PlainLook(); + var set = ExactSet.Concat(new[] + { + Segment(new Vector2(60f, 60f), new Vector2(200f, 140f), 0f, 100f, .1f, .05f, true), + Segment(new Vector2(60f, 220f), new Vector2(200f, 80f), 0f, 100f, .1f, .05f, true) + }).ToArray(); + var doubled = set.Concat(set).ToArray(); + var rawOne = Draw(view, set, look, true); + var rawTwo = Draw(view, doubled, look, true); + var compOne = Draw(view, set, look, false); + var compTwo = Draw(view, doubled, look, false); + float dH = 0f, dC = 0f; + for (var i = 0; i < rawOne.Px.Length; i++) + { + dH = Mathf.Max(dH, Mathf.Abs(rawOne.Px[i].y - rawTwo.Px[i].y)); + dC = Mathf.Max(dC, (compOne.Px[i] - compTwo.Px[i]).magnitude); + } + var peak = compOne.Px.Max(p => p.w); + Info($"union, not sum: worst |h1 - h2| {dH:G3}; worst composite difference {dC:G3} (peak alpha {peak:G3}; an additive core or glow doubles the ink: ~{peak:G3})"); + if (dH > 1e-4f || dC > .01f * peak) Fail("union, not sum", $"h {dH:G4}, composite {dC:G4}"); + } + finally { view.Dispose(); } + } + + // One long line through a pixel gives raw D near 1; K parallel lines inside sigmaD give the kernel-weighted count. + static void DensityCountsLines() + { + var view = Unit256(); + try + { + var look = PlainLook(); + var sigma = look.Contour.SigmaD; + var single = Draw(view, new[] { Contour(new Vector2(10f, 128f), new Vector2(246f, 128f)) }, look, true); + var ys = new[] { 100f, 102f, 104f }; + var parallel = Draw(view, ys.Select(y => Contour(new Vector2(10f, y), new Vector2(246f, y))).ToArray(), look, true); + float worst = 0f, mutant = 0f; + for (var x = 60; x < 190; x++) + { + float Truth(float py, float[] lines) => lines.Sum(y => Mathf.Exp(-(py - y) * (py - y) / (2f * sigma * sigma))); + var d1 = Truth(128.5f, new[] { 128f }); + worst = Mathf.Max(worst, Mathf.Abs(single.At(x, 128).x - d1)); + var dK = Truth(101.5f, ys); + worst = Mathf.Max(worst, Mathf.Abs(parallel.At(x, 101).x - dK)); + // the mutant: the kernel with its mass left in (unnormalised along the normal as well as the line) + mutant = Mathf.Max(mutant, Mathf.Abs(parallel.At(x, 101).x * sigma * Mathf.Sqrt(2f * Mathf.PI) - dK)); + } + Info($"density counts lines: long line D {single.At(128, 128).x:F4}, three lines at 2 px D {parallel.At(128, 101).x:F4}; worst |D - kernel sum| {worst:G3} (mutant unnormalised kernel {mutant:G3}, ratio {mutant / Mathf.Max(worst, 1e-9f):G3})"); + if (worst > DensityBound) Fail("density counts lines", $"worst {worst:G4} > {DensityBound:G4}"); + } + finally { view.Dispose(); } + } + + // A synthetic crowd: concentric polylines and spokes around a centre. + static Seg[] Crowd(Vector2 centre) + { + var list = new List(); + for (var ring = 0; ring < 7; ring++) + { + var radius = 24f + ring * 13f; + for (var i = 0; i < 72; i++) + { + var a0 = i / 72f * Mathf.PI * 2f; + var a1 = (i + 1) / 72f * Mathf.PI * 2f; + list.Add(Segment(centre + radius * new Vector2(Mathf.Cos(a0), Mathf.Sin(a0)), centre + radius * new Vector2(Mathf.Cos(a1), Mathf.Sin(a1)), + radius * a0, radius * a1, .1f, .1f, false, (uint)ring)); + } + } + for (var spoke = 0; spoke < 12; spoke++) + { + var angle = (spoke + .5f) / 12f * Mathf.PI * 2f; + var dir = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)); + for (var i = 0; i < 20; i++) + list.Add(Segment(centre + dir * (20f + i * 5f), centre + dir * (25f + i * 5f), 20f + i * 5f, 25f + i * 5f, .15f, .05f, true, (uint)spoke)); + } + return list.ToArray(); + } + + // The same field rendered with the view shifted by 4 pixels (half a tile) agrees with the unshifted one. + // Mutant: binning dilation 0. + static void NoSeams() + { + var set = Crowd(new Vector2(128f, 128f)); + var look = IsolineLook.Default; + double Disagreement(float dilation) + { + var a = Ortho(new Vector2(128f, 128f), 128f, 256, 256); + var b = Ortho(new Vector2(132f, 128f), 128f, 256, 256); + try + { + var fa = Draw(a, set, look, false, dilation: dilation); + var fb = Draw(b, set, look, false, dilation: dilation); + var worst = 0f; var wx = 0; var wy = 0; var many = 0; + for (var y = 0; y < 256; y++) + for (var x = 8; x < 240; x++) + { + var d = (Premultiplied(fa.At(x + 4, y)) - Premultiplied(fb.At(x, y))).magnitude; + if (d > .05f) many++; + if (d > worst) { worst = d; wx = x; wy = y; } + } + Info($"seams probe (dilation {dilation}): worst at ({wx},{wy}) A {fa.At(wx + 4, wy)} B {fb.At(wx, wy)}; {many} pixels differ by more than .05 (premultiplied)"); + return worst; + } + finally { a.Dispose(); b.Dispose(); } + } + var shipped = Disagreement(-1f); + var mutant = Disagreement(0f); + Info($"tiles leave no seams: worst composite difference after a 4 px shift {shipped:G3} (mutant dilation 0 {mutant:G3}, ratio {mutant / Math.Max(shipped, 1e-9):G3}); R {look.Dilation:G3} px"); + if (shipped > SeamBound) Fail("tiles leave no seams", $"worst {shipped:G4} > {SeamBound:G4}"); + } + + // The tactical pose over a world line that runs behind the eye: no NaN or Inf, h as the CPU clipped projection says, + // s as the unprojected pixel says. Mutant: s interpolated linearly in screen space. + static void Perspective() + { + var view = Tactical(Vector2.zero, 600f, 55f, 0f, 640, 360); + try + { + var a = new Vector2(0f, -1500f); + var b = new Vector2(30f, 800f); + var length = (b - a).magnitude; + var line = Segment(a, b, 0f, length, .1f, .05f, true); + var look = PlainLook(); + var raw = Draw(view, new[] { line }, look, true, 1); + var composite = Draw(view, new[] { line, Contour(new Vector2(-300f, -1500f), new Vector2(200f, 600f)) }, look, false); + var bad = raw.Px.Concat(composite.Px).Count(p => float.IsNaN(p.x + p.y + p.z + p.w) || float.IsInfinity(p.x + p.y + p.z + p.w)); + if (!Project(view, a, b, out var pa, out var pb, out var t0, out var t1)) { Fail("perspective", "the line is entirely behind the eye"); return; } + if (t0 <= 0f && t1 >= 1f) { Fail("perspective", "the line does not cross the near plane: the fixture is vacuous"); return; } + float worstH = 0f, worstS = 0f, mutantS = 0f, mutantH = 0f; var hPixels = 0; var sPixels = 0; + var r = look.Dilation; + // the mutant without the near clip: both ends projected as they are, the one behind the eye mirrored through the screen + var unclipped = UnclippedPixels(view, a, b); + var ua = unclipped.Item1; var ub = unclipped.Item2; + for (var y = 0; y < view.H; y++) + for (var x = 0; x < view.W; x++) + { + var p = new Vector2(x + .5f, y + .5f); + var truth = DistanceToSegment(p, pa, pb); + if (truth > r) continue; + var px = raw.At(x, y); + hPixels++; + worstH = Mathf.Max(worstH, Mathf.Abs(px.y - truth)); + mutantH = Mathf.Max(mutantH, Mathf.Abs(DistanceToSegment(p, ua, ub) - truth)); + if (truth > 1.5f) continue; + // s: the nearest screen point of the CPU segment, unprojected onto the ground, then onto the line + var d = pb - pa; + var u = Mathf.Clamp01(Vector2.Dot(p - pa, d) / Vector2.Dot(d, d)); + var world = Unproject(view, pa + d * u); + var sTruth = Mathf.Clamp(Vector2.Dot(world - a, b - a) / length, 0f, length); + var sLinear = Mathf.Lerp(t0, t1, u) * length; + sPixels++; + worstS = Mathf.Max(worstS, Mathf.Abs(px.z - sTruth)); + mutantS = Mathf.Max(mutantS, Mathf.Abs(sLinear - sTruth)); + } + Info($"perspective: {bad} NaN/Inf values; clipped t range {t0:F4}..{t1:F4}; {hPixels} pixels, worst |h - cpu| {worstH:G3} px (mutant without the near clip {mutantH:G3}, ratio {mutantH / Mathf.Max(worstH, 1e-9f):G3}); {sPixels} pixels, worst |s - unprojected| {worstS:G3} u (mutant screen-linear s {mutantS:G3}, ratio {mutantS / Mathf.Max(worstS, 1e-9f):G3})"); + if (bad != 0) Fail("perspective", $"{bad} NaN or Inf values in the targets"); + if (hPixels < 100 || sPixels < 50) Fail("perspective", $"only {hPixels} h pixels and {sPixels} s pixels"); + if (worstH > PerspectiveHBound) Fail("perspective", $"h off by {worstH:G4} px > {PerspectiveHBound:G4}"); + if (worstS > PerspectiveSBound) Fail("perspective", $"s off by {worstS:G4} u > {PerspectiveSBound:G4}"); + } + finally { view.Dispose(); } + } + + // ---- flow -------------------------------------------------------------------------------------------------------- + + // Six axis-aligned rays, each with the expected motion toward its deeper end: composite at time 0 and dt, the + // along-segment shift of the intensity profile (cross-correlation) points toward greater depth on every ray. + static void CompositeFlow() + { + var view = Unit256(); + try + { + var look = PlainLook(); + look.Contour.W = 0f; + look.Ray.Base = Color.white; look.Ray.W = 3f; look.Ray.Sigma = .75f; look.Ray.G = 0f; + look.Ray.Period = 24f; look.Ray.Duty = .5f; look.Ray.Speed = 1f; + // (a, b, sA, sB, depthA, depthB); the deeper end is the one with the larger depth + var rays = new (Vector2 a, Vector2 b, float sA, float sB, float dA, float dB)[] + { + (new Vector2(128f, 128.5f), new Vector2(228f, 128.5f), 0f, 100f, .15f, .05f), // s rises outward, deeper inward + (new Vector2(128f, 148.5f), new Vector2(28f, 148.5f), 0f, 100f, .15f, .05f), + (new Vector2(60.5f, 60f), new Vector2(60.5f, 160f), 0f, 100f, .15f, .05f), + (new Vector2(30f, 40.5f), new Vector2(130f, 40.5f), 0f, 100f, .05f, .15f), // reversed: s rises toward the deeper end + (new Vector2(130f, 200.5f), new Vector2(230f, 200.5f), 100f, 0f, .05f, .15f), // s falls toward the deeper end + (new Vector2(200.5f, 40f), new Vector2(200.5f, 140f), 0f, 100f, .05f, .15f), // reversed, vertical + }; + var segments = rays.Select(r => Segment(r.a, r.b, r.sA, r.sB, r.dA, r.dB, true)).ToArray(); + var shift = look.Ray.Speed * look.Ray.Period * .25f; // quarter of a second: 6 px + var f0 = Draw(view, segments, look, false, time: 0f); + var f1 = Draw(view, segments, look, false, time: .25f); + var worstError = 0f; + var line = new List(); + foreach (var r in rays) + { + var delta = r.b - r.a; + var n = (int)delta.magnitude; + var step = delta.normalized; + float Intensity(Frame f, int i) + { + var p = r.a + step * (i + .5f); + var px = f.At(Mathf.Clamp((int)p.x, 0, 255), Mathf.Clamp((int)p.y, 0, 255)); + return px.w * (px.x + px.y + px.z); + } + var best = 0; var bestScore = float.NegativeInfinity; + for (var lag = -12; lag <= 12; lag++) + { + var score = 0f; + for (var i = 14; i < n - 14; i++) score += Intensity(f0, i) * Intensity(f1, i + lag); + if (score > bestScore) { bestScore = score; best = lag; } + } + // along the ray's own direction a to b the pattern moves toward its deeper end + var expected = r.dB > r.dA ? shift : -shift; + var error = Mathf.Abs(best - expected); + worstError = Mathf.Max(worstError, error); + line.Add($"{best:+0;-0;0}/{expected:+0;-0;0}"); + } + Info($"the composite moves the way raw dir says: lag/expected px per ray [{string.Join(" ", line)}], worst error {worstError:G3} px (a flipped sign reads {2 * shift:G3})"); + if (worstError > FlowLagBound) Fail("composite flow", $"worst lag error {worstError:G4} px > {FlowLagBound:G4}"); + } + finally { view.Dispose(); } + } + + // ---- guards ------------------------------------------------------------------------------------------------------ + + // A full-screen sentinel written past Count[0] is absent from raw h. + static void CountGuard() + { + var view = Unit256(); + try + { + var real = new[] { Contour(new Vector2(20f, 30f), new Vector2(60f, 30f)) }; + var withSentinel = real.Concat(new[] { Contour(new Vector2(0f, 128f), new Vector2(256f, 128f)) }).ToArray(); + var frame = Draw(view, withSentinel, PlainLook(), true, count: 1); + var onSentinel = frame.At(128, 128).y; + var near = frame.At(40, 30).y; + Info($"count guard: h on the sentinel's line {onSentinel:G3} (no hit reads 1e9), h on the real segment {near:G3}; drawn {frame.Stats[3]}"); + if (onSentinel < 1e8f) Fail("count guard", $"the sentinel past Count[0] was drawn: h {onSentinel}"); + if (near > 1f) Fail("count guard", "the real segment is missing"); + } + finally { view.Dispose(); } + } + + // A pool below need truncates and leaves the words past it alone. + static void PoolGuard() + { + var view = Unit256(); + try + { + var rng = new System.Random(7); + var set = Enumerable.Range(0, 4000).Select(_ => + { + var a = new Vector2((float)rng.NextDouble() * 256f, (float)rng.NextDouble() * 256f); + return Contour(a, a + new Vector2((float)rng.NextDouble() - .5f, (float)rng.NextDouble() - .5f) * 20f); + }).ToArray(); + var guardWords = new uint[IsolineRenderer.PoolGuardWords]; + const uint Sentinel = 0xABCD1234u; + const int Pool = 100; + var frame = Draw(view, set, PlainLook(), true, pool: Pool, + prepare: r => r.Pool.SetData(Enumerable.Repeat(Sentinel, Pool + guardWords.Length).ToArray()), + inspect: r => + { + var all = new uint[Pool + guardWords.Length]; + r.Pool.GetData(all); + Array.Copy(all, Pool, guardWords, 0, guardWords.Length); + }); + var touched = guardWords.Count(w => w != Sentinel); + Info($"pool guard: pool {Pool}, requested {frame.Stats[0]}, written {frame.Stats[1]}, truncated {frame.Stats[2]}; guard words changed: {touched} of {guardWords.Length}"); + if (frame.Stats[2] == 0) Fail("pool guard", "nothing was truncated: the fixture is vacuous"); + if (frame.Stats[1] != Pool) Fail("pool guard", $"written {frame.Stats[1]}, expected the pool's {Pool}"); + if (frame.Stats[1] + frame.Stats[2] != frame.Stats[0]) Fail("pool guard", "written + truncated != requested"); + if (touched != 0) Fail("pool guard", "a scatter wrote past the pool"); + } + finally { view.Dispose(); } + } + + // ---- the real zone ----------------------------------------------------------------------------------------------- + + static readonly Vector2 ZoneCentre = new Vector2(300f, -50f); + const float ZoneHalf = 1600f; + static readonly Vector2 Saddle = new Vector2(381f, -144f); + + static RenderTexture RenderField(Camera camera, int width, int height, out Vector2 origin, out Vector2 perTexel) + { + var target = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat) { filterMode = FilterMode.Point }; + target.Create(); + var previousTarget = camera.targetTexture; + var previousMask = camera.cullingMask; + var previousClear = camera.clearFlags; + var previousColor = camera.backgroundColor; + camera.targetTexture = target; + camera.cullingMask = 1 << GravityLowering.FieldLayer; + camera.clearFlags = CameraClearFlags.SolidColor; + camera.backgroundColor = Color.black; + camera.allowHDR = false; + camera.allowMSAA = false; + camera.Render(); + Vector2 Texel(float x, float y) + { + var p = camera.ViewportToWorldPoint(new Vector3((x + .5f) / width, (y + .5f) / height, 100f)); + return new Vector2(p.x, p.z); + } + origin = Texel(0, 0); + perTexel = new Vector2(Texel(1, 0).x - origin.x, Texel(0, 1).y - origin.y); + camera.targetTexture = previousTarget; + camera.cullingMask = previousMask; + camera.clearFlags = previousClear; + camera.backgroundColor = previousColor; + return target; + } + + static (Seg[] segments, uint[] counts) ReadExtraction(IsolineExtractor extractor) + { + var counts = new uint[2]; + extractor.Count.GetData(counts); + var all = new Seg[extractor.Segments.count]; + extractor.Segments.GetData(all); + return (all.Take((int)counts[0]).ToArray(), counts); + } + + static float ContourRange(Zone zone, Orbit[] orbits) => Math.Max(1f, orbits.Max(o => -zone.GetHeight(new float2(o.Position.x, o.Position.y)))); + + // Rays only, over the real zone's saddle: raw dir against the depth change along +s judged by Zone.GetHeight. + static void FlowOnRealZone(Zone zone, Orbit[] orbits) + { + var fieldCamera = Ortho(ZoneCentre, ZoneHalf, 256, 256); + RenderTexture field = null; + var renderer = new IsolineRenderer(ExtractShader, RenderShader, ShippedSegments, ShippedPool); + var view = Ortho(Saddle, 240f, 512, 512); + var target = new RenderTexture(512, 512, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear) { enableRandomWrite = true, filterMode = FilterMode.Point }; + target.Create(); + var command = new CommandBuffer { name = "IsolineFlowProbe" }; + try + { + field = RenderField(fieldCamera.Camera, 256, 256, out var origin, out var perTexel); + // the contour window is the zone's: from 0 to the deepest body's depth, as MapPresenter.Draw sets it + var levels = new IsolineExtractor.IsolineLevels(0f, ContourRange(zone, orbits), zone.Pack.Radius, SlopeEpsilon); + renderer.Extractor.Extract(command, field, origin, perTexel, levels); + renderer.Draw(command, renderer.Extractor.Segments, renderer.Extractor.Count, levels, view.ViewProjection, target, IsolineLook.Default, 0f, true, 1); + Graphics.ExecuteCommandBuffer(command); + var (segments, _) = ReadExtraction(renderer.Extractor); + var frame = new Frame { W = 512, H = 512, Px = Read(target) }; + + var rays = segments.Where(s => ((s.key >> 8) & 1u) != 0).ToArray(); + var bestH = new float[512 * 512]; + var bestI = new int[512 * 512]; + for (var i = 0; i < bestH.Length; i++) { bestH[i] = float.MaxValue; bestI[i] = -1; } + for (var i = 0; i < rays.Length; i++) + { + Project(view, rays[i].a, rays[i].b, out var pa, out var pb, out _, out _); + var lo = Vector2.Min(pa, pb) - Vector2.one * 2f; + var hi = Vector2.Max(pa, pb) + Vector2.one * 2f; + for (var y = Mathf.Max(0, (int)lo.y); y <= Mathf.Min(511, (int)hi.y); y++) + for (var x = Mathf.Max(0, (int)lo.x); x <= Mathf.Min(511, (int)hi.x); x++) + { + var h = DistanceToSegment(new Vector2(x + .5f, y + .5f), pa, pb); + if (h < bestH[y * 512 + x]) { bestH[y * 512 + x] = h; bestI[y * 512 + x] = i; } + } + } + float Depth(Vector2 p) => -zone.GetHeight(new float2(p.x, p.y)); + int judged = 0, wrong = 0, wrongMutant = 0; + var covered = new HashSet(); + var reversed = new HashSet(); + for (var k = 0; k < bestH.Length; k++) + { + var i = bestI[k]; + if (i < 0 || bestH[k] > 1f) continue; + var s = rays[i]; + if ((s.key & (1u << 10)) != 0) continue; // rho clamped: s is not trustworthy there + if (((s.a + s.b) * .5f - Saddle).magnitude > 200f) continue; + var dChange = Depth(s.b) - Depth(s.a); + if (Mathf.Abs(dChange) < 1e-4f) continue; + var alongS = Sgn(s.sB - s.sA) * Sgn(dChange); // the depth change along +s + if (alongS == 0f) continue; + judged++; + covered.Add(i); + if (alongS > 0f) reversed.Add(i); // s rises with depth: the reversed rays + if (frame.Px[k].w * alongS <= 0f) wrong++; + if (Sgn(s.sA - s.sB) * alongS <= 0f) wrongMutant++; + } + var shipped = judged == 0 ? 1f : wrong / (float)judged; + var mutant = judged == 0 ? 0f : wrongMutant / (float)judged; + Info($"flow near the saddle: {judged} pixels over {covered.Count} rays, {reversed.Count} reversed-s rays covered; wrong-way share {shipped:P2} (mutant dir = sign(sA - sB) {mutant:P2}, ratio {mutant / Mathf.Max(shipped, 1e-9f):G3})"); + if (reversed.Count == 0) Fail("flow", "no reversed-s ray is covered: the fixture drifted off the saddle"); + if (judged < 200) Fail("flow", $"only {judged} pixels judged"); + if (shipped > WrongWayBound) Fail("flow", $"wrong-way share {shipped:P2} > {WrongWayBound:P0}"); + } + finally + { + command.Release(); + target.Release(); + UnityEngine.Object.DestroyImmediate(target); + renderer.Release(); + if (field != null) { field.Release(); UnityEngine.Object.DestroyImmediate(field); } + view.Dispose(); + fieldCamera.Dispose(); + } + } + + // ---- stress, captures and cost ------------------------------------------------------------------------------------ + + // 60 soft-core wells over 1920 x 1080 units at 1 u per texel, steep enough that the contour levels crowd below a pixel. + static float[] StressValues(out float range) + { + const int W = 1920, H = 1080; + var rng = new System.Random(11); + var wells = Enumerable.Range(0, 60).Select(_ => (x: (float)rng.NextDouble() * W, y: (float)rng.NextDouble() * H, + k: 800f + (float)rng.NextDouble() * 3200f, c: 6f + (float)rng.NextDouble() * 14f)).ToArray(); + var values = new float[W * H]; + for (var y = 0; y < H; y++) + for (var x = 0; x < W; x++) + { + var d = 0f; + foreach (var w in wells) + { + var dx = x + .5f - w.x; var dy = y + .5f - w.y; + d += w.k / Mathf.Sqrt(dx * dx + dy * dy + w.c * w.c); + } + values[y * W + x] = d; + } + range = 900f; + return values; + } + + static RenderTexture FieldFrom(float[] values, int width, int height) + { + var texture = new Texture2D(width, height, TextureFormat.RFloat, false); + texture.SetPixelData(values, 0); + texture.Apply(false); + var target = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat) { filterMode = FilterMode.Point }; + target.Create(); + Graphics.CopyTexture(texture, target); + UnityEngine.Object.DestroyImmediate(texture); + return target; + } + + static void StressAndPool(Zone zone, Orbit[] orbits) + { + var values = StressValues(out var range); + var field = FieldFrom(values, 1920, 1080); + var view = Ortho(new Vector2(960f, 540f), 540f, 1920, 1080); + var renderer = new IsolineRenderer(ExtractShader, RenderShader, ShippedSegments, ShippedPool); + var target = new RenderTexture(1920, 1080, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear) { enableRandomWrite = true }; + target.Create(); + var command = new CommandBuffer { name = "IsolineStress" }; + try + { + var levels = new IsolineExtractor.IsolineLevels(0f, range, 1000f, SlopeEpsilon); + // texel (x, y) sits at world (x, y) + .5: origin (.5, .5), step 1 + renderer.Record(command, field, new Vector2(.5f, .5f), Vector2.one, levels, view.ViewProjection, target, IsolineLook.Default, 0f); + Graphics.ExecuteCommandBuffer(command); + var stats = new uint[6]; + renderer.Stats.GetData(stats); + var (_, counts) = ReadExtraction(renderer.Extractor); + Info($"stress 1920 x 1080: Stats [{string.Join(", ", stats)}], extraction Count [{counts[0]}, {counts[1]}] (capacity {ShippedSegments}), pool use {stats[1]} of {ShippedPool} ({stats[1] / (double)ShippedPool:P1})"); + if (stats[2] != 0) Fail("pool guard", $"the shipped pool truncated {stats[2]} entries at the stress field"); + if (stats[4] != counts[0] || stats[5] != counts[1]) Fail("pool guard", $"Stats[4..5] {stats[4]},{stats[5]} differ from the extractor's {counts[0]},{counts[1]}"); + if (counts[1] > ShippedSegments) Fail("pool guard", $"the stress field requests {counts[1]} segments > capacity {ShippedSegments}"); + Save("stress.png", target, 1920, 1080); + } + finally + { + command.Release(); + target.Release(); + UnityEngine.Object.DestroyImmediate(target); + renderer.Release(); + field.Release(); + UnityEngine.Object.DestroyImmediate(field); + view.Dispose(); + } + } + + // The target as an sRGB PNG over black (straight alpha, linear colour). + static void Save(string name, RenderTexture target, int w, int h) + { + var pixels = Read(target); + var png = new Texture2D(w, h, TextureFormat.RGBA32, false, true); + var colours = new Color32[w * h]; + for (var i = 0; i < colours.Length; i++) + { + var p = pixels[i]; + float E(float v) => Mathf.LinearToGammaSpace(Mathf.Clamp01(v * p.w)); + colours[i] = new Color(E(p.x), E(p.y), E(p.z), 1f); + } + png.SetPixels32(colours); + png.Apply(); + var path = Path.Combine(_out, name); + File.WriteAllBytes(path, png.EncodeToPNG()); + UnityEngine.Object.DestroyImmediate(png); + _wrote += path + "\n"; + Info($"wrote {path}"); + } + + static void SaveBlit(string name, RenderTexture picture) + { + var read = new Texture2D(picture.width, picture.height, TextureFormat.RGBA32, false); + var previous = RenderTexture.active; + RenderTexture.active = picture; + read.ReadPixels(new Rect(0, 0, picture.width, picture.height), 0, 0); + read.Apply(); + RenderTexture.active = previous; + var path = Path.Combine(_out, name); + File.WriteAllBytes(path, read.EncodeToPNG()); + UnityEngine.Object.DestroyImmediate(read); + _wrote += path + "\n"; + Info($"wrote {path}"); + } + + static RenderTexture HalfTarget(int w, int h) + { + var t = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear) { enableRandomWrite = true }; + t.Create(); + return t; + } + + static void CapturesAndCost(Zone zone, Orbit[] orbits) + { + var range = ContourRange(zone, orbits); + var levels = new IsolineExtractor.IsolineLevels(0f, range, zone.Pack.Radius, SlopeEpsilon); + var look = IsolineLook.Default; + var minimapMaterial = AssetDatabase.LoadAssetAtPath("Assets/Materials/UI/Minimap Gravity Lines.mat") ?? throw new InvalidOperationException("No Minimap Gravity Lines.mat."); + var mapMaterial = AssetDatabase.LoadAssetAtPath("Assets/Materials/UI/Map Gravity Lines.mat") ?? throw new InvalidOperationException("No Map Gravity Lines.mat."); + + // minimap: the ARPG scene's own Map Gravity camera draws the 128 x 128 field over the fixture zone + var sceneCamera = UnityEngine.Object.FindObjectsByType(FindObjectsInactive.Include, FindObjectsSortMode.None) + .FirstOrDefault(c => c.name == "Map Gravity") ?? throw new InvalidOperationException("No camera named Map Gravity in ARPG.unity."); + sceneCamera.transform.position = new Vector3(ZoneCentre.x, sceneCamera.transform.position.y, ZoneCentre.y); + var minimapField = RenderField(sceneCamera, 128, 128, out var miniOrigin, out var miniPerTexel); + sceneCamera.aspect = 1f; // the minimap camera renders into a square texture; its matrices must say so off-target too + Blit(minimapMaterial, minimapField, 256, 256, range, 10f, "minimap-before.png"); + var miniRenderer = new IsolineRenderer(ExtractShader, RenderShader, ShippedSegments, ShippedPool); + var miniTarget = HalfTarget(256, 256); + var miniVp = GL.GetGPUProjectionMatrix(sceneCamera.projectionMatrix, true) * sceneCamera.worldToCameraMatrix; + RecordAndSave(miniRenderer, minimapField, miniOrigin, miniPerTexel, levels, miniVp, miniTarget, look, "minimap-after.png"); + + // map screen: a screen-sized field over the same zone, ortho size = height * Scale / 2, material _Scale = Scale / 2 + var mapView = Ortho(ZoneCentre, 1100f, 1920, 1080); + var mapField = RenderField(mapView.Camera, 1920, 1080, out var mapOrigin, out var mapPerTexel); + var mapScale = 2200f / 1080f; + Blit(mapMaterial, mapField, 1920, 1080, range, mapScale / 2f, "map-before.png"); + var mapRenderer = new IsolineRenderer(ExtractShader, RenderShader, ShippedSegments, ShippedPool); + var mapTarget = HalfTarget(1920, 1080); + RecordAndSave(mapRenderer, mapField, mapOrigin, mapPerTexel, levels, mapView.ViewProjection, mapTarget, look, "map-after.png"); + var (mapSegments, mapCounts) = ReadExtraction(mapRenderer.Extractor); + var mapStats = new uint[6]; + mapRenderer.Stats.GetData(mapStats); + Info($"map 1920 x 1080 real zone: Stats [{string.Join(", ", mapStats)}], extraction Count [{mapCounts[0]}, {mapCounts[1]}] (capacity {ShippedSegments}); pool use {mapStats[1]} of {ShippedPool}"); + if (mapStats[2] != 0 || mapCounts[1] > ShippedSegments) Fail("pool guard", $"map: truncated {mapStats[2]}, requested {mapCounts[1]}"); + if (mapStats[4] != mapCounts[0] || mapStats[5] != mapCounts[1]) Fail("pool guard", "map: Stats[4..5] differ from the extractor's Count"); + + // tactical: the follow lens at pitch 55 over the zone, from a 1024 x 1024 field of it + var tacticalCamera = Ortho(ZoneCentre, ZoneHalf, 1024, 1024); + var tacticalField = RenderField(tacticalCamera.Camera, 1024, 1024, out var tOrigin, out var tPerTexel); + var tacticalView = Tactical(new Vector2(380f, -100f), 900f, 55f, 20f, 1280, 720); + var tacticalTarget = HalfTarget(1280, 720); + RecordAndSave(mapRenderer, tacticalField, tOrigin, tPerTexel, levels, tacticalView.ViewProjection, tacticalTarget, look, "tactical.png"); + + // flowing rays: six phases of one dash period around the saddle, from a 512 x 512 field + var flowView = Ortho(Saddle, 300f, 512, 512); + var flowField = RenderField(flowView.Camera, 512, 512, out var fOrigin, out var fPerTexel); + var flowLook = look; + flowLook.Ray.Period = 60f; + flowLook.Ray.Speed = 1f; + var flowTarget = HalfTarget(512, 512); + var flowRenderer = new IsolineRenderer(ExtractShader, RenderShader, ShippedSegments, ShippedPool); + for (var phase = 0; phase < 6; phase++) + RecordAndSave(flowRenderer, flowField, fOrigin, fPerTexel, levels, flowView.ViewProjection, flowTarget, flowLook, $"flow-{phase}.png", phase / 6f); + + Cost("256 x 256 (minimap)", miniRenderer, minimapField, miniOrigin, miniPerTexel, levels, miniVp, miniTarget, look, minimapMaterial, 10f, range); + Cost("1920 x 1080 (map)", mapRenderer, mapField, mapOrigin, mapPerTexel, levels, mapView.ViewProjection, mapTarget, look, mapMaterial, mapScale / 2f, range); + var stressValues = StressValues(out var stressRange); + var stressField = FieldFrom(stressValues, 1920, 1080); + var stressView = Ortho(new Vector2(960f, 540f), 540f, 1920, 1080); + Cost("1920 x 1080 (stress)", mapRenderer, stressField, new Vector2(.5f, .5f), Vector2.one, + new IsolineExtractor.IsolineLevels(0f, stressRange, 1000f, SlopeEpsilon), stressView.ViewProjection, mapTarget, look, mapMaterial, mapScale / 2f, stressRange); + Info("captures:\n" + _wrote); + + foreach (var r in new[] { miniRenderer, mapRenderer, flowRenderer }) r.Release(); + foreach (var t in new[] { miniTarget, mapTarget, tacticalTarget, flowTarget, minimapField, mapField, tacticalField, flowField, stressField }) + { + t.Release(); + UnityEngine.Object.DestroyImmediate(t); + } + mapView.Dispose(); tacticalCamera.Dispose(); tacticalView.Dispose(); flowView.Dispose(); stressView.Dispose(); + } + + // Today's look: the field through a gravity-lines material into an ARGB32 target. + static void Blit(Material asset, RenderTexture field, int w, int h, float range, float scale, string name) + { + var lines = new Material(asset); + lines.SetTexture("_DetailTex", field); + lines.SetFloat("_StartDepth", 0f); + lines.SetFloat("_DepthRange", range); + lines.SetFloat("_Scale", scale); + var picture = new RenderTexture(w, h, 0, RenderTextureFormat.ARGB32); + var previous = RenderTexture.active; + RenderTexture.active = picture; + GL.Clear(true, true, Color.black); + Graphics.Blit(Texture2D.whiteTexture, picture, lines); + RenderTexture.active = previous; + SaveBlit(name, picture); + picture.Release(); + UnityEngine.Object.DestroyImmediate(picture); + UnityEngine.Object.DestroyImmediate(lines); + } + + static void RecordAndSave(IsolineRenderer renderer, RenderTexture field, Vector2 origin, Vector2 perTexel, + IsolineExtractor.IsolineLevels levels, Matrix4x4 viewProjection, RenderTexture target, IsolineLook look, string name, float time = 0f) + { + var command = new CommandBuffer { name = "IsolineCapture" }; + renderer.Record(command, field, origin, perTexel, levels, viewProjection, target, look, time); + Graphics.ExecuteCommandBuffer(command); + command.Release(); + Save(name, target, target.width, target.height); + } + + // GPU time per kernel and Extract. The recorder reads 0 in batchmode (no frame loop), so each pass is timed to a fence + // (a Stats readback) on the wall clock: the kernels are recorded as prefixes (0..6 of Args Clear Bin Scan Scatter Shade), + // each prefix repeated Reps times in one command buffer, and a kernel's cost is the paired difference of two + // neighbouring prefixes in the same iteration. Median of 31 interleaved iterations, ms per pass; the old material blit + // at the same size is timed beside them through a 1 pixel readback. + static void Cost(string label, IsolineRenderer renderer, RenderTexture field, Vector2 origin, Vector2 perTexel, + IsolineExtractor.IsolineLevels levels, Matrix4x4 viewProjection, RenderTexture target, IsolineLook look, + Material oldMaterial, float oldScale, float oldRange) + { + const int Reps = 8, Iterations = 31; + var blitTarget = new RenderTexture(target.width, target.height, 0, RenderTextureFormat.ARGB32); + var lines = new Material(oldMaterial); + lines.SetTexture("_DetailTex", field); + lines.SetFloat("_StartDepth", 0f); + lines.SetFloat("_DepthRange", oldRange); + lines.SetFloat("_Scale", oldScale); + var one = new Texture2D(1, 1, TextureFormat.RGBA32, false); + var recorder = Recorder.Get("IsolineRender"); + recorder.enabled = true; + var scratch = new uint[6]; + // fill the buffers once so the kernel prefixes have segments + var fill = new CommandBuffer(); + renderer.Extractor.Extract(fill, field, origin, perTexel, levels); + Graphics.ExecuteCommandBuffer(fill); + fill.Release(); + + double Time(Action record, Action fence) + { + var command = new CommandBuffer { name = "IsolineRender" }; + for (var i = 0; i < Reps; i++) record(command); + var clock = Stopwatch.StartNew(); + Graphics.ExecuteCommandBuffer(command); + fence(); + clock.Stop(); + command.Release(); + return clock.Elapsed.TotalMilliseconds / Reps; + } + void StatsFence() => renderer.Stats.GetData(scratch); + void PixelFence() + { + var previous = RenderTexture.active; + RenderTexture.active = blitTarget; + one.ReadPixels(new Rect(0, 0, 1, 1), 0, 0); + RenderTexture.active = previous; + } + var prefixes = Enumerable.Range(0, 7).Select(_ => new List()).ToArray(); + var extract = new List(); + var blit = new List(); + for (var iteration = -2; iteration < Iterations; iteration++) + { + for (var k = 0; k <= 6; k++) + { + var stop = k; + var t = Time(c => renderer.Draw(c, renderer.Extractor.Segments, renderer.Extractor.Count, levels, viewProjection, target, look, 0f, false, 0, stop), StatsFence); + if (iteration >= 0) prefixes[k].Add(t); + } + var e = Time(c => renderer.Extractor.Extract(c, field, origin, perTexel, levels), () => renderer.Extractor.Count.GetData(new uint[2])); + var b = Time(c => c.Blit(Texture2D.whiteTexture, blitTarget, lines), PixelFence); + if (iteration >= 0) { extract.Add(e); blit.Add(b); } + } + var names = new[] { "Args", "Clear", "Bin", "Scan", "Scatter", "Shade" }; + var parts = new List(); + double sum = 0; + for (var k = 1; k <= 6; k++) + { + var deltas = prefixes[k].Select((v, i) => v - prefixes[k - 1][i]).ToList(); + var m = Median(deltas); + sum += m; + parts.Add($"{names[k - 1]} {m:F3}"); + } + var total = Median(prefixes[6].Select((v, i) => v - prefixes[0][i]).ToList()); + 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}; old material blit {Median(blit):F3}; fence alone {Median(prefixes[0]):F3}; recorder {(recorder.isValid ? recorder.gpuElapsedNanoseconds / 1e6 + " ms" : "unmeasured (no frame loop)")}"); + recorder.enabled = false; + blitTarget.Release(); + UnityEngine.Object.DestroyImmediate(blitTarget); + UnityEngine.Object.DestroyImmediate(lines); + UnityEngine.Object.DestroyImmediate(one); + } + } +} diff --git a/Assets/Scripts/Editor/IsolineRenderSmoke.cs.meta b/Assets/Scripts/Editor/IsolineRenderSmoke.cs.meta new file mode 100644 index 000000000..8c2a249d1 --- /dev/null +++ b/Assets/Scripts/Editor/IsolineRenderSmoke.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 87b6207c8e82c354b878bc6c6c6aee5d \ No newline at end of file