Skip to content

Instantly share code, notes, and snippets.

@michlbro
Created January 17, 2023 22:40
Show Gist options
  • Save michlbro/d4e1523f338ef6d3c5f164da783c278a to your computer and use it in GitHub Desktop.
Save michlbro/d4e1523f338ef6d3c5f164da783c278a to your computer and use it in GitHub Desktop.
--[[
Created by michlbro#0414
USAGE:
local FractalGenerator = require(<path to this module>)
local fractal = FractalGenerator.new(seed: number?, fractalProperties: table?)
fractalProperties = {
amplitude = number?,
frequency = number?,
lacunarity = number?,
persistence = number?,
octaves = number?
}
fractal:GenerateNoise(x: number, y: number?, z: number?): number [-amplitude, amplitude] (I'd probably still clamp it between the +- amplitudes.)
]]
--!strict
export type fractalProperties = {
amplitude: number?,
frequency: number?,
lacunarity: number?,
persistence: number?,
octaves: number?
}
local fractalGenerator = {}
function fractalGenerator:GenerateNoise(xCord: number, yCord: number?, zCord: number?): number
local lacunarity = self.lacunarity
local persistence = self.persistence
local seed = self.seed
local noiseValue = self.amplitude
local tempAmplitude = self.amplitude
local tempFrequency = self.frequency
for _ = 1, self.octaves do
local x = xCord * tempFrequency + seed
local y = (yCord or 0) * tempFrequency + seed
local z = (zCord or 0) * tempFrequency + seed
noiseValue += math.noise(x, y, z) * tempAmplitude
tempFrequency *= lacunarity
tempAmplitude *= persistence
end
return noiseValue
end
local defaultProperties: fractalProperties = {
amplitude = 1,
frequency = 0.05,
octaves = 4,
lacunarity = 2.0,
persistence = 0.5
}
local function new(seed: number?, fractalProperties: fractalProperties?)
local newFractal = setmetatable({
seed = seed or (Random.new():NextNumber()),
amplitude = fractalProperties and fractalProperties.amplitude or defaultProperties.amplitude,
frequency = fractalProperties and fractalProperties.frequency or defaultProperties.frequency,
lacunarity = fractalProperties and fractalProperties.lacunarity or defaultProperties.lacunarity,
persistence = fractalProperties and fractalProperties.persistence or defaultProperties.persistence,
octaves = fractalProperties and fractalProperties.octaves or defaultProperties.octaves
},{
__index = fractalGenerator
})
return newFractal
end
return setmetatable({new = new}, {__index = fractalGenerator})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment