DEVELOPMENT ENVIRONMENT

~alex/mandelbrot-set-gen

ref: 9aa04678e575ad986269c45d84704bc41d963511 mandelbrot-set-gen/src/math.c -rw-r--r-- 1.6 KiB
9aa04678Alejandro Laguna refactor: separate functions into files a month ago
                                                                                
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
#include "mandelbrot.h"
// the mandelbrot set, basically, is a set of points on the complex plane -
// those points are found using the following equation:
//
// z = z^2 + c
//
// c is an initial point on this complex plane. if the value of z is bigger than
// 2 (which means that it's distance from the origin is larger than 2), it means
// the value is out of the set.
//
// but what's going on with all the shapes and colors? this is a recursive
// function.
//
// we start with z as 0, and then with the equation we get a new z, and then put
// that new z onto the equation and we do that over and over. if z doesn't grow
// over 2, then c is part of the set. if it does pass 2, we know for how many
// iterations we have checked and we color based on that

int mandelbrot_iterations(double cr, double ci, int max_iter) {
    double zr = 0.0, zi = 0.0;
    int iter = 0;
    while (iter < max_iter) {
        double zr2 = zr * zr;
        double zi2 = zi * zi;
        // avoids checking for sqrt
        if (zr2 + zi2 > 4.0) {
            break;
        }
        zi = 2.0 * zr * zi + ci;
        zr = zr2 - zi2 + cr;
        iter++;
    }
    return iter;
}

extern int points[WINDOW_WIDTH * WINDOW_HEIGHT];

void calculate_points(position_t* pos) {
    int max_iter = 100;
    for (int py = 0; py < WINDOW_HEIGHT; py++) {
        for (int px = 0; px < WINDOW_WIDTH; px++) {
            double cr = pos->x_min + (pos->x_max - pos->x_min) * px / (WINDOW_WIDTH - 1);
            double ci = pos->y_min + (pos->y_max - pos->y_min) * py / (WINDOW_HEIGHT - 1);
            points[py * WINDOW_WIDTH + px] = mandelbrot_iterations(cr, ci, max_iter);
        }
    }
}