4 #include "client/client.h"
5 #include "client/font.h"
6 #include "client/hud.h"
22 Character chars[NUM_CHARS];
29 } __attribute__((packed)) VertexFontPosition;
34 } __attribute__((packed)) VertexFontTextureCoordinates;
38 VertexFontPosition position;
39 VertexFontTextureCoordinates textureCoordinates;
40 } __attribute__((packed)) VertexFont;
42 static VertexAttribute vertex_attributes[2] = {
47 .size = sizeof(VertexFontPosition),
53 .size = sizeof(VertexFontTextureCoordinates),
57 static VertexLayout vertex_layout = {
58 .attributes = vertex_attributes,
60 .size = sizeof(VertexFont),
65 if (FT_Init_FreeType(&font.library)) {
66 fprintf(stderr, "Failed to initialize Freetype\n");
70 if (FT_New_Face(font.library, RESSOURCEPATH "fonts/Minecraftia.ttf", 0, &font.face)) {
71 fprintf(stderr, "Failed to load Minecraftia.ttf\n");
75 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
76 FT_Set_Pixel_Sizes(font.face, 0, 16);
78 for (unsigned char c = 0; c < NUM_CHARS; c++) {
79 if (FT_Load_Char(font.face, c, FT_LOAD_RENDER)) {
80 fprintf(stderr, "Failed to load glyph %c\n", c);
82 font.chars[c] = (Character) {
88 font.chars[c] = (Character) {
89 .texture = texture_create(font.face->glyph->bitmap.buffer, font.face->glyph->bitmap.width, font.face->glyph->bitmap.rows, GL_RED),
90 .bearing = {font.face->glyph->bitmap_left, font.face->glyph->bitmap_top},
91 .advance = font.face->glyph->advance.x,
96 font.height = font.chars['|'].texture->height;
98 FT_Done_Face(font.face);
99 FT_Done_FreeType(font.library);
106 for (unsigned char c = 0; c < NUM_CHARS; c++) {
107 if (font.chars[c].texture)
108 texture_delete(font.chars[c].texture);
112 Font *font_create(char *text)
114 Font *fnt = malloc(sizeof(fnt));
116 size_t len = strlen(text);
118 fnt->meshes = malloc(sizeof(Mesh *) * len);
119 fnt->meshes_count = len;
121 GLfloat offset = 0.0f;
123 for (size_t i = 0; i < len; i++) {
124 unsigned char c = text[i];
126 if (c >= NUM_CHARS || ! font.chars[c].texture)
129 Character *ch = &font.chars[c];
131 GLfloat width = ch->texture->width;
132 GLfloat height = ch->texture->height;
134 GLfloat x = ch->bearing.x + offset;
135 GLfloat y = font.height - ch->bearing.y;
137 VertexFont vertices[6] = {
138 {{x, y }, {0.0f, 0.0f}},
139 {{x, y + height}, {0.0f, 1.0f}},
140 {{x + width, y + height}, {1.0f, 1.0f}},
141 {{x, y }, {0.0f, 0.0f}},
142 {{x + width, y + height}, {1.0f, 1.0f}},
143 {{x + width, y }, {1.0f, 0.0f}},
146 Mesh *mesh = fnt->meshes[i] = mesh_create();
147 mesh->texture = ch->texture->id;
148 mesh->layout = &vertex_layout;
149 mesh->vertices = vertices;
150 mesh->vertices_count = 6;
151 mesh_configure(mesh);
153 offset += ch->advance >> 6;
159 void font_delete(Font *fnt)
161 for (size_t i = 0; i < fnt->meshes_count; i++)
162 mesh_delete(fnt->meshes[i]);
167 void font_render(Font *fnt)
169 for (size_t i = 0; i < fnt->meshes_count; i++)
170 mesh_render(fnt->meshes[i]);