-
Notifications
You must be signed in to change notification settings - Fork 0
/
perlin_noise.py
84 lines (73 loc) · 2.69 KB
/
perlin_noise.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import random, copy
from objects import distance
#* Perlin Noise Map Generator File
def minAndMax(L):
right, left = -1, 1
for row in L:
if max(row) > right:
right = max(row)
elif min(row) < left:
left = min(row)
return left, right
# returns unit vector between two points
def unitVector(x, y):
k = (x ** 2 + y ** 2) ** -0.5
return (k * x, k * y)
# returns random gradient vector
def gradient():
x, y = random.uniform(-1, 1), random.uniform(-1, 1)
return unitVector(x, y)
# smoothening function
def fade(x):
return 6 * x ** 5 - 15 * x ** 4 + 10 * x ** 3
# returns dot product of two vectors
def dot(v1, v2):
return v1[0] * v2[0] + v1[1] * v2[1]
# linear interpolation formula
def interpolate(d, a, b):
return (1 - d) * a + d * b
# elliptic parabaloid function to create cloud shape
def f(x, y, width, height, dx, dy, a, level):
return ((a * (x - dx * width) / width) ** 2 + ((y - dy * height) / height) ** 2) * level
# https://en.wikipedia.org/wiki/Perlin_noise
# https://adrianb.io/2014/08/09/perlinnoise.html
# creates noise for point x,y
def noise(x, y, scale):
# corners
p1 = int(x), int(y)
p2 = p1[0] + 1, p1[1]
p3 = p1[0], p1[1] + 1
p4 = p1[0] + 1, p1[1] + 1
# gradient vectors
g1, g2, g3, g4 = gradient(), gradient(), gradient(), gradient()
# smooth step
dx, dy = fade(x - p1[0]), fade(y - p1[1])
# dot product
d1, d2 = (x - p1[0], y - p1[1]), (x - p2[0], y - p2[1])
d3, d4 = (x - p3[0], y - p3[1]), (x - p4[0], y - p4[1])
# linear interpolation
top = interpolate(dx, dot(g1, d1), dot(g2, d2))
bottom = interpolate(dx, dot(g3, d3), dot(g4, d4))
return interpolate(dy, top, bottom) * scale
# returns 2D list of noise with octave, persistance, lacunarity parameters
def octave(result, per, lac, octaves, level):
width, height = len(result[0]), len(result)
#! random eccentricity for elliptic base
a = random.uniform(0.5, 2)
#! position of cloud center
dx, dy = random.random(), random.random()
for y in range(height):
for x in range(width):
amp = 10
freq = 0.1
noiseH = 0
for i in range(octaves):
noiseH += (2 * noise(x * freq, y * freq, 1) + 1) * f(x, y, width,
height, dx, dy, a, level)
amp *= per
freq *= lac
result[y][x] = float("{:.2f}".format(noiseH))
return result
imageScale = 5
width, height = 1660 // imageScale, 1020 // imageScale
result = octave([[0] * (width) for y in range(height)], 0.4, 1, 2, random.randint(10,20))