aboutsummaryrefslogtreecommitdiffstats
path: root/source/render/render_font.cpp
blob: 17ac1e0e8f9858bd538b9b30c9020c50548010df (plain) (blame)
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//- font files

// NOTE: first one that exists wins. noto is on basically every linux desktop.
global_variable const char *font_paths_regular[] = {
	"/usr/share/fonts/noto/NotoSans-Regular.ttf",
	"/usr/share/fonts/noto/NotoSans-Regular.otf",
	"/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
	"/usr/share/fonts/TTF/DejaVuSans.ttf",
	"/usr/share/fonts/dejavu/DejaVuSans.ttf",
	"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
};
global_variable const char *font_paths_semibold[] = {
	"/usr/share/fonts/noto/NotoSans-SemiBold.ttf",
	"/usr/share/fonts/noto/NotoSans-Medium.ttf",
	"/usr/share/fonts/truetype/noto/NotoSans-SemiBold.ttf",
	"/usr/share/fonts/TTF/DejaVuSans-Bold.ttf",
	"/usr/share/fonts/dejavu/DejaVuSans-Bold.ttf",
	"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
};
global_variable const char *font_paths_mono[] = {
	"/usr/share/fonts/jetbrains-mono/JetBrainsMono-Regular.ttf",
	"/usr/share/fonts/noto/NotoSansMono-Regular.ttf",
	"/usr/share/fonts/truetype/noto/NotoSansMono-Regular.ttf",
	"/usr/share/fonts/TTF/DejaVuSansMono.ttf",
	"/usr/share/fonts/dejavu/DejaVuSansMono.ttf",
	"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
};

internal String8 font_load_first(Arena *arena, const char **paths, u32 count)
{
	for(u32 index = 0; index < count; ++index) {
		String8 path = str8(paths[index]);
		if(FileExists(arena, path)) {
			String8 data = FileLoad(arena, path);
			if(data.size > 0) {
				return data;
			}
		}
	}
	return str8_zero();
}

//- hashing
// NOTE: fnv-1a, 64 bit. text is short (names), good enough and branch free

// NOTE: 8 bytes per step (fnv-1a was one byte per multiply, a 4 cycle dependency per byte)
internal u64 hash_bytes(const u8 *data, u64 size, u64 seed)
{
	u64 hash = (0x9E3779B97F4A7C15ull ^ seed) + size;
	u64 index = 0;
	for(; index + 8 <= size; index += 8) {
		u64 word = 0;
		MemCpy(&word, data + index, 8);
		hash = (hash ^ word) * 0xFF51AFD7ED558CCDull;
		hash ^= hash >> 32;
	}
	if(index < size) {
		u64 word = 0;
		MemCpy(&word, data + index, size - index);
		hash = (hash ^ word) * 0xC4CEB9FE1A85EC53ull;
	}
	hash ^= hash >> 29;
	hash *= 0xBF58476D1CE4E5B9ull;
	hash ^= hash >> 32;
	return hash ? hash : 1;
}

//- init

internal void font_reset_caches(FontSystem *fonts)
{
	MemSetZero(fonts->atlas, FONT_ATLAS_SIZE * FONT_ATLAS_SIZE);
	MemSetZero(fonts->glyphs, sizeof(GlyphEntry) * FONT_GLYPH_SLOTS);
	fonts->glyph_count = 0;
	fonts->shelf_x     = 1;
	fonts->shelf_y     = 1;
	fonts->shelf_h     = 0;
	fonts->dirty_y0    = 0;
	fonts->dirty_y1    = FONT_ATLAS_SIZE;
	++fonts->atlas_generation; // every run's cached placement is stale now
}

internal void font_reset_runs(FontSystem *fonts)
{
	MemSetZero(fonts->runs, sizeof(ShapedRun) * FONT_RUN_SLOTS);
	fonts->run_count = 0;
	arena_clear(fonts->run_arena);
	++fonts->runs_generation; // every recent entry points at a cleared run now
}

