static Vector2[] grad2D = {new Vector2(1, 0), new Vector2(1,1).normalized, new Vector2(0, 1), new Vector2(-1, 1).normalized,
new Vector2(-1, 0), new Vector2(-1, -1).normalized, new Vector2(0, -1), new Vector2(1, -1).normalized};
//1~255
static int[] p = {151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180,};
static int FastFloor(float x)
{
return x > 0 ? (int)x : (int)x - 1;
}
static float F(float v)
{
return (v * v * v) * (6 * v * v - 15 * v + 10);
}
public static float Perlin(float x, float y, float freq)
{
x = x * freq;
y = y * freq;
int x0 = FastFloor(x);
int y0 = FastFloor(y);
float dx = (x - x0);
float dy = (y - y0);
x0 = x0 & 255;
y0 = y0 & 255;
int x0y0i = p[(x0 + p[y0]) % 255] % 8;
int x1y0i = p[(x0 + 1 + p[y0]) % 255] % 8;
int x0y1i = p[(x0 + p[y0 + 1]) % 255] % 8;
int x1y1i = p[(x0 + 1 + p[y0 + 1]) % 255] % 8;
Vector2 g00 = grad2D[x0y0i];
Vector2 g10 = grad2D[x1y0i];
Vector2 g01 = grad2D[x0y1i];
Vector2 g11 = grad2D[x1y1i];
float v00 = Vector2.Dot(g00, new Vector2(dx, dy));
float v10 = Vector2.Dot(g10, new Vector2(dx - 1, dy));
float v01 = Vector2.Dot(g01, new Vector2(dx, dy - 1));
float v11 = Vector2.Dot(g11, new Vector2(dx - 1, dy - 1));
float u = F(dx);
float v = F(dy);
float n0 = Mathf.Lerp(v00, v10, u);
float n1 = Mathf.Lerp(v01, v11, u);
float nn0 = Mathf.Lerp(n0, n1, v);
float val = (nn0 + 1) / 2.0f;
return val;
}
생각처럼 어려운 개념은 아니였음.
(x,y)에 대해 항상 같은 0~8 사이의 값을 구해야 항상 같은 꼭지점에 같은 gradient를 배정해줄 수가 있음.
그게 x0y0i = p[(x0 + p[y0]) % 255] % 8; 이 부분임.
지금은 %255를 하기 때문에 아마 256.xx에서의 값과 1.xx에서의 값은 같을거임.
반복을 제거하려면 Hash(x,y) -> 0~255 이런 해쉬함수를 만들어서 교체해주면 됨.
참고로 u와 v를 계산 안해주면 이런 결과가 나옴
정보글 개추 절차적 생성이나 쉐이더에 너무 좋은거