FontManager.cpp 13.9 KB
Newer Older
unknown's avatar
unknown committed
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
#include "FontManager.h"
#include <util/log.h>
#include "engine/EngineState.h"

namespace glare
{
	namespace core
	{

		FontManager::FontManager()
		{
			const auto error = FT_Init_FreeType(&m_freetype_library);
			if (error)
			{
				Log_Error << "FreeType library could not be initialized.";
				return;
			}

			const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
			int widthMM, heightMM;
			glfwGetMonitorPhysicalSize(glfwGetPrimaryMonitor(), &widthMM, &heightMM);
			m_dpi = mode->width / (widthMM / 25.4);
		}

		FontManager::~FontManager()
		{

		}

		const FT_Library& FontManager::getLibrary() const
		{
			return m_freetype_library;
		}

		double FontManager::getMonitorDPI() const
		{
			return m_dpi;
		}

		Font::Font(fs::path path): m_current_size(0)
		{
			auto error = FT_New_Face(FontManager::getInstance().getLibrary(),
			                         path.string().c_str(),
			                         0,
			                         &m_font_face);

			if (error)
			{
				Log_Error << "The font at " << path << " could not be loaded.";
				return;
			}

			error = FT_Select_Charmap(m_font_face, FT_ENCODING_UNICODE);

			if (error)
			{
				Log_Error << "Charmap for " << path << " could not be loaded.";
				return;
			}

			Log_Info << "Loaded font having " << m_font_face->num_glyphs << " glyphs";
		}

		Font::~Font()
		{

		}

		void Font::setSize(points size)
		{

			const auto error = FT_Set_Char_Size(m_font_face,
										  0,
										  size * 64,
										  FT_UInt(FontManager::getInstance().getMonitorDPI()),
										  FT_UInt(FontManager::getInstance().getMonitorDPI()));
			if (error)
			{
				Log_Error << "FT_Set_Char_Size failed!";
				return;
			}

			m_current_size = size;
			m_flags.set(FONT_SIZE_SET);
		}

		glm::ivec2 Font::measureText(const std::wstring &text, glm::vec2 max_dimensions) const
		{
			if (!m_flags.are(FONT_SIZE_SET))
			{
				Log_Error << "You have to set a font size before rendering.";
				return glm::ivec2(0);
			}

			glm::ivec2 size(0);

			if (max_dimensions.x == 0 && max_dimensions.y == 0)
				return size;

			int position_x = 0;

			//move one line down to make the top most left point of the text block the text origin.
			int position_y = 0;
			size.y = getLineHeight();

			int size_at_last_break = 0;
			int size_from_last_break = 0;
			int longest_line = 0;
			int second_longest_line = 0;
			int current_line = 0;
			int second_longest_line_size = 0;

			for (const wchar_t &character : text)
			{
				if (character == '\n')
				{
					++current_line;
					position_x = 0;
					position_y -= getLineHeight();
					size.y += getLineHeight();
					size_at_last_break = 0;
					continue;
				}
124
				else if (text::isLineBreakable(character))
unknown's avatar
unknown committed
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
				{
					size_at_last_break = position_x;
					size_from_last_break = 0;
				}

				const Glyph &glyph = getGlyph(character);

				position_x += glyph.advance.x;
				size_from_last_break += glyph.advance.x;

				if (max_dimensions.x != -1 && position_x > max_dimensions.x)
				{
					if (size_at_last_break == 0)
					{
						++current_line;
						position_x = glyph.advance.x;
						position_y -= getLineHeight();
						size.y += getLineHeight();
					}
					else
					{
						++current_line;
						position_x = size_from_last_break;
						position_y -= getLineHeight();
						size.y += getLineHeight();

						if (longest_line == current_line)
						{
							longest_line = second_longest_line;
							size.x = glm::max(second_longest_line_size, size_at_last_break);
						}

						size_at_last_break = 0;
					}
					continue;
				}

				if (position_x > size.x)
				{
					second_longest_line = longest_line;
					longest_line = current_line;
					second_longest_line_size = size.x;
				}

				size.x = glm::max(size.x, position_x);

				position_y += glyph.advance.y;
			}

			return size;
		}

