src/text.c
1#include "alba.h"
2
3#include <pthread.h>
4
5#include "freetype/ftglyph.h"
6
7#include "internal.h"
8
9extern char _binary_Roboto_Regular_ttf_start[];
10extern char _binary_Roboto_Regular_ttf_end[];
11
12static FT_Library freetype = NULL;
13static FT_Face roboto = NULL;
14Atlas atlas;
15pthread_mutex_t freetype_mutex = PTHREAD_MUTEX_INITIALIZER;
16
17void initialize_freetype()
18{
19 // already initialized
20 if (freetype != NULL) return;
21
22 pthread_mutex_lock(&freetype_mutex);
23 if (FT_Init_FreeType(&freetype))
24 {
25 printf("fatal error: initializeing FreeType failed");
26 pthread_mutex_unlock(&freetype_mutex);
27 exit(1);
28 }
29
30 FT_Error error = FT_New_Memory_Face(
31 freetype,
32 _binary_Roboto_Regular_ttf_start,
33 _binary_Roboto_Regular_ttf_end - _binary_Roboto_Regular_ttf_start,
34 0, // face index
35 &roboto
36 );
37 if (error)
38 {
39 printf("error: cound not load built in Roboto font");
40 }
41 error = FT_Set_Pixel_Sizes(roboto, 0 /* width, same as height */, 18);
42 if (error)
43 {
44 printf("error: cound not set Roboto face size");
45 }
46
47 atlas = atlas_new(1024);
48
49 pthread_mutex_unlock(&freetype_mutex);
50}
51
52
53void draw_text(AlbaWindow* window, const float x, const float y, uint64_t length, const char* text)
54{
55 initialize_freetype();
56
57 if (length == 0)
58 {
59 length = strlen(text);
60 }
61
62 pthread_mutex_lock(&freetype_mutex);
63 for (uint64_t i = 0; i < length; i++)
64 {
65 atlas_append(&atlas, roboto, text[i]); // TODO: unicode
66 }
67 pthread_mutex_unlock(&freetype_mutex);
68
69 // FT_Error error = FT_Load_Char(roboto, '7', FT_LOAD_RENDER);
70 // printf("%d\n", roboto->glyph->bitmap.width);
71 // error = FT_Load_Char(roboto, 'l', FT_LOAD_RENDER);
72 // printf("%d\n", roboto->glyph->bitmap.width);
73 // error = FT_Load_Char(roboto, 'm', FT_LOAD_RENDER);
74 // printf("%d\n", roboto->glyph->bitmap.width);
75
76 atlas_generate_image(&atlas);
77
78 WGPUTexture texture = create_texture(
79 window,
80 WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst,
81 atlas.width, atlas.height,
82 WGPUTextureFormat_RG8Unorm, 1, // TODO: do not assume format
83 atlas.image
84 );
85
86 // window.
87}