internal b32 font_init(Arena *arena, FontSystem *fonts)
{
	MemSetZero(fonts, sizeof(*fonts));
	if(FT_Init_FreeType(&fonts->library) != 0) {
		Log("freetype init failed");
		return false;
	}

	fonts->font_data[FONT_REGULAR]  = font_load_first(arena, font_paths_regular, ArrayCount(font_paths_regular));
	fonts->font_data[FONT_SEMIBOLD] = font_load_first(arena, font_paths_semibold, ArrayCount(font_paths_semibold));
	fonts->font_data[FONT_MONO]     = font_load_first(arena, font_paths_mono, ArrayCount(font_paths_mono));
	if(fonts->font_data[FONT_REGULAR].size == 0) {
		Log("no usable font found (install noto-fonts or dejavu)");
		return false;
	}
	for(u32 kind = 0; kind < FONT_KIND_COUNT; ++kind) {
		if(fonts->font_data[kind].size == 0) {
			fonts->font_data[kind] = fonts->font_data[FONT_REGULAR];
		}
	}

	for(u32 kind = 0; kind < FONT_KIND_COUNT; ++kind) fonts->face_index[kind] = -1;
	fonts->buffer    = hb_buffer_create();
	fonts->atlas     = PushArrayAligned(arena, u8, FONT_ATLAS_SIZE * FONT_ATLAS_SIZE);
	fonts->glyphs    = PushArrayAligned(arena, GlyphEntry, FONT_GLYPH_SLOTS);
	fonts->runs      = PushArrayAligned(arena, ShapedRun, FONT_RUN_SLOTS);
	fonts->run_arena = ArenaCreate(MiB(8));
	fonts->recent    = PushArrayAligned(arena, RecentRun, FONT_RECENT_SLOTS);
	fonts->scale     = 1.0f;
	fonts->runs_generation  = 1; // zeroed entries (generation 0) never match
	fonts->atlas_generation = 1;
	for(u32 kind = 0; kind < FONT_KIND_COUNT; ++kind) fonts->last_face[kind] = FONT_NO_FACE;
	font_reset_caches(fonts);
	return true;
}

internal void font_drop_faces(FontSystem *fonts)
{
	for(u32 index = 0; index < fonts->face_count; ++index) {
		hb_font_destroy(fonts->faces[index].hb);
		FT_Done_Face(fonts->faces[index].face);
	}
	fonts->face_count = 0;
	for(u32 kind = 0; kind < FONT_KIND_COUNT; ++kind) fonts->last_face[kind] = FONT_NO_FACE;
	font_reset_caches(fonts);
	font_reset_runs(fonts);
}

internal void font_set_scale(FontSystem *fonts, f32 scale)
{
	if(scale == fonts->scale) {
		return;
	}
	// NOTE: every physical size changes, drop all faces and caches
	fonts->scale = scale;
	font_drop_faces(fonts);
}

// NOTE: swap the font file behind a kind. a no-op unless it actually changed, so the ui can call
// it every frame with whatever the settings say.
internal void font_set_data(FontSystem *fonts, FontKind kind, String8 data)
{
	if(data.size == 0 || data.data == fonts->font_data[kind].data) {
		return;
	}
	fonts->font_data[kind]  = data;
	fonts->face_index[kind] = -1;
	font_drop_faces(fonts);
}

// NOTE: a .ttc collection holds many faces (iosevka: 100+, the first one is "Thin"). pick the
// one whose style is plain "Regular", once per file, not once per size.
internal s32 font_pick_face(FontSystem *fonts, String8 data)
{
	FT_Face face = NULL;
	if(FT_New_Memory_Face(fonts->library, data.data, (FT_Long)data.size, -1, &face) != 0) {
		return 0;
	}
	FT_Long count = face->num_faces;
	FT_Done_Face(face);
	for(FT_Long index = 0; index < count; ++index) {
		if(FT_New_Memory_Face(fonts->library, data.data, (FT_Long)data.size, index, &face) != 0) continue;
		b32 regular = face->style_name && strcmp(face->style_name, "Regular") == 0;
		FT_Done_Face(face);
		if(regular) return (s32)index;
	}
	return 0;
}

internal u32 font_face_lookup(FontSystem *fonts, FontKind kind, f32 size);
internal u32 font_face(FontSystem *fonts, FontKind kind, f32 size)
{
	if(fonts->last_face[kind] != FONT_NO_FACE && fonts->last_size[kind] == size) {
		return fonts->last_face[kind];
	}
	u32 face = font_face_lookup(fonts, kind, size);
	fonts->last_size[kind] = size;
	fonts->last_face[kind] = face;
	return face;
}

internal u32 font_face_lookup(FontSystem *fonts, FontKind kind, f32 size)
{
	u32 px = (u32)(size * fonts->scale + 0.5f);
	for(u32 index = 0; index < fonts->face_count; ++index) {
		if(fonts->faces[index].kind == kind && fonts->faces[index].px == px) {
			return index;
		}
	}

	if(fonts->face_count >= FONT_MAX_FACES) {
		// NOTE: font sizes are user settings now, so faces can pile up while someone drags a size
		// around. start over: drop every face and both caches, they refill on demand.
		font_drop_faces(fonts);
	}

	FontFace *face = &fonts->faces[fonts->face_count];
	String8   data = fonts->font_data[kind];
	if(fonts->face_index[kind] < 0) {
		fonts->face_index[kind] = font_pick_face(fonts, data);
	}
	if(FT_New_Memory_Face(fonts->library, data.data, (FT_Long)data.size, fonts->face_index[kind], &face->face) != 0) {
		return 0;
	}
	FT_Set_Pixel_Sizes(face->face, 0, px);
	face->hb          = hb_ft_font_create_referenced(face->face);
	hb_ft_font_set_load_flags(face->hb, FT_LOAD_DEFAULT | FT_LOAD_TARGET_LIGHT);
	face->kind        = kind;
	face->px          = px;
	face->ascent      = (f32)face->face->size->metrics.ascender / 64.0f;
	face->descent     = (f32)-face->face->size->metrics.descender / 64.0f;
	face->line_height = (f32)face->face->size->metrics.height / 64.0f;
	return fonts->face_count++;
}

//- glyph atlas

internal GlyphEntry *font_glyph(FontSystem *fonts, u32 face_index, u32 glyph)
{
	u32 key  = ((face_index << 20) | (glyph & 0xFFFFF)) + 1;
	u32 slot = (key * 2654435761u) & (FONT_GLYPH_SLOTS - 1);

	for(;;) {
		GlyphEntry *entry = &fonts->glyphs[slot];
		if(entry->key == key) {
			return entry;
		}
		if(entry->key == 0) {
			break;
		}
		slot = (slot + 1) & (FONT_GLYPH_SLOTS - 1);
	}

	if(fonts->glyph_count >= FONT_GLYPH_SLOTS * 3 / 4) {
		font_reset_caches(fonts);
		return font_glyph(fonts, face_index, glyph);
	}

	//- rasterize
	FontFace *face = &fonts->faces[face_index];
	if(FT_Load_Glyph(face->face, glyph, FT_LOAD_DEFAULT | FT_LOAD_TARGET_LIGHT) != 0 ||
	   FT_Render_Glyph(face->face->glyph, FT_RENDER_MODE_LIGHT) != 0) {
		return NULL;
	}
	FT_GlyphSlot slot_data = face->face->glyph;
	FT_Bitmap   *bitmap    = &slot_data->bitmap;
	u32          w         = Min(bitmap->width, 255u);
	u32          h         = Min(bitmap->rows, 255u);

	//- pack, 1px gutter so bilinear never bleeds a neighbour in
	if(fonts->shelf_x + w + 1 > FONT_ATLAS_SIZE) {
		fonts->shelf_x = 1;
		fonts->shelf_y += fonts->shelf_h + 1;
		fonts->shelf_h = 0;
	}
	if(fonts->shelf_y + h + 1 > FONT_ATLAS_SIZE) {
		font_reset_caches(fonts);
		return font_glyph(fonts, face_index, glyph);
	}

	u32 x = fonts->shelf_x;
	u32 y = fonts->shelf_y;
	for(u32 row = 0; row < h; ++row) {
		MemCpy(fonts->atlas + (u64)(y + row) * FONT_ATLAS_SIZE + x, bitmap->buffer + (s64)row * bitmap->pitch, w);
	}
	fonts->shelf_x += w + 1;
	fonts->shelf_h  = Max(fonts->shelf_h, h);

	if(fonts->dirty_y0 >= fonts->dirty_y1) {
		fonts->dirty_y0 = (s32)y;
		fonts->dirty_y1 = (s32)(y + h);
	} else {
		fonts->dirty_y0 = Min(fonts->dirty_y0, (s32)y);
		fonts->dirty_y1 = Max(fonts->dirty_y1, (s32)(y + h));
	}

	GlyphEntry *entry = &fonts->glyphs[slot];
	entry->key        = key;
	entry->x          = (u16)x;
	entry->y          = (u16)y;
	entry->w          = (u8)w;
	entry->h          = (u8)h;
	entry->bearing_x  = (s16)slot_data->bitmap_left;
	entry->bearing_y  = (s16)slot_data->bitmap_top;
	++fonts->glyph_count;
	return entry;
}