		const Glyph &Font::getGlyph(wchar_t character) const
		{
			Glyph &glyph = m_glyph_storage[m_current_size][character];

			//If the texture has not been loaded yet, render a new one.
			if (!(glyph.texture))
			{
				if (FT_Load_Char(m_font_face, character, FT_LOAD_RENDER)) return glyph;

				glyph.advance = { m_font_face->glyph->advance.x >> 6, m_font_face->glyph->advance.y >> 6 };
				glyph.texture_offset = { m_font_face->glyph->bitmap_left, m_font_face->glyph->bitmap_top };

				glyph.texture.reset(new TextureR_UB(m_font_face->glyph->bitmap.width, m_font_face->glyph->bitmap.rows, m_font_face->glyph->bitmap.buffer));
			}

			return glyph;
		}

		int Font::getLineHeight() const
		{
			return int(m_font_face->size->metrics.height >> 6);
		}

		const FT_Face& Font::getFontFace() const
		{
			return m_font_face;
		}

		Font::TextBufferData Font::renderText(const std::wstring &text, Align align, glm::vec2 max_dimensions) const
		{
			TextBufferData data;

			if (max_dimensions == glm::vec2(0))
				return data;

			if (!m_flags.are(FONT_SIZE_SET))
			{
				Log_Error << "You have to set a font size before rendering.";
				return data;
			}

			int position_x;

			//move one line down to make the top most left point of the text block the text origin.
			int position_y = (m_font_face->size->metrics.height >> 6) + (m_font_face->size->metrics.descender >> 6);

			std::vector<int> line_offsets;
			int max_width = 0;
			line_offsets.push_back(0);

			int space = getGlyph(' ').advance.x;
			if (align != Align::eLeft)
			{
				int current_line = 0;
				int size_from_line_start_to_last_break = 0;
				int size_from_last_break = 0;

				int longest_line = 0;
				int second_longest_line = 0;

				bool was_space = false;
				int c_ = 0;
				for (const wchar_t &character : text)
				{
					++c_;
					const Glyph &glyph = getGlyph(character);

					if (character == '\n')
					{
						++current_line;
						size_from_line_start_to_last_break = 0;
						size_from_last_break = 0;
						line_offsets.push_back(0);
						continue;
					}
252
					else if (text::isLineBreakable(character))
unknown's avatar
unknown committed
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
					{
						if (character == ' ')
						{
							size_from_line_start_to_last_break = line_offsets[current_line];
							size_from_last_break = 0;
							was_space = true;
						}
						else
						{
							size_from_line_start_to_last_break = line_offsets[current_line];
							size_from_last_break = 0;
							was_space = false;
						}
					}

					if (line_offsets[current_line] > max_width)
					{
						max_width = line_offsets[current_line];
						second_longest_line = longest_line;
						longest_line = current_line;
					}

					if (max_dimensions.x != -1 && line_offsets[current_line] + glyph.advance.x > max_dimensions.x)
					{
						//break the line.
						if (size_from_line_start_to_last_break == 0)
						{
							++current_line;
							line_offsets.push_back(0);
							size_from_last_break = 0;
							size_from_line_start_to_last_break = 0;
						}
						else
						{
							line_offsets[current_line] -= size_from_last_break;

							line_offsets.push_back(size_from_last_break);

							if (longest_line == current_line)
							{
								longest_line = second_longest_line;
								max_width = line_offsets[longest_line];
							}

							size_from_last_break = 0;
							size_from_line_start_to_last_break = 0;
							++current_line;

							if (was_space)
							{
								line_offsets[current_line] -= space;
							}
						}
						was_space = false;
					}

					size_from_last_break += glyph.advance.x;
					line_offsets[current_line] += glyph.advance.x;
				}
				max_width = line_offsets[longest_line];
			}

			line_offsets.push_back(max_width);
			line_offsets.push_back(max_width);
			line_offsets.push_back(max_width);
			line_offsets.push_back(max_width);
			line_offsets.push_back(max_width);
			line_offsets.push_back(max_width);

			switch (align)
			{
			default:
			case Align::eLeft:
				position_x = 0;
				break;
			case Align::eRight:
				position_x = max_width - line_offsets[0];
				break;
			case Align::eCenter:
				position_x = int(max_width / 2.f - line_offsets[0] / 2.f);
				break;
			}

			int last_line_break_position = 0;
			int line = 1;
			for (unsigned c = 0; c < text.size(); c++)
			{
				const wchar_t norm_character = text[c];

				if (norm_character == '\n')
				{
					switch (align)
					{
					default:
					case Align::eLeft:
						position_x = 0;
						break;
					case Align::eRight:
						position_x = max_width - line_offsets[line];
						break;
					case Align::eCenter:
						position_x = int(max_width / 2.f - line_offsets[line] / 2.f);
						break;
					}
					last_line_break_position = 0;
					line++;
					position_y -= m_font_face->size->metrics.height >> 6;
					continue;
				}
362
				else if (text::isLineBreakable(norm_character))
unknown's avatar
unknown committed
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
				{
					last_line_break_position = c;
				}

				const Glyph &glyph = getGlyph(norm_character);

				if (max_dimensions.x != -1 && position_x + glyph.advance.x > max_dimensions.x)
				{
					int continue_at = c - 1;
					if (last_line_break_position != 0)
					{
						continue_at = last_line_break_position;
					}

					c = continue_at;

					if (text[c + 1] == ' ')
					{
						c += 1;
					}

					data.resize(c + 1);
					switch (align)
					{
					default:
					case Align::eLeft:
						position_x = 0;
						break;
					case Align::eRight:
						position_x = max_width - line_offsets[line];
						break;
					case Align::eCenter:
						position_x = int(max_width / 2.f - line_offsets[line] / 2.f);
						break;
					}
					last_line_break_position = 0;
					line++;
					position_y -= m_font_face->size->metrics.height >> 6;
					continue;
				}

				//Draw glyph_texture...
				data.push_back(TextBufferItem {
					glyph.texture->getResidentTextureID(),
					{ position_x + glyph.texture_offset.x, position_y + glyph.texture_offset.y},
					glyph.texture->getSize()
				});

				position_x += glyph.advance.x;
				position_y += glyph.advance.y;
			}

			return data;
		}

