Merge hands/cultmath-trophic-nodes

Verdicts s1, s2 and s3 of cut trophic-nodes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-16 21:23:11 +02:00
commit 7e6881af9b
20 changed files with 3945 additions and 14 deletions

View file

@ -28,8 +28,12 @@ shader semantics.
`min`, `max`, `clamp`, `saturate`, `lerp`, `step`, `smoothstep`, `dot`,
`cross`, `length`, `distance`, `normalize`, `reflect`, `csum`, `erf`,
`erfinv` (scalar only), exponential
`decay`/`damp`, intercept/segment helpers, Catmull-Rom, Bezier curves, and
`decay`/`damp`, intercept/segment helpers (`distance_to_segment` in 2D and 3D, with and without `out closest`, and `segment_closest`), Catmull-Rom, Bezier curves, and
deterministic value-noise primitives
- Site cells: `power_cells` and `multiplicative_cells` return the two nearest sites of a point as `CultSiteCells`,
`soft_gabriel_gate` gates a pair of sites by the empty-disc margin. Each is a loop over the shader steps
`cultmath_power_score` / `cultmath_multiplicative_score`, `cultmath_site_cells_empty`, `cultmath_site_cells_insert`,
`cultmath_site_cells_border`, `cultmath_power_border_step` (the exact power cell border, `power_border`) and `cultmath_gabriel_margin`; a shader loops over its own buffer.
- `shaders/CultMath.hlsl`, a canonical HLSL mirror include for shader-side
parity. HLSL already owns `float2`, `float3`, and `float4`; the include
exposes `cultmath_*` functions for shared semantics HLSL does not provide.

View file

@ -138,7 +138,8 @@ fields is compared to its C# counterpart field by field, recursing into each
field's own components, down to bit-for-bit scalars, matching each leaf's
declaration path (field names, not just position) and declared type as well
as its value. `CultCellular` (`math.cs`, `cellular`), `CultPhasor`
(`math.Phacelle.cs`, `phacelle`) and `SpanNoise` (`math.Span.cs`, `span_fbm`) are its consumers. A struct return with a mismatched, reordered-by-name, or
(`math.Phacelle.cs`, `phacelle`), `SpanNoise` (`math.Span.cs`, `span_fbm`) and `CultSiteCells`
(`math.Sites.cs`, `site_cells_insert`) are its consumers. `CultSiteCells` is also a struct parameter (`site_cells_insert`, `site_cells_border`). A struct return with a mismatched, reordered-by-name, or
retyped field does not get a second comparison path or a shape of its own;
it fails the same walk that already handles a bare vector return.
@ -488,6 +489,41 @@ Known C# friction: under `using static CultMath.math;` the constructor
functions (`float3(...)`, `float3x3(...)`) hide the type names in member access,
so static members need a qualified type (`CultMath.float3x3.Euler(...)`).
## Sites
A site is `float4(position.xyz, weight)`; a 2D consumer uses z = 0. `math.Sites.cs` scores a query point
against a site two ways and keeps the two best:
- `power_score(p, site)`: value `|p - s|^2 - w^2`, gradient `2 (p - s)`. A power cell is the intersection of the
half-spaces bounded by the radical planes against every other site, so `power_border` is exact.
- `multiplicative_score(p, site)`: value `|p - s| / w`, gradient `(p - s) / (|p - s| w)`, zero at `p = s`
(cellular's degenerate convention). Its borders are Apollonius circles, and the border distance is first order.
A span function is a C# loop over a per-site step that has a shader twin, because the HLSL mirror cannot take a
span or a buffer. `site_cells_empty()` starts the fold, `site_cells_insert(cells, score, index)` folds one score
in (strict `<` against F1, the old F1 moving to second, else strict `<` against F2, so an exact tie keeps the
earlier index first), and `site_cells_border(cells)` reads `float4(unit normal, distance)`, with `n = grad F2 -
grad F1` pointing toward the nearest site and `(0, 0, 0, 1.0e30)` when there is no second site. That border is
the distance to the bisector of the two lowest scores, first order and for either metric; it is not the distance
to the nearest site's cell boundary (the F2 - F1 edge error: the second-lowest score is not the nearest plane in
general). The exact power cell border is a second pass: `power_border_step(p, owner, other, border)` takes the
running `float4(unit normal toward the owner, distance)` and the radical plane of `owner` against `other`, with
the distance built from the offset `owner - p` and the weight difference `(w1 - w2)(w1 + w2)` so it does not
cancel for close sites seen from far; the cell boundary distance is the least over every site except the owner
(the fold's nearest), and a site coincident with the owner has no plane. The step trusts the caller's owner: a
query outside the owner's cell reports distance 0 with that plane's normal, not an error. `power_border(p, sites)` is that loop.
Cell spans refuse a non-finite query, site position or weight, and more than 2^24 sites (indices are floats).
`power_cells` and
`multiplicative_cells` are that loop over a `ReadOnlySpan<float4>` and nothing else; a shader caller writes the
same loop over its own buffer. Every site of an explicit span is visited, so no window and no weight-ratio range
apply. `CultSiteCells` holds the two score fields and the two site indices (floats, -1 for none).
`gabriel_margin(a, b, other)` is `(|other - (a + b) / 2| - r) / r` with `r = |a - b| / 2`: zero on the diameter
circle, negative inside it, -1 when `a` and `b` coincide. `soft_gabriel_gate(sites, first, second, softness)`
is `smoothstep(-softness, softness, least margin over every other site)` on positions alone, 1 when no other site
exists; it is C# only. `distance_to_segment(point, start, end)` has out-free 2D and 3D forms beside the `out`
form, all over one public `segment_closest` per dimension, each with its 2D and 3D shader overload.
## Intervals
`math.Interval.cs` and `shaders/CultMath.Interval.hlsl` (included from

View file

@ -600,6 +600,126 @@ CultCellular cultmath_cellular(vec3 p)
return result;
}
// Sites: a site is vec4(position.xyz, weight). A span is a loop over a per-site step, because a shader
// function cannot take a span in the mirror (design.md, "Sites"). The consumer's loop, over its own buffer:
// CultSiteCells cells = cultmath_site_cells_empty();
// for (int i = 0; i < count; i++)
// cells = cultmath_site_cells_insert(cells, cultmath_power_score(p, sites[i]), i);
// The exact power cell border is a second loop over the buffer, skipping the owner cells.nearestSite:
// vec4 border = vec4(0.0, 0.0, 0.0, 1.0e30); int owner = int(cells.nearestSite);
// for (int k = 0; k < count; k++) if (k != owner) border = cultmath_power_border_step(p, sites[owner], sites[k], border);
// The step trusts the owner: a p outside the owner's cell reports distance 0 with that plane's normal, not an error.
// Statement for statement with math.Sites.cs (power_score, multiplicative_score, site_cells_*, gabriel_margin).
struct CultSiteCells
{
vec4 nearest;
vec4 second;
float nearestSite;
float secondSite;
};
vec4 cultmath_power_score(vec3 p, vec4 site)
{
vec3 offset = p - site.xyz;
return vec4(offset * 2.0, dot(offset, offset) - site.w * site.w);
}
vec4 cultmath_multiplicative_score(vec3 p, vec4 site)
{
vec3 offset = p - site.xyz;
float r = length(offset);
vec3 gradient = r > 0.0 ? offset / (r * site.w) : vec3(0.0, 0.0, 0.0);
return vec4(gradient, r / site.w);
}
CultSiteCells cultmath_site_cells_empty()
{
CultSiteCells result;
result.nearest = vec4(0.0, 0.0, 0.0, 1.0e30);
result.second = vec4(0.0, 0.0, 0.0, 1.0e30);
result.nearestSite = -1.0;
result.secondSite = -1.0;
return result;
}
CultSiteCells cultmath_site_cells_insert(CultSiteCells cells, vec4 score, int index)
{
CultSiteCells result = cells;
if (score.w < cells.nearest.w)
{
result.second = cells.nearest;
result.secondSite = cells.nearestSite;
result.nearest = score;
result.nearestSite = float(index);
}
else if (score.w < cells.second.w)
{
result.second = score;
result.secondSite = float(index);
}
return result;
}
vec4 cultmath_site_cells_border(CultSiteCells cells)
{
vec3 n = cells.second.xyz - cells.nearest.xyz;
float len = length(n);
if (cells.secondSite < 0.0 || len <= 0.0)
return vec4(0.0, 0.0, 0.0, 1.0e30);
return vec4(n / len, (cells.second.w - cells.nearest.w) / len);
}
vec4 cultmath_power_border_step(vec3 p, vec4 owner, vec4 other, vec4 border)
{
vec3 d = other.xyz - owner.xyz;
float len = length(d);
if (len <= 0.0)
return border;
float plane = max((dot(owner.xyz - p, d) + 0.5 * (dot(d, d) + (owner.w - other.w) * (owner.w + other.w))) / len, 0.0);
return plane < border.w ? vec4(-d / len, plane) : border;
}
float cultmath_gabriel_margin(vec3 a, vec3 b, vec3 other)
{
float r = cultmath_distance(a, b) * 0.5;
if (r <= 0.0)
return -1.0;
return (cultmath_distance(other, (a + b) * 0.5) - r) / r;
}
vec2 cultmath_segment_closest(vec2 point_value, vec2 start, vec2 end)
{
vec2 segment = end - start;
float segmentLengthSq = cultmath_lengthsq(segment);
if (segmentLengthSq <= 0.0)
return start;
float t = cultmath_saturate(dot(point_value - start, segment) / segmentLengthSq);
return start + segment * t;
}
vec3 cultmath_segment_closest(vec3 point_value, vec3 start, vec3 end)
{
vec3 segment = end - start;
float segmentLengthSq = cultmath_lengthsq(segment);
if (segmentLengthSq <= 0.0)
return start;
float t = cultmath_saturate(dot(point_value - start, segment) / segmentLengthSq);
return start + segment * t;
}
float cultmath_distance_to_segment(vec2 point_value, vec2 start, vec2 end)
{
return cultmath_distance(point_value, cultmath_segment_closest(point_value, start, end));
}
float cultmath_distance_to_segment(vec3 point_value, vec3 start, vec3 end)
{
return cultmath_distance(point_value, cultmath_segment_closest(point_value, start, end));
}

View file

@ -600,6 +600,126 @@ CultCellular cultmath_cellular(float3 p)
return result;
}
// Sites: a site is float4(position.xyz, weight). A span is a loop over a per-site step, because a shader
// function cannot take a span in the mirror (design.md, "Sites"). The consumer's loop, over its own buffer:
// CultSiteCells cells = cultmath_site_cells_empty();
// for (int i = 0; i < count; i++)
// cells = cultmath_site_cells_insert(cells, cultmath_power_score(p, sites[i]), i);
// The exact power cell border is a second loop over the buffer, skipping the owner cells.nearestSite:
// float4 border = float4(0.0, 0.0, 0.0, 1.0e30); int owner = (int)cells.nearestSite;
// for (int k = 0; k < count; k++) if (k != owner) border = cultmath_power_border_step(p, sites[owner], sites[k], border);
// The step trusts the owner: a p outside the owner's cell reports distance 0 with that plane's normal, not an error.
// Statement for statement with math.Sites.cs (power_score, multiplicative_score, site_cells_*, gabriel_margin).
struct CultSiteCells
{
float4 nearest;
float4 second;
float nearestSite;
float secondSite;
};
float4 cultmath_power_score(float3 p, float4 site)
{
float3 offset = p - site.xyz;
return float4(offset * 2.0, dot(offset, offset) - site.w * site.w);
}
float4 cultmath_multiplicative_score(float3 p, float4 site)
{
float3 offset = p - site.xyz;
float r = length(offset);
float3 gradient = r > 0.0 ? offset / (r * site.w) : float3(0.0, 0.0, 0.0);
return float4(gradient, r / site.w);
}
CultSiteCells cultmath_site_cells_empty()
{
CultSiteCells result;
result.nearest = float4(0.0, 0.0, 0.0, 1.0e30);
result.second = float4(0.0, 0.0, 0.0, 1.0e30);
result.nearestSite = -1.0;
result.secondSite = -1.0;
return result;
}
CultSiteCells cultmath_site_cells_insert(CultSiteCells cells, float4 score, int index)
{
CultSiteCells result = cells;
if (score.w < cells.nearest.w)
{
result.second = cells.nearest;
result.secondSite = cells.nearestSite;
result.nearest = score;
result.nearestSite = (float)index;
}
else if (score.w < cells.second.w)
{
result.second = score;
result.secondSite = (float)index;
}
return result;
}
float4 cultmath_site_cells_border(CultSiteCells cells)
{
float3 n = cells.second.xyz - cells.nearest.xyz;
float len = length(n);
if (cells.secondSite < 0.0 || len <= 0.0)
return float4(0.0, 0.0, 0.0, 1.0e30);
return float4(n / len, (cells.second.w - cells.nearest.w) / len);
}
float4 cultmath_power_border_step(float3 p, float4 owner, float4 other, float4 border)
{
float3 d = other.xyz - owner.xyz;
float len = length(d);
if (len <= 0.0)
return border;
float plane = max((dot(owner.xyz - p, d) + 0.5 * (dot(d, d) + (owner.w - other.w) * (owner.w + other.w))) / len, 0.0);
return plane < border.w ? float4(-d / len, plane) : border;
}
float cultmath_gabriel_margin(float3 a, float3 b, float3 other)
{
float r = cultmath_distance(a, b) * 0.5;
if (r <= 0.0)
return -1.0;
return (cultmath_distance(other, (a + b) * 0.5) - r) / r;
}
float2 cultmath_segment_closest(float2 point_value, float2 start, float2 end)
{
float2 segment = end - start;
float segmentLengthSq = cultmath_lengthsq(segment);
if (segmentLengthSq <= 0.0)
return start;
float t = cultmath_saturate(dot(point_value - start, segment) / segmentLengthSq);
return start + segment * t;
}
float3 cultmath_segment_closest(float3 point_value, float3 start, float3 end)
{
float3 segment = end - start;
float segmentLengthSq = cultmath_lengthsq(segment);
if (segmentLengthSq <= 0.0)
return start;
float t = cultmath_saturate(dot(point_value - start, segment) / segmentLengthSq);
return start + segment * t;
}
float cultmath_distance_to_segment(float2 point_value, float2 start, float2 end)
{
return cultmath_distance(point_value, cultmath_segment_closest(point_value, start, end));
}
float cultmath_distance_to_segment(float3 point_value, float3 start, float3 end)
{
return cultmath_distance(point_value, cultmath_segment_closest(point_value, start, end));
}
#include "CultMath.Phacelle.hlsl"
#include "CultMath.Interval.hlsl"
#include "CultMath.Cycles.hlsl"

View file

@ -0,0 +1,30 @@
namespace CultMath;
/// <summary>
/// The two nearest sites of a query point under one site score (<see cref="math.power_score"/> or
/// <see cref="math.multiplicative_score"/>), built by folding sites through
/// <see cref="math.site_cells_insert"/>. Each score field follows the
/// <c>float4(gradient.xyz, value.w)</c> layout of a bare value-and-gradient return.
/// </summary>
public struct CultSiteCells
{
/// <summary>(&#8711;F1, F1): the smallest score and its gradient. 1.0e30 in w when no site was inserted.</summary>
public float4 nearest;
/// <summary>(&#8711;F2, F2): the second smallest score and its gradient. 1.0e30 in w when fewer than two sites were inserted.</summary>
public float4 second;
/// <summary>Index of the nearest site as inserted, -1 when none. A float so the struct holds one scalar type, as <see cref="CultCellular.id"/> does; exact below 2^24.</summary>
public float nearestSite;
/// <summary>Index of the second nearest site as inserted, -1 when none.</summary>
public float secondSite;
public CultSiteCells(float4 nearest, float4 second, float nearestSite, float secondSite)
{
this.nearest = nearest;
this.second = second;
this.nearestSite = nearestSite;
this.secondSite = secondSite;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f6479c37f7d349708f54ec7e4d671200

View file

@ -0,0 +1,197 @@
namespace CultMath;
public static partial class math
{
// Sites: the model page's span element float4(position.xyz, weight). A span function is a C# loop over
// a per-site step that has a shader twin (site_cells_empty, then site_cells_insert per site); a shader
// cannot take a span, so shader callers write the same loop over their own buffer. One fold, one rule.
// Power score of a site: value |p - s|^2 - w^2, gradient 2 (p - s). The cell of a site is the intersection
// of the half-spaces bounded by its radical planes against every other site (power_border_step).
public static float4 power_score(float3 p, float4 site)
{
var offset = p - site.xyz;
return new float4(offset * 2.0f, dot(offset, offset) - site.w * site.w);
}
// Multiplicative score of a site: value |p - s| / w, gradient (p - s) / (|p - s| w). At p = s the
// gradient is zero, cellular's degenerate-gradient convention.
public static float4 multiplicative_score(float3 p, float4 site)
{
var offset = p - site.xyz;
var r = length(offset);
var gradient = r > 0.0f ? offset / (r * site.w) : new float3(0.0f, 0.0f, 0.0f);
return new float4(gradient, r / site.w);
}
// The fold's identity: no site yet. 1.0e30 is cellular's sentinel (GLSL ES has no inf literal).
public static CultSiteCells site_cells_empty() =>
new(new float4(0.0f, 0.0f, 0.0f, 1.0e30f), new float4(0.0f, 0.0f, 0.0f, 1.0e30f), -1.0f, -1.0f);
// One fold step. Strict < against F1 (the old F1 moves to second), else strict < against F2, so an exact
// tie keeps the earlier index first.
public static CultSiteCells site_cells_insert(CultSiteCells cells, float4 score, int index)
{
var result = cells;
if (score.w < cells.nearest.w)
{
result.second = cells.nearest;
result.secondSite = cells.nearestSite;
result.nearest = score;
result.nearestSite = (float)index;
}
else if (score.w < cells.second.w)
{
result.second = score;
result.secondSite = (float)index;
}
return result;
}
// float4(unit normal, distance) of the bisector of the two lowest scores: n = grad F2 - grad F1, distance
// (F2 - F1) / |n|, normal n / |n| (into the nearest site's cell). First order, for either metric. It is NOT
// the distance to the nearest site's cell boundary, which the second-lowest score does not give in general;
// for power scores that is power_border. (0, 0, 0, 1.0e30) when there is no second site or |n| = 0.
public static float4 site_cells_border(CultSiteCells cells)
{
var n = cells.second.xyz - cells.nearest.xyz;
var len = length(n);
if (cells.secondSite < 0.0f || len <= 0.0f)
return new float4(0.0f, 0.0f, 0.0f, 1.0e30f);
return new float4(n / len, (cells.second.w - cells.nearest.w) / len);
}
// One step of the exact power cell border. owner is the site whose cell p lies in (the fold's nearest);
// other is another site. The radical plane of the pair is {x : |x - s1|^2 - w1^2 = |x - s2|^2 - w2^2};
// with d = s2 - s1 the signed distance from p to it, positive on the owner's side, is
// ((s1 - p).d + (|d|^2 + w1^2 - w2^2) / 2) / |d|. It is built from the offset s1 - p and the weight
// difference (w1 - w2)(w1 + w2), never from a difference of two large squared distances, so it does not
// cancel for a far query or close sites. border is the running (unit normal toward the owner, distance),
// starting at (0, 0, 0, 1.0e30): the cell's boundary distance is the least plane distance over every other
// site. A site coincident with the owner has no plane and leaves border unchanged. The step trusts the caller's
// owner: a p outside the owner's cell has a negative signed distance to some plane, which is clamped to 0, so the
// step reports distance 0 with that plane's normal, a plausible on-the-border answer, not an error.
public static float4 power_border_step(float3 p, float4 owner, float4 other, float4 border)
{
var d = other.xyz - owner.xyz;
var len = length(d);
if (len <= 0.0f)
return border;
var plane = max((dot(owner.xyz - p, d) + 0.5f * (dot(d, d) + (owner.w - other.w) * (owner.w + other.w))) / len, 0.0f);
return plane < border.w ? new float4(-d / len, plane) : border;
}
// Gabriel margin of the pair (a, b) against a third site: (|other - mid| - r) / r with mid = (a + b) / 2
// and r = |a - b| / 2. 0 on the diameter circle, negative inside it, -1 when a and b coincide.
public static float gabriel_margin(float3 a, float3 b, float3 other)
{
var r = distance(a, b) * 0.5f;
if (r <= 0.0f)
return -1.0f;
return (distance(other, (a + b) * 0.5f) - r) / r;
}
// Index floats hold integers exactly up to 2^24, so a longer span is refused.
private const int MaxSiteSpan = 1 << 24;
private static bool all_finite(float3 v) => float.IsFinite(v.x) && float.IsFinite(v.y) && float.IsFinite(v.z);
// The one validation of a cell span: finite query, finite positions and weights, weights above zero when
// positiveWeights, at most 2^24 sites. Messages name the parameter, never a value.
private static void require_cell_span(float3 p, ReadOnlySpan<float4> sites, bool positiveWeights)
{
if (!all_finite(p))
throw new ArgumentException("The query point must be finite.", nameof(p));
if (sites.Length > MaxSiteSpan)
throw new ArgumentException("A site span holds at most 2^24 sites.", nameof(sites));
for (var i = 0; i < sites.Length; i++)
{
if (!all_finite(sites[i].xyz))
throw new ArgumentException("Site positions must be finite.", nameof(sites));
if (!float.IsFinite(sites[i].w) || (positiveWeights && !(sites[i].w > 0.0f)))
throw new ArgumentException(positiveWeights ? "Site weights must be finite and greater than zero." : "Site weights must be finite.", nameof(sites));
}
}
/// <summary>
/// The two nearest sites of <paramref name="p"/> by <see cref="power_score"/> (the power diagram), every
/// site visited. A site is <c>float4(position.xyz, weight)</c>; use z = 0 for 2D. Ties keep the lower index first.
/// </summary>
/// <exception cref="ArgumentException">The query or a site position or weight is not finite, or the span holds more than 2^24 sites.</exception>
public static CultSiteCells power_cells(float3 p, ReadOnlySpan<float4> sites)
{
require_cell_span(p, sites, positiveWeights: false);
var cells = site_cells_empty();
for (var i = 0; i < sites.Length; i++)
cells = site_cells_insert(cells, power_score(p, sites[i]), i);
return cells;
}
/// <summary>
/// The exact distance from <paramref name="p"/> to the boundary of its power cell, and the unit normal of the
/// nearest boundary plane pointing into the cell: <c>float4(normal, distance)</c>. The cell is the
/// intersection of the half-spaces bounded by the radical planes against every other site, so the distance is
/// the least <see cref="power_border_step"/> over them. A site coincident with the owner has no plane; a cell
/// with no bounding plane (one site, or only coincident ones) gives <c>(0, 0, 0, 1.0e30)</c>.
/// </summary>
/// <exception cref="ArgumentException">As <see cref="power_cells"/>.</exception>
public static float4 power_border(float3 p, ReadOnlySpan<float4> sites)
{
var border = new float4(0.0f, 0.0f, 0.0f, 1.0e30f);
var owner = (int)power_cells(p, sites).nearestSite;
if (owner < 0)
return border;
for (var k = 0; k < sites.Length; k++)
if (k != owner)
border = power_border_step(p, sites[owner], sites[k], border);
return border;
}
/// <summary>
/// The two nearest sites of <paramref name="p"/> by <see cref="multiplicative_score"/> (distance divided by
/// weight), every site visited. A site is <c>float4(position.xyz, weight)</c>; use z = 0 for 2D.
/// </summary>
/// <exception cref="ArgumentException">The query or a site position is not finite, a weight is not finite and greater than zero, or the span holds more than 2^24 sites.</exception>
public static CultSiteCells multiplicative_cells(float3 p, ReadOnlySpan<float4> sites)
{
require_cell_span(p, sites, positiveWeights: true);
var cells = site_cells_empty();
for (var i = 0; i < sites.Length; i++)
cells = site_cells_insert(cells, multiplicative_score(p, sites[i]), i);
return cells;
}
/// <summary>
/// Whether sites <paramref name="first"/> and <paramref name="second"/> are neighbours in the Gabriel graph
/// of <paramref name="sites"/> (positions only; weights are ignored): smoothstep(-softness, softness, the
/// least <see cref="gabriel_margin"/> over every other site). 1 when no other site exists.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">An index is outside the span.</exception>
/// <exception cref="ArgumentException">The indices are equal, softness is not finite and greater than zero, or a site position is not finite.</exception>
public static float soft_gabriel_gate(ReadOnlySpan<float4> sites, int first, int second, float softness)
{
if (first < 0 || first >= sites.Length)
throw new ArgumentOutOfRangeException(nameof(first), "Index is outside the site span.");
if (second < 0 || second >= sites.Length)
throw new ArgumentOutOfRangeException(nameof(second), "Index is outside the site span.");
if (first == second)
throw new ArgumentException("The two indices must differ.", nameof(second));
if (!(float.IsFinite(softness) && softness > 0.0f))
throw new ArgumentException("Softness must be finite and greater than zero.", nameof(softness));
for (var k = 0; k < sites.Length; k++)
if (!all_finite(sites[k].xyz))
throw new ArgumentException("Site positions must be finite.", nameof(sites));
var margin = float.PositiveInfinity;
for (var k = 0; k < sites.Length; k++)
{
if (k == first || k == second)
continue;
margin = min(margin, gabriel_margin(sites[first].xyz, sites[second].xyz, sites[k].xyz));
}
return smoothstep(-softness, softness, margin);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 856a5e425b6b45f4a8b3e9a8cd32fe38

View file

@ -317,18 +317,41 @@ public static partial class math
}
public static float distance_to_segment(float2 point, float2 start, float2 end, out float2 closest)
{
closest = segment_closest(point, start, end);
return distance(point, closest);
}
/// <summary>The distance from <paramref name="point"/> to the segment <paramref name="start"/>-<paramref name="end"/>; a degenerate segment is its start.</summary>
public static float distance_to_segment(float2 point, float2 start, float2 end) =>
distance(point, segment_closest(point, start, end));
/// <summary>The distance from <paramref name="point"/> to the segment <paramref name="start"/>-<paramref name="end"/>; a degenerate segment is its start.</summary>
public static float distance_to_segment(float3 point, float3 start, float3 end) =>
distance(point, segment_closest(point, start, end));
/// <summary>The point of the segment <paramref name="start"/>-<paramref name="end"/> nearest <paramref name="point_value"/>; a degenerate segment is its start.</summary>
public static float2 segment_closest(float2 point_value, float2 start, float2 end)
{
var segment = end - start;
var segmentLengthSq = lengthsq(segment);
if (segmentLengthSq <= 0.0f)
{
closest = start;
return distance(point, start);
}
return start;
var t = saturate(dot(point - start, segment) / segmentLengthSq);
closest = start + segment * t;
return distance(point, closest);
var t = saturate(dot(point_value - start, segment) / segmentLengthSq);
return start + segment * t;
}
/// <summary>The point of the segment <paramref name="start"/>-<paramref name="end"/> nearest <paramref name="point_value"/>; a degenerate segment is its start.</summary>
public static float3 segment_closest(float3 point_value, float3 start, float3 end)
{
var segment = end - start;
var segmentLengthSq = lengthsq(segment);
if (segmentLengthSq <= 0.0f)
return start;
var t = saturate(dot(point_value - start, segment) / segmentLengthSq);
return start + segment * t;
}
public static float catmullrom(float p0, float p1, float p2, float p3, float t)

View file

@ -522,6 +522,8 @@ static int4 clamp(int4 x, int4 a, int4 b) { if (a.x > b.x || a.y > b.y || a.z >
private sealed record Family(string Glsl, string Tolerance, Func<System.Random, object[]> Arguments, string? Check = null, Platform Platform = Platform.None, Func<JsonArray, string>? Verify = null);
private static float Uniform(System.Random r, float lo, float hi) => lo + (hi - lo) * r.NextSingle();
private static float2 Point2(System.Random r) => new(Uniform(r, -50.0f, 50.0f), Uniform(r, -50.0f, 50.0f));
private static float3 Point3(System.Random r) => new(Uniform(r, -50.0f, 50.0f), Uniform(r, -50.0f, 50.0f), Uniform(r, -50.0f, 50.0f));
// A point on the simplex tie set, where snoise's x0 has equal components (NoiseGradTests.SnoiseIsContinuousOnTheSimplexDiagonal):
@ -795,6 +797,57 @@ static int4 clamp(int4 x, int4 a, int4 b) { if (a.x > b.x || a.y > b.y || a.z >
new Family("vec4 cultmath_snoise_grad(vec3)", "ulp-bounded, coordinate bands 1e2 to 4e6", r => new object[] { BandPoint3(r, 1.0e2, 4.0e6) }, SpanAllowanceRead, Verify: cases => AssertSpanAllowance(cases, hessian: false, small: false)),
new Family("mat3 cultmath_snoise_hessian(vec3)", "ulp-bounded, coordinate bands 1e-4 to 1e2", r => new object[] { BandPoint3(r, 1.0e-4, 1.0e2) }, SpanAllowanceRead, Verify: cases => AssertSpanAllowance(cases, hessian: true, small: true)),
new Family("mat3 cultmath_snoise_hessian(vec3)", "ulp-bounded, coordinate bands 1e2 to 4e6", r => new object[] { BandPoint3(r, 1.0e2, 4.0e6) }, SpanAllowanceRead, Verify: cases => AssertSpanAllowance(cases, hessian: true, small: false)),
// Segment distance in 2D and 3D (one segment in eight degenerate), then the site cells: scores, fold step
// over states built by inserting 0-3 random scores (one in four with an exactly tied score), border, margin.
new Family("float cultmath_distance_to_segment(vec2, vec2, vec2)", "ulp-bounded", r =>
{
var start = Point2(r);
return new object[] { Point2(r), start, r.Next(8) == 0 ? start : Point2(r) };
}),
new Family("vec2 cultmath_segment_closest(vec2, vec2, vec2)", "ulp-bounded", r =>
{
var start = Point2(r);
return new object[] { Point2(r), start, r.Next(8) == 0 ? start : Point2(r) };
}),
new Family("float cultmath_distance_to_segment(vec3, vec3, vec3)", "ulp-bounded", r =>
{
var start = Point3(r);
return new object[] { Point3(r), start, r.Next(8) == 0 ? start : Point3(r) };
}),
new Family("vec3 cultmath_segment_closest(vec3, vec3, vec3)", "ulp-bounded", r =>
{
var start = Point3(r);
return new object[] { Point3(r), start, r.Next(8) == 0 ? start : Point3(r) };
}),
// The border step: owner and other random (one in six coincident), a running border either empty or a
// random (normal, distance); one in six other is a distinct site within 1e-3 of the owner (inside the 1e-2 guard a
// changed length test would trip), one in six coincident.
new Family("vec4 cultmath_power_border_step(vec3, vec4, vec4, vec4)", "ulp-bounded", r =>
{
var owner = Site(r, 0.1f, 20.0f);
var border = r.Next(2) == 0 ? new float4(0.0f, 0.0f, 0.0f, 1.0e30f) : new float4(Point3(r), Uniform(r, 0.0f, 50.0f));
var pick = r.Next(6);
var near = new float4(owner.xyz + new float3(Uniform(r, 1.0e-4f, 1.0e-3f), Uniform(r, -1.0e-3f, 1.0e-3f), Uniform(r, -1.0e-3f, 1.0e-3f)), Uniform(r, 0.1f, 20.0f));
return new object[] { Point3(r), owner, pick == 0 ? owner : pick == 1 ? near : Site(r, 0.1f, 20.0f), border };
}),
new Family("vec4 cultmath_power_score(vec3, vec4)", "ulp-bounded", r => new object[] { Point3(r), Site(r, 0.1f, 20.0f) }),
new Family("vec4 cultmath_multiplicative_score(vec3, vec4)", "ulp-bounded", r => new object[] { Point3(r), Site(r, 0.1f, 100.0f, logWeight: true) }),
new Family("CultSiteCells cultmath_site_cells_insert(CultSiteCells, vec4, int)", "ulp-bounded", r =>
{
var (cells, scores) = CellsState(r);
var score = r.Next(4) == 0 && scores.Count > 0 ? scores[r.Next(scores.Count)] : PowerOrMultiplicative(r);
return new object[] { cells, score, scores.Count };
}),
new Family("vec4 cultmath_site_cells_border(CultSiteCells)", "ulp-bounded", r =>
{
var (cells, _) = CellsState(r, minimum: r.Next(8) == 0 ? 0 : 2);
return new object[] { cells };
}),
new Family("float cultmath_gabriel_margin(vec3, vec3, vec3)", "ulp-bounded", r =>
{
var a = Point3(r);
return new object[] { a, r.Next(8) == 0 ? a : Point3(r), Point3(r) };
}),
}).ToArray();
// A point of magnitude m, m log-uniform in [lo, hi]: one component at +-m, the other two uniform in [-m, m],
@ -807,6 +860,32 @@ static int4 clamp(int4 x, int4 a, int4 b) { if (a.x > b.x || a.y > b.y || a.z >
return new float3((float)v[0], (float)v[1], (float)v[2]);
}
// A site float4(position.xyz, weight): the weight uniform in [lo, hi], or log-uniform when logWeight.
private static float4 Site(System.Random r, float lo, float hi, bool logWeight = false)
{
var p = Point3(r);
return new float4(p.x, p.y, p.z, logWeight ? lo * MathF.Pow(hi / lo, r.NextSingle()) : Uniform(r, lo, hi));
}
private static float4 PowerOrMultiplicative(System.Random r) =>
r.Next(2) == 0 ? math.power_score(Point3(r), Site(r, 0.1f, 20.0f)) : math.multiplicative_score(Point3(r), Site(r, 0.1f, 100.0f, logWeight: true));
// A fold state made by the production path: site_cells_insert over a few random scores (at least minimum).
private static (CultSiteCells Cells, List<float4> Scores) CellsState(System.Random r, int minimum = 0)
{
var scores = new List<float4>();
var cells = math.site_cells_empty();
for (var i = minimum + r.Next(4 - minimum); i > 0; i--)
{
var score = r.Next(4) == 0 && scores.Count > 0 ? scores[^1] : PowerOrMultiplicative(r);
cells = math.site_cells_insert(cells, score, scores.Count);
scores.Add(score);
}
return (cells, scores);
}
private static object[] SpanArguments(System.Random r)
{
var stage = SpanStageTests.Stage.Draw(r);
@ -876,6 +955,7 @@ static int4 clamp(int4 x, int4 a, int4 b) { if (a.x > b.x || a.y > b.y || a.z >
["float"] = typeof(float), ["int"] = typeof(int), ["vec2"] = typeof(float2), ["vec3"] = typeof(float3),
["vec4"] = typeof(float4), ["ivec3"] = typeof(int3), ["ivec4"] = typeof(int4),
["SpanPath"] = typeof(SpanPath), ["SpanStage"] = typeof(SpanStage),
["CultSiteCells"] = typeof(CultSiteCells),
};
// The C# math method a GLSL signature names: cultmath_ dropped, parameter types mapped.

View file

@ -27,6 +27,18 @@ public sealed class HlslSourceCompatibilityTests
Assert.NotNull(ShaderFunction(shader, "cultmath_value_noise_bicubic", typeof(float2)));
Assert.NotNull(ShaderFunction(shader, "cultmath_smin_grad", typeof(float4), typeof(float4), typeof(float)));
Assert.NotNull(ShaderFunction(shader, "cultmath_cellular", typeof(float3)));
var siteCells = shader.GetNestedType("CultSiteCells", BindingFlags.Public | BindingFlags.NonPublic)!;
Assert.NotNull(ShaderFunction(shader, "cultmath_power_score", typeof(float3), typeof(float4)));
Assert.NotNull(ShaderFunction(shader, "cultmath_multiplicative_score", typeof(float3), typeof(float4)));
Assert.NotNull(ShaderFunction(shader, "cultmath_site_cells_empty"));
Assert.NotNull(ShaderFunction(shader, "cultmath_site_cells_insert", siteCells, typeof(float4), typeof(int)));
Assert.NotNull(ShaderFunction(shader, "cultmath_site_cells_border", siteCells));
Assert.NotNull(ShaderFunction(shader, "cultmath_gabriel_margin", typeof(float3), typeof(float3), typeof(float3)));
Assert.NotNull(ShaderFunction(shader, "cultmath_power_border_step", typeof(float3), typeof(float4), typeof(float4), typeof(float4)));
Assert.NotNull(ShaderFunction(shader, "cultmath_segment_closest", typeof(float2), typeof(float2), typeof(float2)));
Assert.NotNull(ShaderFunction(shader, "cultmath_distance_to_segment", typeof(float2), typeof(float2), typeof(float2)));
Assert.NotNull(ShaderFunction(shader, "cultmath_segment_closest", typeof(float3), typeof(float3), typeof(float3)));
Assert.NotNull(ShaderFunction(shader, "cultmath_distance_to_segment", typeof(float3), typeof(float3), typeof(float3)));
Assert.NotNull(ShaderFunction(shader, "cultmath_snoise_grad", typeof(float3)));
Assert.NotNull(ShaderFunction(shader, "cultmath_snoise_hessian", typeof(float3)));
Assert.NotNull(ShaderFunction(shader, "cultmath_integral_clamp_linear", typeof(float), typeof(float), typeof(float), typeof(float), typeof(float), typeof(float)));
@ -120,6 +132,16 @@ public sealed class HlslSourceCompatibilityTests
for (var k = 0; k < 64; k++) { var values = Enumerable.Range(0, 32).Select(_ => Next()).ToArray(); cases.Add(i => values[i]); }
for (var k = 0; k < 16; k++) { var values = Enumerable.Range(0, 32).Select(_ => Next()).ToArray(); cases.Add(i => values[i & ~1]); }
// Distinct sites closer than 1e-2 (slots 3-6 are the owner and 7-10 the other site of
// cultmath_power_border_step): a length guard wider than "coincident" changes the result for these only.
for (var k = 0; k < 16; k++)
{
var values = Enumerable.Range(0, 32).Select(_ => Next()).ToArray();
for (var c = 0; c < 3; c++) values[7 + c] = values[3 + c] + (random.NextSingle() * 2.0f - 1.0f) * 1.0e-3f;
values[7] += 2.0e-4f;
cases.Add(i => values[i]);
}
// Points aimed squarely at cellular's HLSL mirror (F6/F3 Soul findings): the generic random
// and special-value cases above pass ~92 inputs through cultmath_cellular and never happen to
// hit a point where a radius-2 cell wins (about 3.5e-5 of points, Soul measured) or an
@ -178,7 +200,7 @@ public sealed class HlslSourceCompatibilityTests
}
Assert.True(mismatches.Count == 0, $"{mismatches.Count} mismatches:{Environment.NewLine}{string.Join(Environment.NewLine, mismatches.Take(12))}");
Assert.Equal(127, compared.Count);
Assert.Equal(136, compared.Count);
}
/// <summary>

View file

@ -0,0 +1,517 @@
using Xunit;
using static CultMath.math;
namespace CultMath.Tests;
/// <summary>
/// The site cells (power and multiplicative scores, the fold, the border), the Gabriel margin and gate, and the
/// out-free segment distance. Every reference is written here in double from the site data, never by calling the
/// function under test.
/// </summary>
public sealed class SiteCellsTests
{
private static float4[] RandomSites(System.Random r, int max)
{
var count = r.Next(max + 1);
var sites = new float4[count];
for (var i = 0; i < count; i++)
{
sites[i] = i > 0 && r.Next(4) == 0
? sites[r.Next(i)]
: new float4(Span(r, 10.0f), Span(r, 10.0f), Span(r, 10.0f), 0.5f + 2.5f * r.NextSingle());
}
return sites;
}
private static float Span(System.Random r, float extent) => (r.NextSingle() * 2.0f - 1.0f) * extent;
private static float3 Point(System.Random r) => new(Span(r, 10.0f), Span(r, 10.0f), Span(r, 10.0f));
private static double PowerReference(float3 p, float4 s)
{
double dx = (double)p.x - s.x, dy = (double)p.y - s.y, dz = (double)p.z - s.z;
return dx * dx + dy * dy + dz * dz - (double)s.w * s.w;
}
private static double MultiplicativeReference(float3 p, float4 s)
{
double dx = (double)p.x - s.x, dy = (double)p.y - s.y, dz = (double)p.z - s.z;
return Math.Sqrt(dx * dx + dy * dy + dz * dz) / s.w;
}
// Checks cells against the stable (score, index) order of a double reference. A pair whose reference scores
// differ by less than a float's resolution may legitimately order either way, so such a pair is skipped; an
// exact tie (a duplicated site) is compared.
private static int CheckFold(CultSiteCells cells, double[] reference)
{
var order = Enumerable.Range(0, reference.Length).OrderBy(i => reference[i]).ThenBy(i => i).ToArray();
if (order.Length < 2)
{
Assert.Equal(-1.0f, cells.secondSite);
Assert.Equal(1.0e30f, cells.second.w);
}
if (order.Length < 1)
{
Assert.Equal(-1.0f, cells.nearestSite);
Assert.Equal(1.0e30f, cells.nearest.w);
return 0;
}
bool Clear(int a, int b) => reference[a] == reference[b] || Math.Abs(reference[b] - reference[a]) > 1.0e-4 * (1.0 + Math.Abs(reference[b]));
if (order.Length >= 2 && !Clear(order[0], order[1]))
return 0;
Assert.Equal((float)order[0], cells.nearestSite);
if (order.Length < 2 || (order.Length > 2 && !Clear(order[1], order[2])))
return 1;
Assert.Equal((float)order[1], cells.secondSite);
return 1;
}
[Fact]
public void PowerAndMultiplicativeCellsAreTheTwoSmallestScoresInIndexOrder()
{
var r = new System.Random(0x517E);
var checkedSpans = 0;
for (var n = 0; n < 4000; n++)
{
var sites = RandomSites(r, 12);
var p = Point(r);
checkedSpans += CheckFold(power_cells(p, sites), sites.Select(s => PowerReference(p, s)).ToArray());
checkedSpans += CheckFold(multiplicative_cells(p, sites), sites.Select(s => MultiplicativeReference(p, s)).ToArray());
}
Assert.True(checkedSpans > 5000, $"only {checkedSpans} spans were comparable");
}
[Fact]
public void ExactTiesKeepTheLowerIndexFirst()
{
var site = new float4(1.0f, 2.0f, 3.0f, 1.5f);
var sites = new[] { site, site, site };
var cells = power_cells(new float3(0.0f, 0.0f, 0.0f), sites);
Assert.Equal(0.0f, cells.nearestSite);
Assert.Equal(1.0f, cells.secondSite);
}
// TN2: for power scores F2 - F1 is affine, so site_cells_border is the distance to the bisector plane of the
// two winners {x : |x - s1|^2 - w1^2 = |x - s2|^2 - w2^2}, computed here in double. That is not the distance
// to the nearest site's cell boundary (PowerBorderIsTheLeastRadicalPlaneDistance).
[Fact]
public void SiteCellsBorderIsTheDistanceToTheWinnersBisector()
{
var r = new System.Random(0xB0DE);
var compared = 0;
for (var n = 0; n < 3000; n++)
{
var sites = RandomSites(r, 8);
if (sites.Length < 3)
continue;
var p = Point(r);
var reference = sites.Select(s => PowerReference(p, s)).ToArray();
var order = Enumerable.Range(0, sites.Length).OrderBy(i => reference[i]).ThenBy(i => i).ToArray();
if (reference[order[1]] - reference[order[0]] < 1.0e-2 || reference[order[2]] - reference[order[1]] < 1.0e-2)
continue;
var (a, b) = (sites[order[0]], sites[order[1]]);
double nx = 2.0 * ((double)a.x - b.x), ny = 2.0 * ((double)a.y - b.y), nz = 2.0 * ((double)a.z - b.z);
var norm = Math.Sqrt(nx * nx + ny * ny + nz * nz);
if (norm < 1.0e-2)
continue;
var expected = (reference[order[1]] - reference[order[0]]) / norm;
var border = site_cells_border(power_cells(p, sites));
Assert.InRange(border.w, expected - 1.0e-4 * expected - 1.0e-3, expected + 1.0e-4 * expected + 1.0e-3);
// F2 - F1 grows toward the nearest site: the normal is (s1 - s2) / |s1 - s2|.
Assert.InRange(border.x, nx / norm - 1.0e-3, nx / norm + 1.0e-3);
Assert.InRange(border.y, ny / norm - 1.0e-3, ny / norm + 1.0e-3);
Assert.InRange(border.z, nz / norm - 1.0e-3, nz / norm + 1.0e-3);
compared++;
}
Assert.True(compared > 1000, $"only {compared} borders were comparable");
}
[Fact]
public void BorderIsEmptyWithoutASecondSite()
{
var one = power_cells(new float3(1.0f, 2.0f, 3.0f), new[] { new float4(0.0f, 0.0f, 0.0f, 1.0f) });
Assert.Equal(new float4(0.0f, 0.0f, 0.0f, 1.0e30f), site_cells_border(one));
Assert.Equal(new float4(0.0f, 0.0f, 0.0f, 1.0e30f), site_cells_border(site_cells_empty()));
}
// Two sites with weights w1 != w2: the border |p - s1| / w1 = |p - s2| / w2 is the Apollonius circle, centre
// (w1^2 s2 - w2^2 s1) / (w1^2 - w2^2), radius w1 w2 |s1 - s2| / |w1^2 - w2^2| (built in double). On it the
// multiplicative border distance vanishes; off it the distance is nonzero.
[Fact]
public void MultiplicativeBorderVanishesOnTheApolloniusCircle()
{
var r = new System.Random(0xA9011);
for (var n = 0; n < 300; n++)
{
var s1 = new float4(Span(r, 5.0f), Span(r, 5.0f), 0.0f, 1.0f + 2.0f * r.NextSingle());
var s2 = new float4(Span(r, 5.0f), Span(r, 5.0f), 0.0f, 1.0f + 2.0f * r.NextSingle());
double w1 = s1.w, w2 = s2.w, k = w1 * w1 - w2 * w2;
double sep = Math.Sqrt(Math.Pow((double)s1.x - s2.x, 2) + Math.Pow((double)s1.y - s2.y, 2));
if (Math.Abs(k) < 0.5 || sep < 1.0)
continue;
double cx = (w1 * w1 * s2.x - w2 * w2 * s1.x) / k, cy = (w1 * w1 * s2.y - w2 * w2 * s1.y) / k;
var radius = w1 * w2 * sep / Math.Abs(k);
if (radius > 50.0)
continue;
var sites = new[] { s1, s2 };
var angle = r.NextDouble() * 2.0 * Math.PI;
var on = new float3((float)(cx + radius * Math.Cos(angle)), (float)(cy + radius * Math.Sin(angle)), 0.0f);
var onBorder = site_cells_border(multiplicative_cells(on, sites));
Assert.True(Math.Abs(onBorder.w) < 1.0e-3 * radius + 1.0e-3, $"on the circle: {onBorder.w}");
var off = new float3((float)(cx + 1.5 * radius * Math.Cos(angle)), (float)(cy + 1.5 * radius * Math.Sin(angle)), 0.0f);
var offBorder = site_cells_border(multiplicative_cells(off, sites));
Assert.True(Math.Abs(offBorder.w) > 1.0e-2 * radius, $"off the circle: {offBorder.w}");
}
}
// Central differences in double of each score's value against the returned gradient.
[Fact]
public void ScoreGradientsAreAnalytic()
{
var r = new System.Random(0x6AAD);
const double h = 1.0e-3;
for (var n = 0; n < 500; n++)
{
var site = RandomSites(r, 1).FirstOrDefault(new float4(1.0f, -2.0f, 0.5f, 1.5f));
var p = Point(r);
if (Math.Abs(p.x - site.x) + Math.Abs(p.y - site.y) + Math.Abs(p.z - site.z) < 1.0f)
continue;
foreach (var (score, reference) in new (Func<float3, float4, float4>, Func<float3, float4, double>)[] { (power_score, PowerReference), (multiplicative_score, MultiplicativeReference) })
{
var got = score(p, site);
var axes = new[] { new float3((float)h, 0.0f, 0.0f), new float3(0.0f, (float)h, 0.0f), new float3(0.0f, 0.0f, (float)h) };
var expected = axes.Select(a => (reference(p + a, site) - reference(p - a, site)) / (2.0 * h)).ToArray();
var scale = 1.0 + Math.Abs(expected[0]) + Math.Abs(expected[1]) + Math.Abs(expected[2]);
Assert.True(Math.Abs(got.x - expected[0]) < 2.0e-3 * scale, "x");
Assert.True(Math.Abs(got.y - expected[1]) < 2.0e-3 * scale, "y");
Assert.True(Math.Abs(got.z - expected[2]) < 2.0e-3 * scale, "z");
Assert.Equal(reference(p, site), got.w, 1.0e-3 * (1.0 + Math.Abs(got.w)));
}
}
}
[Fact]
public void MultiplicativeGradientIsZeroAtTheSite()
{
var site = new float4(1.0f, 2.0f, 3.0f, 2.0f);
var score = multiplicative_score(new float3(1.0f, 2.0f, 3.0f), site);
Assert.Equal(new float4(0.0f, 0.0f, 0.0f, 0.0f), score);
}
private static double MarginReference(float4 a, float4 b, float4 o)
{
double mx = ((double)a.x + b.x) / 2, my = ((double)a.y + b.y) / 2, mz = ((double)a.z + b.z) / 2;
var rr = Math.Sqrt(Math.Pow((double)a.x - b.x, 2) + Math.Pow((double)a.y - b.y, 2) + Math.Pow((double)a.z - b.z, 2)) / 2;
var d = Math.Sqrt(Math.Pow(o.x - mx, 2) + Math.Pow(o.y - my, 2) + Math.Pow(o.z - mz, 2));
return (d - rr) / rr;
}
private static double SmoothstepReference(double lo, double hi, double x)
{
var t = Math.Clamp((x - lo) / (hi - lo), 0.0, 1.0);
return t * t * (3.0 - 2.0 * t);
}
[Fact]
public void SoftGabrielGateFollowsTheEmptyDiscMargin()
{
var a = new float4(-2.0f, 0.0f, 0.0f, 1.0f);
var b = new float4(2.0f, 0.0f, 0.0f, 1.0f);
// On the diameter circle (radius 2 about the origin): margin 0, gate 0.5. At half radius: margin -0.5, gate 0.
Assert.Equal(0.5f, soft_gabriel_gate(new[] { a, b, new float4(0.0f, 2.0f, 0.0f, 1.0f) }, 0, 1, 0.15f), 6);
Assert.Equal(0.0f, soft_gabriel_gate(new[] { a, b, new float4(0.0f, 1.0f, 0.0f, 1.0f) }, 0, 1, 0.15f));
Assert.Equal(1.0f, soft_gabriel_gate(new[] { a, b }, 0, 1, 0.15f));
var r = new System.Random(0x6ABE);
for (var n = 0; n < 500; n++)
{
var sites = RandomSites(r, 9);
if (sites.Length < 3 || sites[0].Equals(sites[1]))
continue;
var first = r.Next(sites.Length);
var second = (first + 1 + r.Next(sites.Length - 1)) % sites.Length;
var softness = 0.05f + 0.5f * r.NextSingle();
var margin = Enumerable.Range(0, sites.Length).Where(k => k != first && k != second).Min(k => MarginReference(sites[first], sites[second], sites[k]));
if (!double.IsFinite(margin))
continue;
Assert.Equal(SmoothstepReference(-softness, softness, margin), soft_gabriel_gate(sites, first, second, softness), 1.0e-3);
}
// Continuity: a tiny radial step of a third site moves the gate by a small share of the softness band.
var prev = soft_gabriel_gate(new[] { a, b, new float4(0.0f, 1.8f, 0.0f, 1.0f) }, 0, 1, 0.3f);
for (var y = 1.8f; y < 2.2f; y += 0.001f)
{
var gate = soft_gabriel_gate(new[] { a, b, new float4(0.0f, y, 0.0f, 1.0f) }, 0, 1, 0.3f);
Assert.True(Math.Abs(gate - prev) < 0.01f, $"step at y={y}");
prev = gate;
}
}
[Fact]
public void SpanFunctionsRefuseBadInputsWithoutEchoingThem()
{
var good = new float4(0.0f, 0.0f, 0.0f, 1.0f);
var marker = 12345.678f;
foreach (var weight in new[] { 0.0f, -marker, float.NaN, float.PositiveInfinity })
{
var e = Assert.Throws<ArgumentException>(() => multiplicative_cells(default, new[] { good, new float4(1.0f, 1.0f, 1.0f, weight) }));
Assert.Equal("sites", e.ParamName);
Assert.DoesNotContain("12345", e.Message);
}
foreach (var weight in new[] { float.NaN, float.PositiveInfinity, float.NegativeInfinity })
Assert.Equal("sites", Assert.Throws<ArgumentException>(() => power_cells(default, new[] { good, new float4(1.0f, 1.0f, 1.0f, weight) })).ParamName);
var three = new[] { good, new float4(1.0f, 0.0f, 0.0f, 1.0f), new float4(0.0f, 1.0f, 0.0f, 1.0f) };
Assert.Equal("second", Assert.Throws<ArgumentException>(() => soft_gabriel_gate(three, 1, 1, 0.1f)).ParamName);
Assert.Equal("first", Assert.Throws<ArgumentOutOfRangeException>(() => soft_gabriel_gate(three, -1, 1, 0.1f)).ParamName);
Assert.Equal("second", Assert.Throws<ArgumentOutOfRangeException>(() => soft_gabriel_gate(three, 0, 3, 0.1f)).ParamName);
foreach (var softness in new[] { 0.0f, -marker, float.NaN, float.PositiveInfinity })
{
var e = Assert.Throws<ArgumentException>(() => soft_gabriel_gate(three, 0, 1, softness));
Assert.Equal("softness", e.ParamName);
Assert.DoesNotContain("12345", e.Message);
}
}
[Fact]
public void OutFreeDistanceToSegmentEqualsTheOutForm()
{
var r = new System.Random(0x5E61);
for (var n = 0; n < 2000; n++)
{
var p = new float2(Span(r, 5.0f), Span(r, 5.0f));
var start = new float2(Span(r, 5.0f), Span(r, 5.0f));
var end = r.Next(8) == 0 ? start : new float2(Span(r, 5.0f), Span(r, 5.0f));
var outForm = distance_to_segment(p, start, end, out var closest);
Assert.Equal(BitConverter.SingleToInt32Bits(outForm), BitConverter.SingleToInt32Bits(distance_to_segment(p, start, end)));
Assert.Equal(distance(p, closest), outForm);
double sx = (double)end.x - start.x, sy = (double)end.y - start.y, qx = (double)p.x - start.x, qy = (double)p.y - start.y;
var t2 = sx * sx + sy * sy > 0.0 ? Math.Clamp((qx * sx + qy * sy) / (sx * sx + sy * sy), 0.0, 1.0) : 0.0;
var expected2 = Math.Sqrt(Math.Pow(qx - t2 * sx, 2) + Math.Pow(qy - t2 * sy, 2));
Assert.Equal(expected2, outForm, 1.0e-4 * (1.0 + expected2));
var p3 = new float3(Span(r, 5.0f), Span(r, 5.0f), Span(r, 5.0f));
var a3 = new float3(Span(r, 5.0f), Span(r, 5.0f), Span(r, 5.0f));
var b3 = r.Next(8) == 0 ? a3 : new float3(Span(r, 5.0f), Span(r, 5.0f), Span(r, 5.0f));
var got = distance_to_segment(p3, a3, b3);
if (a3.Equals(b3))
{
Assert.Equal(distance(p3, a3), got);
continue;
}
double ex = (double)b3.x - a3.x, ey = (double)b3.y - a3.y, ez = (double)b3.z - a3.z;
double px = (double)p3.x - a3.x, py = (double)p3.y - a3.y, pz = (double)p3.z - a3.z;
var t = Math.Clamp((px * ex + py * ey + pz * ez) / (ex * ex + ey * ey + ez * ez), 0.0, 1.0);
var expected = Math.Sqrt(Math.Pow(px - t * ex, 2) + Math.Pow(py - t * ey, 2) + Math.Pow(pz - t * ez, 2));
Assert.Equal(expected, got, 1.0e-4 * (1.0 + expected));
}
}
// The cell of the owner is the intersection of the half-spaces of its radical planes. Reference in double,
// written here: x.d = c with d = s2 - s1, c = (|s2|^2 - |s1|^2 + w1^2 - w2^2) / 2, signed distance (c - p.d) / |d|.
private static (double Distance, double[] Normal) CellBoundary(float3 p, float4[] sites, int owner)
{
var best = double.PositiveInfinity;
var normal = new double[3];
var s1 = new[] { (double)sites[owner].x, sites[owner].y, sites[owner].z };
var q = new[] { (double)p.x, p.y, p.z };
for (var k = 0; k < sites.Length; k++)
{
var s2 = new[] { (double)sites[k].x, sites[k].y, sites[k].z };
var d = new[] { s2[0] - s1[0], s2[1] - s1[1], s2[2] - s1[2] };
var dd = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
if (k == owner || dd == 0.0)
continue;
double w1 = sites[owner].w, w2 = sites[k].w;
var c = (s2.Sum(v => v * v) - s1.Sum(v => v * v) + w1 * w1 - w2 * w2) / 2.0;
var distance = (c - (q[0] * d[0] + q[1] * d[1] + q[2] * d[2])) / Math.Sqrt(dd);
if (distance < best)
{
best = distance;
normal = new[] { -d[0] / Math.Sqrt(dd), -d[1] / Math.Sqrt(dd), -d[2] / Math.Sqrt(dd) };
}
}
return (best, normal);
}
// Spans with duplicated sites, zero weights, collinear sites and single-site spans.
private static float4[] AwkwardSites(System.Random r)
{
var count = 1 + r.Next(9);
var collinear = r.Next(5) == 0;
var sites = new float4[count];
for (var i = 0; i < count; i++)
{
var weight = r.Next(5) == 0 ? 0.0f : 0.5f + 2.5f * r.NextSingle();
sites[i] = i > 0 && r.Next(4) == 0 ? sites[r.Next(i)]
: collinear ? new float4(Span(r, 10.0f), 0.0f, 0.0f, weight)
: new float4(Span(r, 10.0f), Span(r, 10.0f), Span(r, 10.0f), weight);
}
return sites;
}
[Fact]
public void PowerBorderIsTheLeastRadicalPlaneDistance()
{
var r = new System.Random(0xCE11);
var finite = 0;
var unbounded = 0;
for (var n = 0; n < 6000; n++)
{
var sites = AwkwardSites(r);
var p = Point(r);
var reference = sites.Select(s => PowerReference(p, s)).ToArray();
var order = Enumerable.Range(0, sites.Length).OrderBy(i => reference[i]).ThenBy(i => i).ToArray();
if (order.Length > 1 && reference[order[1]] - reference[order[0]] < 1.0e-2 && reference[order[1]] != reference[order[0]])
continue;
var (distance, normal) = CellBoundary(p, sites, order[0]);
var border = power_border(p, sites);
if (double.IsPositiveInfinity(distance))
{
Assert.Equal(1.0e30f, border.w);
unbounded++;
continue;
}
Assert.InRange(border.w, distance - 1.0e-4 * Math.Abs(distance) - 1.0e-4, distance + 1.0e-4 * Math.Abs(distance) + 1.0e-4);
finite++;
// The normal is the minimising plane's, pointing into the cell, when that plane is clear of the rest.
var others = Enumerable.Range(0, sites.Length).Where(k => k != order[0]).Select(k => CellBoundary(p, new[] { sites[order[0]], sites[k] }, 0).Distance).Where(v => !double.IsPositiveInfinity(v)).OrderBy(v => v).ToArray();
if (others.Length > 1 && others[1] - others[0] > 1.0e-2)
{
Assert.InRange(border.x, normal[0] - 1.0e-3, normal[0] + 1.0e-3);
Assert.InRange(border.y, normal[1] - 1.0e-3, normal[1] + 1.0e-3);
Assert.InRange(border.z, normal[2] - 1.0e-3, normal[2] + 1.0e-3);
}
}
Assert.True(finite > 2500 && unbounded > 50, $"{finite} bounded and {unbounded} unbounded cells were compared");
}
[Fact]
public void ADuplicateOfTheOwnerLeavesTheCellBorderToTheOtherSites()
{
var a = new float4(0.0f, 0.0f, 0.0f, 1.0f);
var far = new float4(10.0f, 0.0f, 0.0f, 1.0f);
// p is nearer the owner's duplicate than anything else: the duplicate is the second-nearest site.
var border = power_border(new float3(1.0f, 0.0f, 0.0f), new[] { a, a, far });
Assert.Equal(4.0f, border.w, 1.0e-4f);
Assert.Equal(-1.0f, border.x, 1.0e-5f);
// Only coincident sites: the cell has no bounding plane.
Assert.Equal(1.0e30f, power_border(new float3(1.0f, 0.0f, 0.0f), new[] { a, a }).w);
Assert.Equal(1.0e30f, power_border(new float3(1.0f, 0.0f, 0.0f), new[] { a }).w);
Assert.Equal(1.0e30f, power_border(new float3(1.0f, 0.0f, 0.0f), ReadOnlySpan<float4>.Empty).w);
}
// Close sites seen from a far query: the plane distance must not cancel (the old gradient-difference form
// had 1.5e-4 relative error at this geometry and 3.5e-3 at coordinates near 1e4).
[Theory]
[InlineData(0.0f)]
[InlineData(10000.0f)]
public void PowerBorderKeepsItsPrecisionForCloseSitesAndAFarQuery(float shift)
{
var sites = new[] { new float4(shift - 1.453f, shift + 1.986f, 0.0f, 13.085f), new float4(shift - 1.539f, shift + 2.103f, 0.0f, 5.113f) };
var p = new float3(shift - 154.2f, shift + 188.9f, 0.0f);
var expected = CellBoundary(p, sites, (int)power_cells(p, sites).nearestSite).Distance;
Assert.True(expected > 100.0);
Assert.InRange(power_border(p, sites).w, expected * (1.0 - 1.0e-5), expected * (1.0 + 1.0e-5));
}
[Fact]
public void CoincidentGabrielPairHasMarginMinusOne()
{
var a = new float3(1.0f, 2.0f, 3.0f);
foreach (var other in new[] { a, new float3(0.0f, 0.0f, 0.0f), new float3(9.0f, -4.0f, 2.0f) })
Assert.Equal(-1.0f, gabriel_margin(a, a, other));
var pair = new[] { new float4(a, 1.0f), new float4(a, 1.0f), new float4(5.0f, 5.0f, 5.0f, 1.0f) };
Assert.Equal(0.0f, soft_gabriel_gate(pair, 0, 1, 0.15f));
// smoothstep(-3, 3, -1) = 3t^2 - 2t^3 at t = 1/3.
Assert.Equal(7.0 / 27.0, soft_gabriel_gate(pair, 0, 1, 3.0f), 1.0e-5);
Assert.Equal(1.0f, soft_gabriel_gate(pair[..2], 0, 1, 0.15f));
}
[Fact]
public void CellSpansRefuseNonFinitePositionsAndQueriesAndOverlongSpans()
{
var good = new float4(0.0f, 0.0f, 0.0f, 1.0f);
var origin = new float3(0.0f, 0.0f, 0.0f);
foreach (var bad in new[] { float.NaN, float.PositiveInfinity, float.NegativeInfinity })
{
var site = new[] { new float4(bad, 0.0f, 0.0f, 1.0f), good, new float4(2.0f, 0.0f, 0.0f, 1.0f) };
Assert.Equal("sites", Assert.Throws<ArgumentException>(() => power_cells(origin, site)).ParamName);
Assert.Equal("sites", Assert.Throws<ArgumentException>(() => multiplicative_cells(origin, site)).ParamName);
Assert.Equal("sites", Assert.Throws<ArgumentException>(() => power_border(origin, site)).ParamName);
Assert.Equal("sites", Assert.Throws<ArgumentException>(() => soft_gabriel_gate(site, 1, 2, 0.1f)).ParamName);
var query = new float3(0.0f, bad, 0.0f);
Assert.Equal("p", Assert.Throws<ArgumentException>(() => power_cells(query, new[] { good })).ParamName);
Assert.Equal("p", Assert.Throws<ArgumentException>(() => multiplicative_cells(query, new[] { good })).ParamName);
Assert.Equal("p", Assert.Throws<ArgumentException>(() => power_border(query, new[] { good })).ParamName);
}
// Indices are floats, exact only to 2^24: a span of 2^24 + 1 real sites is refused for its length.
var overlong = new float4[(1 << 24) + 1];
foreach (var call in new Func<ArgumentException>[]
{
() => Assert.Throws<ArgumentException>(() => power_cells(origin, overlong)),
() => Assert.Throws<ArgumentException>(() => multiplicative_cells(origin, overlong)),
() => Assert.Throws<ArgumentException>(() => power_border(origin, overlong)),
})
{
var e = call();
Assert.Equal("sites", e.ParamName);
Assert.Contains("2^24", e.Message);
}
}
[Fact]
public void SegmentClosestIsTheClampedFootOfThePerpendicular()
{
var start = new float3(0.0f, 0.0f, 0.0f);
var end = new float3(4.0f, 0.0f, 0.0f);
Assert.Equal(new float3(2.0f, 0.0f, 0.0f), segment_closest(new float3(2.0f, 3.0f, 1.0f), start, end));
Assert.Equal(end, segment_closest(new float3(9.0f, 3.0f, 1.0f), start, end));
Assert.Equal(start, segment_closest(new float3(-9.0f, 3.0f, 1.0f), start, end));
Assert.Equal(start, segment_closest(new float3(2.0f, 3.0f, 1.0f), start, start));
Assert.Equal(new float2(4.0f, 0.0f), segment_closest(new float2(9.0f, 3.0f), new float2(0.0f, 0.0f), new float2(4.0f, 0.0f)));
}
[Fact]
public void PowerBorderStepOutsideTheOwnersCellReportsDistanceZeroWithThatPlanesNormal()
{
var left = new float4(0.0f, 0.0f, 0.0f, 1.0f);
var right = new float4(4.0f, 0.0f, 0.0f, 1.0f);
var empty = new float4(0.0f, 0.0f, 0.0f, 1.0e30f);
var inside = power_border_step(new float3(1.0f, 0.0f, 0.0f), left, right, empty);
Assert.Equal(new float4(-1.0f, 0.0f, 0.0f, 1.0f), inside);
var outside = power_border_step(new float3(3.5f, 0.0f, 0.0f), left, right, empty);
Assert.Equal(new float4(-1.0f, 0.0f, 0.0f, 0.0f), outside);
}
[Fact]
public void PowerBorderStepLeavesTheBorderAloneForASiteCoincidentWithTheOwner()
{
var owner = new float4(1.0f, 2.0f, 3.0f, 1.0f);
var heavier = new float4(1.0f, 2.0f, 3.0f, 2.0f);
var running = new float4(1.0f, 0.0f, 0.0f, 5.0f);
foreach (var other in new[] { owner, heavier })
foreach (var border in new[] { running, new float4(0.0f, 0.0f, 0.0f, 1.0e30f) })
{
var result = power_border_step(new float3(4.0f, 4.0f, 4.0f), owner, other, border);
Assert.Equal(border.x, result.x);
Assert.Equal(border.w, result.w);
}
}
}

View file

@ -42,7 +42,7 @@ function Get-Zero([string]$type) {
return "$type(0.0)"
}
$calls = foreach ($match in [regex]::Matches($library, '(?m)^\w+\s+(cultmath_\w+)\s*\(([^)]*)\)')) {
$arguments = foreach ($parameter in ($match.Groups[2].Value -split ',')) {
$arguments = foreach ($parameter in ($match.Groups[2].Value -split ',' | Where-Object { $_.Trim() })) {
Get-Zero (($parameter.Trim() -split '\s+')[0])
}
" $($match.Groups[1].Value)($($arguments -join ', '));"

View file

@ -600,6 +600,126 @@ CultCellular cultmath_cellular(float3 p)
return result;
}
// Sites: a site is float4(position.xyz, weight). A span is a loop over a per-site step, because a shader
// function cannot take a span in the mirror (design.md, "Sites"). The consumer's loop, over its own buffer:
// CultSiteCells cells = cultmath_site_cells_empty();
// for (int i = 0; i < count; i++)
// cells = cultmath_site_cells_insert(cells, cultmath_power_score(p, sites[i]), i);
// The exact power cell border is a second loop over the buffer, skipping the owner cells.nearestSite:
// float4 border = float4(0.0, 0.0, 0.0, 1.0e30); int owner = (int)cells.nearestSite;
// for (int k = 0; k < count; k++) if (k != owner) border = cultmath_power_border_step(p, sites[owner], sites[k], border);
// The step trusts the owner: a p outside the owner's cell reports distance 0 with that plane's normal, not an error.
// Statement for statement with math.Sites.cs (power_score, multiplicative_score, site_cells_*, gabriel_margin).
struct CultSiteCells
{
float4 nearest;
float4 second;
float nearestSite;
float secondSite;
};
float4 cultmath_power_score(float3 p, float4 site)
{
float3 offset = p - site.xyz;
return float4(offset * 2.0, dot(offset, offset) - site.w * site.w);
}
float4 cultmath_multiplicative_score(float3 p, float4 site)
{
float3 offset = p - site.xyz;
float r = length(offset);
float3 gradient = r > 0.0 ? offset / (r * site.w) : float3(0.0, 0.0, 0.0);
return float4(gradient, r / site.w);
}
CultSiteCells cultmath_site_cells_empty()
{
CultSiteCells result;
result.nearest = float4(0.0, 0.0, 0.0, 1.0e30);
result.second = float4(0.0, 0.0, 0.0, 1.0e30);
result.nearestSite = -1.0;
result.secondSite = -1.0;
return result;
}
CultSiteCells cultmath_site_cells_insert(CultSiteCells cells, float4 score, int index)
{
CultSiteCells result = cells;
if (score.w < cells.nearest.w)
{
result.second = cells.nearest;
result.secondSite = cells.nearestSite;
result.nearest = score;
result.nearestSite = (float)index;
}
else if (score.w < cells.second.w)
{
result.second = score;
result.secondSite = (float)index;
}
return result;
}
float4 cultmath_site_cells_border(CultSiteCells cells)
{
float3 n = cells.second.xyz - cells.nearest.xyz;
float len = length(n);
if (cells.secondSite < 0.0 || len <= 0.0)
return float4(0.0, 0.0, 0.0, 1.0e30);
return float4(n / len, (cells.second.w - cells.nearest.w) / len);
}
float4 cultmath_power_border_step(float3 p, float4 owner, float4 other, float4 border)
{
float3 d = other.xyz - owner.xyz;
float len = length(d);
if (len <= 0.0)
return border;
float plane = max((dot(owner.xyz - p, d) + 0.5 * (dot(d, d) + (owner.w - other.w) * (owner.w + other.w))) / len, 0.0);
return plane < border.w ? float4(-d / len, plane) : border;
}
float cultmath_gabriel_margin(float3 a, float3 b, float3 other)
{
float r = cultmath_distance(a, b) * 0.5;
if (r <= 0.0)
return -1.0;
return (cultmath_distance(other, (a + b) * 0.5) - r) / r;
}
float2 cultmath_segment_closest(float2 point_value, float2 start, float2 end)
{
float2 segment = end - start;
float segmentLengthSq = cultmath_lengthsq(segment);
if (segmentLengthSq <= 0.0)
return start;
float t = cultmath_saturate(dot(point_value - start, segment) / segmentLengthSq);
return start + segment * t;
}
float3 cultmath_segment_closest(float3 point_value, float3 start, float3 end)
{
float3 segment = end - start;
float segmentLengthSq = cultmath_lengthsq(segment);
if (segmentLengthSq <= 0.0)
return start;
float t = cultmath_saturate(dot(point_value - start, segment) / segmentLengthSq);
return start + segment * t;
}
float cultmath_distance_to_segment(float2 point_value, float2 start, float2 end)
{
return cultmath_distance(point_value, cultmath_segment_closest(point_value, start, end));
}
float cultmath_distance_to_segment(float3 point_value, float3 start, float3 end)
{
return cultmath_distance(point_value, cultmath_segment_closest(point_value, start, end));
}
#include "CultMath.Phacelle.hlsl"
#include "CultMath.Interval.hlsl"
#include "CultMath.Cycles.hlsl"

View file

@ -14,7 +14,7 @@ namespace GameCult.Caching.MessagePack;
/// The canonical System.Text.Json shape of every public CultMath value type, the JSON twin of
/// <see cref="CultMathResolver"/>. Vectors, quaternions and colors are objects keyed by their
/// field names (<c>{"x":1,"y":2}</c>), matrices are arrays of row objects, <c>rect</c> is
/// <c>{"min":..,"max":..}</c>, <c>CultCellular</c> is <c>{"nearest":..,"edge":..,"id":..}</c>, <c>CultPhasor</c> is <c>{"cos":..,"sin":..}</c>, <c>SpanNoise</c> is <c>{"field":..,"curvature":..,"fold":..}</c>, <c>SpanPath</c> is <c>{"midpoint":..,"velocity":..,"speed":..,"acceleration":..,"halfLength":..}</c>, and <c>SpanStage</c> is <c>{"frequency":..,"stretch":..,"axis":..,"shift":..,"offset":..,"octaveStep":..}</c>.
/// <c>{"min":..,"max":..}</c>, <c>CultCellular</c> is <c>{"nearest":..,"edge":..,"id":..}</c>, <c>CultPhasor</c> is <c>{"cos":..,"sin":..}</c>, <c>SpanNoise</c> is <c>{"field":..,"curvature":..,"fold":..}</c>, <c>SpanPath</c> is <c>{"midpoint":..,"velocity":..,"speed":..,"acceleration":..,"halfLength":..}</c>, <c>SpanStage</c> is <c>{"frequency":..,"stretch":..,"axis":..,"shift":..,"offset":..,"octaveStep":..}</c>, and <c>CultSiteCells</c> is <c>{"nearest":..,"second":..,"nearestSite":..,"secondSite":..}</c>.
/// Property names are fixed: <c>PropertyNamingPolicy</c> does not rename them, and
/// <c>PropertyNameCaseInsensitive</c> makes reading case-insensitive.
/// <para>
@ -481,7 +481,7 @@ public static class CultMathJson
Add<Random, uint>(UIntScalar.Instance, new Fields<uint>(("state", Val<uint>())),
a => new Random { state = a[0] }, (v, a) => a[0] = v.state),
// Compositions: matrices are arrays of row objects, rect is {min, max}, CultCellular is {nearest, edge, id}, CultPhasor is {cos, sin}, SpanNoise is {field, curvature, fold}, SpanPath is {midpoint, velocity, speed, acceleration, halfLength}, SpanStage is {frequency, stretch, axis, shift, offset, octaveStep}.
// Compositions: matrices are arrays of row objects, rect is {min, max}, CultCellular is {nearest, edge, id}, CultPhasor is {cos, sin}, SpanNoise is {field, curvature, fold}, SpanPath is {midpoint, velocity, speed, acceleration, halfLength}, SpanStage is {frequency, stretch, axis, shift, offset, octaveStep}, CultSiteCells is {nearest, second, nearestSite, secondSite}.
Add<float2x2, float>(f, new Rows<float>(2, Xy<float>()),
a => new float2x2(a[0], a[1], a[2], a[3]),
(v, a) => { a[0] = v[0].x; a[1] = v[0].y; a[2] = v[1].x; a[3] = v[1].y; }),
@ -539,6 +539,14 @@ public static class CultMathJson
a[8] = v.offset.x; a[9] = v.offset.y; a[10] = v.offset.z;
a[11] = v.octaveStep.x; a[12] = v.octaveStep.y; a[13] = v.octaveStep.z;
}),
Add<CultSiteCells, float>(f, new Fields<float>(("nearest", Xyzw<float>()), ("second", Xyzw<float>()), ("nearestSite", Val<float>()), ("secondSite", Val<float>())),
a => new CultSiteCells(new float4(a[0], a[1], a[2], a[3]), new float4(a[4], a[5], a[6], a[7]), a[8], a[9]),
(v, a) =>
{
a[0] = v.nearest.x; a[1] = v.nearest.y; a[2] = v.nearest.z; a[3] = v.nearest.w;
a[4] = v.second.x; a[5] = v.second.y; a[6] = v.second.z; a[7] = v.second.w;
a[8] = v.nearestSite; a[9] = v.secondSite;
}),
};
var map = new Dictionary<Type, JsonConverter>();

View file

@ -180,7 +180,7 @@ public sealed class CultMathResolver : IFormatterResolver
return value;
}),
// Compositions: matrices are rows, rect is [min, max], CultCellular is [nearest, edge, id], CultPhasor is [cos, sin], SpanNoise is [field, curvature, fold], SpanPath is [midpoint, velocity, speed, acceleration, halfLength], SpanStage is [frequency, stretch, axis, shift, offset, octaveStep].
// Compositions: matrices are rows, rect is [min, max], CultCellular is [nearest, edge, id], CultPhasor is [cos, sin], SpanNoise is [field, curvature, fold], SpanPath is [midpoint, velocity, speed, acceleration, halfLength], SpanStage is [frequency, stretch, axis, shift, offset, octaveStep], CultSiteCells is [nearest, second, nearestSite, secondSite].
Shape<float2x2>((ref MessagePackWriter w, float2x2 v) => { w.WriteArrayHeader(2); PutFloat2(ref w, v[0]); PutFloat2(ref w, v[1]); },
(ref MessagePackReader r) =>
{
@ -289,6 +289,23 @@ public sealed class CultMathResolver : IFormatterResolver
}
return value;
}),
Shape<CultSiteCells>((ref MessagePackWriter w, CultSiteCells v) => { w.WriteArrayHeader(4); PutFloat4(ref w, v.nearest); PutFloat4(ref w, v.second); w.Write(v.nearestSite); w.Write(v.secondSite); },
(ref MessagePackReader r) =>
{
var value = default(CultSiteCells);
for (int i = 0, n = r.ReadArrayHeader(); i < n; i++)
{
switch (i)
{
case 0: value.nearest = GetFloat4(ref r); break;
case 1: value.second = GetFloat4(ref r); break;
case 2: value.nearestSite = r.ReadSingle(); break;
case 3: value.secondSite = r.ReadSingle(); break;
default: r.Skip(); break;
}
}
return value;
}),
};
var map = new Dictionary<Type, object>();