//- shaping

internal ShapedRun *font_shape_slow(FontSystem *fonts, u32 face_index, String8 text);
internal ShapedRun *font_shape(FontSystem *fonts, u32 face_index, String8 text)
{
	u64        key    = ((u64)(uintptr_t)text.data >> 3) ^ ((u64)text.size << 40) ^ ((u64)face_index << 56);
	RecentRun *recent = &fonts->recent[(u32)((key * 0x9E3779B97F4A7C15ull) >> 54) & (FONT_RECENT_SLOTS - 1)];
	if(recent->generation == fonts->runs_generation && recent->text == text.data && recent->size == text.size &&
	   recent->face == face_index && memcmp(recent->run->text, text.data, text.size) == 0) {
		return recent->run;
	}
	ShapedRun *run = font_shape_slow(fonts, face_index, text);
	// NOTE: shaping can clear the run table (bumping the generation), so record after
	recent->text       = text.data;
	recent->size       = (u32)text.size;
	recent->face       = face_index;
	recent->run        = run;
	recent->generation = fonts->runs_generation;
	return run;
}

internal ShapedRun *font_shape_slow(FontSystem *fonts, u32 face_index, String8 text)
{
	u64 hash = hash_bytes(text.data, text.size, face_index * 0x9E3779B97F4A7C15ull);
	u32 slot = (u32)hash & (FONT_RUN_SLOTS - 1);

	for(;;) {
		ShapedRun *run = &fonts->runs[slot];
		if(run->hash == hash && run->face == face_index && run->text_size == text.size &&
		   memcmp(run->text, text.data, text.size) == 0) {
			return run;
		}
		if(run->hash == 0) {
			break;
		}
		slot = (slot + 1) & (FONT_RUN_SLOTS - 1);
	}

	if(fonts->run_count >= FONT_RUN_SLOTS / 2 || arena_position(fonts->run_arena) > MiB(6)) {
		font_reset_runs(fonts);
		return font_shape_slow(fonts, face_index, text);
	}

	FontFace *face = &fonts->faces[face_index];
	hb_buffer_clear_contents(fonts->buffer);
	hb_buffer_add_utf8(fonts->buffer, (const char *)text.data, (int)text.size, 0, (int)text.size);
	hb_buffer_guess_segment_properties(fonts->buffer);
	hb_shape(face->hb, fonts->buffer, NULL, 0);

	u32                  count     = 0;
	hb_glyph_info_t     *infos     = hb_buffer_get_glyph_infos(fonts->buffer, &count);
	hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(fonts->buffer, &count);

	ShapedRun *run   = &fonts->runs[slot];
	run->hash        = hash;
	run->face        = face_index;
	run->glyph_count = count;
	run->text_size   = (u32)text.size;
	run->text        = PushArray(fonts->run_arena, u8, Max(text.size, 1ull));
	MemCpy(run->text, text.data, text.size);
	run->glyphs = PushArray(fonts->run_arena, ShapedGlyph, Max(count, 1u));
	run->placed = PushArray(fonts->run_arena, RunGlyph, Max(count, 1u));
	run->atlas_generation = 0; // placed on first draw

	f32 pen = 0.0f;
	for(u32 index = 0; index < count; ++index) {
		ShapedGlyph *out = &run->glyphs[index];
		out->glyph       = infos[index].codepoint;
		out->face        = face_index;
		out->x           = pen + (f32)positions[index].x_offset / 64.0f;
		out->y           = -(f32)positions[index].y_offset / 64.0f;
		pen += (f32)positions[index].x_advance / 64.0f;
	}
	run->width = pen;
	++fonts->run_count;
	return run;
}

