# BASIC-RoBots / src / 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``` ```## ## noise.py for BASIC-RoBots ## ## Copyright (C) 2012 Pierre Surply ## ## ## This file is part of BASIC-RoBots. ## ## BASIC-RoBots is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## BASIC-RoBots is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with BASIC-RoBots. If not, see . ## ## Started on Thu Jun 28 17:06:53 2012 Pierre Surply ## Last update Wed Aug 1 17:49:37 2012 Pierre Surply ## import random import math class Noise: def __init__(self, w, h, p, n): self.w = w self.h = h self.p = p self.n = n self.w_max = int(math.ceil(w * pow(2, n-1) / p)) self.h_max = int(math.ceil(h * pow(2, n-1) / p)) self.values = [0] * (self.w_max * self.h_max + 1) for i in range(len(self.values)): self.values[i] = random.random() def get_noise(self, x, y): return self.values[x * self.w_max + y] def inter_cos1D(self, a, b, x): k = (1 - math.cos(x * math.pi)) / 2 return a * (1-k) + b*k def inter_cos2D(self, a, b, c, d, x, y): y1 = self.inter_cos1D(a, b, x) y2 = self.inter_cos1D(c, d, x) return self.inter_cos1D(y1, y2, y) def noise_func(self, x, y): i = int(x / self.p) j = int(y / self.p) return self.inter_cos2D(self.get_noise(i, j), \ self.get_noise(i+1, j), \ self.get_noise(i, j+1), \ self.get_noise(i+1, j+1),\ math.fmod(x / self.p, 1),\ math.fmod(y / self.p, 1)) def smooth_noise(self, x, y, persistance): somme = 0 p = 1 f = 1 for i in range(self.n-1): somme += p*self.noise_func(x*f, y*f) p *= persistance f *= 2 return somme * (1 - persistance) / (1 - p) ```