summaryrefslogtreecommitdiff
path: root/framebuffer.c
blob: b6e922e964af4bcd91b8ce036869f94b1dc7b4ab (plain) (blame)
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
#include <stdlib.h>

#include "framebuffer.h"

Framebuffer fb_new(size_t width, size_t height) {
    Framebuffer fb;

    /* In case malloc() fails and we return early */
    fb.width = 0;
    fb.height = 0;

    fb.fb = malloc(sizeof(Pixel *) * height);
    if (fb.fb == NULL) return fb;

    for (size_t i = 0; i < height; i++) {
        fb.fb[i] = malloc(sizeof(Pixel) * width);
        if (fb.fb[i] == NULL) {
            /* FIXME: Memory leak; should free all prev. malloced rows */
            fb.fb = NULL;
            return fb;
        }
    }

    fb.width = width;
    fb.height = height;
    return fb;
}

void fb_free(Framebuffer *fb) {
    if (fb->fb == NULL) goto ret;

    for (size_t i = 0; i < fb->height; i++) {
        free(fb->fb[i]);
    }
    free(fb->fb);

ret:
    fb->width = 0;
    fb->height = 0;
    return;
}

void fb_fill(Framebuffer fb, Pixel pixel) {
    for (size_t row = 0; row < fb.height; row++) {
        for (size_t col = 0; col < fb.width; col++) {
            fb_put(fb, row, col, pixel);
        }
    }
}

void inline fb_put(Framebuffer fb, size_t row, size_t col, Pixel pixel) {
    fb.fb[row][col] = pixel;
}

void fb_init(void);

void fb_cleanup(void);

void fb_print(Framebuffer fb);