//- public

internal f32 font_measure(FontSystem *fonts, FontKind kind, f32 size, String8 text)
{
	u32        face = font_face(fonts, kind, size);
	ShapedRun *run  = font_shape(fonts, face, text);
	return run->width / fonts->scale;
}

internal f32 font_line_height(FontSystem *fonts, FontKind kind, f32 size)
{
	return fonts->faces[font_face(fonts, kind, size)].line_height / fonts->scale;
}

internal f32 font_ascent(FontSystem *fonts, FontKind kind, f32 size)
{
	return fonts->faces[font_face(fonts, kind, size)].ascent / fonts->scale;
}

internal void draw_run(DrawList *list, FontSystem *fonts, u32 face, ShapedRun *run, u32 glyph_count, f32 x, f32 baseline, u32 color)
{
	// NOTE: snap the origin to the physical grid, glyph bitmaps are rendered for whole pixels
	f32 ox    = floorf(x * fonts->scale + 0.5f);
	f32 oy    = floorf(baseline * fonts->scale + 0.5f);

	// NOTE: place the whole run once per atlas generation. rasterizing can fill the atlas and
	// reset it halfway through, then the earlier placements are stale: go again (rare, bounded:
	// one run always fits an empty atlas).
	for(u32 attempt = 0; run->atlas_generation != fonts->atlas_generation && attempt < 3; ++attempt) {
		u32 generation = fonts->atlas_generation;
		for(u32 index = 0; index < run->glyph_count; ++index) {
			GlyphEntry *glyph = font_glyph(fonts, run->glyphs[index].face, run->glyphs[index].glyph);
			RunGlyph   *place = &run->placed[index];
			if(glyph) {
				*place = RunGlyph{glyph->x, glyph->y, glyph->w, glyph->h, glyph->bearing_x, glyph->bearing_y};
			} else {
				*place = RunGlyph{};
			}
		}
		if(fonts->atlas_generation == generation) run->atlas_generation = generation;
	}

	for(u32 index = 0; index < glyph_count; ++index) {
		ShapedGlyph *shaped = &run->glyphs[index];
		RunGlyph    *glyph  = &run->placed[index];
		if(glyph->w == 0 || glyph->h == 0) {
			continue;
		}
		f32 x0 = floorf(ox + shaped->x + 0.5f) + glyph->bearing_x;
		f32 y0 = floorf(oy + shaped->y + 0.5f) - glyph->bearing_y;
		draw_glyph_physical(list, x0, y0, x0 + glyph->w, y0 + glyph->h, glyph->x, glyph->y, color);
	}
}

internal f32 draw_text(DrawList *list, FontSystem *fonts, FontKind kind, f32 size, f32 x, f32 baseline, String8 text, u32 color)
{
	if(text.size == 0) {
		return 0.0f;
	}
	u32        face = font_face(fonts, kind, size);
	ShapedRun *run  = font_shape(fonts, face, text);
	draw_run(list, fonts, face, run, run->glyph_count, x, baseline, color);
	return run->width / fonts->scale;
}

internal f32 draw_text_fit(DrawList *list, FontSystem *fonts, FontKind kind, f32 size, f32 x, f32 baseline, f32 max_width, String8 text, u32 color)
{
	if(text.size == 0) {
		return 0.0f;
	}
	u32        face  = font_face(fonts, kind, size);
	ShapedRun *run   = font_shape(fonts, face, text);
	f32        limit = max_width * fonts->scale;

	if(run->width <= limit) {
		draw_run(list, fonts, face, run, run->glyph_count, x, baseline, color);
		return run->width / fonts->scale;
	}

	ShapedRun *dots      = font_shape(fonts, face, str8("…"));
	f32        available = limit - dots->width;
	u32        keep      = 0;
	while(keep < run->glyph_count && run->glyphs[keep].x < available) {
		++keep;
	}
	keep = (keep > 0) ? keep - 1 : 0;

	draw_run(list, fonts, face, run, keep, x, baseline, color);
	f32 cut = (keep < run->glyph_count) ? run->glyphs[keep].x : run->width;
	draw_run(list, fonts, face, dots, dots->glyph_count, x + cut / fonts->scale, baseline, color);
	return (cut + dots->width) / fonts->scale;
}