#include #include #include #include static void putpixel(struct SDL_Surface *screen, const int x, const int y, const unsigned char r, const unsigned char g, const unsigned char b) { int offset = y * screen->pitch + x * 4; unsigned char *buf = screen->pixels; buf[offset++] = b; buf[offset++] = g; buf[offset] = r; } #define MAX_ITERATION 1000 int get_mandelbrot_iterations(double x0, double y0) { double x = 0, y = 0, xtemp; int iteration = 0; while ((x * x + y * y < 2 * 2) && iteration < MAX_ITERATION) { xtemp = x * x - y * y + x0; y = 2 * x * y + y0; x = xtemp; iteration++; } return iteration; } int draw_mandelbrot(struct SDL_Surface *screen, double x1, double x2, double y1, double y2) { double x0, y0, xlen, ylen, xstep, ystep; int iteration, xs, ys; xlen = x2 - x1; ylen = y2 - y1; xstep = xlen / (double)screen->w; ystep = ylen / (double)screen->h; for (ys = 0, y0 = y1; ys < screen->h; y0 += ystep, ys++) { for (xs = 0, x0 = x1; xs < screen->w; x0 += xstep, xs++) { iteration = get_mandelbrot_iterations(x0, y0); if (iteration == MAX_ITERATION) putpixel(screen, xs, ys, 255, 255, 255); else putpixel(screen, xs, ys, iteration * 8, iteration, iteration / 4); } SDL_Flip(screen); } return 0; } int main(int argc, char *argv[]) { SDL_Surface *screen; int flags = SDL_DOUBLEBUF | SDL_HWSURFACE | SDL_RESIZABLE; int xres = 800, yres = 600; if (SDL_Init(SDL_INIT_VIDEO) != 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } atexit(SDL_Quit); screen = SDL_SetVideoMode(xres, yres, 32, flags); if (screen == NULL) { fprintf(stderr, "Unable to set video mode: %s\n", SDL_GetError()); return 2; } SDL_WM_SetCaption(argv[0], NULL); draw_mandelbrot(screen, -2.5, 1, -1, 1); yres = read(0, &xres, 1); return 0; }