You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
1.9 KiB
C

12 years ago
#include "SDL.h"
#include <complex.h>
#include <stdbool.h>
/* The maximum iteration count. */
const int max_it = 170;
12 years ago
/* Compute the out-coloring based on the iteration counter. */
Uint32 outcolor(int it) {
return 0x00010001 * ((it * 0xff) / max_it);
12 years ago
}
12 years ago
/* "Compute" the in-coloring. */
12 years ago
Uint32 incolor() {
return 0x00000000; /* black */
12 years ago
}
void drawmandelbrot(SDL_Surface * surface) {
12 years ago
if (SDL_MUSTLOCK(surface)) {
SDL_LockSurface(surface);
12 years ago
}
12 years ago
Uint32 *pixels = (Uint32 *) surface->pixels;
for (int i = 0; i < surface->w * surface->h; i++) {
int y = i / surface->w;
int x = i % surface->w;
12 years ago
float complex c = ((3.0f * x / surface->w) - 2.0f)
+ I * ((2.0f * y / surface->h) - 1.0f);
12 years ago
bool diverges = false;
float complex z = 0;
int it;
12 years ago
for (it = 1; it <= max_it; it++) {
/* z = z² + c */
12 years ago
z = cpowf(z, 2) + c;
12 years ago
/* If |z| ever gets greater than 2, it diverges. */
if (cabsf(z) > 2) {
12 years ago
diverges = true;
break;
}
}
12 years ago
Uint32 color;
12 years ago
if (diverges) {
12 years ago
color = outcolor(it);
12 years ago
} else {
12 years ago
color = incolor();
12 years ago
}
pixels[i] = color;
12 years ago
/* Update the screen every 10 lines. */
if (y % 10 == 0 && x == 0) {
12 years ago
SDL_Flip(surface);
}
12 years ago
}
12 years ago
12 years ago
/* Update the screen a final time. */
SDL_Flip(surface);
12 years ago
if (SDL_MUSTLOCK(surface)) {
SDL_UnlockSurface(surface);
}
}
int main(void) {
12 years ago
/* Set up SDL. */
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
fprintf(stderr, "Error: Could not initialize SDL: %s.\n",
SDL_GetError());
12 years ago
exit(1);
}
SDL_Surface *screen = SDL_SetVideoMode(320, 240, 32, SDL_SWSURFACE);
12 years ago
12 years ago
/* Do the mandelbrot. */
drawmandelbrot(screen);
12 years ago
/* Save BMP */
char *file = "mandelbrot.bmp";
if (SDL_SaveBMP(screen, file) != 0) {
fprintf(stderr, "Could not write %s!\n", file);
}
12 years ago
/* Quit. */
/* FIXME: wait for key press here */
SDL_Delay(0*20000);
12 years ago
SDL_Quit();
}