gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
python如何实现2D柏林噪声越中间值越大
- User
python如何实现2D柏林噪声越中间值越大
- Assistant
以下是Python实现的2D柏林噪声,其中越中间值越大的效果通过添加一个权重系数,使得中心点的值更大:
import random def interpolate(a, b, x): ft = x * 3.1415927 f = (1 - math.cos(ft)) * 0.5 return a*(1-f) + b*f def get_noise(x, y): n = x + y * 57 n = (n<<13) ^ n return (1.0 - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0) def get_smooth_noise(x, y): corners = (get_noise(x-1, y-1)+get_noise(x+1, y-1)+get_noise(x-1, y+1)+get_noise(x+1, y+1)) / 16 sides = (get_noise(x-1, y)+get_noise(x+1, y)+get_noise(x, y-1)+get_noise(x, y+1)) / 8 center = get_noise(x, y) / 4 return corners + sides + center def get_interpolated_noise(x, y): int_x = int(x) frac_x = x - int_x int_y = int(y) frac_y = y - int_y v1 = get_smooth_noise(int_x, int_y) v2 = get_smooth_noise(int_x + 1, int_y) v3 = get_smooth_noise(int_x, int_y + 1) v4 = get_smooth_noise(int_x + 1, int_y + 1) i1 = interpolate(v1, v2, frac_x) i2 = interpolate(v3, v4, frac_x) return interpolate(i1, i2, frac_y) def get_weighted_noise(x, y, weight): return get_interpolated_noise(x, y) * weight size = 10 noise_map = [] for y in range(size): row = [] for x in range(size): weight = abs(x - size/2) + abs(y - size/2) # 计算权重系数 row.append(get_weighted_noise(x/10, y/10, weight/10)) noise_map.append(row) for row in noise_map: print(row)注意,在计算权重系数时,我使用了
abs(x - size/2) + abs(y - size/2)这个公式,它计算了当前节点到中心点的曼哈顿距离,然后将其除以10,作为get_weighted_noise函数的第三个参数,用于在get_interpolated_noise中将中心点的值放大。你可以根据需要调整除以的参数。