108 lines
2.2 KiB
C
108 lines
2.2 KiB
C
#include "stdio.h"
|
|
#include "math.h"
|
|
#include "stdint.h"
|
|
#include "stdbool.h"
|
|
|
|
#define MAX_DEPTH 50
|
|
#define WIDTH 420
|
|
#define HEIGHT 360
|
|
|
|
#define X_MIN -2.0
|
|
#define X_MAX 1.1
|
|
#define Y_MIN -1.3
|
|
#define Y_MAX 1.3
|
|
|
|
#define SIZE (WIDTH * HEIGHT)
|
|
|
|
typedef struct Complex {
|
|
double real, imag;
|
|
} Complex;
|
|
|
|
typedef struct Color {
|
|
uint8_t r, g, b;
|
|
} Color;
|
|
|
|
int diverge(Complex c);
|
|
Color color_map(int depth);
|
|
void write_ppm(char *path, Color img[SIZE]);
|
|
|
|
int main() {
|
|
Color img[SIZE];
|
|
for (int i = 0; i < HEIGHT; i++) {
|
|
for (int j = 0; j < WIDTH; j++) {
|
|
double x = ((double)j / (double)WIDTH) * (X_MAX - X_MIN) + X_MIN;
|
|
double y = ((double)i / (double)HEIGHT) * (Y_MAX - Y_MIN) + Y_MIN;
|
|
Complex c = {.real = x, .imag = y};
|
|
int depth = diverge(c);
|
|
img[i * WIDTH + j] = color_map(depth);
|
|
}
|
|
}
|
|
write_ppm("mandelbrot.c.ppm", img);
|
|
|
|
return 1;
|
|
}
|
|
|
|
/////////////////////
|
|
// complex numbers //
|
|
/////////////////////
|
|
|
|
void cx_print(Complex z) {
|
|
printf("%f + %f i\n", z.real, z.imag);
|
|
}
|
|
|
|
static inline Complex cx_square(Complex z) {
|
|
return (Complex){z.real * z.real - z.imag * z.imag, 2 * z.real * z.imag};
|
|
}
|
|
|
|
static inline Complex cx_add(Complex z1, Complex z2) {
|
|
return (Complex){z1.real + z2.real, z1.imag + z2.imag};
|
|
}
|
|
|
|
static inline double cx_abs(Complex z) {
|
|
return sqrt(z.real * z.real + z.imag * z.imag);
|
|
}
|
|
|
|
////////////////
|
|
// mandelbrot //
|
|
////////////////
|
|
|
|
static inline Complex f(Complex z, Complex c) {
|
|
return cx_add(cx_square(z), c);
|
|
}
|
|
|
|
// return iteration count, MAX_DEPTH if diverge
|
|
int diverge(Complex c) {
|
|
int depth = 0;
|
|
Complex z = {0.0, 0.0};
|
|
while (depth < MAX_DEPTH) {
|
|
z = f(z, c);
|
|
if (cx_abs(z) > 2)
|
|
return depth;
|
|
depth++;
|
|
}
|
|
return MAX_DEPTH;
|
|
}
|
|
|
|
Color color_map(int depth) {
|
|
bool cond = depth % 2 == 0;
|
|
return (Color){
|
|
cond ? 255 : 0,
|
|
cond ? 255 : 0,
|
|
cond ? 255 : 0
|
|
};
|
|
}
|
|
|
|
////////////////
|
|
// ppm-writer //
|
|
////////////////
|
|
|
|
void write_ppm(char *path, Color img[SIZE]) {
|
|
FILE *fptr;
|
|
fptr = fopen(path, "w");
|
|
fprintf(fptr, "P3\n%d %d\n255\n", WIDTH, HEIGHT);
|
|
for (int i = 0; i < SIZE; i++)
|
|
fprintf(fptr, "%d %d %d\n", img[i].r, img[i].g, img[i].b);
|
|
printf("successfully wrote to %s\n", path);
|
|
fclose(fptr);
|
|
}
|