Skip to content

Instantly share code, notes, and snippets.

@vietnt
Created March 29, 2016 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vietnt/52c1208c5a4970889137 to your computer and use it in GitHub Desktop.
Save vietnt/52c1208c5a4970889137 to your computer and use it in GitHub Desktop.
open System
open System.Drawing
open System.Drawing.Imaging
let perlinNoise width height persistence octaves zoom seed bias amplitudeBias handler =
let inline noise x y =
let n = x + y * 57;
let n = (n <<< 13) ^^^ n
1.0 - (float ((n * (n * n * 15731 + 789221) + 1376312589) &&& 0x7fffffff)) / 1073741824.0
let inline interpolate x y a =
let f = (1.0 - (cos (a * Math.PI))) * 0.5
x * (1.0 - f) + y * f
let inline smoothedNoise x y =
let xi = int x |> float
let yi = int y |> float
let xfrac = (x - xi) |> float
let yfrac = (y - yi) |> float
let xi = xi |> int
let yi = yi |> int
let v1 = noise xi yi
let v2 = noise (xi + 1) yi
let v3 = noise xi (yi + 1)
let v4 = noise (xi + 1) (yi + 1)
let s = interpolate v1 v2 xfrac
let t = interpolate v3 v4 xfrac
interpolate s t yfrac
let inline pixel x y =
seq { 0 .. octaves - 1 }
|> Seq.sumBy (fun octave -> let octave = float octave
let frequency = 0.0098976543 * (octave ** 2.0)
let amplitude = (persistence ** octave) * 0.917183 * amplitudeBias
smoothedNoise ((float (x + seed)) * frequency / zoom) ((float (y + seed)) * frequency / zoom) |> (*) amplitude)
for x in 0 .. width - 1 do
for y in 0 .. height - 1 do
pixel x y |> (+) bias |> handler x y
let generate () =
let width = 4000
let height = 4000
let bitmap = new Bitmap(width, height)
let prng = new Random()
(fun x y v ->
let c = (v + 0.5) * 255.0 |> int |> min 255 |> max 0
let color =
if c < 8 then Color.FromArgb(0, 0, 96) // Color.FromArgb(0,0,c)
elif c < 32 then Color.FromArgb(0, 0, 160)
elif c < 64 then Color.FromArgb(64, 64, 192)
//elif c < 96 then Color.FromArgb(255, 128, 31)
elif c < 128 then Color.FromArgb(255, 192, 0)
elif c < 191 then Color.Green // Color.FromArgb(0,c,63)
else Color.White
bitmap.SetPixel(x, y, color))
|> perlinNoise width height 0.5 8 (10.87654321) (prng.Next() % (Int32.MaxValue / 4)) 0.1368 0.96
bitmap.Save(@"z:\perlin-noise.jpg")
[<EntryPoint>]
let main argv =
generate()
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment