Advertisement
Badwrong

GameMaker - Perlin Noise

Jan 22nd, 2023 (edited)
2,956
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Game Maker 11.45 KB | Source Code | 0 0
  1. GameMaker solution for Perlin Noise
  2. Author: Nathan Hunter, badwronggames@gmail.com
  3.  
  4. //////////////////////////////////////////////
  5.  
  6. MIT License
  7.  
  8. Copyright (c) 2023 Nathan Hunter
  9.  
  10. Permission is hereby granted, free of charge, to any person obtaining a copy
  11. of this software and associated documentation files (the "Software"), to deal
  12. in the Software without restriction, including without limitation the rights
  13. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. copies of the Software, and to permit persons to whom the Software is
  15. furnished to do so, subject to the following conditions:
  16.  
  17. The above copyright notice and this permission notice shall be included in all
  18. copies or substantial portions of the Software.
  19.  
  20. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  26. SOFTWARE.
  27.  
  28. //////////////////////////////////////////////
  29.  
  30. SETUP: Create the shader below as instructed, and copy the rest of the code after into a GML script file
  31. USE: Call the perlin_noise(_offset, _rate) or perlin_noise_2d(_x, _y) functions
  32.  
  33.  
  34. // Create a GLSL ES shader in GameMaker and name it: shd_perlin_noise_glsl_es
  35. // Copy and paste the following vertex and fragement code into the shader
  36.  
  37. // *********  Vertex Shader ********* //
  38. precision highp float;
  39.  
  40. #if __VERSION__ >= 130
  41.     #define attribute in
  42.     #define varying out
  43. #endif
  44.  
  45. attribute vec3 in_Position;
  46. attribute vec4 in_Colour;
  47. attribute vec2 in_TextureCoord;
  48.  
  49. varying vec2 tex_coord;
  50.  
  51. void main()
  52. {
  53.     gl_Position = gm_Matrices[MATRIX_WORLD_VIEW_PROJECTION] * vec4(in_Position.xyz, 1.0);
  54.     tex_coord = in_TextureCoord;
  55. }
  56. // ********* END Vertex Shader ********* //
  57.  
  58. // ********* Fragment Shader ********* //
  59. // Reference - https://adrianb.io/2014/08/09/perlinnoise.html
  60. precision highp float;
  61.  
  62. #if __VERSION__ >= 130
  63.     out vec4 frag_color;
  64.     #define varying in
  65.     #define texture2D texture
  66. #else
  67.     #define frag_color gl_FragColor
  68. #endif
  69.  
  70. #define M_PI   3.1415926535897932384626433832795
  71.  
  72. float fade(float t)
  73. {
  74.     return t * t * t * (t * (t * 6.0 - 15.0) + 10.0);
  75. }
  76.  
  77. float grad(int hash, float x, float y, float z)
  78. {
  79.     float h = mod(float(hash), 16.0);                                    
  80.     float u = h < 8.0 ? x : y;                
  81.    
  82.     float v;                                            
  83.    
  84.     if(h < 4.0)                              
  85.         v = y;
  86.     else if(h == 12.0 || h == 14.0)
  87.         v = x;
  88.     else                                                
  89.         v = z;
  90.    
  91.     return (mod(h, 2.0) == 0.0 ? u : -u) + (mod(h, 3.0) < 2.0 ? v : -v);    
  92. }
  93.  
  94. float perlin(vec3 pos, int[256] table)
  95. {
  96.     int xi = int(mod(pos.x, 256.0));                          
  97.     int yi = int(mod(pos.y, 256.0));                              
  98.     int zi = int(mod(pos.z, 256.0));  
  99.    
  100.     int xj = int(mod(pos.x + 1.0, 256.0));
  101.     int yj = int(mod(pos.y + 1.0, 256.0));
  102.     int zj = int(mod(pos.z + 1.0, 256.0));
  103.    
  104.     int aaa = table[table[table[xi] + yi]+ zi];
  105.     int aba = table[table[table[xi] + yj]+ zi];
  106.     int aab = table[table[table[xi] + yi]+ zj];
  107.     int abb = table[table[table[xi] + yj]+ zj];
  108.     int baa = table[table[table[xj] + yi]+ zi];
  109.     int bba = table[table[table[xj] + yj]+ zi];
  110.     int bab = table[table[table[xj] + yi]+ zj];
  111.     int bbb = table[table[table[xj] + yj]+ zj];
  112.    
  113.     float xf = fract(pos.x);
  114.     float yf = fract(pos.y);
  115.     float zf = fract(pos.z);
  116.    
  117.     float u = fade(xf);
  118.     float v = fade(yf);
  119.     float w = fade(zf);
  120.    
  121.     float x1 = mix(grad(aaa, xf, yf,       zf), grad(baa, xf - 1.0, yf,       zf), u);                                    
  122.     float y1 = mix(grad(aba, xf, yf - 1.0, zf), grad(bba, xf - 1.0, yf - 1.0, zf), u);
  123.     float z1 = mix(x1, y1, v);
  124.  
  125.     float x2 = mix(grad(aab, xf, yf,       zf - 1.0), grad(bab, xf - 1.0, yf,       zf - 1.0), u);
  126.     float y2 = mix(grad(abb, xf, yf - 1.0, zf - 1.0), grad(bbb, xf - 1.0, yf - 1.0, zf - 1.0), u);
  127.     float z2 = mix (x2, y2, v);
  128.    
  129.     return (mix(z1, z2, w) + 1.0) * 0.5;   
  130. }
  131.  
  132. varying vec2 tex_coord;
  133.  
  134. uniform float u_seed;
  135. uniform int u_table[256]; // permutation table of values 0 - 255
  136.  
  137. void main()
  138. {
  139.     float value = perlin(vec3(sin(abs(tex_coord - 0.5) * M_PI * 0.5) * u_seed, fract(u_seed) * 1.387), u_table);
  140.     frag_color = vec4(vec3(value), 1.0);
  141. }
  142. // ********* END Fragment Shader ********* //
  143.  
  144. // ************** COPY AND PASTE ALL CODE BELOW HERE INTO A GML SCRIPT FILE ***************** //
  145.  
  146. /// feather ignore all
  147.  
  148. #macro C_PERLIN_NOISE_SIZE 1024
  149. #macro C_PERLIN_NOISE_SIZE_MASK 1023
  150. #macro C_PERLIN_NOISE_BUFFER_SIZE 1048576
  151. #macro C_PERLIN_NOISE_BUFFER_MASK 1048575
  152.  
  153. /// @function                   perlin_noise(_offset, _rate)
  154. /// @param {integer} _offset    A fixed positive offset into the buffer (use a constant)
  155. /// @param {real} _rate         Rate of sample over time (used with current_time)
  156. /// @description                Returns perlin noise value from -1 to 1 using premade buffer using offset and rate
  157. function perlin_noise(_offset, _rate)
  158. {  
  159.     // This is a solid way to sample from perlin noise.  It uses time and an offset value which
  160.     // makes each next sample close the previous based on how small the _rate argument is.
  161.     // The _offset argument should be a constant which does not change, and it's purpose is
  162.     // so that different objects, animations, or whatever sample from different places (but still over time)
  163.    
  164.     static _perlin_noise_buffer = get_perlin_noise_buffer();
  165.     var _value = buffer_peek(_perlin_noise_buffer, (floor(_offset + current_time * _rate) & C_PERLIN_NOISE_BUFFER_MASK) << 2, buffer_f32);
  166.     return (_value - 0.5) * 2.0;
  167. }
  168.  
  169. /// @function                   perlin_noise_irange(_value1, _value2, _offset, _rate)
  170. /// @param {integer} _value1    The first value
  171. /// @param {integer} _value2    The second value
  172. /// @param {integer} _offset    A fixed positive offset into the buffer (use a constant)
  173. /// @param {real} _rate         Rate of sample over time (used with current_time)
  174. /// @description                Returns an integer value between the two values using perlin noise
  175. function perlin_noise_irange(_value1, _value2, _offset, _rate)
  176. {  
  177.     static _perlin_noise_buffer = get_perlin_noise_buffer();
  178.     var _pos = buffer_peek(_perlin_noise_buffer, (floor(_offset + current_time * _rate) & C_PERLIN_NOISE_BUFFER_MASK) << 2, buffer_f32);
  179.     return round(lerp(_value1, _value2, _pos));
  180. }
  181.  
  182. /// @function                   perlin_noise_range(_value1, _value2, _offset, _rate)
  183. /// @param {real} _value1       The first value
  184. /// @param {real} _value2       The second value
  185. /// @param {integer} _offset    A fixed positive offset into the buffer (use a constant)
  186. /// @param {real} _rate         Rate of sample over time (used with current_time)
  187. /// @description                Returns a real value between the two values using perlin noise
  188. function perlin_noise_range(_value1, _value2, _offset, _rate)
  189. {  
  190.     static _perlin_noise_buffer = get_perlin_noise_buffer();
  191.     var _pos = buffer_peek(_perlin_noise_buffer, (floor(_offset + current_time * _rate) & C_PERLIN_NOISE_BUFFER_MASK) << 2, buffer_f32);
  192.     return lerp(_value1, _value2, _pos);
  193. }
  194.  
  195. /// @function           perlin_noise_2d(_x, _y)
  196. /// @param {real} _x    The x coordinate to sample from (should be positive value)
  197. /// @param {real} _y    The y coordinate to sample from (should be positive value)
  198. /// @description        Samples perlin noise value from -1 to 1 using premade buffer using 2D coordinates
  199. function perlin_noise_2d(_x, _y)
  200. {
  201.     // This function is when you want to really specify where to sample from the buffer,
  202.     // and is rarely used over the normal perlin_noise() function
  203.    
  204.     static _perlin_noise_buffer = get_perlin_noise_buffer();
  205.     _x = floor(_x) & C_PERLIN_NOISE_SIZE_MASK;
  206.     _y = floor(_y) & C_PERLIN_NOISE_SIZE_MASK;
  207.     var _value = buffer_peek(_perlin_noise_buffer, (_x + _y * C_PERLIN_NOISE_SIZE) << 2, buffer_f32);
  208.     return (_value - 0.5) * 2.0;
  209. }
  210.  
  211. function draw_perlin_noise_buffer(_x, _y)
  212. {
  213.     // *** DEBUG ONLY ***
  214.     // Extremely slow function used to visualize the perlin noise buffer
  215.     // Draw it to a surface once or frame rate will die
  216.    
  217.     var _buff = get_perlin_noise_buffer(),
  218.         _dx = _x,
  219.         _dy = _y,
  220.         _val = 0,
  221.         _col = 0;
  222.  
  223.     for (var _c = 0; _c < C_PERLIN_NOISE_SIZE; _c++)
  224.     {
  225.         _dy = _y;
  226.    
  227.         for (var _r = 0; _r < C_PERLIN_NOISE_SIZE; _r++)
  228.         {
  229.             _val = buffer_peek(_buff, (_c + _r * C_PERLIN_NOISE_SIZE) << 2, buffer_f32) * 255;
  230.             _col = make_color_rgb(_val, _val, _val);
  231.             draw_rectangle_color(_dx, _dy, _dx + 1, _dy + 1, _col, _col, _col, _col, false);
  232.        
  233.             _dy++;
  234.         }
  235.         _dx++;
  236.     }  
  237. }
  238.  
  239. function shader_set_perlin_noise(_seed_value = 0)
  240. {
  241.     // Draws anything with a perlin noise texture
  242.     // Will repeat if the UVs are the full 0 - 1 on the quad
  243.     // Mainly just used for the private functions which create the buffer
  244.    
  245.     static _u_seed  = shader_get_uniform(shd_perlin_noise_glsl_es, "u_seed");
  246.     static _u_table = shader_get_uniform(shd_perlin_noise_glsl_es, "u_table");
  247.     static _table   = create_perlin_hash_table();
  248.     static _seed    = random_range(25.11111, 29.99999);
  249.  
  250.     if (_seed_value != 0)
  251.         _seed = _seed_value + random_range(0.11111, 0.99999);
  252.  
  253.     shader_set(shd_perlin_noise_glsl_es);
  254.     shader_set_uniform_f(_u_seed, _seed);
  255.     shader_set_uniform_i_array(_u_table, _table);
  256. }
  257.  
  258. #region Private Functions
  259.  
  260.     function get_perlin_noise_buffer()
  261.     {
  262.         static _perlin_noise_buffer = create_perlin_noise_buffer();
  263.         return _perlin_noise_buffer;
  264.     }
  265.  
  266.     function create_perlin_noise_buffer()
  267.     {  
  268.         var _surf  = surface_create(C_PERLIN_NOISE_SIZE, C_PERLIN_NOISE_SIZE),
  269.             _size  = C_PERLIN_NOISE_BUFFER_SIZE,
  270.             _buff  = buffer_create(_size << 2, buffer_fast, 1),  // Uses unsigned8 to store RGBA
  271.             _buff2 = buffer_create(_size << 2, buffer_fixed, 4), // Uses float32 to store single value
  272.             _peek  = 0;
  273.    
  274.         // Draw perlin noise to a surface
  275.         shader_set_perlin_noise();
  276.         surface_set_target(_surf)
  277.  
  278.             draw_clear_alpha(c_black, 0);
  279.             draw_primitive_begin_texture(pr_trianglestrip, -1);
  280.             draw_vertex_texture(0, 0, 0, 0);
  281.             draw_vertex_texture(C_PERLIN_NOISE_SIZE, 0, 1, 0);
  282.             draw_vertex_texture(0, C_PERLIN_NOISE_SIZE, 0, 1);
  283.             draw_vertex_texture(C_PERLIN_NOISE_SIZE, C_PERLIN_NOISE_SIZE, 1, 1);
  284.             draw_primitive_end();
  285.        
  286.         shader_reset();
  287.         surface_reset_target();
  288.  
  289.         // Convert surface to normal buffer
  290.         buffer_get_surface(_buff, _surf, 0);
  291.         surface_free(_surf);
  292.    
  293.         // Remove 3 channels from RGBA since we only need 1
  294.         buffer_seek(_buff2, buffer_seek_start, 0);
  295.         for (var _b = 0; _b < _size; _b++)
  296.         {
  297.             buffer_write(_buff2, buffer_f32, buffer_peek(_buff, _peek, buffer_u8)/255.0);
  298.             _peek += 4;
  299.         }
  300.    
  301.         buffer_delete(_buff);
  302.    
  303.         return _buff2; 
  304.     }
  305.  
  306.     function create_perlin_hash_table()
  307.     {
  308.         // Creates a permutation hash table used for perlin noise shader
  309.    
  310.         var _size    = 256,
  311.             _values  = ds_list_create(),
  312.             _table   = array_create(256),
  313.             _index   = 0,
  314.             _num     = 0,
  315.        
  316.         // Populate values
  317.         while (_index < 256)
  318.         {
  319.             _values[| _index] = _index++;
  320.         }
  321.    
  322.         // Creates random permutation of values from 0 - 255
  323.         _index = 0;
  324.         while (_index < 256)
  325.         {
  326.             _num = irandom(--_size);
  327.             _table[_index++] = _values[| _num];
  328.             ds_list_delete(_values, _num);
  329.         }
  330.        
  331.         ds_list_destroy(_values);
  332.  
  333.         return _table;
  334.     }
  335.  
  336. #endregion
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement