1
#include "sfont.h"
2
#include "renderer.h"
3
4
/* adorable CGA: https://en.wikipedia.org/wiki/Color_Graphics_Adapter#Color_palette */
5
int cga_colors[16] = {
6
0x000000,
7
0x0000AA,
8
0x00AA00,
9
0x00AAAA,
10
0xAA0000,
11
0xAA00AA,
12
0xAA5500,
13
0xAAAAAA,
14
0x555555,
15
0x5555FF,
16
0x55FF55,
17
0x55FFFF,
18
0xFF5555,
19
0xFF55FF,
20
0xFFFF55,
21
0xFFFFFF,
22
};
23
24
typedef struct {
25
unsigned char bitmap[FONT_HEIGHT];
26
} rawchar_t;
27
28
typedef struct {
29
rawchar_t charset[256];
30
} rawfont_t;
31
32
sdlfont_t *read_raw_sdlfont(const char *filename) {
33
rawfont_t font;
34
FILE *f = fopen(filename, "r");
35
fread(&font, sizeof(rawfont_t), 1, f);
36
fclose(f);
37
38
sdlfont_t *sfont = malloc(sizeof(*sfont));
39
40
for (int i = 0; i < 256; ++i) {
41
rawchar_t c = font.charset[i];
42
SDL_Texture *t = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, FONT_WIDTH, FONT_HEIGHT);
43
SDL_SetTextureBlendMode(t, SDL_BLENDMODE_BLEND);
44
SDL_SetRenderTarget(renderer, t);
45
SDL_RenderClear(renderer);
46
47
for (int row = 0; row < FONT_HEIGHT; ++row) {
48
unsigned char rowdata = c.bitmap[row],
49
mask = 0x80;
50
for (int offset = 0; offset < FONT_WIDTH; ++offset) {
51
if (rowdata & mask) {
52
SDL_RenderDrawPoint(renderer, offset, row);
53
}
54
mask /= 2;
55
}
56
}
57
58
sfont->charset[i] = t;
59
}
60
61
SDL_SetRenderTarget(renderer, NULL);
62
63
return sfont;
64
}
65
66
void render_sfont(sdlfont_t *sfont, unsigned short pair, int x, int y) {
67
int bg = cga_colors[(pair >> (8 + 4)) & 0x7],
68
fg = cga_colors[(pair >> 8) & 0xf],
69
character = pair & 0xff;
70
SDL_SetRenderDrawColor(renderer, bg >> 16, (bg >> 8) & 0xff, bg & 0xff, SDL_ALPHA_OPAQUE);
71
SDL_Rect bgrect = { x * FONT_WIDTH, y * FONT_HEIGHT, FONT_WIDTH, FONT_HEIGHT };
72
SDL_RenderFillRect(renderer, &bgrect);
73
74
SDL_Rect src = { 0, 0, FONT_WIDTH, FONT_HEIGHT };
75
SDL_Rect dest = { x * FONT_WIDTH, y * FONT_HEIGHT, FONT_WIDTH, FONT_HEIGHT };
76
SDL_SetTextureColorMod(sfont->charset[character], fg >> 16, (fg >> 8) & 0xff, fg & 0xff);
77
SDL_RenderCopy(renderer, sfont->charset[character], &src, &dest);
78
}
79
80
void free_sdlfont(sdlfont_t *sfont) {
81
for (int i = 0; i < 256; ++i) {
82
SDL_DestroyTexture(sfont->charset[i]);
83
}
84
85
free(sfont);
86
}
87
88
/* vim: set sw=4 et: */
89