Isoline curvature path deleted: rho, kappa, the Hessian, PullSlope, the seam and clamp key bits, RhoMax

Once s is chain arclength nothing reads curvature (campaign aetheria-release, cut isoline-chain-arclength).
GravityField.ProfileSlope and PullSlope, the gravityTermPullSlope template and gravitySample's Hessian go (Gravity.cginc
regenerated); Sample writes (gx, gy, d, |g|); March and Crossing lose rho, seam and clamp; IsoKey is (level, family) with
bits 9..31 reserved 0; IsolineLevels loses RhoMax. Rays' and contours' s are 0 until the chain kernels land. The smokes lose
every curvature bound and the s-quality gates; PullSlope stays recoverable at c551a27d6.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-12-01 00:46:37 +01:00
commit 3cb2b756c3
9 changed files with 88 additions and 519 deletions

View file

@ -15,7 +15,7 @@ using Debug = UnityEngine.Debug;
namespace Aetheria.EditorTools
{
/// <summary>
/// Batchmode check for campaign aetheria-release, cuts isoline-extraction and isoline-s-from-exact-curvature:
/// Batchmode check for campaign aetheria-release, cuts isoline-extraction and isoline-chain-arclength:
/// IsolineExtract.compute evaluates a gravity field in closed form from its lowered wells and writes the segments of its
/// contours and iso-angle rays into IsolineExtractor's buffer. Each check reads the buffer back (here only; the runtime
/// never reads back) and compares it with what the field says: the real zone's own lowered terms, judged by Zone.GetHeight,
@ -31,7 +31,6 @@ namespace Aetheria.EditorTools
public static class IsolineExtractSmoke
{
const string Tag = "[IsolineExtractSmoke]";
const float RhoMax = 500f;
const float SlopeEpsilon = 1e-3f;
const int Contours = 21;
@ -41,29 +40,14 @@ namespace Aetheria.EditorTools
// Contour endpoint's |-GetHeight - level|, in level spacings, over the real zone: shipped worst 0.0705, least mutant
// (crossing at the edge midpoint) 0.512, separation 7.25. Re-set on the analytic sample if the run moves them.
const float LevelErrorBound = 0.19f;
// Ring ratio sum|ds| / sum(length) minus 1, worst over a profile's rings, on the softened log wells (rho = r exactly):
// shipped worst 5.3e-4; least mutant (rho = d / |grad d|, tight well) 0.715, separation 37; the raw-theta mutant reads 0.99.
const float ArcRatioBound = 0.0195f;
// Ray endpoint |s / r - 1| on the same wells: shipped worst 5.4e-4; least mutant (rho = d / |grad d|) 0.697, separation 36.
const float RayRhoBound = 0.0194f;
// Ray endpoint's angle off its level, rad: shipped worst 4.0e-4; least mutant (levels half a step off) 0.262, separation 25.
const float RayAngleBound = 0.0103f;
// Endpoint depth |depth / d(r) - 1| and slope |slope / |d'(r)| - 1| on the radial wells: shipped worst 3.5e-4 and 1.1e-3.
// The bounds are the previous fixtures' (their mutants were read on the texture path and not re-read on the well fixtures).
const float DepthBound = 0.0049f;
const float SlopeBound = 0.0133f;
// Share of the real zone's rays or contours carrying the rho-clamp bit at RhoMax = the zone's radius.
const float ClampedBound = 0.13f;
// Share of unclamped real-zone rays whose s rises with depth.
const float WrongWayBound = 0.226f;
// The analytic sample against the law: d within GravityFieldParityVerify.Tolerance (0.03 u), the gradient angle within its
// GradientDegrees (3) where |grad| exceeds its FlatForce (1e-3): the parity verify's own ruled ceilings. kappa through rho
// = 1 / |kappa| against the CPU closed form in double over the same records, worst relative error over unclamped samples
// where |grad| > FlatForce: shipped worst 0.0023 (real zone), least mutant PullSlope = 0 13.1 (the saddle fixture; the
// real zone reads 150), sqrt(0.0023 x 13.1) = 0.174, separation 75. On a radial well kappa does not depend on PullSlope,
// so the radial fixtures cannot claim that mutant.
const float AnalyticRhoBound = 0.174f;
static float _zoneRhoMax;
// GradientDegrees (3) where |grad| exceeds its FlatForce (1e-3): the parity verify's own ruled ceilings.
static bool _ok = true;
static string _out;
@ -83,7 +67,7 @@ namespace Aetheria.EditorTools
public IsolineExtractor.IsoSegment[] Segments; // the written ones
public IsolineExtractor.IsoSegment[] Backing; // the whole buffer
public uint Written, Requested;
public Vector4[] Samples; // (gx, gy, d, rho) per sample, row-major
public Vector4[] Samples; // (gx, gy, d, |g|) per sample, row-major
}
static ComputeShader Shader => AssetDatabase.LoadAssetAtPath<ComputeShader>("Assets/Shaders/IsolineExtract.compute")
@ -115,29 +99,21 @@ namespace Aetheria.EditorTools
return records.Take(terms.Count).ToArray();
}
// d = -height, grad d and the Hessian of d at p, in double, from GravityField over the records: the same closed form the
// shader evaluates. mutantSlope replaces PullSlope by 0 (the mutant the kappa bound is set against).
internal static void CpuSample(GravityLowering.TermRecord[] records, float exaggeration, Vector2 p, bool mutantSlope,
out double d, out double gx, out double gy, out double hxx, out double hxy, out double hyy)
// d = -height and grad d at p, in double, from GravityField over the records: the same closed form the shader evaluates.
internal static void CpuSample(GravityLowering.TermRecord[] records, float exaggeration, Vector2 p, out double d, out double gx, out double gy)
{
double height = 0;
gx = gy = hxx = hxy = hyy = 0;
gx = gy = 0;
foreach (var t in records)
{
double ox = p.x - (double)t.Position.x, oy = p.y - (double)t.Position.y;
var r = Math.Sqrt(ox * ox + oy * oy);
if (!(r < t.Outer)) continue;
height += t.Strength * (double)GravityField.Potential(t.Softening, t.Inner, t.Outer, (float)r) - t.Reference;
var k = -(double)t.Strength / exaggeration;
var slope = mutantSlope ? 0.0 : GravityField.PullSlope(t.Softening, t.Inner, t.Outer, (float)r);
if (r < 1e-6 * t.Softening || r < 1e-20) { hxx += k * slope; hyy += k * slope; continue; }
var pull = (double)GravityField.Pull(t.Softening, t.Inner, t.Outer, (float)r);
double ux = ox / r, uy = oy / r, turn = pull / r;
gx += k * pull * ux;
gy += k * pull * uy;
hxx += k * (slope * ux * ux + turn * (1 - ux * ux));
hxy += k * (slope - turn) * ux * uy;
hyy += k * (slope * uy * uy + turn * (1 - uy * uy));
if (r < 1e-20) continue;
var k = -(double)t.Strength / exaggeration * GravityField.Pull(t.Softening, t.Inner, t.Outer, (float)r) / r;
gx += k * ox;
gy += k * oy;
}
d = -height / exaggeration;
}
@ -200,8 +176,6 @@ namespace Aetheria.EditorTools
static bool IsRay(uint key) => ((key >> 8) & 1u) != 0;
static int LevelOf(uint key) => (int)(key & 0xFFu);
static bool Seam(uint key) => (key & (1u << 9)) != 0;
static bool Clamped(uint key) => (key & (1u << 10)) != 0;
static float Length(IsolineExtractor.IsoSegment s) => (s.b - s.a).magnitude;
// ---- entry -------------------------------------------------------------------------------------------------------
@ -268,7 +242,7 @@ namespace Aetheria.EditorTools
// A 2 x 2 grid under one well whose single cell holds exactly one contour segment, with every field of it known from the
// CPU closed form over the same record: the C# struct is 48 bytes and each field the shader wrote lands in the field the
// C# side reads. RhoMax 10 sits below the contour's radius (17 to 20 u), so the rho-clamp bit is set.
// C# side reads. s is 0 on a contour.
static void Layout()
{
var size = Marshal.SizeOf<IsolineExtractor.IsoSegment>();
@ -281,24 +255,22 @@ namespace Aetheria.EditorTools
var perTexel = new Vector2(2f, 3f);
var corners = new[] { Vector2.zero, new Vector2(1f, 0f), new Vector2(1f, 1f), new Vector2(0f, 1f) }
.Select(c => origin + new Vector2(c.x * perTexel.x, c.y * perTexel.y)).ToArray();
var cpu = corners.Select(c => { CpuSample(records, 1f, c, false, out var d, out var gx, out var gy, out _, out _, out _); return (d, gx, gy); }).ToArray();
var cpu = corners.Select(c => { CpuSample(records, 1f, c, out var d, out var gx, out var gy); return (d, gx, gy); }).ToArray();
var mean = (float)(cpu[0].d + cpu[3].d) / 2f;
var spacing = 4f * (float)Math.Abs(cpu[3].d - cpu[0].d);
var levels = new IsolineExtractor.IsolineLevels(mean - spacing, 20f * spacing, 10f, SlopeEpsilon);
var levels = new IsolineExtractor.IsolineLevels(mean - spacing, 20f * spacing, SlopeEpsilon);
var result = Extract(terms, origin, perTexel, new Vector2Int(2, 2), levels, 16);
if (result.Written != 1 || result.Requested != 1) { Fail("layout", $"expected one segment, written {result.Written} requested {result.Requested}"); return; }
var s = result.Segments[0];
void Near(string what, float got, float want, float tolerance = 1e-3f) { if (Math.Abs(got - want) > tolerance) Fail("layout", $"{what}: {got:G8}, expected {want:G8}"); }
Near("a.x", s.a.x, 10f); Near("a.y", s.a.y, 21.5f, 2e-3f); Near("b.x", s.b.x, 12f); Near("b.y", s.b.y, 21.5f, 2e-3f);
// edge 3 joins corners 0 and 3 (a), edge 1 joins corners 1 and 2 (b); every value is the clamped rho (10) times the
// corner's angle, unwrapped to corner 0, halfway along the edge
float Theta(int i) => (float)Math.Atan2(-cpu[i].gy, -cpu[i].gx);
float Unwrapped(int i) => Theta(0) + Mathf.DeltaAngle(Theta(0) * Mathf.Rad2Deg, Theta(i) * Mathf.Rad2Deg) * Mathf.Deg2Rad;
// edge 3 joins corners 0 and 3 (a), edge 1 joins corners 1 and 2 (b); the slopes and depths are the corners' halfway
// along the edge, and s is 0 on a contour
float Slope(int i) => (float)Math.Sqrt(cpu[i].gx * cpu[i].gx + cpu[i].gy * cpu[i].gy);
Near("sA", s.sA, 10f * (Unwrapped(0) + Unwrapped(3)) / 2f); Near("sB", s.sB, 10f * (Unwrapped(1) + Unwrapped(2)) / 2f);
Near("sA", s.sA, 0f); Near("sB", s.sB, 0f);
Near("slopeA", s.slopeA, (Slope(0) + Slope(3)) / 2f, 1e-4f); Near("slopeB", s.slopeB, (Slope(1) + Slope(2)) / 2f, 1e-4f);
Near("depthA", s.depthA, mean, 2e-3f); Near("depthB", s.depthB, mean, 2e-3f);
if (s.key != (1u << 10)) Fail("layout", $"key {s.key:X}, expected level 0, contour, no seam, rho clamped (0x400)");
if (s.key != 0) Fail("layout", $"key {s.key:X}, expected level 0, contour, reserved bits 0");
if (s.cell != 0) Fail("layout", $"cell {s.cell}, expected 0");
Info($"layout: {size} bytes, segment a={s.a} b={s.b} s={s.sA:G6}/{s.sB:G6} slope={s.slopeA:G4}/{s.slopeB:G4} depth={s.depthA:G4}/{s.depthB:G4} key={s.key:X} cell={s.cell}");
}
@ -326,7 +298,7 @@ namespace Aetheria.EditorTools
try
{
var back = ReadRecords(terms);
float D(int x, int y) { CpuSample(back, 1f, Texel(x, y), false, out var d, out _, out _, out _, out _, out _); return (float)d; }
float D(int x, int y) { CpuSample(back, 1f, Texel(x, y), out var d, out _, out _); return (float)d; }
var corner = new[] { D(cx, cx), D(cx + 1, cx), D(cx + 1, cx + 1), D(cx, cx + 1) };
var mean = .25f * (corner[0] + corner[1] + corner[2] + corner[3]);
var high = Math.Min(corner[0], corner[2]);
@ -335,7 +307,7 @@ namespace Aetheria.EditorTools
var delta = .2f * (Math.Min(corner[0], corner[2]) - Math.Max(corner[1], corner[3]));
var spacing = 2f * delta;
var start = mean - 3.5f * spacing;
var result = Extract(terms, origin, perTexel, new Vector2Int(n, n), new IsolineExtractor.IsolineLevels(start, 20f * spacing, RhoMax, SlopeEpsilon), 1 << 16);
var result = Extract(terms, origin, perTexel, new Vector2Int(n, n), new IsolineExtractor.IsolineLevels(start, 20f * spacing, SlopeEpsilon), 1 << 16);
var cell = (uint)(cx * n + cx);
// level index 2 is mean - delta (the centre is high), 3 is mean + delta (the centre is low)
foreach (var (level, connected) in new[] { (2, true), (3, false) })
@ -356,7 +328,7 @@ namespace Aetheria.EditorTools
Fail("saddle", $"level {level} ({(connected ? "centre high" : "centre low")}): segments cut off corners {{{string.Join(",", cutOff)}}}, expected {{{string.Join(",", want)}}}");
}
Info($"saddle: corners {string.Join(", ", corner.Select(c => c.ToString("G6")))} centre mean {mean:G6}");
SamplesMatchTheLaw("saddle", result, terms, origin, perTexel, new Vector2Int(n, n), RhoMax, null);
SamplesMatchTheLaw("saddle", result, terms, origin, perTexel, new Vector2Int(n, n), null);
}
finally { Free(terms); }
}
@ -411,55 +383,22 @@ namespace Aetheria.EditorTools
var (terms, origin, perTexel, centre, start, range) = RadialField(profile);
try
{
var result = Extract(terms, origin, perTexel, new Vector2Int(GridSize, GridSize), new IsolineExtractor.IsolineLevels(start, range, RhoMax, SlopeEpsilon), 1 << 18);
var result = Extract(terms, origin, perTexel, new Vector2Int(GridSize, GridSize), new IsolineExtractor.IsolineLevels(start, range, SlopeEpsilon), 1 << 18);
var contours = result.Segments.Where(s => !IsRay(s.key)).ToArray();
var rays = result.Segments.Where(s => IsRay(s.key)).ToArray();
if (contours.Length < 200 || rays.Length < 100) { Fail("along-line", $"{profile.Name}: {contours.Length} contour and {rays.Length} ray segments, the check would be vacuous"); continue; }
// contours: summed over a level's ring, the change of s over segment length is 1 where s does not wrap (a single
// short segment is dominated by the endpoint interpolation, so the ratio is taken over the ring)
double arcWorst = 0, arcMutant = 0, arcMutantRho = 0;
var arcLevels = 0;
foreach (var ring in contours.Where(s => !Seam(s.key) && !Clamped(s.key) && InBand((s.a + s.b) * .5f - centre)).GroupBy(s => LevelOf(s.key)))
{
double ds = 0, length = 0, rawTheta = 0, dsRho = 0;
foreach (var s in ring)
{
ds += Math.Abs(s.sB - s.sA);
length += Length(s);
// mutant: s = raw theta (the angle itself, no radius): it grows by 1 / r per unit of length
// mutant: rho = d / |grad d|
var thA = Math.Atan2(s.a.y - centre.y, s.a.x - centre.x);
var thB = thA + Mathf.DeltaAngle((float)(thA * Mathf.Rad2Deg), Mathf.Atan2(s.b.y - centre.y, s.b.x - centre.x) * Mathf.Rad2Deg) * Mathf.Deg2Rad;
dsRho += Math.Abs(thB * s.depthB / s.slopeB - thA * s.depthA / s.slopeA);
rawTheta += Math.Abs(Mathf.DeltaAngle(Mathf.Atan2(s.a.y - centre.y, s.a.x - centre.x) * Mathf.Rad2Deg, Mathf.Atan2(s.b.y - centre.y, s.b.x - centre.x) * Mathf.Rad2Deg)) * Mathf.Deg2Rad;
}
arcWorst = Math.Max(arcWorst, Math.Abs(ds / length - 1.0));
arcMutant = Math.Max(arcMutant, Math.Abs(rawTheta / length - 1.0));
arcMutantRho = Math.Max(arcMutantRho, Math.Abs(dsRho / length - 1.0));
arcLevels++;
}
// rays: s is the distance to the centre; the mutants take rho = d / |grad d|, and levels half a step off
double rhoWorst = 0, rhoMutant = 0, angleWorst = 0, angleMutant = 0, worstAt = 0;
var rayCount = 0;
// rays: each endpoint's angle off its level; the mutant puts the levels half a step off
double angleWorst = 0, angleMutant = 0;
var step = 2 * Math.PI / 12;
foreach (var s in rays)
foreach (var p in new[] { s.a, s.b })
{
if (Clamped(s.key)) continue;
foreach (var (p, sv, slope, depth) in new[] { (s.a, s.sA, s.slopeA, s.depthA), (s.b, s.sB, s.slopeB, s.depthB) })
{
var r = (p - centre).magnitude;
if (!InBand(p - centre)) continue;
var error = Math.Abs(sv / r - 1.0);
if (error > rhoWorst) { rhoWorst = error; worstAt = r; }
rhoMutant = Math.Max(rhoMutant, Math.Abs(depth / slope / r - 1.0));
var theta = Math.Atan2(p.y - centre.y, p.x - centre.x);
double Off(double level) { var diff = Math.Abs(theta - level); return Math.Min(diff, 2 * Math.PI - diff); }
angleWorst = Math.Max(angleWorst, Off((LevelOf(s.key) + .5) * step - Math.PI));
angleMutant = Math.Max(angleMutant, Off(LevelOf(s.key) * step - Math.PI));
rayCount++;
}
if (!InBand(p - centre)) continue;
var theta = Math.Atan2(p.y - centre.y, p.x - centre.x);
double Off(double level) { var diff = Math.Abs(theta - level); return Math.Min(diff, 2 * Math.PI - diff); }
angleWorst = Math.Max(angleWorst, Off((LevelOf(s.key) + .5) * step - Math.PI));
angleMutant = Math.Max(angleMutant, Off(LevelOf(s.key) * step - Math.PI));
}
// no ray in the cell that holds the centre
var texel = new Vector2((centre.x - origin.x) / perTexel.x, (centre.y - origin.y) / perTexel.y);
@ -467,21 +406,16 @@ namespace Aetheria.EditorTools
if (rays.Any(s => s.cell == holding)) Fail("rays", $"{profile.Name}: a ray segment lies in the cell holding the well centre");
EndpointAttributes(profile, result.Segments, centre, origin, perTexel, GridSize);
SamplesMatchTheLaw("radial " + profile.Name, result, terms, origin, perTexel, new Vector2Int(GridSize, GridSize), RhoMax, null);
Continuity("radial " + profile.Name, contours, perTexel);
SamplesMatchTheLaw("radial " + profile.Name, result, terms, origin, perTexel, new Vector2Int(GridSize, GridSize), null);
Info($"ray segments per level, {profile.Name}: {string.Join(" ", Enumerable.Range(0, 12).Select(k => rays.Count(r => LevelOf(r.key) == k)))}");
Info($"along-line {profile.Name}: {contours.Length} contour / {rays.Length} ray segments; arc ratio error worst over {arcLevels} rings {arcWorst:G4} (mutants: raw theta {arcMutant:G4}, rho = d/|g| {arcMutantRho:G4}); ray rho error worst {rhoWorst:G4} at r={worstAt:F1} (mutant d/|g| worst {rhoMutant:G4}, {rayCount} endpoints); ray angle error worst {angleWorst:G4} rad (mutant half-step levels {angleMutant:G4})");
{
if (arcWorst > ArcRatioBound) Fail("along-line", $"{profile.Name}: contour |ds|/length is off by {arcWorst:G4} > {ArcRatioBound:G4}");
if (rhoWorst > RayRhoBound) Fail("along-line", $"{profile.Name}: ray s is off the distance by {rhoWorst:G4} > {RayRhoBound:G4}");
if (angleWorst > RayAngleBound) Fail("rays", $"{profile.Name}: a ray endpoint's angle is off its level by {angleWorst:G4} rad > {RayAngleBound:G4}");
}
Info($"along-line {profile.Name}: {contours.Length} contour / {rays.Length} ray segments; ray angle error worst {angleWorst:G4} rad (mutant levels half a step off {angleMutant:G4})");
if (angleWorst > RayAngleBound) Fail("rays", $"{profile.Name}: a ray endpoint's angle is off its level by {angleWorst:G4} rad > {RayAngleBound:G4}");
}
finally { Free(terms); }
}
}
// ---- endpoint attributes, continuity, cell, ray window -----------------------------------------------------------------
// ---- endpoint attributes, cell, ray window -----------------------------------------------------------------
// Slope and depth at each endpoint, against the profile's own d(r) and |d'(r)|. A ray's depth runs along its edge, so an
// end swap or a missing interpolation moves it by far more than the field's sampling error does. Bounds by the margin
@ -522,48 +456,6 @@ namespace Aetheria.EditorTools
if (outside != 0) Fail("cell", $"{what}: {outside} segments have an endpoint outside their cell");
}
// The seam bit says s jumps by a full turn between a straddling cell and its neighbour. At every pair of bitwise-equal
// contour endpoints where s jumps, one side must carry the bit; and the field must have jumps (else the check is vacuous).
static void Continuity(string what, IsolineExtractor.IsoSegment[] contours, Vector2 perTexel)
{
var jump = .5f * Math.Max(Math.Abs(perTexel.x), Math.Abs(perTexel.y));
var seen = new Dictionary<(int, int, int), (float s, bool seam)>();
int jumps = 0, unflagged = 0;
foreach (var seg in contours)
foreach (var (p, sv) in new[] { (seg.a, seg.sA), (seg.b, seg.sB) })
{
var key = (LevelOf(seg.key), BitConverter.SingleToInt32Bits(p.x), BitConverter.SingleToInt32Bits(p.y));
if (seen.TryGetValue(key, out var other))
{
if (Math.Abs(other.s - sv) > jump)
{
jumps++;
if (!other.seam && !Seam(seg.key)) unflagged++;
}
seen.Remove(key);
}
else seen[key] = (sv, Seam(seg.key));
}
Info($"continuity {what}: {jumps} jumps in s between shared endpoints, {unflagged} without a seam bit");
if (jumps == 0) Fail("seam", $"{what}: no jump in s anywhere; the check is vacuous");
if (unflagged != 0) Fail("seam", $"{what}: {unflagged} jumps in s have no seam-flagged side");
}
// s on the real zone: how much of it the rho clamp spoils, and whether it runs the way the flowing dashes need (a
// ray's s falls as it descends toward a well). The mutant (s negated) reads the complement.
static void RealZoneS(IsolineExtractor.IsoSegment[] segments)
{
var rays = segments.Where(s => IsRay(s.key)).ToArray();
var contours = segments.Where(s => !IsRay(s.key)).ToArray();
double rayClamped = rays.Count(s => Clamped(s.key)) / (double)rays.Length;
double contourClamped = contours.Count(s => Clamped(s.key)) / (double)contours.Length;
var live = rays.Where(s => !Clamped(s.key) && Math.Abs(s.depthB - s.depthA) > 1e-4f).ToArray();
var wrong = live.Count(s => (s.sB - s.sA) * (s.depthB - s.depthA) > 0) / (double)live.Length;
Info($"real zone s: rho clamped on {rayClamped:P1} of rays, {contourClamped:P1} of contours (RhoMax {_zoneRhoMax:G5}); {live.Length} unclamped rays, s rises with depth on {wrong:P1} (mutant s negated {1 - wrong:P1})");
if (rayClamped > ClampedBound || contourClamped > ClampedBound) Fail("real zone s", $"rho is clamped on {rayClamped:P1} of rays, {contourClamped:P1} of contours > {ClampedBound:P0}");
if (wrong > WrongWayBound) Fail("real zone s", $"s rises with depth on {wrong:P1} of unclamped rays > {WrongWayBound:P0}");
}
// Rays exist only where the cell reaches the contour window [Start, Start + Range] (IsolinesUI draws none outside it).
// Window r 50..90 of the offset well: no ray beyond a cell's reach of it, and rays in the middle of it.
static void RayWindow()
@ -574,7 +466,7 @@ namespace Aetheria.EditorTools
{
var start = (float)profile.D(90);
var range = (float)(profile.D(50) - profile.D(90));
var result = Extract(terms, origin, perTexel, new Vector2Int(GridSize, GridSize), new IsolineExtractor.IsolineLevels(start, range, RhoMax, SlopeEpsilon), 1 << 18);
var result = Extract(terms, origin, perTexel, new Vector2Int(GridSize, GridSize), new IsolineExtractor.IsolineLevels(start, range, SlopeEpsilon), 1 << 18);
var rays = result.Segments.Where(s => IsRay(s.key)).ToArray();
var outside = rays.Count(s => new[] { s.a, s.b }.Any(p => (p - centre).magnitude < 44f || (p - centre).magnitude > 96f));
var inside = rays.Count(s => (((s.a + s.b) * .5f) - centre).magnitude is > 60f and < 80f);
@ -592,7 +484,7 @@ namespace Aetheria.EditorTools
var (terms, origin, perTexel, _, start, range) = RadialField(Profiles[0]);
try
{
var levels = new IsolineExtractor.IsolineLevels(start, range, RhoMax, SlopeEpsilon);
var levels = new IsolineExtractor.IsolineLevels(start, range, SlopeEpsilon);
var size = new Vector2Int(GridSize, GridSize);
var full = Extract(terms, origin, perTexel, size, levels, 1 << 18);
var needed = (int)full.Requested;
@ -619,44 +511,28 @@ namespace Aetheria.EditorTools
// ---- the analytic sample ----------------------------------------------------------------------------------------------
// Per sample of the grid: d against the law (truthD, Zone.GetHeight for the real zone; the CPU closed form over the same
// records when null), the gradient angle against the CPU closed form, and rho = 1 / |kappa| against the CPU closed form in
// double, with the mutant PullSlope = 0 (the Hessian's radial part dropped) read beside it.
// records when null), the gradient angle against the CPU closed form.
static void SamplesMatchTheLaw(string what, Result result, GravityLowering.GravityTerms terms, Vector2 origin, Vector2 perTexel,
Vector2Int size, float rhoMax, Func<Vector2, double> truthD)
Vector2Int size, Func<Vector2, double> truthD)
{
var records = ReadRecords(terms);
var texel = Math.Max(Math.Abs(perTexel.x), Math.Abs(perTexel.y));
double dWorst = 0, angleWorst = 0, rhoWorst = 0, rhoMutant = 0;
var rhoCount = 0;
double dWorst = 0, angleWorst = 0;
for (var y = 0; y < size.y; y++)
for (var x = 0; x < size.x; x++)
{
var sample = result.Samples[y * size.x + x];
var p = origin + new Vector2(x * perTexel.x, y * perTexel.y);
CpuSample(records, terms.Exaggeration, p, false, out var d, out var gx, out var gy, out var hxx, out var hxy, out var hyy);
CpuSample(records, terms.Exaggeration, p, out var d, out var gx, out var gy);
dWorst = Math.Max(dWorst, Math.Abs(sample.z - (truthD?.Invoke(p) ?? d)));
var slope = Math.Sqrt(gx * gx + gy * gy);
if (slope <= GravityFieldParityVerify.FlatForce) continue;
var cross = sample.x * gy - sample.y * gx;
var dot = sample.x * gx + sample.y * gy;
angleWorst = Math.Max(angleWorst, Math.Abs(Math.Atan2(cross, dot)) * 180 / Math.PI);
double Rho(double hxx_, double hxy_, double hyy_)
{
var kappa = (gy * gy * hxx_ - 2 * gx * gy * hxy_ + gx * gx * hyy_) / (slope * slope * slope);
return Math.Abs(kappa) > 1e-12 ? 1.0 / Math.Abs(kappa) : double.PositiveInfinity;
}
var rho = Rho(hxx, hxy, hyy);
if (!(rho > texel * 1.01 && rho < rhoMax * .99)) continue;
CpuSample(records, terms.Exaggeration, p, true, out _, out _, out _, out var mxx, out var mxy, out var myy);
rhoWorst = Math.Max(rhoWorst, Math.Abs(sample.w / rho - 1));
rhoMutant = Math.Max(rhoMutant, Math.Abs(Rho(mxx, mxy, myy) / rho - 1));
rhoCount++;
}
Info($"analytic sample, {what}: {size.x * size.y} samples; d worst {dWorst:G3} u (bound {GravityFieldParityVerify.Tolerance:G3}); gradient angle worst {angleWorst:G3} deg (bound {GravityFieldParityVerify.GradientDegrees:G3}); rho worst relative error {rhoWorst:G3} over {rhoCount} unclamped samples (mutant PullSlope = 0 {rhoMutant:G3}, bound {AnalyticRhoBound:G3})");
Info($"analytic sample, {what}: {size.x * size.y} samples; d worst {dWorst:G3} u (bound {GravityFieldParityVerify.Tolerance:G3}); gradient angle worst {angleWorst:G3} deg (bound {GravityFieldParityVerify.GradientDegrees:G3})");
if (dWorst > GravityFieldParityVerify.Tolerance) Fail("analytic sample", $"{what}: d is off the law by {dWorst:G4} u > {GravityFieldParityVerify.Tolerance:G4} (the fallback is a spec revision: stop)");
if (angleWorst > GravityFieldParityVerify.GradientDegrees) Fail("analytic sample", $"{what}: the gradient angle is off by {angleWorst:G4} degrees > {GravityFieldParityVerify.GradientDegrees:G4} (the fallback is a spec revision: stop)");
if (rhoCount < 50) Fail("analytic sample", $"{what}: only {rhoCount} samples carry a kappa reading, the check is vacuous");
if (rhoWorst > AnalyticRhoBound) Fail("analytic sample", $"{what}: rho is off the closed form by {rhoWorst:G4} > {AnalyticRhoBound:G4}");
}
// ---- the real zone -----------------------------------------------------------------------------------------------
@ -703,12 +579,10 @@ namespace Aetheria.EditorTools
{
TopFrame(ZoneCentre, ZoneHalf, 256, 256, out var origin, out var perTexel);
var range = Math.Max(1f, orbits.Max(o => -zone.GetHeight(new float2(o.Position.x, o.Position.y))));
// RhoMax from the zone: its radius, the largest curvature radius a contour can have inside it.
_zoneRhoMax = zone.Pack.Radius;
var levels = new IsolineExtractor.IsolineLevels(0f, range, _zoneRhoMax, SlopeEpsilon);
var levels = new IsolineExtractor.IsolineLevels(0f, range, SlopeEpsilon);
var size = new Vector2Int(256, 256);
var result = Extract(terms, origin, perTexel, size, levels, 1 << 20);
SamplesMatchTheLaw("real zone", result, terms, origin, perTexel, size, _zoneRhoMax, p => -zone.GetHeight(new float2(p.x, p.y)));
SamplesMatchTheLaw("real zone", result, terms, origin, perTexel, size, p => -zone.GetHeight(new float2(p.x, p.y)));
var spacing = range / (Contours - 1);
var contours = result.Segments.Where(s => !IsRay(s.key)).ToArray();
if (result.Written != result.Requested) Fail("real zone", $"{result.Requested} requested, only {result.Written} written");
@ -758,9 +632,7 @@ namespace Aetheria.EditorTools
if (!Border(p) && seen[(LevelOf(s.key), BitConverter.SingleToInt32Bits(p.x), BitConverter.SingleToInt32Bits(p.y))] != 2)
open++;
Info($"real zone: {open} contour endpoints off the border without exactly one partner");
Continuity("real zone", contours, perTexel);
CellBoxes("real zone", result.Segments, origin, perTexel, 256);
RealZoneS(result.Segments);
if (open != 0) Fail("contours close", $"{open} endpoints are not shared with exactly one other endpoint");
}
@ -796,7 +668,7 @@ namespace Aetheria.EditorTools
File.WriteAllBytes(Path.Combine(_out, "before.png"), before.EncodeToPNG());
// segments.png: the extracted segments over the same frame, contours cyan and rays magenta.
var levels = new IsolineExtractor.IsolineLevels(0f, range, zone.Pack.Radius, SlopeEpsilon);
var levels = new IsolineExtractor.IsolineLevels(0f, range, SlopeEpsilon);
var result = Extract(terms, origin, perTexel, new Vector2Int(128, 128), levels, 1 << 18);
var raster = new Texture2D(CaptureSize, CaptureSize, TextureFormat.RGBA32, false);
raster.SetPixels32(Enumerable.Repeat(new Color32(0, 0, 0, 255), CaptureSize * CaptureSize).ToArray());

View file

@ -27,7 +27,6 @@ namespace Aetheria.EditorTools
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;
@ -45,14 +44,6 @@ namespace Aetheria.EditorTools
const float WrongWayBound = 0.045f;
const float FlowLagBound = 3.5f;
// s quality on the map pose (margin rule against Soul's readings on ab17b688b, the finite-difference mutant; the
// shipped reading is this cut's). Rays |ds|/L (1 is arclength): p5 shipped 0.349 against 0.193 (higher is better), p50 1.00
// against 1.63, p75 1.00 against 7.34, p95 11.4 against 38.7; non-isometric share 19.1% against 57.3%; s sign flips at
// joints 12.2 against 258.4 per 1000; near the deepest well |s - r| / r p50 1.9e-6 against 5.1e-3 (its p95 reads 0.851 on
// both: not separated, unclaimed). Each bound is the geometric mean, separations 1.35, 1.28, 2.7, 1.8, 1.7, 4.6, 52.
const double RayP5Floor = 0.2595, RayP50Ceiling = 1.277, RayP75Ceiling = 2.709, RayP95Ceiling = 21.0;
const double NonIsometricCeiling = 0.3308, SignFlipCeiling = 56.1, NearWellP50Ceiling = 9.86e-5;
static bool _ok = true;
static string _out;
static string _wrote = "";
@ -119,7 +110,7 @@ namespace Aetheria.EditorTools
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);
static IsolineExtractor.IsolineLevels Levels => new IsolineExtractor.IsolineLevels(0f, 1f, SlopeEpsilon);
sealed class Frame
{
@ -288,7 +279,6 @@ namespace Aetheria.EditorTools
var terms = GravityLowering.Lower(zone, 0f, ref wells);
field = GravityLowering.CreateField(material);
Guarded("flow follows depth near the real-zone saddle", () => FlowOnRealZone(zone, orbits, terms));
Guarded("s quality on the map pose", () => SQuality(zone, orbits, terms));
Guarded("stress field and the shipped pool", StressAndPool);
Guarded("captures and cost", () => CapturesAndCost(zone, orbits, terms));
Info(_ok ? "PASS" : "FAIL: see errors above");
@ -607,154 +597,6 @@ namespace Aetheria.EditorTools
}
}
// The real zone at the map pose (1920 x 1080 at 2.04 u/px) through the extractor, its ray and contour chains measured:
// the |ds| / L of every edge (1 is true arclength), s sign flips at joints, and |s - r| / r near the deepest well, where
// the radius is the truth. Readings against Soul's at ab17b688b (finite-difference kappa, unity-r1.log), which are the
// mutant of this cut. Then the dash runs along 20 ray chains at the map pose, the flow frame's |ds| / L at 1.17 u/px, the
// two named kinks at 0.117 u/texel, and the captures flow-after.png and e1-after.png.
static void SQuality(Zone zone, Orbit[] orbits, GravityLowering.GravityTerms terms)
{
var range = ContourRange(zone, orbits);
var levels = new IsolineExtractor.IsolineLevels(0f, range, zone.Pack.Radius, SlopeEpsilon);
var mapView = Ortho(ZoneCentre, 1100f, 1920, 1080);
try
{
var ppx = 2200f / 1080f;
IsolineExtractSmoke.TopFrame(ZoneCentre, 1100f, 1920, 1080, out var mapOrigin, out var mapPerTexel);
var map = ExtractThrough(terms, mapOrigin, mapPerTexel, new Vector2Int(1920, 1080), levels);
var deepest = orbits.OrderByDescending(o => -zone.GetHeight(new float2(o.Position.x, o.Position.y))).First();
var well1 = new Vector2(deepest.Position.x, deepest.Position.y);
var rays = BuildChains(map, 1u);
var contours = BuildChains(map, 0u);
Info($"s quality: map pose, {map.Length} segments, {rays.Count} ray chains, {contours.Count} contour chains");
foreach (var (label, chains) in new[] { ("rays", rays), ("contours", contours) })
{
var ratio = new List<double>();
var near = new List<double>();
int edges = 0, nonIso = 0, joints = 0, flips = 0;
foreach (var chain in chains)
{
var e = EdgesOf(map, chain);
for (var i = 0; i < e.Count; i++)
{
edges++;
var r = e[i].L > 1e-6f ? Mathf.Abs(e[i].Ds) / e[i].L : 0f;
ratio.Add(r);
if (r < .5f || r > 2f) nonIso++;
var mid = (e[i].P0 + e[i].P1) * .5f;
if (label == "rays" && (mid - well1).magnitude < 900f
&& orbits.All(o => o == deepest || (mid - new Vector2(o.Position.x, o.Position.y)).magnitude > 250f))
near.Add(Mathf.Abs((e[i].S0 + e[i].S1) * .5f - (mid - well1).magnitude) / Mathf.Max((mid - well1).magnitude, 1f));
if (i + 1 < e.Count)
{
joints++;
if (Sgn(e[i].Ds) * Sgn(e[i + 1].Ds) < 0f) flips++;
}
}
}
if (label == "rays")
{
var nonIsoShare = nonIso / (double)Math.Max(edges, 1);
var flipRate = flips * 1000.0 / Math.Max(joints, 1);
if (Pct(ratio, .05) < RayP5Floor) Fail("s quality", $"rays |ds|/L p5 {Pct(ratio, .05):G4} < {RayP5Floor:G4}");
if (Pct(ratio, .5) > RayP50Ceiling) Fail("s quality", $"rays |ds|/L p50 {Pct(ratio, .5):G4} > {RayP50Ceiling:G4}");
if (Pct(ratio, .75) > RayP75Ceiling) Fail("s quality", $"rays |ds|/L p75 {Pct(ratio, .75):G4} > {RayP75Ceiling:G4}");
if (Pct(ratio, .95) > RayP95Ceiling) Fail("s quality", $"rays |ds|/L p95 {Pct(ratio, .95):G4} > {RayP95Ceiling:G4}");
if (nonIsoShare > NonIsometricCeiling) Fail("s quality", $"non-isometric share {nonIsoShare:P1} > {NonIsometricCeiling:P1}");
if (flipRate > SignFlipCeiling) Fail("s quality", $"s sign flips {flipRate:F1}/1000 > {SignFlipCeiling:F1}");
if (near.Count < 1000 || Pct(near, .5) > NearWellP50Ceiling) Fail("s quality", $"near well 1: {near.Count} edges, |s-r|/r p50 {Pct(near, .5):G4} > {NearWellP50Ceiling:G4}");
}
Info($"s quality {label}: {edges} edges; |ds|/L {Pcts(ratio)}; non-isometric (<0.5 or >2) {nonIso / (double)Math.Max(edges, 1):P1}; s sign flips at joints {flips * 1000.0 / Math.Max(joints, 1):F1}/1000"
+ (near.Count > 0 ? $"; near well 1 ({near.Count} edges) |s-r|/r p50 {Pct(near, .5):G3} p95 {Pct(near, .95):G3}" : ""));
}
// dash runs along the ray chains at the map pose, rays only, Period 160 u (78.5 px)
var rayLook = IsolineLook.Default;
rayLook.Contour.W = 0f; rayLook.Contour.G = 0f; rayLook.Contour.Bloom = 0f; rayLook.Ray.Bloom = 0f;
var e1 = RecordFrame(terms, mapOrigin, mapPerTexel, new Vector2Int(1920, 1080), levels, mapView, rayLook, "e1-after.png");
var rates = new List<double>();
var runs = new List<double>();
foreach (var chain in rays)
{
var e = EdgesOf(map, chain);
if (e.Sum(x => x.L) / ppx < 150f) continue;
var samples = new List<float>();
foreach (var edge in e)
{
var steps = Mathf.Max(1, Mathf.RoundToInt(edge.L / ppx));
for (var q = 0; q < steps; q++)
{
var p = Vector2.Lerp(edge.P0, edge.P1, (q + .5f) / steps);
Project(mapView, p, p, out var pa, out _, out _, out _);
var ix = Mathf.Clamp((int)pa.x, 0, 1919);
var iy = Mathf.Clamp((int)pa.y, 0, 1079);
var m = 0f;
for (var dy = -1; dy <= 1; dy++)
for (var dx = -1; dx <= 1; dx++) m = Mathf.Max(m, e1.At(Mathf.Clamp(ix + dx, 0, 1919), Mathf.Clamp(iy + dy, 0, 1079)).w);
samples.Add(m);
}
}
if (samples.Count < 100) continue;
var threshold = .5f * samples.Max();
if (threshold < .02f) continue;
var on = samples.Select(v => v > threshold).ToList();
var run = 1;
for (var q = 1; q < on.Count; q++)
{
if (on[q] != on[q - 1]) { runs.Add(run); run = 1; }
else run++;
}
}
Info($"dash runs (E1): {runs.Count} runs along the ray chains over 150 px; run length px {Pcts(runs)} (Soul's shipped p5 1, p25 7, p50 38; true arclength p5 28, p25 45, p50 51)");
// the flow frame pose around the saddle (Period 60 u, 512 x 512 over 600 u = 1.17 u/px)
var flowView = Ortho(Saddle, 300f, 512, 512);
try
{
IsolineExtractSmoke.TopFrame(Saddle, 300f, 512, 512, out var flowOrigin, out var flowPerTexel);
var flow = ExtractThrough(terms, flowOrigin, flowPerTexel, new Vector2Int(512, 512), levels);
var flowRatio = new List<double>();
foreach (var chain in BuildChains(flow, 1u))
foreach (var edge in EdgesOf(flow, chain)) flowRatio.Add(edge.L > 1e-6f ? Mathf.Abs(edge.Ds) / edge.L : 0f);
Info($"flow frame: {flowRatio.Count} ray edges at 1.17 u/px, |ds|/L {Pcts(flowRatio)} (Soul's shipped p95 62)");
var flowLook = IsolineLook.Default;
flowLook.Ray.Period = 60f;
flowLook.Ray.Speed = 1f;
RecordFrame(terms, flowOrigin, flowPerTexel, new Vector2Int(512, 512), levels, flowView, flowLook, "flow-after.png");
}
finally { flowView.Dispose(); }
// the two named kinks at 0.117 u/texel (a 120 u crop over 1024 samples) against the map's 2.04
foreach (var (kink, index) in new[] { (new Vector2(586.5f, -625f), 0), (new Vector2(993.5f, -219.7f), 1) })
{
IsolineExtractSmoke.TopFrame(kink, 60f, 1024, 1024, out var fineOrigin, out var finePerTexel);
var fine = ExtractThrough(terms, fineOrigin, finePerTexel, new Vector2Int(1024, 1024), levels);
float WindowTurn(Seg[] segs)
{
var best = 0f;
foreach (var chain in BuildChains(segs, 1u))
{
var e = EdgesOf(segs, chain);
var cumulative = new float[e.Count + 1];
for (var i = 0; i < e.Count; i++) cumulative[i + 1] = cumulative[i] + e[i].L;
for (var i = 1; i < e.Count; i++)
{
if ((e[i].P0 - kink).magnitude > 25f) continue;
int j = i, k = i;
while (j > 0 && cumulative[i] - cumulative[j] < 6f) j--;
while (k < e.Count - 1 && cumulative[k] - cumulative[i] < 6f) k++;
if (cumulative[i] - cumulative[j] < 6f || cumulative[k] - cumulative[i] < 6f) continue;
best = Mathf.Max(best, Vector2.Angle(e[i].P0 - e[j].P0, e[k].P0 - e[i].P0));
}
}
return best;
}
Info($"kink {index} at {kink}: max net turn over 6 u windows {WindowTurn(map):F0} deg at map resolution, {WindowTurn(fine):F0} deg at {finePerTexel.x:F3} u/texel (Soul's shipped: {(index == 0 ? "49 and 180" : "24 and 172")})");
}
}
finally { mapView.Dispose(); }
}
static void Guarded(string name, Action check)
{
try { check(); }
@ -1191,7 +1033,7 @@ namespace Aetheria.EditorTools
{
IsolineExtractSmoke.TopFrame(ZoneCentre, ZoneHalf, 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);
var levels = new IsolineExtractor.IsolineLevels(0f, ContourRange(zone, orbits), SlopeEpsilon);
renderer.Extractor.Extract(command, terms, origin, perTexel, new Vector2Int(256, 256), levels);
renderer.Draw(command, renderer.Extractor.Segments, renderer.Extractor.Count, levels, view.ViewProjection, target, IsolineLook.Default, 0f, true, 1);
Graphics.ExecuteCommandBuffer(command);
@ -1223,7 +1065,6 @@ namespace Aetheria.EditorTools
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;
@ -1282,7 +1123,7 @@ namespace Aetheria.EditorTools
var command = new CommandBuffer { name = "IsolineStress" };
try
{
var levels = new IsolineExtractor.IsolineLevels(0f, range, 1000f, SlopeEpsilon);
var levels = new IsolineExtractor.IsolineLevels(0f, range, SlopeEpsilon);
// texel (x, y) sits at world (x, y) + .5: origin (.5, .5), step 1
renderer.Record(command, terms, new Vector2(.5f, .5f), Vector2.one, new Vector2Int(1920, 1080), levels, view.ViewProjection, target, IsolineLook.Default, 0f);
Graphics.ExecuteCommandBuffer(command);
@ -1352,7 +1193,7 @@ namespace Aetheria.EditorTools
static void CapturesAndCost(Zone zone, Orbit[] orbits, GravityLowering.GravityTerms terms)
{
var range = ContourRange(zone, orbits);
var levels = new IsolineExtractor.IsolineLevels(0f, range, zone.Pack.Radius, SlopeEpsilon);
var levels = new IsolineExtractor.IsolineLevels(0f, range, SlopeEpsilon);
var look = IsolineLook.Default;
var minimapMaterial = AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/UI/Minimap Gravity Lines.mat") ?? throw new InvalidOperationException("No Minimap Gravity Lines.mat.");
var mapMaterial = AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/UI/Map Gravity Lines.mat") ?? throw new InvalidOperationException("No Map Gravity Lines.mat.");
@ -1409,7 +1250,7 @@ namespace Aetheria.EditorTools
var stressField = RenderField(mapView.Camera, 1920, 1080, out _, out _); // the old material's input; it only times the blit
var stressView = Ortho(new Vector2(960f, 540f), 540f, 1920, 1080);
Cost("1920 x 1080 (stress)", mapRenderer, stressTerms, new Vector2Int(1920, 1080), stressField, new Vector2(.5f, .5f), Vector2.one,
new IsolineExtractor.IsolineLevels(0f, stressRange, 1000f, SlopeEpsilon), stressView.ViewProjection, mapTarget, look, mapMaterial, mapScale / 2f, stressRange);
new IsolineExtractor.IsolineLevels(0f, stressRange, SlopeEpsilon), stressView.ViewProjection, mapTarget, look, mapMaterial, mapScale / 2f, stressRange);
stressTerms.Buffer.Release();
Info("captures:\n" + _wrote);