Guest User

Untitled

a guest
Jun 24th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. float pi = atan(1.0)*4;
  5.  
  6. float noise(int x, int y){
  7. int n = x + y * 57;
  8. n = (n<<13) ^ n;
  9. return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0);
  10. }
  11.  
  12. float smooth_noise(float x, float y){
  13. float corners = ( noise(x-1, y-1)+noise(x+1, y-1)+noise(x-1, y+1)+noise(x+1, y+1) ) / 16;
  14. float sides = ( noise(x-1, y) +noise(x+1, y) +noise(x, y-1) +noise(x, y+1) ) / 8;
  15. float center = noise(x, y) / 4;
  16. return corners + sides + center;
  17. }
  18.  
  19. //cosine interpolate
  20. float interpolate(float a, float b, float x){
  21. float ft = x * pi;
  22. float f = (1 - (cos(ft))) * 0.5;
  23. return a * (1-f) + b*f;
  24. }
  25.  
  26. float interpolated_noise(float x, float y){
  27. int integer_X = (int)x;
  28. float fractional_X = x - integer_X;
  29. int integer_Y = (int)y;
  30. float fractional_Y = y - integer_Y;
  31.  
  32. float v1 = smooth_noise(integer_X, integer_Y);
  33. float v2 = smooth_noise(integer_X + 1, integer_Y);
  34. float v3 = smooth_noise(integer_X, integer_Y + 1);
  35. float v4 = smooth_noise(integer_X + 1, integer_Y + 1);
  36.  
  37. float i1 = interpolate(v1 , v2 , fractional_X);
  38. float i2 = interpolate(v3 , v4 , fractional_X);
  39.  
  40. return interpolate(i1 , i2 , fractional_Y);
  41. }
  42.  
  43. float perlinnoise_2d(float x, float y, float persistence, float octaves){
  44. float total = 0;
  45. float p = persistence;
  46. float n = octaves - 1;
  47. for (int i=0; i<n; i++){
  48. float frequency = pow(2,i);
  49. float amplitude = pow(pi,i);
  50. total = total + interpolated_noise(x * frequency, y * frequency) * amplitude;
  51. }
  52. return total;
  53. }
  54.  
  55. int main(int argc, char *argv[]){
  56. float persistence = 0.2;
  57. float octaves = 8.0;
  58. for(int i=0; i<10; i++){
  59. for(int j=0; j<10; j++){
  60. float tmp = perlinnoise_2d(i,j,persistence,octaves);
  61. int c = ((int)(tmp*255)) & 0xff;
  62. printf("%d\n", c);
  63. }
  64. }
  65. }
Add Comment
Please, Sign In to add comment