DEVELOPMENT ENVIRONMENT

~alex/mandelbrot-set-gen

ref: b7b7cbb105dea088b4a265ef62df391d719e2cf2 mandelbrot-set-gen/src/main.c -rw-r--r-- 2.3 KiB
b7b7cbb1Alejandro Laguna feat: SDL3 display a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "SDL3/SDL.h"
#include "mandelbrot.h"
#include <SDL3/SDL_events.h>
#include <SDL3/SDL_init.h>
#include <SDL3/SDL_oldnames.h>
#include <SDL3/SDL_rect.h>
#include <SDL3/SDL_render.h>
#include <SDL3/SDL_surface.h>
#include <SDL3/SDL_video.h>
#include <stdio.h>
#include <stdlib.h>

// TODO: GPU shadering option
// TODO: flexible window size
// TODO: zooming in and out
// TODO: maybe? change colors

#define WINDOW_TITLE "Mandelbrot Visualization"
#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600

static int points[WINDOW_WIDTH * WINDOW_HEIGHT];

void calculate_points() {
    double x_min = -2.0, x_max = 1.0;
    double y_min = -1.2, y_max = 1.2;
    int max_iter = 100;
    for (int py = 0; py < WINDOW_HEIGHT; py++) {
        for (int px = 0; px < WINDOW_WIDTH; px++) {
            double cr = x_min + (x_max - x_min) * px / (WINDOW_WIDTH - 1);
            double ci = y_min + (y_max - y_min) * py / (WINDOW_HEIGHT - 1);
            points[py * WINDOW_WIDTH + px] = mandelbrot_iterations(cr, ci, max_iter);
        }
    }
}

void draw_points(SDL_Surface* surface) {
    for (int py = 0; py < WINDOW_HEIGHT; py++) {
        for (int px = 0; px < WINDOW_WIDTH; px++) {
            int r, g, b;
            get_color(points[py * WINDOW_WIDTH + px], 100, &r, &g, &b);
            SDL_WriteSurfacePixel(surface, px, py, r, g, b, 255);
        }
    }
};

int main(void) {
    if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)) {
        fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
        return -1;
    }

    SDL_Window* window =
        SDL_CreateWindow(WINDOW_TITLE, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_HIDDEN);
    if (window == NULL) {
        fprintf(stderr, "CreateWindowAndRenderer failed: %s\n", SDL_GetError());
        SDL_Quit();
        return -1;
    }

    SDL_Surface* surface = SDL_GetWindowSurface(window);
    if (!surface) {
        return -1;
    }
    SDL_Event e;
    bool running = true;
    SDL_UpdateWindowSurface(window);
    SDL_ShowWindow(window);
    while (running) {
        while (SDL_PollEvent(&e)) {
            if (e.type == SDL_EVENT_QUIT) {
                running = false;
            }
        }
        calculate_points();
        draw_points(surface);
        SDL_UpdateWindowSurface(window);
        SDL_Delay(16);
    }

    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}