MetaD - MetaBin - mandelbrot.hs

simple Mandelbrot generator


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import Color            -- This module is based on http://www.haskell.org/haskellwiki/Library_for_colours
import PPM              -- http://www.haskell.org/haskellwiki/Library_for_PPM_images
import Data.Complex

-- Image generation testing functions
-- all black
black :: Integer -> Integer -> Color
black x y = Color 0 0 0
-- all white
white :: Integer -> Integer -> Color
white x y = Color 1 1 1
-- grey gradient
diffgrey :: Integer -> Integer -> Integer -> Integer -> Color
diffgrey width height x y = Color tint tint tint where tint = (fromIntegral(x) / fromIntegral(width)) - (fromIntegral(y) / fromIntegral(height))
-- red/green gradient
redgreen :: Integer -> Integer -> Integer -> Integer -> Color
redgreen width height x y = Color (fromIntegral(x)/fromIntegral(width)) (fromIntegral(y)/fromIntegral(height)) 0

-- iterDuration counts the amount of iterations that are needed before the condition is met
iterDuration condition max = length . takeWhile condition . take max

-- Mandelbrot formula
pBrot c z = z ^ 2 + c
-- The mandelbrot iteration
mMandel steps c = (fromIntegral . iterDuration ((<= 2) . magnitude) steps $ iterate (pBrot c) 0) / fromIntegral(steps)

-- Tranform the coordinate system
transform func width height x y = func nx ny
    where
        ws = 4.5 / fromIntegral(width)
        xt = -2.75
        hs = 3 / fromIntegral(height)
        yt = -1.5
        nx = fromIntegral(x) * ws + xt
        ny = fromIntegral(y) * hs + yt

-- The mandelbrot color function, this does not translate the coordinate system, and takes Doubles
mandelbrot :: Double -> Double -> Color
mandelbrot x y = Color tint tint tint where tint = 1 - (mMandel 64 (x :+ y))

-- genImage --
-- Generates the [[Color]] list of the image
-- colorFunc is a function that takes the pixel coordinates, and returns the correct color
genImage :: Integer -> Integer -> (Integer -> Integer -> Color) -> [[Color]]
genImage width height colorFunc = [[ colorFunc x y | x <- [0..width]] | y <- [0..height]]

-- genImageN --
-- also pass the width and height parameters to the colorFunc
-- usefull in combination with a transform function
genImageN width height colorFunc = genImage width height $ colorFunc width height

main = do
        save_ppm "mandelbrot.ppm" $ genImageN 600 400 $ transform mandelbrot

Beginpagina - Auto wrap - Zonder opmaak