Advertisement
Guest User

Untitled

a guest
Jan 10th, 2013
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. from random import Random
  2. import math
  3.  
  4. def perlin_noise_2d(width, height, **kwargs):
  5. (period_x, period_y) = kwargs.get("period", (width,height)) # Period of the noise
  6. seed = kwargs.get("seed", None) # PRNG seed to use
  7. interpolation_function = kwargs.get("interpolation_function", lambda x: 3*x**2 - 2*x**3)
  8. minimum = kwargs.get("minimum", 0)
  9. maximum = kwargs.get("maximum", 255)
  10.  
  11. prng = Random(seed)
  12.  
  13. def unit(x,y):
  14. if x == 0 and y == 0:
  15. return (0,0)
  16. abs = math.sqrt(x**2 + y**2)
  17. x = x / abs
  18. y = y / abs
  19. return (x,y)
  20.  
  21. gradients = []
  22. for y in range(height/period_y + 1):
  23. for x in range(width/period_x + 1):
  24. gradients.append(unit(prng.random(), prng.random() ))
  25. def get_noise(x,y):
  26. x = x / period_x
  27. y = y / period_y
  28. return [gradients[x+y*(width/period_x)], # top left
  29. gradients[x+1+y*(width/period_x)], # top right
  30. gradients[x+y*(width/period_x+1)], # bottom left
  31. gradients[x+1+y*(width/period_x+1)] # bottom right
  32. ]
  33.  
  34. def dot ((x0,y0), (x1,y1)):
  35. return x0*x1 + y0*y1
  36.  
  37. values = []
  38. for y in range(height):
  39. for x in range(width):
  40. noise = get_noise(x,y)
  41.  
  42. (delta_x, delta_y) = (x % period_x, y % period_y)
  43.  
  44. tl = abs(dot(noise[0], unit(delta_x,delta_y)))
  45. tr = abs(dot(noise[1], unit(1-delta_x,delta_y)))
  46. bl = abs(dot(noise[2], unit(delta_x,1-delta_y)))
  47. br = abs(dot(noise[3], unit(1-delta_x,1-delta_y)))
  48.  
  49.  
  50. top = tl*interpolation_function(delta_x) + tr*(1-interpolation_function(delta_x))
  51. bottom = bl*interpolation_function(delta_x) + br*(1-interpolation_function(delta_x))
  52.  
  53. value = top*interpolation_function(delta_y) + bottom*(1-interpolation_function(delta_y))
  54.  
  55. if value > 1:
  56. print "Value: "+str(value)
  57. print "top: "+str(top)+" bottom: "+str(bottom)
  58. print "Noise: "+str(noise)
  59. print "Magnitude of noise: "+str([math.sqrt(x**2+y**2) for (x,y) in noise])
  60. print "Delta: "+str((delta_x,delta_y))
  61. print "dot products: "+str((tl,tr,bl,br))
  62. raise Exception
  63.  
  64. values.append(int(value*(maximum-minimum)+minimum))
  65. return values
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement