summaryrefslogtreecommitdiff
path: root/deps/bitmap/bitmap.c
blob: 068bc3f89090c858f935224f19b325ccb2129da3 (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct bitmap {
    unsigned char *data;
    int width;
    int height;
};

struct bitmap * bitmap_new(int width, int height, int value) {
	struct bitmap *bmp = (struct bitmap *)malloc(sizeof(struct bitmap));
    bmp->width = width;
    bmp->height = height;
    int size = (width * height + 7) / 8; // Calculate total bytes needed
    bmp->data = (unsigned char *)calloc(size,1 );
    memset(bmp->data, value ? 0xFF : 0x00, size);
	return bmp;
}

int bitmap_set(struct bitmap *bmp, int x, int y, int value) {
    if (x < 0 || y < 0 || x >= bmp->width || y >= bmp->height) {
        return -1; // Return error code if coordinates are out of bounds
    }
    int idx = y * bmp->width + x;
    if (value)
        bmp->data[idx / 8] |= (1 << (idx % 8));
    else
        bmp->data[idx / 8] &= ~(1 << (idx % 8));
    return 0;
}

int bitmap_get(struct bitmap *bmp, int x, int y) {
    if (x < 0 || y < 0 || x >= bmp->width || y >= bmp->height) {
        return -1; // Return error code if coordinates are out of bounds
    }
    int idx = y * bmp->width + x;
    return (bmp->data[idx / 8] & (1 << (idx % 8))) != 0;
}

void bitmap_free(struct bitmap *bmp) {
	if(bmp)
	{
		if(bmp->data)free(bmp->data);
		free(bmp);
	}
}

int bitmap_is_all_zero(struct bitmap *bmp, int x, int y, int length) {
    if (x < 0 || y < 0 || x >= bmp->width || y >= bmp->height) {
        return -1; // Return error code if coordinates are out of bounds
    }
    int idx = y * bmp->width + x;
    if (idx + length > bmp->width * bmp->height) {
        return -1; // Return error if range exceeds bitmap bounds
    }
    for (int i = 0; i < length; i++) {
        if (bmp->data[(idx + i) / 8] & (1 << ((idx + i) % 8))) {
            return 0; // Return 0 if any bit is not zero
        }
    }
    return 1; // Return 1 if all bits are zero
}

int test_bitmap() {
    struct bitmap *bmp = bitmap_new(10, 5, 1); // Create a 10x5 bitmap
    if (bitmap_set(bmp, 2, 2, 1) == 0) { // Set bit at position (2,2)
        printf("Bit at (2,2): %d\n", bitmap_get(bmp, 2, 2)); // Get bit at position (2,2)
    }
    bitmap_free(bmp);
    return 0;
}