Files

42 lines
1.4 KiB
C#

using UnityEngine;
namespace BlockWorld
{
/// <summary>确定性值噪声(和网页版/APK 用同一套公式,同一坐标出来是同一座山)</summary>
public static class Noise
{
static float Hash(int x, int y, int salt)
{
int h = x * 374761393 + y * 668265263 + salt * 1442695041;
h = (h ^ (h >> 13)) * 1274126177;
h ^= h >> 16;
return (h & 0x7fffffff) / (float)0x7fffffff;
}
static float Smooth(float t) => t * t * (3f - 2f * t);
public static float Value2(float x, float y, int salt)
{
int xi = Mathf.FloorToInt(x), yi = Mathf.FloorToInt(y);
float xf = x - xi, yf = y - yi;
float a = Hash(xi, yi, salt), b = Hash(xi + 1, yi, salt);
float c = Hash(xi, yi + 1, salt), d = Hash(xi + 1, yi + 1, salt);
float u = Smooth(xf), v = Smooth(yf);
return Mathf.Lerp(Mathf.Lerp(a, b, u), Mathf.Lerp(c, d, u), v);
}
public static float Fbm2(float x, float y, int octaves, int salt)
{
float sum = 0, amp = 0.5f, norm = 0, f = 1f;
for (int i = 0; i < octaves; i++)
{
sum += Value2(x * f, y * f, salt + i * 37) * amp;
norm += amp;
amp *= 0.5f;
f *= 2f;
}
return norm > 0 ? sum / norm : 0.5f;
}
}
}