View file

@ -102,6 +102,7 @@ broken graph whole (an `ExprGraphException` naming the rule), so a consumer
| `rect` | `[min, max]` of `float2` | `{"min":{..},"max":{..}}` |
| `CultCellular` | `[nearest, edge, id]` | `{"nearest":{..},"edge":{..},"id":..}` |
| `CultPhasor` | `[cos, sin]` of `float4` | `{"cos":{..},"sin":{..}}` |
| `CultSiteCells` | `[nearest, second, nearestSite, secondSite]` | `{"nearest":{..},"second":{..},"nearestSite":..,"secondSite":..}` |
Floats are MessagePack float32 (`0xCA`), doubles float64 (`0xCB`), integers the
shortest MessagePack integer.

View file

@ -51,6 +51,8 @@ namespace GameCult.Caching.Tests
"""{"midpoint":{"x":1,"y":2,"z":3},"velocity":{"x":4,"y":5,"z":6},"speed":7,"acceleration":8,"halfLength":9}""");
Json(new SpanStage { frequency = 1f, stretch = 2f, axis = new float3(3f, 4f, 5f), shift = new float3(6f, 7f, 8f), offset = new float3(9f, 10f, 11f), octaveStep = new float3(12f, 13f, 14f) }).Should().Be(
"""{"frequency":1,"stretch":2,"axis":{"x":3,"y":4,"z":5},"shift":{"x":6,"y":7,"z":8},"offset":{"x":9,"y":10,"z":11},"octaveStep":{"x":12,"y":13,"z":14}}""");
Json(new CultSiteCells(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8), 9f, 10f)).Should().Be(
"""{"nearest":{"x":1,"y":2,"z":3,"w":4},"second":{"x":5,"y":6,"z":7,"w":8},"nearestSite":9,"secondSite":10}""");
}
[Test]
@ -78,6 +80,8 @@ namespace GameCult.Caching.Tests
RoundTrip(new SpanNoise(new float4(1, 2, 3, 4), 0.25f, 0.5f));
RoundTrip(new SpanPath { midpoint = new float3(1f, 2f, 3f), velocity = new float3(4f, 5f, 6f), speed = 7f, acceleration = 8f, halfLength = 9f });
RoundTrip(new SpanStage { frequency = 1f, stretch = 2f, axis = new float3(3f, 4f, 5f), shift = new float3(6f, 7f, 8f), offset = new float3(9f, 10f, 11f), octaveStep = new float3(12f, 13f, 14f) });
RoundTrip(new CultSiteCells(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8), 9f, 10f));
RoundTrip(new CultSiteCells(new float4(0, 0, 0, 1.0e30f), new float4(0, 0, 0, 1.0e30f), -1f, -1f));
}
[Test]

