Skip to content

Instantly share code, notes, and snippets.

@youssefsahli
Created August 22, 2023 19:46
Show Gist options
  • Save youssefsahli/273ae4a7665102453ae14b4a983d161d to your computer and use it in GitHub Desktop.
Save youssefsahli/273ae4a7665102453ae14b4a983d161d to your computer and use it in GitHub Desktop.
Perlin Lua
local function mix(a, b, t) return (t * (b - a)) + a end
local function mod(a, b) return ((a % b) + b) % b end
local function fract(x) return x - math.floor(x) end
local function clamp(a, b, c) return math.min(math.max(a, b), c) end
local function dot(a, b)
local s = 0
for i = 1, #a do
s = s + a[i] * b[i]
end
return s
end
local function sign(x) return x > 0 and 1 or (x < 0 and -1 or 0) end
local function pow2(a, b) return math.pow(math.abs(a), b) * sign(a) end
local function pal(i, r, g, b)
i = i < 0 and 0 or (i > 15 and 15 or i)
if r == nil and g == nil and b == nil then
return peek(0x3fc0 + (i * 3)),
peek(0x3fc0 + (i * 3) + 1),
peek(0x3fc0 + (i * 3) + 2)
else
poke(0x3fc0 + (i * 3) + 2, clamp(b, 0, 255))
poke(0x3fc0 + (i * 3) + 1, clamp(g, 0, 255))
poke(0x3fc0 + (i * 3), clamp(r, 0, 255))
end
end
local seed = {
a = 500 + (math.random() * 1e4),
fx = 500 + (math.random() * 1e4),
fy = 500 + (math.random() * 1e4),
px = math.random() - 0.5,
py = math.random() - 0.5
}
local function pseudorandom2D(x, y)
return fract(math.sin(dot({x + seed.px, y + seed.py}, {seed.fx, seed.fy})) * seed.a)
end
local function perlin(x, y)
return mix(
mix(
pseudorandom2D(math.floor(x), math.floor(y)),
pseudorandom2D(math.floor(x) + 1, math.floor(y)),
fract(x)
),
mix(
pseudorandom2D(math.floor(x), math.floor(y) + 1),
pseudorandom2D(math.floor(x) + 1, math.floor(y) + 1),
fract(x)
),
fract(y)
)
end
local function f(x, y)
x = x / 15
y = y / 15
local iterations = 4
local sum = 0
for i = 0, iterations - 1 do
seed.a = 500 + (fract(math.sin((i + 0.512) * 512) * 725.63) * 1e4)
sum = sum + perlin(x * (i + 1), y * (i + 1))
end
return sum / iterations
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment