-
Notifications
You must be signed in to change notification settings - Fork 0
/
font.h
69 lines (57 loc) · 2.22 KB
/
font.h
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
#ifndef FONT_H
#define FONT_H
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#define FONT_CHAR_START ' '
#define FONT_CHAR_COUNT ('~' - ' ' + 1)
// Reads a font generated by figlet-to-font.py, outputting each character's width and height to
// `width` and `height`. `*out` will be malloc'd and filled with the font data - 0 for black pixel,
// 255 for white. You better free `*out` once you're done.
void load_font(const char *path, int *width, int *height, uint8_t **out) {
FILE *fp = fopen(path, "r");
if (fp == NULL) {
fprintf(stderr, "Couldn't open font %s\n", path);
exit(1);
}
char *lineptr = NULL;
size_t line_len;
// Read width
if (getline(&lineptr, &line_len, fp) == -1) {
fprintf(stderr, "Couldn't read font width\n");
exit(1);
}
*width = strtol(lineptr, NULL, 10);
// Read height
if (getline(&lineptr, &line_len, fp) == -1) {
fprintf(stderr, "Couldn't read font height\n");
exit(1);
}
*height = strtol(lineptr, NULL, 10);
free(lineptr);
printf("Font dims %d x %d\n", *width, *height);
// Alloc memory
// Range is inclusive
*out = malloc(FONT_CHAR_COUNT * *width * *height * sizeof(**out));
// Read chars
// + 1 for the newline
char *line = malloc((*width + 1) * sizeof(*line));
for (int i = 0; i < FONT_CHAR_COUNT; i++) {
// For each char...
for (int j = 0; j < *height; j++) {
// And for each line...
if (fread(line, 1, *width + 1, fp) != *width + 1) {
fprintf(stderr, "Couldn't read char %c\n", (char)i);
exit(1);
}
for (int k = 0; k < *width; k++) {
// And for each pixel...
// Set pixel in output
(*out)[i * *width * *height + j * *width + k] =
line[k] == '#' ? 255 : 0;
}
}
}
free(line);
}
#endif // FONT_H