cellular2D.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Cellular noise ("Worley noise") in 2D in GLSL.
  2. // Copyright (c) Stefan Gustavson 2011-04-19. All rights reserved.
  3. // This code is released under the conditions of the MIT license.
  4. // See LICENSE file for details.
  5. // https://github.com/stegu/webgl-noise
  6. using static Unity.Mathematics.math;
  7. namespace Unity.Mathematics
  8. {
  9. public static partial class noise
  10. {
  11. // Cellular noise, returning F1 and F2 in a float2.
  12. // Standard 3x3 search window for good F1 and F2 values
  13. public static float2 cellular(float2 P)
  14. {
  15. const float K = 0.142857142857f; // 1/7
  16. const float Ko = 0.428571428571f; // 3/7
  17. const float jitter = 1.0f; // Less gives more regular pattern
  18. float2 Pi = mod289(floor(P));
  19. float2 Pf = frac(P);
  20. float3 oi = float3(-1.0f, 0.0f, 1.0f);
  21. float3 of = float3(-0.5f, 0.5f, 1.5f);
  22. float3 px = permute(Pi.x + oi);
  23. float3 p = permute(px.x + Pi.y + oi); // p11, p12, p13
  24. float3 ox = frac(p * K) - Ko;
  25. float3 oy = mod7(floor(p * K)) * K - Ko;
  26. float3 dx = Pf.x + 0.5f + jitter * ox;
  27. float3 dy = Pf.y - of + jitter * oy;
  28. float3 d1 = dx * dx + dy * dy; // d11, d12 and d13, squared
  29. p = permute(px.y + Pi.y + oi); // p21, p22, p23
  30. ox = frac(p * K) - Ko;
  31. oy = mod7(floor(p * K)) * K - Ko;
  32. dx = Pf.x - 0.5f + jitter * ox;
  33. dy = Pf.y - of + jitter * oy;
  34. float3 d2 = dx * dx + dy * dy; // d21, d22 and d23, squared
  35. p = permute(px.z + Pi.y + oi); // p31, p32, p33
  36. ox = frac(p * K) - Ko;
  37. oy = mod7(floor(p * K)) * K - Ko;
  38. dx = Pf.x - 1.5f + jitter * ox;
  39. dy = Pf.y - of + jitter * oy;
  40. float3 d3 = dx * dx + dy * dy; // d31, d32 and d33, squared
  41. // Sort out the two smallest distances (F1, F2)
  42. float3 d1a = min(d1, d2);
  43. d2 = max(d1, d2); // Swap to keep candidates for F2
  44. d2 = min(d2, d3); // neither F1 nor F2 are now in d3
  45. d1 = min(d1a, d2); // F1 is now in d1
  46. d2 = max(d1a, d2); // Swap to keep candidates for F2
  47. d1.xy = (d1.x < d1.y) ? d1.xy : d1.yx; // Swap if smaller
  48. d1.xz = (d1.x < d1.z) ? d1.xz : d1.zx; // F1 is in d1.x
  49. d1.yz = min(d1.yz, d2.yz); // F2 is now not in d2.yz
  50. d1.y = min(d1.y, d1.z); // nor in d1.z
  51. d1.y = min(d1.y, d2.x); // F2 is in d1.y, we're done.
  52. return sqrt(d1.xy);
  53. }
  54. }
  55. }