		/*std::wstring Text::wfrom(const std::string& text)
		{
			const unsigned char* ch_text = reinterpret_cast<const unsigned char*>(text.data());

			return std::wstring(&ch_text[0], &ch_text[text.size()]);
		}*/

		void Text::set(const std::wstring &text, glm::vec2 max_dimensions)
		{
			if (!m_current_font)
			{
				Log_Error << "Cannot render a text without a font.";
				return;
			}

			m_max_dimensions = max_dimensions;
			m_text = text;

			m_length = unsigned(text.size());

		}

		Text::Text(): m_length(0)
		{
			m_text_buffer = std::make_unique<Buffer<gl::BufferType::eShaderStorage>>();
		}

		Text::~Text()
		{

		}

		void Text::setAlignment(Align align)
		{
			m_align = align;
			set(m_text, m_max_dimensions);
		}

		std::wstring& Text::operator=(std::wstring& text)
		{
			set(text, m_max_dimensions);
			return m_text;
		}

		std::wstring& Text::operator=(std::string& text)
		{
			set(text, m_max_dimensions);
			return m_text;
		}

		std::wstring& Text::operator+(std::wstring& text)
		{
			return *this = text;
		}

		std::wstring& Text::operator+(std::string& text)
		{
			return *this = text;
		}

		std::wstring& Text::operator+=(std::wstring& text)
		{
			return m_text += text;
		}

