§ Вариант 1: 2D
1
2float rnd(float x, float y) {
3
4 float m = 43758.5453123*sin(x*12.9898 + y*78.233);
5 return m - floor(m);
6}
7
8
9float noise(float x, float y) {
10
11 float ix = floor(x), iy = floor(y);
12 float fx = x - ix;
13 float fy = y - iy;
14
15 float a = rnd(ix, iy);
16 float b = rnd(ix + 1, iy);
17 float c = rnd(ix, iy + 1);
18 float d = rnd(ix + 1, iy + 1);
19
20 float ux = fx*fx*(3 - 2*fx);
21 float uy = fy*fy*(3 - 2*fy);
22
23 return a * (1 - ux) + b * ux + (c - a) * uy * (1 - ux) + (d - b) * ux * uy;
24}
25
26
27float fbm(float x, float y, int octaves) {
28
29 float value = 0;
30 float amp = 0.5;
31
32 for (int i = 0; i < octaves; i++) {
33
34 value += amp * noise(x, y);
35 x *= 2;
36 y *= 2;
37 amp = amp * .5;
38 }
39
40 return value;
41}
§ Вариант 2: 3D
1
2struct vec3 { double x, y, z; };
3struct vec4 { double x, y, z, w; };
4
5
6double mix(double x, double y, double a) {
7 return x*(1.0-a) + y*a;
8}
9
10
11double noise(vec3 p)
12{
13
14 vec3 i = {floor(p.x), floor(p.y), floor(p.z)};
15
16
17 double d = i.x + i.y*57.0 + i.z*21.0;
18
19
20 vec4 a = {d, d + 57.0, d + 21.0, d + 78.0};
21
22
23 vec3 f = {
24 0.5 - cos((p.x-i.x)*M_PI)/2.0,
25 0.5 - cos((p.y-i.y)*M_PI)/2.0,
26 0.5 - cos((p.z-i.z)*M_PI)/2.0,
27 };
28
29
30 a.x = mix(sin(cos(a.x)*a.x), sin(cos(1+a.x)*(1+a.x)), f.x);
31 a.y = mix(sin(cos(a.y)*a.y), sin(cos(1+a.y)*(1+a.y)), f.x);
32 a.z = mix(sin(cos(a.z)*a.z), sin(cos(1+a.z)*(1+a.z)), f.x);
33 a.w = mix(sin(cos(a.w)*a.w), sin(cos(1+a.w)*(1+a.w)), f.x);
34
35
36 a.x = mix(a.x, a.y, f.y);
37 a.y = mix(a.z, a.w, f.y);
38
39 return mix(a.x, a.y, f.z);
40}