From 2791567370385c9c8d7a5aeaa64c4588346e1779 Mon Sep 17 00:00:00 2001 From: yum Date: Sun, 12 Apr 2026 19:39:39 -0700 Subject: add 2d voronoi noise --- math.cginc | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) (limited to 'math.cginc') diff --git a/math.cginc b/math.cginc index b79d9b6..514d21f 100755 --- a/math.cginc +++ b/math.cginc @@ -213,8 +213,39 @@ float3 domain_warp_3d_tex(Texture3D noise_tex, SamplerState s, float3 uvw, return noise; } -// Return distance to the nearest cell edge in a Voronoi pattern. -float voronoi_edge_distance(float3 x) { +// Return distance to the nearest voronoi cell edge, clamped to [0, 0.5]. +// 0.5 is on the edge, 0 is far from it. +float voronoi_d_2d(float2 x) { + float2 x_floor = floor(x); + float2 x_frac = frac(x); + float d1 = 1e6; + float d2 = 1e6; + float2 p1 = 0; + float2 p2 = 0; + + for (int j = -1; j <= 1; j++) { + for (int i = -1; i <= 1; i++) { + float2 cell_offset = float2(i, j); + float2 r = cell_offset + hash22_fast(x_floor + cell_offset) - x_frac; + float d = dot(r, r); + if (d < d1) { + d2 = d1; + p2 = p1; + d1 = d; + p1 = r; + } else if (d < d2) { + d2 = d; + p2 = r; + } + } + } + float d = (d2 - d1) / (2.0f * max(1e-4, length(p2 - p1))); + return max(0.0f, 0.5f - d); +} + +// Return distance to the nearest voronoi cell edge, clamped to [0, 0.5]. +// 0.5 is on the edge, 0 is far from it. +float voronoi_d_3d(float3 x) { float3 x_floor = floor(x); float3 x_frac = frac(x); float d1 = 1e6; @@ -240,7 +271,8 @@ float voronoi_edge_distance(float3 x) { } } } - return (d2 - d1) / (2.0 * max(1e-4, length(p2 - p1))); + float d = (d2 - d1) / (2.0f * max(1e-4, length(p2 - p1))); + return max(0.0f, 0.5f - d); } float median(float3 x) { -- cgit v1.2.3