		std::wstring& Text::operator+=(std::string& text)
		{
485
			return m_text += text::to_wstring(text);
unknown's avatar
unknown committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
		}

		glm::ivec2 Text::measure(glm::vec2 max_dimensions)
		{
			m_max_dimensions = max_dimensions;
			m_size = m_current_font->measureText(m_text, max_dimensions);
			return m_size;
		}

		void Text::setFont(std::shared_ptr<Font> font)
		{
			m_current_font = font;
			set(m_text, m_max_dimensions);
		}

		void Text::invalidate()
		{
			m_size = measure(m_max_dimensions);
			const auto data = m_current_font->renderText(m_text, m_align, m_max_dimensions);
			m_text_buffer->upload<TextBufferItem>(data, gl::BufferUsage::eDynamicDraw);
		}

		std::shared_ptr<Font> Text::getFont() const
		{
			return m_current_font;
		}

		void Text::setColor(const color::rgba32f& color)
		{
			m_color = color;
		}

		void Text::set(const std::string text, glm::vec2 max_dimensions)
		{
520
			const auto txt = text::to_wstring(text);
unknown's avatar
unknown committed
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
			set(txt, max_dimensions);
		}

		const Buffer<gl::BufferType::eShaderStorage>& Text::getBuffer() const
		{
			return *m_text_buffer;
		}

		const color::rgba32f& Text::getColor() const
		{
			return m_color;
		}

		unsigned Text::getLength() const
		{
			return m_length;
		}

		glm::vec2 Text::getSize() const
		{
			return m_size;
		}

		Align Text::getAlignment() const
		{
			return m_align;
		}

		glm::vec2 Text::getBaseOffset() const
		{
			return {0, m_current_font->getLineHeight() + (m_current_font->getFontFace()->size->metrics.descender >> 6)};
		}

		TextRenderer::TextRenderer()
		{
			const std::vector<std::shared_ptr<Shader>> shaders = {
				std::make_shared<Shader>(gl::ShaderType::eVertex, "/text/text.vert"),
				std::make_shared<Shader>(gl::ShaderType::eGeometry, "/text/text.geom"),
				std::make_shared<Shader>(gl::ShaderType::eFragment, "/text/text.frag")
			};

			m_shader.reset(new ShaderProgram(shaders));
			m_vertex_array = std::make_unique<VertexArray>();
		}

		TextRenderer::~TextRenderer()
		{
		}

		void TextRenderer::draw(const Text &text, const math::Rect &bounds) const
		{
			
			m_shader->use();

			const glm::mat4 base_transformation = EngineState::main_camera->getScreenMatrix();

			glm::mat4 matrix = base_transformation;

			switch (text.getAlignment())
			{
			default:
			case Align::eLeft:
				//Use default matrix
				matrix = matrix * glm::translate(glm::vec3(bounds.position() + glm::vec2(0, text.getSize().y) - 2 * text.getBaseOffset(), 0));
				break;
			case Align::eRight:
				matrix = matrix * glm::translate(glm::vec3(bounds.position() + glm::vec2(0, text.getSize().y) - 2 * text.getBaseOffset() + glm::vec2(bounds.size().x - text.getSize().x, 0), 0));
				break;
			case Align::eCenter:
				matrix = matrix * glm::translate(glm::vec3(bounds.position() + glm::vec2(0, text.getSize().y) - 2 * text.getBaseOffset() + glm::vec2(bounds.size().x / 2.f - text.getSize().x / 2.f, 0), 0));
				break;
			}

			m_shader->updateUniformMatrix("u_screen_matrix", matrix);
			m_shader->updateUniformVec4("u_text_color", text.getColor());

			m_shader->updateStorageBuffer("TextBuffer", text.getBuffer());
598
599
600

			m_vertex_array->bind();
			gl::drawArrays(gl::PrimitiveType::ePoints, 0, text.getLength());
unknown's avatar
unknown committed
601
602
603
604
605
			m_vertex_array->unbind();

		}
	}
}