View file

@ -105,6 +105,8 @@ namespace GameCult.Caching.Tests
RoundTrip(new SpanNoise(new float4(1, 2, 3, 4), 0.25f, 0.5f));
RoundTrip(new SpanPath { midpoint = new float3(1f, 2f, 3f), velocity = new float3(4f, 5f, 6f), speed = 7f, acceleration = 8f, halfLength = 9f });
RoundTrip(new SpanStage { frequency = 1f, stretch = 2f, axis = new float3(3f, 4f, 5f), shift = new float3(6f, 7f, 8f), offset = new float3(9f, 10f, 11f), octaveStep = new float3(12f, 13f, 14f) });
RoundTrip(new CultSiteCells(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8), 9f, 10f));
RoundTrip(new CultSiteCells(new float4(0, 0, 0, 1.0e30f), new float4(0, 0, 0, 1.0e30f), -1f, -1f));
}
[Test]
@ -158,6 +160,12 @@ namespace GameCult.Caching.Tests
"93CA40C00000CA40E00000CA41000000" +
"93CA41100000CA41200000CA41300000" +
"93CA41400000CA41500000CA41600000");
Hex(new CultSiteCells(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8), 9f, 10f)).Should().Be(
"94" +
"94CA3F800000CA40000000CA40400000CA40800000" +
"94CA40A00000CA40C00000CA40E00000CA41000000" +
"CA41100000" +
"CA41200000");
}
[Test]