]> git.itanic.dy.fi Git - mandelbrot/blob - mandelbrot.c
Improve colors
[mandelbrot] / mandelbrot.c
1 #include <SDL.h>
2 #include <unistd.h>
3 #include <stdio.h>
4 #include <time.h>
5
6 static void putpixel(struct SDL_Surface *screen, const int x, const int y,
7                      const unsigned char r, const unsigned char g,
8                      const unsigned char b)
9 {
10         int offset = y * screen->pitch + x * 4;
11         unsigned char *buf = screen->pixels;
12
13         buf[offset++] = b;
14         buf[offset++] = g;
15         buf[offset]   = r;
16 }
17
18 #define MAX_ITERATION 1000
19
20 int get_mandelbrot_iterations(double x0, double y0)
21 {
22         double x = 0, y = 0, xtemp;
23         int iteration = 0;
24
25         while ((x * x + y * y < 2 * 2) && iteration < MAX_ITERATION) {
26
27                 xtemp = x * x - y * y + x0;
28                 y = 2 * x * y + y0;
29
30                 x = xtemp;
31                 iteration++;
32         }
33
34         return iteration;
35 }
36
37 int draw_mandelbrot(struct SDL_Surface *screen, double x1, double x2,
38                 double y1, double y2)
39 {
40         double x0, y0, xlen, ylen, xstep, ystep;
41         int iteration, xs, ys;
42
43         xlen = x2 - x1;
44         ylen = y2 - y1;
45         xstep = xlen / (double)screen->w;
46         ystep = ylen / (double)screen->h;
47
48         for (ys = 0, y0 = y1; ys < screen->h; y0 += ystep, ys++) {
49                 for (xs = 0, x0 = x1; xs < screen->w; x0 += xstep, xs++) {
50                         iteration = get_mandelbrot_iterations(x0, y0);
51
52                         if (iteration == MAX_ITERATION)
53                                 putpixel(screen, xs, ys, 255, 255, 255);
54                         else
55                                 putpixel(screen, xs, ys,
56                                         iteration * 8, iteration,
57                                         iteration / 4);
58                 }
59
60                 SDL_Flip(screen);
61         }
62
63         return 0;
64 }
65
66 int main(int argc, char *argv[])
67 {
68         SDL_Surface *screen;
69         int flags = SDL_DOUBLEBUF | SDL_HWSURFACE | SDL_RESIZABLE;
70         int xres = 800, yres = 600;
71
72         if (SDL_Init(SDL_INIT_VIDEO) != 0) {
73                 fprintf(stderr, "Unable to initialize SDL: %s\n",
74                         SDL_GetError());
75
76                 return 1;
77         }
78         atexit(SDL_Quit);
79
80         screen = SDL_SetVideoMode(xres, yres, 32, flags);
81         if (screen == NULL) {
82                 fprintf(stderr, "Unable to set video mode: %s\n",
83                         SDL_GetError());
84                 return 2;
85         }
86
87         SDL_WM_SetCaption(argv[0], NULL);
88
89         draw_mandelbrot(screen, -2.5, 1, -1, 1);
90
91         yres = read(0, &xres, 1);
92
93         return 0;
94 }