aboutsummaryrefslogtreecommitdiff
path: root/Week11 Mandelbrot/src/fractals/Mandelbrot.java
blob: 74b522ec5d62dd2ac05ec814183f110537d5627b (plain) (blame)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package fractals;

/**
 * An example of the use of our pixel drawing framework
 * @author Sjaak Smetsers
 * @version 1.0, 14-03-2013
 */
public class Mandelbrot {
    
    public final static int MAX_MANDEL_NUMBER = 100; // infinity will be this + 1
    
    public Mandelbrot() {
        MainWindow fractal_win = new MainWindow ();
        GridFiller filler = new GridFiller (fractal_win.getGrid());
        filler.fill();
        
        System.out.println(Integer.toString(mandelNumber(0,0)));
    }
    
    public static void main(String args[]) {    	       
        Mandelbrot mandelbrot = new Mandelbrot();
    }
    
    public static int mandelNumber(double x, double y) {
        double x_n = x, y_n = y;
        int n = 0;
        
        while (x_n * x_n + y_n * y_n <= 4 && n <= MAX_MANDEL_NUMBER) {
            double new_x_n = x_n * x_n - y_n * y_n + x;
            y_n = 2 * x_n * y_n + y;
            x_n = new_x_n;
            n++;
        }
        
        return n;
    }
    
    private class GridFiller {
        private Grid grid;              // the grid to be filled
        
        /**
         * The constructor
         * @param grid to be filled
         */
        public GridFiller (Grid grid) {
            this.grid = grid;
        }
        
        private final double MIN_X = -2.5, MAX_X = 2.5, MIN_Y = -2.5, MAX_Y = 2.5;

        /**
         * fills the whole grid with some arbitrarily chosen color
         * 
         */
        public void fill () {
            int grid_w = grid.getWidth(), grid_h = grid.getHeight();
            for (float i = 0; i < grid_w; i++) {
                for (float j = 0; j < grid_h; j++) {
                    int grayscale = mandelNumber(MIN_X + (i / grid_w) * (MAX_X - MIN_X), MIN_Y + (j / grid_h) * (MAX_Y - MIN_Y)) * 256 / MAX_MANDEL_NUMBER;
                    int[] color = {grayscale, grayscale, grayscale};
                    grid.setPixel((int) i, (int) j, color);
                }               
            }
        }
    }

}