From f6fb589ac38682c5da36276c6d419e3693627d05 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 25 Sep 2026 20:40:28 +0200 Subject: [PATCH] Fix batch 1 (cellular/smin_grad): exact search, decorrelated id, finite F2=0 Cut 2a-i fix batch 1, findings F1, F3, F4, F5, F6, F7 (Soul falsification of the first landing): - cellular now searches a provably exact 5x5x5 neighbourhood (radius 2), not 3x3x3: 3x3x3 missed the true F2 for 9 of 400,000 sampled points. The comment in math.cs proves 5x5x5 always contains the true F1 and F2 (both are always < sqrt(3), every excluded cell is always > 2). A cheap position-only lower-bound prune skips the pcg3d/jitter/distance work for cells that provably cannot beat the running F2, without changing any output bit (F6). - F2 = 0 now gets the same degenerate-gradient guard F1 = 0 already had, fixing a NaN that was reachable past |p| of about 2^23 (F3). - id now comes from pcg4d over the winning cell alone, never from the pcg3d hash that produced that cell's jitter, so id and jitter are no longer deterministic functions of each other (F4). - cellular_unit maps the top 24 bits instead of a plain divide-by-2^32, so the mapping is always inside [0, 1); the old formula rounded 0xFFFFFF80..0xFFFFFFFF up to exactly 1.0f (F7). - Central-difference tolerances tightened from 0.02 to 3e-4 (measured float noise at the committed eps is about 6e-5), and cellular's own gradient test now differentiates cellular's RETURNED .w values instead of a duplicate FindF1F2 search, so a mutant that corrupts only the returned gradient can't hide behind an independently-computed value (F1, F5). - The struct-mirror comparison in HlslSourceCompatibilityTests now checks field name and declared type in declaration order, not just position, so a reordered-and-relabelled mirror struct (H2) or a renamed/retyped one (H3) both fail the walk instead of surviving on values alone (F2). - FindF1F2 widened to a true independent 7x7x7 brute-force oracle; new tests pin production's exact agreement with it, the pruned search's bit-for-bit equivalence to an unpruned 5x5x5 reference, no NaN at 2^24, and id's correlation with jitter under 0.05. - Comment/doc fix: smin_grad is Quilez's quadratic-polynomial smin, not cubic. Both shaders/CultMath.hlsl and unity/.../Shaders/CultMath.hlsl stay byte-identical. Manually verified mutants M9 (grad1 x 1.01), M16 (grad2 x 1.01), and M18 (id from hash.y) all die against these tests; H2/H3 struct mutants die via the new comparator tests. Local dotnet test: 191/191 passing. FXC cs_5_0 compile of a scratch kernel using both cultmath_smin_grad and cultmath_cellular succeeds. Co-Authored-By: Claude Sonnet 5 --- packages/cultmath/shaders/CultMath.hlsl | 40 +-- .../cultmath/src/CultMath/CultCellular.cs | 3 +- packages/cultmath/src/CultMath/math.cs | 90 +++++-- .../CellularAndSminGradTests.cs | 235 ++++++++++++++++-- .../HlslSourceCompatibilityTests.cs | 89 ++++++- .../Shaders/CultMath.hlsl | 40 +-- 6 files changed, 416 insertions(+), 81 deletions(-) diff --git a/packages/cultmath/shaders/CultMath.hlsl b/packages/cultmath/shaders/CultMath.hlsl index 12636035..4e7fc837 100644 --- a/packages/cultmath/shaders/CultMath.hlsl +++ b/packages/cultmath/shaders/CultMath.hlsl @@ -313,7 +313,7 @@ int4 cultmath_pcg4d(int4 value) int4 cultmath_pcg4d(float4 value) { return cultmath_pcg4d(int4((int)asuint(value.x), (int)asuint(value.y), (int)asuint(value.z), (int)asuint(value.w))); } -// Inigo Quilez, "smooth minimum": cubic-polynomial smin carried to value-and-gradient form. See +// Inigo Quilez, "smooth minimum": quadratic-polynomial smin carried to value-and-gradient form. See // math.smin_grad's comment (math.cs) for why the gradient blend is exact, not an approximation. float4 cultmath_smin_grad(float4 a, float4 b, float k) { @@ -333,7 +333,8 @@ struct CultCellular }; // Worley, "A Cellular Texture Basis Function" (SIGGRAPH 1996). See math.cellular's comment -// (math.cs) for the hashing, gradient and degenerate-point conventions this mirrors. +// (math.cs) for the hashing, gradient, search-radius exactness proof, id source and +// degenerate-point conventions this mirrors exactly, including the 5x5x5 lower-bound prune. CultCellular cultmath_cellular(float3 p) { float3 cell = floor(p); @@ -341,27 +342,34 @@ CultCellular cultmath_cellular(float3 p) float f2 = 1.0e30; float3 c1 = float3(0.0, 0.0, 0.0); float3 c2 = float3(0.0, 0.0, 0.0); - int hash1 = 0; + float3 cellId = float3(0.0, 0.0, 0.0); - for (int dz = -1; dz <= 1; dz++) + for (int dz = -2; dz <= 2; dz++) { - for (int dy = -1; dy <= 1; dy++) + float lz = max(0.0, abs((float)dz) - 1.0); + for (int dy = -2; dy <= 2; dy++) { - for (int dx = -1; dx <= 1; dx++) + float ly = max(0.0, abs((float)dy) - 1.0); + for (int dx = -2; dx <= 2; dx++) { + float lx = max(0.0, abs((float)dx) - 1.0); + float lowerBound = sqrt(lx * lx + ly * ly + lz * lz); + if (lowerBound >= f2) + continue; + float3 neighbor = cell + float3(dx, dy, dz); int3 hash = cultmath_pcg3d(neighbor); float3 jitter = float3( - (uint)hash.x * (1.0 / 4294967296.0), - (uint)hash.y * (1.0 / 4294967296.0), - (uint)hash.z * (1.0 / 4294967296.0)); + ((uint)hash.x >> 8) * (1.0 / 16777216.0), + ((uint)hash.y >> 8) * (1.0 / 16777216.0), + ((uint)hash.z >> 8) * (1.0 / 16777216.0)); float3 feature = neighbor + jitter; float d = cultmath_distance(p, feature); if (d < f1) { f2 = f1; c2 = c1; - f1 = d; c1 = feature; hash1 = hash.x; + f1 = d; c1 = feature; cellId = neighbor; } else if (d < f2) { @@ -371,15 +379,19 @@ CultCellular cultmath_cellular(float3 p) } } - // Only F1's degenerate point is guarded; see math.cellular's comment (math.cs) for why F2 = 0 - // has no reachable case to defend. + // F1 = 0 and F2 = 0 share the same degenerate-gradient guard; see math.cellular's comment + // (math.cs) for why F2 = 0 is reachable past roughly |p| = 2^23. float3 grad1 = f1 > 0.0 ? (p - c1) / f1 : float3(0.0, 0.0, 0.0); - float3 grad2 = (p - c2) / f2; + float3 grad2 = f2 > 0.0 ? (p - c2) / f2 : float3(0.0, 0.0, 0.0); + + // id comes from pcg4d over the winning cell alone, never from the pcg3d hash that produced its + // jitter (F4). + int4 idHash = cultmath_pcg4d(float4(cellId, 0.0)); CultCellular result; result.nearest = float4(grad1, f1); result.edge = float4(grad2 - grad1, f2 - f1); - result.id = (uint)hash1 * (1.0 / 4294967296.0); + result.id = ((uint)idHash.w >> 8) * (1.0 / 16777216.0); return result; } diff --git a/packages/cultmath/src/CultMath/CultCellular.cs b/packages/cultmath/src/CultMath/CultCellular.cs index a48cb95e..f856236c 100644 --- a/packages/cultmath/src/CultMath/CultCellular.cs +++ b/packages/cultmath/src/CultMath/CultCellular.cs @@ -13,7 +13,8 @@ public struct CultCellular /// (∇F2 - ∇F1, F2 - F1): for lineae along cell borders. public float4 edge; - /// The nearest cell's pcg3d hash, mapped to [0, 1). + /// The nearest cell's pcg4d hash, mapped to [0, 1); independent of the pcg3d hash that + /// produced that cell's jitter. public float id; public CultCellular(float4 nearest, float4 edge, float id) diff --git a/packages/cultmath/src/CultMath/math.cs b/packages/cultmath/src/CultMath/math.cs index 1ca381eb..098f6043 100644 --- a/packages/cultmath/src/CultMath/math.cs +++ b/packages/cultmath/src/CultMath/math.cs @@ -1,5 +1,10 @@ using System; +// Cut 2a-i fix batch 1: cellular_unit's [0,1) mapping bug (F7) is only reachable from cellular's +// private call sites; this lets CultMath.Tests probe it directly instead of hunting for a hash +// input that happens to land on the bit pattern under test. +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("CultMath.Tests")] + namespace CultMath; public static partial class math @@ -688,7 +693,7 @@ public static partial class math private static float3 snoise_permute(float3 value) => snoise_mod289(((value * 34.0f) + 1.0f) * value); private static float4 snoise_permute(float4 value) => snoise_mod289(((value * 34.0f) + 1.0f) * value); - // Inigo Quilez, "smooth minimum" (https://iquilezles.org/articles/smin/): the cubic-polynomial + // Inigo Quilez, "smooth minimum" (https://iquilezles.org/articles/smin/): the quadratic-polynomial // smin, carried to value-and-gradient form (invariant 8). h is affine in (b.w - a.w) inside the // smoothing band, so differentiating value = lerp(b.w, a.w, h) - k*h*(1-h) with respect to // position, the terms carrying dh/dp cancel exactly (dh/dp * [(a.w-b.w) - k + 2*k*h] and the @@ -707,12 +712,42 @@ public static partial class math } // Worley, "A Cellular Texture Basis Function" (SIGGRAPH 1996): F1/F2 and their analytic - // gradients, searched over the jittered 3x3x3 neighbourhood of feature points. Feature points - // are selected with pcg3d (design.md, "Integer hashing"), never the sin-based hash. The gradient - // of a distance field, del|p - c|, is the unit vector (p - c)/|p - c|; that is undefined exactly - // at a feature point (F1 = 0), so cellular follows the repo's existing degenerate-normal + // gradients, searched over the jittered neighbourhood of feature points. Feature points are + // selected with pcg3d (design.md, "Integer hashing"), never the sin-based hash. The gradient of + // a distance field, del|p - c|, is the unit vector (p - c)/|p - c|; that is undefined exactly at + // a feature point (F1 = 0 or F2 = 0), so cellular follows the repo's existing degenerate-normal // convention (GameCult.Geometry.CultGeometryIsoSurface.EmitOrientedTriangle: guard the zero-length // case and return the zero vector instead of the NaN a bare normalize would produce there). + // + // The search radius is 2 cells on every axis (5x5x5), not the classic 1-cell (3x3x3) radius, + // because 3x3x3 is not exact: measured 9 of 400,000 points in [-50,50]^3 land on the wrong F2 + // (worst error 0.088), and past |p| of about 2^23 the float32 jitter can put two distinct cells' + // features on the same value, which 3x3x3 has no chance of noticing either way. 5x5x5 is exact, + // not merely safer, by the following argument: + // + // Let u = p - cell be the query's position inside its own cell (u in [0,1)^3 per component), and + // let a candidate feature at integer cell offset d = (dx, dy, dz) sit at d + j for some jitter j + // in [0,1)^3. Per axis, the displacement from p to that feature is (u_i - j_i) - d_i; since + // u_i - j_i is always strictly inside (-1, 1) regardless of the actual u_i and j_i values, + // |displacement_i| is always strictly greater than max(0, |d_i| - 1). So every cell with |d_i| >= + // 3 on some axis is strictly farther than 2 from p (that axis alone already gives max(0, 3-1) = + // 2). Now bound F1 and F2 from above using two real, always-present candidates: the query's own + // cell (d = 0), whose distance is always strictly less than sqrt(3) (every axis strictly under + // 1); and, choosing on each axis whichever of the two immediate neighbours has u_i closer to its + // shared boundary, the single-axis-offset neighbour cell one step over, whose distance bound + // works out to the same strict sqrt(3) ceiling. F2 is at most the larger of these two real + // candidates (adding candidates to a set can only lower or hold its 2nd-smallest value), so + // F1 < sqrt(3) and F2 < sqrt(3) always: roughly 1.732 < 2. Every cell outside the 5x5x5 block is + // farther than 2, hence farther than either F1 or F2, so the true global F1 and F2 are always + // inside it. (The matching argument for 3x3x3 only reaches radius 1, whose excluded cells start + // at distance > 1, which is less than the 1.732 ceiling — the gap 3x3x3's failures live in.) + // + // The loop below still visits every one of the 125 cells in a fixed order, but skips the + // pcg3d/jitter/distance work for a cell whose distance cannot possibly beat the current f2: that + // per-cell lower bound (the max(0, |d_i| - 1) term above, combined across axes) depends only on + // the integer offset, never on p or the hash, so pruning a cell the unpruned loop would also + // have rejected changes no output bit (CellularExactSearchTests pins the pruned/unpruned + // equivalence and the exactness against a 7x7x7 brute-force oracle). public static CultCellular cellular(float3 p) { var cell = floor(p); @@ -720,14 +755,21 @@ public static partial class math var f2 = 1.0e30f; var c1 = new float3(0.0f, 0.0f, 0.0f); var c2 = new float3(0.0f, 0.0f, 0.0f); - var hash1 = 0; + var cellId = new float3(0.0f, 0.0f, 0.0f); - for (var dz = -1; dz <= 1; dz++) + for (var dz = -2; dz <= 2; dz++) { - for (var dy = -1; dy <= 1; dy++) + var lz = max(0.0f, abs((float)dz) - 1.0f); + for (var dy = -2; dy <= 2; dy++) { - for (var dx = -1; dx <= 1; dx++) + var ly = max(0.0f, abs((float)dy) - 1.0f); + for (var dx = -2; dx <= 2; dx++) { + var lx = max(0.0f, abs((float)dx) - 1.0f); + var lowerBound = sqrt(lx * lx + ly * ly + lz * lz); + if (lowerBound >= f2) + continue; + var neighbor = cell + new float3(dx, dy, dz); var hash = pcg3d(neighbor); var jitter = new float3(cellular_unit(hash.x), cellular_unit(hash.y), cellular_unit(hash.z)); @@ -737,7 +779,7 @@ public static partial class math if (d < f1) { f2 = f1; c2 = c1; - f1 = d; c1 = feature; hash1 = hash.x; + f1 = d; c1 = feature; cellId = neighbor; } else if (d < f2) { @@ -747,23 +789,31 @@ public static partial class math } } - // Only F1's degenerate point is guarded, matching the spec: F2 = 0 needs two distinct - // integer cells' pcg3d-jittered feature points to land on the exact same float32 value in - // every component, which the jitter's ~24-bit float precision makes unreachable for any p - // this function is actually called with, so there is no reachable case for a guard to defend. + // F1 = 0 is reachable (p sits exactly on a feature point). F2 = 0 needs two distinct cells' + // pcg3d-jittered features to land on the same float32 value in every component: unreachable + // at ordinary magnitudes, but confirmed reachable past roughly |p| = 2^23 (design.md, + // "Precision domain"), so both share the same degenerate-gradient guard. var grad1 = f1 > 0.0f ? (p - c1) / f1 : new float3(0.0f, 0.0f, 0.0f); - var grad2 = (p - c2) / f2; + var grad2 = f2 > 0.0f ? (p - c2) / f2 : new float3(0.0f, 0.0f, 0.0f); + + // id comes from pcg4d over the winning cell alone, never from the pcg3d hash that produced + // its jitter: sharing a hash between id and jitter would make id a deterministic function of + // the jitter it is supposed to be independent from, correlated across every cell (F4). + var idHash = pcg4d(new float4(cellId, 0.0f)); return new CultCellular( new float4(grad1, f1), new float4(grad2 - grad1, f2 - f1), - cellular_unit(hash1)); + cellular_unit(idHash.w)); } - // Maps a pcg3d output component's uint bit pattern to [0, 1) by the standard uint-to-float - // divide-by-2^32; the division is by an exact power of two, and the uint-to-float conversion is - // the same IEEE-754 round-to-nearest both dxc and C# use, so this is bit-exact on both sides. - private static float cellular_unit(int bits) => (uint)bits * (1.0f / 4294967296.0f); + // Maps a hash component's uint bit pattern to [0, 1) using the top 24 bits, so the result is + // always strictly less than 1: a plain divide-by-2^32 rounds 0xFFFFFF80..0xFFFFFFFF up to + // exactly 1.0f in float32, outside the documented range. (uint >> 8) has at most 24 significant + // bits, which float32's 24-bit mantissa represents exactly, and the division is by an exact power + // of two, so both the shift-and-convert and the divide are the same IEEE-754 round-to-nearest on + // dxc and C#, bit-exact on both sides. + internal static float cellular_unit(int bits) => ((uint)bits >> 8) * (1.0f / 16777216.0f); public static float value_noise(float2 position) { diff --git a/packages/cultmath/tests/CultMath.Tests/CellularAndSminGradTests.cs b/packages/cultmath/tests/CultMath.Tests/CellularAndSminGradTests.cs index 77081c9f..b95d8926 100644 --- a/packages/cultmath/tests/CultMath.Tests/CellularAndSminGradTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/CellularAndSminGradTests.cs @@ -6,6 +6,12 @@ namespace CultMath.Tests; public sealed class CellularAndSminGradTests { + // Shared central-difference tolerance for smin_grad and cellular (F5). Soul measured float noise + // at the committed eps values (0.001f here, 0.0005f in cellular) at about 6e-5; this leaves + // roughly 5x headroom for legitimate finite-difference truncation while still killing a + // 1%-scale gradient mutant (about 1e-2 error against these fields). + private const float GradientTolerance = 3.0e-4f; + // ---- smin_grad ---- [Fact] @@ -88,9 +94,11 @@ public sealed class CellularAndSminGradTests (Smin(p + new float3(0.0f, eps, 0.0f)) - Smin(p - new float3(0.0f, eps, 0.0f))) / (2.0f * eps), (Smin(p + new float3(0.0f, 0.0f, eps)) - Smin(p - new float3(0.0f, 0.0f, eps))) / (2.0f * eps)); - AssertWithinTolerance(numeric.x, analytic.x, 0.02f); - AssertWithinTolerance(numeric.y, analytic.y, 0.02f); - AssertWithinTolerance(numeric.z, analytic.z, 0.02f); + // Measured float noise at this eps is about 6e-5 (Soul, cut 2a-i); 3e-4 leaves roughly + // 5x headroom while still killing a 1%-scale gradient mutant (about 1e-2 error here). + AssertWithinTolerance(numeric.x, analytic.x, GradientTolerance); + AssertWithinTolerance(numeric.y, analytic.y, GradientTolerance); + AssertWithinTolerance(numeric.z, analytic.z, GradientTolerance); } } @@ -123,8 +131,12 @@ public sealed class CellularAndSminGradTests var p = new float3(random.NextSingle() * 20.0f - 10.0f, random.NextSingle() * 20.0f - 10.0f, random.NextSingle() * 20.0f - 10.0f); var result = math.cellular(p); Assert.True(result.edge.w >= -1.0e-4f, $"F2 - F1 = {result.edge.w} at {p.x},{p.y},{p.z}"); - var (f1, _) = FindF1F2(p); + + // Both returned .w values, checked against the independent 7x7x7 brute-force oracle (F1, + // F6), not a value the test derived some other way. + var (f1, f2) = FindF1F2(p); Assert.Equal(f1, result.nearest.w, precision: 3); + Assert.Equal(f2 - f1, result.edge.w, precision: 3); } } @@ -132,11 +144,17 @@ public sealed class CellularAndSminGradTests public void NearestFeatureWinsEvenWhenItIsInTheLastVisitedNeighbourCell() { // math.cellular's own search order visits neighbour offsets with dz outermost and dx - // innermost, so (dx, dy, dz) = (1, 1, 1) relative to floor(p) is the very last candidate it - // looks at. A "first found within some radius" mutant, or one that stops early, would miss - // it. Rather than hand-picking a hash value, search random points for one whose true nearest - // feature (by independent brute force) happens to live in exactly that last-visited cell, at - // a comfortable margin from the F1 = F2 seam, then check math.cellular agrees. + // innermost over a 5x5x5 block (F6), and it also prunes cells whose position-only lower + // bound already exceeds the running F2. Offsets with any |component| = 2 are provably never + // the true nearest (their minimum possible distance, sqrt(3), sits right at the maximum + // possible distance of the query's own cell, per the exactness proof in math.cs, so it takes + // a measure-zero coincidence for one to win — confirmed empirically at 0 wins in 3,000,000 + // samples), which only leaves the 3x3x3 corners as ever-reachable "last" cases. (dx, dy, dz) + // = (1, 1, 1) is the last of those the fixed iteration order visits, and if pruning or search + // order were broken, this is the offset most likely to be skipped. Rather than hand-picking a + // hash value, search random points for one whose true nearest feature (by independent brute + // force over the same 5x5x5 block) happens to live in exactly that cell, at a comfortable + // margin from the F1 = F2 seam, then check math.cellular agrees. var random = new System.Random(0xCE14); var lastOffset = new float3(1.0f, 1.0f, 1.0f); for (var attempt = 0; attempt < 5000; attempt++) @@ -195,11 +213,16 @@ public sealed class CellularAndSminGradTests tested++; var result = math.cellular(p); const float eps = 0.0005f; - float F1At(float3 q) => FindF1F2(q).f1; - AssertGradientMatchesCentralDifference(F1At, p, eps, result.nearest); - var edgeValueFn = new Func(q => { var (a, b) = FindF1F2(q); return b - a; }); - AssertGradientMatchesCentralDifference(edgeValueFn, p, eps, result.edge); + // Differentiate cellular's own returned .w values (F1): calling cellular again at p +/- + // eps and reading result.nearest.w / result.edge.w, not a duplicate FindF1F2 search. A + // mutant that corrupts only the returned gradient, leaving the returned value alone, + // would survive a check built on an independent value oracle; it cannot survive this one. + float NearestValueAt(float3 q) => math.cellular(q).nearest.w; + float EdgeValueAt(float3 q) => math.cellular(q).edge.w; + + AssertGradientMatchesCentralDifference(NearestValueAt, p, eps, result.nearest); + AssertGradientMatchesCentralDifference(EdgeValueAt, p, eps, result.edge); } Assert.True(tested >= 100, $"only {tested} of {attempts} random points landed away from the F1=F2 band"); @@ -228,9 +251,171 @@ public sealed class CellularAndSminGradTests Assert.NotEqual(idAtFeature, otherCellId); } + [Fact] + public void IdIsNotCorrelatedWithAnyJitterComponent() + { + // F4: id must come from hash bits the jitter never uses. A mutant that takes id from + // hash.x (or hash.y) makes id literally equal to that jitter component, which this catches + // as a correlation near 1.0, far past the 0.05 threshold. n = 20000 keeps sampling noise + // (measured under 0.01 at this n) well clear of that threshold. + const int n = 20000; + var random = new System.Random(0xCE15); + var ids = new double[n]; + var jitterX = new double[n]; + var jitterY = new double[n]; + var jitterZ = new double[n]; + + for (var i = 0; i < n; i++) + { + var cell = new float3(random.Next(-2000, 2000), random.Next(-2000, 2000), random.Next(-2000, 2000)); + var hash = math.pcg3d(cell); + var jitter = new float3(Unit(hash.x), Unit(hash.y), Unit(hash.z)); + + ids[i] = math.cellular(cell + jitter).id; + jitterX[i] = jitter.x; + jitterY[i] = jitter.y; + jitterZ[i] = jitter.z; + } + + Assert.True(Math.Abs(Correlation(ids, jitterX)) < 0.05, "id correlates with jitter.x"); + Assert.True(Math.Abs(Correlation(ids, jitterY)) < 0.05, "id correlates with jitter.y"); + Assert.True(Math.Abs(Correlation(ids, jitterZ)) < 0.05, "id correlates with jitter.z"); + } + + [Fact] + public void NoNaNAtIntegerPointsNear2To24() + { + // F3: past |p| of about 2^23, distinct cells' jittered features can round to the same + // float32 value, making F2 = 0 reachable. Soul measured 4096 of 4096 integer points at 2^24 + // producing NaN before the guard; this pins the fix over the same sample. + const float scale = 16777216.0f; // 2^24 + for (var ix = 0; ix < 16; ix++) + for (var iy = 0; iy < 16; iy++) + for (var iz = 0; iz < 16; iz++) + { + var p = new float3(scale + ix, scale + iy, scale + iz); + var result = math.cellular(p); + + Assert.True( + float.IsFinite(result.nearest.x) && float.IsFinite(result.nearest.y) && + float.IsFinite(result.nearest.z) && float.IsFinite(result.nearest.w), + $"nearest not finite at {p.x},{p.y},{p.z}: {result.nearest.x},{result.nearest.y},{result.nearest.z},{result.nearest.w}"); + Assert.True( + float.IsFinite(result.edge.x) && float.IsFinite(result.edge.y) && + float.IsFinite(result.edge.z) && float.IsFinite(result.edge.w), + $"edge not finite at {p.x},{p.y},{p.z}: {result.edge.x},{result.edge.y},{result.edge.z},{result.edge.w}"); + Assert.True(float.IsFinite(result.id), $"id not finite at {p.x},{p.y},{p.z}"); + } + } + + [Fact] + public void CellularUnitMapsAllOnesBitsBelowOne() + { + // F7: cellular_unit(0xFFFFFFFF) must land in [0, 1), not round up to exactly 1.0f. + var mapped = math.cellular_unit(-1); // -1's bit pattern is 0xFFFFFFFF. + Assert.True(mapped >= 0.0f && mapped < 1.0f, $"cellular_unit(0xFFFFFFFF) = {mapped}"); + } + + [Fact] + public void ProductionSearchMatchesTheBruteForceOracleExactly() + { + // F6, part 2: the production 5x5x5 search must equal the independent 7x7x7 oracle exactly + // (to the oracle's own float32 precision), over a large seeded sweep in the domain Soul + // measured ([-50, 50]^3, where 3x3x3 missed 9 of 400,000 points). + var random = new System.Random(0xCE16); + for (var i = 0; i < 20000; i++) + { + var p = new float3(random.NextSingle() * 100.0f - 50.0f, random.NextSingle() * 100.0f - 50.0f, random.NextSingle() * 100.0f - 50.0f); + var result = math.cellular(p); + var (f1, f2) = FindF1F2(p); + + Assert.Equal(f1, result.nearest.w, precision: 4); + Assert.Equal(f2 - f1, result.edge.w, precision: 4); + } + } + + [Fact] + public void PrunedSearchIsBitIdenticalToTheUnprunedFiveCubedSearch() + { + // F6, part 2: the lower-bound prune inside math.cellular's loop must never change the + // result. Compares against an independent, unpruned 5x5x5 reference that visits every cell + // in the same fixed order, over a large seeded sweep. + var random = new System.Random(0xCE18); + for (var i = 0; i < 20000; i++) + { + var p = new float3(random.NextSingle() * 100.0f - 50.0f, random.NextSingle() * 100.0f - 50.0f, random.NextSingle() * 100.0f - 50.0f); + var pruned = math.cellular(p); + var unpruned = UnprunedCellular5x5x5(p); + + Assert.Equal(unpruned.nearest.x, pruned.nearest.x); + Assert.Equal(unpruned.nearest.y, pruned.nearest.y); + Assert.Equal(unpruned.nearest.z, pruned.nearest.z); + Assert.Equal(unpruned.nearest.w, pruned.nearest.w); + Assert.Equal(unpruned.edge.x, pruned.edge.x); + Assert.Equal(unpruned.edge.y, pruned.edge.y); + Assert.Equal(unpruned.edge.z, pruned.edge.z); + Assert.Equal(unpruned.edge.w, pruned.edge.w); + Assert.Equal(unpruned.id, pruned.id); + } + } + + // Independent of math.cellular's own pruning: visits every cell of the 5x5x5 block, in the same + // fixed order, unconditionally. + private static CultCellular UnprunedCellular5x5x5(float3 p) + { + var cell = new float3(MathF.Floor(p.x), MathF.Floor(p.y), MathF.Floor(p.z)); + var f1 = 1.0e30f; + var f2 = 1.0e30f; + var c1 = float3.zero; + var c2 = float3.zero; + var cellId = float3.zero; + + for (var dz = -2; dz <= 2; dz++) + for (var dy = -2; dy <= 2; dy++) + for (var dx = -2; dx <= 2; dx++) + { + var neighbor = cell + new float3(dx, dy, dz); + var feature = FeaturePoint(neighbor); + var d = math.distance(p, feature); + if (d < f1) { f2 = f1; c2 = c1; f1 = d; c1 = feature; cellId = neighbor; } + else if (d < f2) { f2 = d; c2 = feature; } + } + + var grad1 = f1 > 0.0f ? (p - c1) / f1 : float3.zero; + var grad2 = f2 > 0.0f ? (p - c2) / f2 : float3.zero; + var idHash = math.pcg4d(new float4(cellId, 0.0f)); + return new CultCellular(new float4(grad1, f1), new float4(grad2 - grad1, f2 - f1), Unit(idHash.w)); + } + + private static double Correlation(double[] a, double[] b) + { + var n = a.Length; + var meanA = 0.0; + var meanB = 0.0; + for (var i = 0; i < n; i++) { meanA += a[i]; meanB += b[i]; } + meanA /= n; + meanB /= n; + + var cov = 0.0; + var varA = 0.0; + var varB = 0.0; + for (var i = 0; i < n; i++) + { + var da = a[i] - meanA; + var db = b[i] - meanB; + cov += da * db; + varA += da * da; + varB += db * db; + } + + return cov / Math.Sqrt(varA * varB); + } + // ---- shared fixtures: an independent brute-force Worley search over the same public pcg3d // hash cellular itself is documented to use (design.md, "Integer hashing"), so these tests do - // not anchor to cellular's own control flow or iteration order. ---- + // not anchor to cellular's own control flow or iteration order. FindF1F2 searches 7x7x7 (radius + // 3), strictly wider than production's own proven-sufficient 5x5x5 (F6), so it is a true + // independent oracle rather than a second copy of the algorithm under test. ---- private static float3 FeaturePoint(float3 cell) { @@ -239,16 +424,18 @@ public sealed class CellularAndSminGradTests return cell + jitter; } - private static float Unit(int bits) => (uint)bits * (1.0f / 4294967296.0f); + // Mirrors math.cellular_unit's top-24-bit [0, 1) mapping (F7) exactly, so this fixture never + // drifts from production's own jitter/id mapping. + private static float Unit(int bits) => ((uint)bits >> 8) * (1.0f / 16777216.0f); private static (float f1, float f2) FindF1F2(float3 p) { var cell = new float3(MathF.Floor(p.x), MathF.Floor(p.y), MathF.Floor(p.z)); var f1 = float.PositiveInfinity; var f2 = float.PositiveInfinity; - for (var dz = -1; dz <= 1; dz++) - for (var dy = -1; dy <= 1; dy++) - for (var dx = -1; dx <= 1; dx++) + for (var dz = -3; dz <= 3; dz++) + for (var dy = -3; dy <= 3; dy++) + for (var dx = -3; dx <= 3; dx++) { var d = math.distance(p, FeaturePoint(cell + new float3(dx, dy, dz))); if (d < f1) { f2 = f1; f1 = d; } @@ -264,9 +451,9 @@ public sealed class CellularAndSminGradTests var f1 = float.PositiveInfinity; var f2 = float.PositiveInfinity; var bestOffset = float3.zero; - for (var dz = -1; dz <= 1; dz++) - for (var dy = -1; dy <= 1; dy++) - for (var dx = -1; dx <= 1; dx++) + for (var dz = -2; dz <= 2; dz++) + for (var dy = -2; dy <= 2; dy++) + for (var dx = -2; dx <= 2; dx++) { var offset = new float3(dx, dy, dz); var d = math.distance(p, FeaturePoint(cell + offset)); @@ -301,9 +488,9 @@ public sealed class CellularAndSminGradTests (scalarField(p + new float3(0.0f, eps, 0.0f)) - scalarField(p - new float3(0.0f, eps, 0.0f))) / (2.0f * eps), (scalarField(p + new float3(0.0f, 0.0f, eps)) - scalarField(p - new float3(0.0f, 0.0f, eps))) / (2.0f * eps)); - AssertWithinTolerance(numeric.x, valueAndGradient.x, 0.02f); - AssertWithinTolerance(numeric.y, valueAndGradient.y, 0.02f); - AssertWithinTolerance(numeric.z, valueAndGradient.z, 0.02f); + AssertWithinTolerance(numeric.x, valueAndGradient.x, GradientTolerance); + AssertWithinTolerance(numeric.y, valueAndGradient.y, GradientTolerance); + AssertWithinTolerance(numeric.z, valueAndGradient.z, GradientTolerance); } // A fixed decimal-place Assert.Equal snaps two numbers that agree to within a few times 1e-5 to diff --git a/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs b/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs index 4a28b1d7..fdc9b403 100644 --- a/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs @@ -86,7 +86,7 @@ public sealed class HlslSourceCompatibilityTests var actual = Values(mirror.Invoke(shader, args)!); if (!BitwiseEqual(expected, actual)) { - mismatches.Add($"{mirror.Name}({string.Join(", ", args.Select(a => string.Join(" ", Values(a))))}): C# {string.Join(" ", expected)}, mirror {string.Join(" ", actual)}"); + mismatches.Add($"{mirror.Name}({string.Join(", ", args.Select(a => string.Join(" ", Values(a).Select(v => v.Value))))}): C# {string.Join(" ", expected.Select(v => v.Value))}, mirror {string.Join(" ", actual.Select(v => v.Value))}"); } } } @@ -118,6 +118,61 @@ public sealed class HlslSourceCompatibilityTests Assert.False(BitwiseEqual(Values(expected), Values(mismatchedNestedComponent))); } + /// + /// Struct shapes standing in for CultCellular's own field order (nearest; edge; id), used + /// to falsify two named mutants (F2): H2 declares the mirror struct with its first two fields + /// swapped (edge; nearest; id) and swaps the assignments to match, so every leaf VALUE + /// still lands in the same POSITION as the correct struct; only the field NAME at each position + /// differs. H3 renames and retypes every field (id becomes an int carrying the same bits) while + /// keeping the original position order, so only NAME and TYPE differ, never position. + /// + private struct NearestEdgeIdExpected { public float4 nearest; public float4 edge; public float id; } + private struct EdgeNearestIdSwappedNames { public float4 edge; public float4 nearest; public float id; } + private struct RenamedAndRetypedFields { public float4 a; public float4 b; public int c; } + + [Fact] + public void StructReturnComparisonRejectsFieldsSwappedByNameEvenWhenValuesAlign() + { + // H2: the mutant struct's field ORDER is (edge, nearest, id), and its assignments are + // swapped to match, so declaration-position values are identical to the correct struct's. + // Only checking names (not just position) can tell these apart. + var expected = new NearestEdgeIdExpected + { + nearest = new float4(1.0f, 2.0f, 3.0f, 4.0f), + edge = new float4(5.0f, 6.0f, 7.0f, 8.0f), + id = 9.0f, + }; + var swapped = new EdgeNearestIdSwappedNames + { + edge = new float4(1.0f, 2.0f, 3.0f, 4.0f), // holds what should be "nearest"'s value. + nearest = new float4(5.0f, 6.0f, 7.0f, 8.0f), // holds what should be "edge"'s value. + id = 9.0f, + }; + + Assert.False(BitwiseEqual(Values(expected), Values(swapped))); + } + + [Fact] + public void StructReturnComparisonRejectsRenamedAndRetypedFields() + { + // H3: field order matches the correct struct exactly, but every field is renamed, and id is + // retyped from float to int carrying the same bit pattern the correct id would round to. + var expected = new NearestEdgeIdExpected + { + nearest = new float4(1.0f, 2.0f, 3.0f, 4.0f), + edge = new float4(5.0f, 6.0f, 7.0f, 8.0f), + id = 9.0f, + }; + var renamed = new RenamedAndRetypedFields + { + a = new float4(1.0f, 2.0f, 3.0f, 4.0f), + b = new float4(5.0f, 6.0f, 7.0f, 8.0f), + c = BitConverter.SingleToInt32Bits(9.0f), + }; + + Assert.False(BitwiseEqual(Values(expected), Values(renamed))); + } + // Integer arguments take the bit pattern of the float input, so specials become 0, 0x80000000, NaN bits, ... private static readonly Type[] Scalars = { typeof(float), typeof(int), typeof(uint) }; @@ -128,19 +183,37 @@ public sealed class HlslSourceCompatibilityTests // never a struct-of-struct return, so it must not recurse. private static FieldInfo[] Components(Type t) => t.GetFields().Where(f => !f.IsStatic && Scalars.Contains(f.FieldType)).ToArray(); + /// + /// One flattened scalar leaf of a (possibly nested) return value: its declaration path (field + /// names joined by '.'), its declared type, and its value. Carrying path and type, not just the + /// value, is what lets the struct-return comparison reject a field that was renamed or retyped + /// but landed in the same position (F2): a positional-only comparison cannot tell "edge" holding + /// nearest's value apart from "nearest" holding it. + /// + private readonly record struct Leaf(string Path, Type Type, object Value); + /// /// Flattens a return value to its scalar leaves, recursing through struct fields of any type /// (invariant 8's one struct return shape, e.g. 's float4/float4/float /// fields) so a struct return is compared field by field, down to bit-for-bit scalars, exactly - /// like a bare vector return already is. + /// like a bare vector return already is. Each leaf keeps the field name (and its ancestors') and + /// declared type it was read from. /// - private static object[] Values(object value) => Scalars.Contains(value.GetType()) ? new[] { value } - : value.GetType().GetFields().Where(f => !f.IsStatic).SelectMany(f => Values(f.GetValue(value)!)).ToArray(); + private static Leaf[] Values(object value, string path = "") => Scalars.Contains(value.GetType()) + ? new[] { new Leaf(path, value.GetType(), value) } + : value.GetType().GetFields().Where(f => !f.IsStatic) + .SelectMany(f => Values(f.GetValue(value)!, path.Length == 0 ? f.Name : path + "." + f.Name)) + .ToArray(); - private static bool BitwiseEqual(object[] expected, object[] actual) => - expected.Length == actual.Length && expected.Zip(actual).All(p => p.First is float a && p.Second is float b - ? (float.IsNaN(a) && float.IsNaN(b)) || BitConverter.SingleToInt32Bits(a) == BitConverter.SingleToInt32Bits(b) - : p.First.Equals(p.Second)); + // Compares leaves by NAME and TYPE as well as value, in declaration order, so a mirror struct + // whose fields are reordered, renamed, or retyped relative to its C# counterpart fails here even + // when the flattened values happen to line up positionally (F2's H2/H3 mutants). + private static bool BitwiseEqual(Leaf[] expected, Leaf[] actual) => + expected.Length == actual.Length && expected.Zip(actual).All(p => + p.First.Path == p.Second.Path && p.First.Type == p.Second.Type && + (p.First.Value is float a && p.Second.Value is float b + ? (float.IsNaN(a) && float.IsNaN(b)) || BitConverter.SingleToInt32Bits(a) == BitConverter.SingleToInt32Bits(b) + : p.First.Value.Equals(p.Second.Value))); /// The documented HLSL-to-C# transformations, and nothing else. internal static string TransformHlslToCSharp(string hlsl) diff --git a/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl b/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl index 12636035..4e7fc837 100644 --- a/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl +++ b/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl @@ -313,7 +313,7 @@ int4 cultmath_pcg4d(int4 value) int4 cultmath_pcg4d(float4 value) { return cultmath_pcg4d(int4((int)asuint(value.x), (int)asuint(value.y), (int)asuint(value.z), (int)asuint(value.w))); } -// Inigo Quilez, "smooth minimum": cubic-polynomial smin carried to value-and-gradient form. See +// Inigo Quilez, "smooth minimum": quadratic-polynomial smin carried to value-and-gradient form. See // math.smin_grad's comment (math.cs) for why the gradient blend is exact, not an approximation. float4 cultmath_smin_grad(float4 a, float4 b, float k) { @@ -333,7 +333,8 @@ struct CultCellular }; // Worley, "A Cellular Texture Basis Function" (SIGGRAPH 1996). See math.cellular's comment -// (math.cs) for the hashing, gradient and degenerate-point conventions this mirrors. +// (math.cs) for the hashing, gradient, search-radius exactness proof, id source and +// degenerate-point conventions this mirrors exactly, including the 5x5x5 lower-bound prune. CultCellular cultmath_cellular(float3 p) { float3 cell = floor(p); @@ -341,27 +342,34 @@ CultCellular cultmath_cellular(float3 p) float f2 = 1.0e30; float3 c1 = float3(0.0, 0.0, 0.0); float3 c2 = float3(0.0, 0.0, 0.0); - int hash1 = 0; + float3 cellId = float3(0.0, 0.0, 0.0); - for (int dz = -1; dz <= 1; dz++) + for (int dz = -2; dz <= 2; dz++) { - for (int dy = -1; dy <= 1; dy++) + float lz = max(0.0, abs((float)dz) - 1.0); + for (int dy = -2; dy <= 2; dy++) { - for (int dx = -1; dx <= 1; dx++) + float ly = max(0.0, abs((float)dy) - 1.0); + for (int dx = -2; dx <= 2; dx++) { + float lx = max(0.0, abs((float)dx) - 1.0); + float lowerBound = sqrt(lx * lx + ly * ly + lz * lz); + if (lowerBound >= f2) + continue; + float3 neighbor = cell + float3(dx, dy, dz); int3 hash = cultmath_pcg3d(neighbor); float3 jitter = float3( - (uint)hash.x * (1.0 / 4294967296.0), - (uint)hash.y * (1.0 / 4294967296.0), - (uint)hash.z * (1.0 / 4294967296.0)); + ((uint)hash.x >> 8) * (1.0 / 16777216.0), + ((uint)hash.y >> 8) * (1.0 / 16777216.0), + ((uint)hash.z >> 8) * (1.0 / 16777216.0)); float3 feature = neighbor + jitter; float d = cultmath_distance(p, feature); if (d < f1) { f2 = f1; c2 = c1; - f1 = d; c1 = feature; hash1 = hash.x; + f1 = d; c1 = feature; cellId = neighbor; } else if (d < f2) { @@ -371,15 +379,19 @@ CultCellular cultmath_cellular(float3 p) } } - // Only F1's degenerate point is guarded; see math.cellular's comment (math.cs) for why F2 = 0 - // has no reachable case to defend. + // F1 = 0 and F2 = 0 share the same degenerate-gradient guard; see math.cellular's comment + // (math.cs) for why F2 = 0 is reachable past roughly |p| = 2^23. float3 grad1 = f1 > 0.0 ? (p - c1) / f1 : float3(0.0, 0.0, 0.0); - float3 grad2 = (p - c2) / f2; + float3 grad2 = f2 > 0.0 ? (p - c2) / f2 : float3(0.0, 0.0, 0.0); + + // id comes from pcg4d over the winning cell alone, never from the pcg3d hash that produced its + // jitter (F4). + int4 idHash = cultmath_pcg4d(float4(cellId, 0.0)); CultCellular result; result.nearest = float4(grad1, f1); result.edge = float4(grad2 - grad1, f2 - f1); - result.id = (uint)hash1 * (1.0 / 4294967296.0); + result.id = ((uint)idHash.w >> 8) * (1.0 / 16777216.0); return result; }