diff --git a/src/lib/simplex_map.lua b/src/lib/simplex_map.lua new file mode 100644 index 0000000..a197122 --- /dev/null +++ b/src/lib/simplex_map.lua @@ -0,0 +1,77 @@ +local simplex = require "lib.simplex" + +local simplex_map = {} + +simplex_map.min = function(map) + local r = math.huge + for i=1,#map do + if map[i] then + for j=1,#map[1] do + local v = map[i][j] + if v and r > v then r = v end + end + end + end + return r +end +simplex_map.max = function(map) + local r = -math.huge + for i=1,#map do + if map[i] then + for j=1,#map[1] do + local v = map[i][j] + if v and r < v then r = v end + end + end + end + return r +end + +simplex_map.normalize = function(map, new_min, new_max) + local minimum = simplex_map.min(map) + local initialRange = simplex_map.max(map) - minimum + local finalRange = new_max - new_min + for i = 1, #map do + for j = 1, #map[1] do + map[i][j] = (map[i][j] - minimum) / initialRange * finalRange + new_min + end + end + map.min = simplex_map.min(map) + map.max = simplex_map.max(map) + return map -- superfluous +end + +simplex_map.generate = function(size, scale, min, max, octaves, lacunarity, gain) + if type(size) == "table" then + scale = size.scale + min = size.min + max = size.max + octaves = size.octaves + lacunarity = size.lacunarity + gain = size.gain + + size = size.size + end + + simplex.Seed(math.random()) + local map = {} + map.size = size + + scale = scale or 0.005 + for x = 1, map.size do + map[x] = {} + for y = 1, map.size do + map[x][y] = simplex.FractalBrownianMotion2D(x * scale, y * scale, octaves, lacunarity, gain) + end + end + + if min or max then + min = min or 0 + max = max or 1 + simplex_map.normalize(map, min, max) + end + + return map +end + +return simplex_map