XorDev

GLSL Noise functions

Jun 10th, 2021
660
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Typical pseudo random hash (white noise).
  2. float hash(vec2 p)
  3. {
  4.     p = mod(p, 7.31); //Bring 'p' to a useful range.
  5.     //Generate a pseudo random number from 'p'.
  6.     return fract( sin(p.x*12.9898 + p.y*78.233) * 43758.5453);
  7. }
  8.  
  9. //Standard value noise.
  10. float value_noise(vec2 pos)
  11. {
  12.     vec2 cell = floor(pos); //Cell (whole number) coordinates.
  13.     vec2 sub = pos-cell; //Sub-cell (fractional) coordinates.
  14.     sub *= sub*(3.-2.*sub); //Cubic interpolation (comment out for linear interpolation).
  15.     const vec2 off = vec2(0,1); //Offset vector.
  16.  
  17.     //Sample cell corners and interpolate between them.
  18.     return mix( mix(hash(cell+off.xx), hash(cell+off.yx), sub.x),
  19.                 mix(hash(cell+off.xy), hash(cell+off.yy), sub.x), sub.y);
  20. }
  21.  
  22. //Generate 'fractal' noise from multiple value noise 'octaves'.
  23. float fractal_noise(vec2 pos, int steps, float amp)
  24. {
  25.     float noise_sum = 0.; //Noise total.
  26.     float weight_sum = 0.; //Weight total.
  27.     float weight = 1.; //Octave weight.
  28.  
  29.     for(int i = 0; i < steps; i++) //Iterate through octaves
  30.     {
  31.         noise_sum += value_noise(pos) * weight; //Add noise octave.
  32.         weight_sum += weight; //Add octave weight.
  33.         weight *= amp; //Reduce octave amplitude by multiplier.
  34.         pos *= mat2(1.6,1.2,-1.2,1.6); //Rotate and scale.
  35.     }
  36.     return noise_sum/weight_sum; //Compute average.
  37. }
RAW Paste Data