From 84158eb038ec5ea29c996a64223d56da4b6db5b6 Mon Sep 17 00:00:00 2001 From: Alejandro Laguna Date: Fri, 10 Jul 2026 18:07:08 +0200 Subject: [PATCH] feat: basic .ppm output --- Makefile | 2 +- src/main.c | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index a1e33b27b8dc26d1bda2b0b8301736c3a153edd1..71b16f06d421f9ac9878eb974be8a8ef1b30ed70 100644 --- a/Makefile +++ b/Makefile @@ -11,7 +11,7 @@ bear: bear -- make fclean all $(OUT): $(OBJ) - $(CC) -o $(OUT) $(OBJ) + $(CC) -o $(OUT) $(OBJ) -lm clean: rm -f $(OBJ) diff --git a/src/main.c b/src/main.c index bf7041f0546b2e233be541ec037ca2903dd88f79..5ef378263e3f13f6273f0b73c361303092327833 100644 --- a/src/main.c +++ b/src/main.c @@ -1,3 +1,70 @@ +#include + +// 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; +} + +void get_color(int iter, int max_iter, int* r, int* g, int* b) { + if (iter == max_iter) { + *r = *g = *b = 0; // black inside the set + return; + } + double t = (double)iter / max_iter; + int gray = (int)((1.0 - t) * 255); // whiter the furthest it was + *r = *g = *b = gray; +} + int main() { - return -1; -}; + int width = 800; + int height = 600; + int max_iter = 100; + + double x_min = -2.0, x_max = 1.0; + double y_min = -1.2, y_max = 1.2; + + // PPM header (P3 = ASCII, width, height, max color value) + printf("P3\n%d %d\n255\n", width, height); + + for (int py = 0; py < height; py++) { + for (int px = 0; px < width; px++) { + double cr = x_min + (x_max - x_min) * px / (width - 1); + double ci = y_min + (y_max - y_min) * py / (height - 1); + int iter = mandelbrot_iterations(cr, ci, max_iter); + int r, g, b; + get_color(iter, max_iter, &r, &g, &b); + printf("%d %d %d ", r, g, b); + } + printf("\n"); + } + return 0; +}