-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFont.cpp
More file actions
624 lines (522 loc) · 19.3 KB
/
Copy pathFont.cpp
File metadata and controls
624 lines (522 loc) · 19.3 KB
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
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
520
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
#include "stdafx.h"
#include "Font.h"
#include "BMFont.h"
#include "DK2Font.h"
//////////////////////////////////////////////////////////////////////////
#define STB_RECT_PACK_IMPLEMENTATION
#define STBRP_STATIC
#include "stb_rect_pack.h"
//////////////////////////////////////////////////////////////////////////
Font::Font(const std::string& fontName)
: mFontName(fontName)
{
}
void Font::Load()
{
Purge();
if (LoadFont_FromFile())
{
mIsLoadedFromFile = true;
}
else
{
InitDefault();
}
mTexturePixelFormat = mAtlasBitmap.GetPixelFormat();
}
void Font::InitDefault()
{
Purge();
mIsDefaultFont = true;
mLineHeight = 10;
mAtlasBitmap.Create(ePixelFormat_R8, Point2D{8, 8}, COLOR_WHITE);
mWideChars.clear();
for (CharEntry& roller: mAnsiChars)
{
roller.mRect.x = 0;
roller.mRect.y = 0;
roller.mRect.w = 8;
roller.mRect.h = 8;
}
InitTexcoords();
mTexturePixelFormat = mAtlasBitmap.GetPixelFormat();
}
void Font::Purge()
{
mIsRenderDataInited = false;
mIsDefaultFont = false;
mIsLoadedFromFile = false;
mLineHeight = 0;
mTexturePixelFormat = ePixelFormat_Null;
mAtlasBitmap.Clear();
mWideChars.clear();
mGpuTextureResource.reset();
}
void Font::InitRenderData()
{
if (IsRenderDataInited())
return;
if (!IsInited())
{
cxx_assert(false);
return;
}
mIsRenderDataInited = true;
static bool enableFiltering = true;
static bool freeSystemBits = true;
if (mAtlasBitmap.HasContent())
{
eTextureFiltering texFilteting = enableFiltering ? eTextureFiltering_Bilinear : eTextureFiltering_None;
// create texture
mGpuTextureResource = gRenderDevice.CreateTexture2D(mAtlasBitmap, texFilteting, eTextureRepeating_ClampToEdge);
cxx_assert(mGpuTextureResource);
if (mGpuTextureResource)
{
// success
if (freeSystemBits)
{
mAtlasBitmap.Clear();
}
return;
}
}
cxx_assert(false);
gConsole.LogMessage(eLogLevel_Warning, "Cannot initialize font render data ('%s'), trying fallback", mFontName.c_str());
// fallback in case of failure
BitmapImage bi;
if (!bi.Create(ePixelFormat_RGBA8, Point2D { 8, 8 }, COLOR_WHITE))
{
cxx_assert(false);
}
mGpuTextureResource = gRenderDevice.CreateTexture2D(bi);
cxx_assert(!!mGpuTextureResource);
}
void Font::BuildTextMesh(const std::wstring_view& wideString, const Point2D& pos, Color32 color, std::vector<Quad2D>& outQuads) const
{
outQuads.clear();
const int printablesCount = CountPrintableCharacters(wideString);
if (printablesCount == 0)
return;
outQuads.reserve(printablesCount);
// generate vertices
int currX = pos.x;
int currY = pos.y;
for (wchar_t wideChar: wideString)
{
if (wideChar == L'\n')
{
currX = pos.x;
currY += mLineHeight;
continue;
}
if (wideChar < L' ') continue;
const CharEntry& fontchar = GetCharEntry(wideChar);
int spacew = (fontchar.mRect.w == 0) ? fontchar.mOuterWidth : fontchar.mRect.w;
if (spacew == 0)
continue;
if (wideChar == L' ')
{
currX += spacew;
continue;
}
Quad2D& characterQuad = outQuads.emplace_back();
// setup quad vertices in specific order
characterQuad.mPoints[0].mColor = color;
characterQuad.mPoints[0].mTexcoord[0] = fontchar.mTexcoords.mU0;
characterQuad.mPoints[0].mTexcoord[1] = fontchar.mTexcoords.mV0;
characterQuad.mPoints[0].mPosition.x = (currX + fontchar.mOffset.x) * 1.0f;
characterQuad.mPoints[0].mPosition.y = (currY + fontchar.mOffset.y) * 1.0f;
characterQuad.mPoints[1].mColor = color;
characterQuad.mPoints[1].mTexcoord[0] = fontchar.mTexcoords.mU0;
characterQuad.mPoints[1].mTexcoord[1] = fontchar.mTexcoords.mV1;
characterQuad.mPoints[1].mPosition.x = (currX + fontchar.mOffset.x) * 1.0f;
characterQuad.mPoints[1].mPosition.y = (currY + fontchar.mRect.h + fontchar.mOffset.y) * 1.0f;
characterQuad.mPoints[2].mColor = color;
characterQuad.mPoints[2].mTexcoord[0] = fontchar.mTexcoords.mU1;
characterQuad.mPoints[2].mTexcoord[1] = fontchar.mTexcoords.mV1;
characterQuad.mPoints[2].mPosition.x = (currX + fontchar.mOffset.x + spacew) * 1.0f;
characterQuad.mPoints[2].mPosition.y = (currY + fontchar.mRect.h + fontchar.mOffset.y) * 1.0f;
characterQuad.mPoints[3].mColor = color;
characterQuad.mPoints[3].mTexcoord[0] = fontchar.mTexcoords.mU1;
characterQuad.mPoints[3].mTexcoord[1] = fontchar.mTexcoords.mV0;
characterQuad.mPoints[3].mPosition.x = (currX + fontchar.mOffset.x + spacew) * 1.0f;
characterQuad.mPoints[3].mPosition.y = (currY + fontchar.mOffset.y) * 1.0f;
currX += fontchar.mOuterWidth;
}
}
void Font::BuildTextMesh(const std::wstring_view& wideString, const Rect2D& rect,
eTextHorzAlignment horzAlign,
eTextVertAlignment vertAlign, Color32 color, std::vector<Quad2D>& outQuads) const
{
outQuads.clear();
bool hasHorzBounds = (rect.w > 0);
bool hasVertBounds = (rect.h > 0);
const int printablesCount = CountPrintableCharacters(wideString);
if (printablesCount == 0)
return;
outQuads.reserve(printablesCount);
// tokenize text
struct LineWord
{
std::wstring_view::const_iterator begin_it;
std::wstring_view::const_iterator end_it;
int wordWidth = 0;
};
struct LineEntry
{
Temp_List<LineWord> wordsList;
int lineWidth = 0;
};
Temp_List<LineEntry> linesList;
linesList.emplace_back();
for (auto curr_char_it = wideString.begin(), string_end_it = wideString.end();
curr_char_it != string_end_it; )
{
// get next word
LineWord currWord;
currWord.begin_it = curr_char_it;
currWord.end_it = std::find_if(curr_char_it + 1, string_end_it, [](wchar_t wideChar){ return wideChar <= L' '; });
for (auto word_it = currWord.begin_it; word_it != currWord.end_it; ++word_it)
{
const CharEntry& fontchar = GetCharEntry(*word_it);
int spacew = (fontchar.mRect.w == 0) ? fontchar.mOuterWidth : fontchar.mRect.w;
if (spacew > 0)
{
currWord.wordWidth += fontchar.mOuterWidth;
}
}
if (currWord.wordWidth > 0)
{
// word wrap detection logic
if (hasHorzBounds)
{
int currWidth = linesList.back().lineWidth;
if ((currWidth > 0) && ((currWidth + currWord.wordWidth) > rect.w))
{
// line overflow, move to next line
LineEntry& nextLine = linesList.emplace_back();
}
}
// append word
LineEntry& currLine = linesList.back();
currLine.lineWidth += currWord.wordWidth;
currLine.wordsList.push_back(currWord);
}
curr_char_it = currWord.end_it;
if ((curr_char_it == string_end_it) || (*curr_char_it == 0)) break;
if (*curr_char_it == L'\n')
{
// start new line
linesList.emplace_back();
}
}
int currY = rect.y;
for (const LineEntry& currLine: linesList)
{
int currX = rect.x;
if (hasHorzBounds && (currLine.lineWidth <= rect.w))
{
switch (horzAlign)
{
case eTextHorzAlignment_Center:
currX = (rect.w / 2) - currLine.lineWidth / 2;
break;
case eTextHorzAlignment_Right:
currX = (rect.x + rect.w - 1) - currLine.lineWidth;
break;
}
}
for (const LineWord& currWord: currLine.wordsList)
{
for (auto it = currWord.begin_it; it != currWord.end_it; ++it)
{
wchar_t wideChar = *it;
if (wideChar < L' ') continue;
const CharEntry& fontchar = GetCharEntry(wideChar);
int spacew = (fontchar.mRect.w == 0) ? fontchar.mOuterWidth : fontchar.mRect.w;
if (spacew == 0)
continue;
if (wideChar == L' ')
{
currX += spacew;
continue;
}
Quad2D& characterQuad = outQuads.emplace_back();
// setup quad vertices in specific order
characterQuad.mPoints[0].mColor = color;
characterQuad.mPoints[0].mTexcoord[0] = fontchar.mTexcoords.mU0;
characterQuad.mPoints[0].mTexcoord[1] = fontchar.mTexcoords.mV0;
characterQuad.mPoints[0].mPosition.x = (currX + fontchar.mOffset.x) * 1.0f;
characterQuad.mPoints[0].mPosition.y = (currY + fontchar.mOffset.y) * 1.0f;
characterQuad.mPoints[1].mColor = color;
characterQuad.mPoints[1].mTexcoord[0] = fontchar.mTexcoords.mU0;
characterQuad.mPoints[1].mTexcoord[1] = fontchar.mTexcoords.mV1;
characterQuad.mPoints[1].mPosition.x = (currX + fontchar.mOffset.x) * 1.0f;
characterQuad.mPoints[1].mPosition.y = (currY + fontchar.mRect.h + fontchar.mOffset.y) * 1.0f;
characterQuad.mPoints[2].mColor = color;
characterQuad.mPoints[2].mTexcoord[0] = fontchar.mTexcoords.mU1;
characterQuad.mPoints[2].mTexcoord[1] = fontchar.mTexcoords.mV1;
characterQuad.mPoints[2].mPosition.x = (currX + fontchar.mOffset.x + spacew) * 1.0f;
characterQuad.mPoints[2].mPosition.y = (currY + fontchar.mRect.h + fontchar.mOffset.y) * 1.0f;
characterQuad.mPoints[3].mColor = color;
characterQuad.mPoints[3].mTexcoord[0] = fontchar.mTexcoords.mU1;
characterQuad.mPoints[3].mTexcoord[1] = fontchar.mTexcoords.mV0;
characterQuad.mPoints[3].mPosition.x = (currX + fontchar.mOffset.x + spacew) * 1.0f;
characterQuad.mPoints[3].mPosition.y = (currY + fontchar.mOffset.y) * 1.0f;
currX += fontchar.mOuterWidth;
}
}
currY += mLineHeight;
}
}
Point2D Font::ComputeTextDims(const std::wstring_view& wideString) const
{
Point2D resultDims { 0, 0 };
for (wchar_t wideChar: wideString)
{
if (wideChar == 0) break;
if (wideChar == L'\n')
{
resultDims.x = 0;
resultDims.y += mLineHeight;
continue;
}
if (wideChar < L' ') continue;
const CharEntry& charEntry = GetCharEntry(wideChar);
int spacew = (charEntry.mRect.w == 0) ? charEntry.mOuterWidth : charEntry.mRect.w;
if (spacew == 0)
continue;
if (wideChar == L' ')
{
resultDims.x += spacew;
continue;
}
resultDims.x += charEntry.mOuterWidth;
}
return resultDims;
}
int Font::CountPrintableCharacters(const std::wstring_view& wideString) const
{
int printablesCount = 0;
for (wchar_t wideChar: wideString)
{
if (wideChar == 0) break;
if (wideChar <= L' ')
continue;
const CharEntry& charEntry = GetCharEntry(wideChar);
int spacew = (charEntry.mRect.w == 0) ? charEntry.mOuterWidth : charEntry.mRect.w;
if (spacew == 0)
continue;
++printablesCount;
}
return printablesCount;
}
bool Font::LoadFont_FromFile()
{
bool bmfont = false;
const std::string& fontName = mFontName;
if (fontName.empty())
{
cxx_assert(false);
return false;
}
std::string fontFilePath;
if (!gFiles.LocateFont(fontName + ".bf4", fontFilePath))
{
if (gFiles.LocateFont(fontName + ".fnt", fontFilePath))
{
bmfont = true;
}
else
{
gConsole.LogMessage(eLogLevel_Warning, "Cannot locate font file '%s'", fontName.c_str());
return false;
}
}
std::ifstream fileStream(fontFilePath, std::ios::in | std::ios::binary);
if (!fileStream.is_open())
{
gConsole.LogMessage(eLogLevel_Warning, "Cannot open font file '%s'", fontName.c_str());
return false;
}
bool isSuccess = bmfont ?
LoadFont_BMF(fileStream) :
LoadFont_BF4(fileStream);
if (isSuccess)
{
InitTexcoords();
}
else
{
gConsole.LogMessage(eLogLevel_Warning, "Cannot load font data '%s'", fontName.c_str());
}
return isSuccess;
}
bool Font::LoadFont_BF4(std::istream& bitstream)
{
DK2FontDesc bf4Font;
if (!DK2_BF4_LoadFromStream(bitstream, bf4Font))
{
gConsole.LogMessage(eLogLevel_Warning, "BF4 font reading failed");
return false;
}
mLineHeight = bf4Font.mMaxHeight;
// setup glyphs
int numCharacters = 0;
for (const DK2FontEntry& fontChracter: bf4Font.mEntries)
{
CharEntry& charEntry = (fontChracter.mCharacter < AnsiCharsCount) ?
mAnsiChars[fontChracter.mCharacter] :
mWideChars[fontChracter.mCharacter];
charEntry.mRect.h = fontChracter.mHeight;
charEntry.mRect.w = fontChracter.mWidth;
charEntry.mOffset.x = fontChracter.mOffsetX;
charEntry.mOffset.y = fontChracter.mOffsetY;
charEntry.mOuterWidth = fontChracter.mOuterWidth;
++numCharacters; // num specified characters
}
std::vector<stbrp_node> stbrp_nodes(MaxAtlasSize);
std::vector<stbrp_rect> stbrp_rects(numCharacters);
// prepare characters
for (int ichar = 0, icurr = 0, MAX = bf4Font.mEntries.size(); ichar < MAX; ++ichar)
{
if (bf4Font.mEntries[ichar].mHeight > 0 && bf4Font.mEntries[ichar].mWidth > 0)
{
stbrp_rects[icurr].id = ichar;
stbrp_rects[icurr].w = bf4Font.mEntries[ichar].mWidth + 2;
stbrp_rects[icurr].h = bf4Font.mEntries[ichar].mHeight + 2;
++icurr;
}
}
int currentAtlasSizeX = 128;
int currentAtlasSizeY = 128;
int nn = 0;
for (bool isPacked = false; !isPacked; ++nn)
{
// reset status
for (stbrp_rect& rc: stbrp_rects)
{
rc.was_packed = 0;
}
stbrp_context context;
stbrp_init_target(&context, currentAtlasSizeX, currentAtlasSizeY, stbrp_nodes.data(), stbrp_nodes.size());
isPacked = stbrp_pack_rects(&context, stbrp_rects.data(), stbrp_rects.size()) > 0;
if (!isPacked)
{
if (nn & 1) { currentAtlasSizeY <<= 1; } // increase size
else { currentAtlasSizeX <<= 1; } // increase size
if ((currentAtlasSizeX > MaxAtlasSize) ||
(currentAtlasSizeY > MaxAtlasSize))
{
gConsole.LogMessage(eLogLevel_Warning, "BF4 font atlas generation exceeds size limit");
return false;
}
}
}
for (const stbrp_rect& rc: stbrp_rects)
{
wchar_t char_index = bf4Font.mEntries[rc.id].mCharacter;
CharEntry& charEntry = (char_index < AnsiCharsCount) ? mAnsiChars[char_index] : mWideChars[char_index];
charEntry.mRect.x = rc.x;
charEntry.mRect.y = rc.y;
}
// generate atlas
Point2D atlasDims { currentAtlasSizeX, currentAtlasSizeY };
if (!mAtlasBitmap.Create(ePixelFormat_R8, atlasDims, nullptr))
{
gConsole.LogMessage(eLogLevel_Warning, "BM4 font atlas pixels allocation failed");
return nullptr;
}
mAtlasBitmap.SetHasAlphaHint(true);
unsigned char* sourceImagePixels = mAtlasBitmap.GetMipPixels(0);
cxx_assert(sourceImagePixels);
for (int iy = 0; iy < currentAtlasSizeY; ++iy)
{
for (int ix = 0; ix < currentAtlasSizeX; ++ix)
{
sourceImagePixels[iy * currentAtlasSizeX + ix] = 0;
}
}
for (stbrp_rect& rc: stbrp_rects)
{
unsigned char* char_pixels = bf4Font.mEntries[rc.id].mImage.data();
// copy pixels
const int char_real_w = bf4Font.mEntries[rc.id].mWidth;
const int char_real_h = bf4Font.mEntries[rc.id].mHeight;
for (int iy = 0; iy < char_real_h; ++iy)
{
for (int ix = 0; ix < char_real_w; ++ix)
{
sourceImagePixels[(iy + rc.y) * currentAtlasSizeX + (ix + rc.x)] = char_pixels[iy * char_real_w + ix];
}
}
}
return true;
}
bool Font::LoadFont_BMF(std::istream& bitstream)
{
BMFontMetadata metadata;
BMFontError errorcode;
if (!BMFontReadMetadata(bitstream, metadata, errorcode))
{
gConsole.LogMessage(eLogLevel_Warning, "BMFont metadata reading failed, error '%s'", ToString(errorcode));
return false;
}
std::string textureName = cxx::va("fonts/%s", metadata.mInfoEx.mTextureName);
std::string resourcePath;
if (gFiles.PathToFile(textureName, resourcePath))
{
if (!mAtlasBitmap.LoadFromFile(resourcePath))
{
gConsole.LogMessage(eLogLevel_Warning, "BMFont atlas loading error, '%s'", textureName.c_str());
return false;
}
}
else
{
gConsole.LogMessage(eLogLevel_Warning, "BMFont atlas missing '%s'", textureName.c_str());
return false;
}
const int CharactersCount = std::min<int>(AnsiCharsCount, BMFONT_NUMCHARS);
for (int ichar = 0; ichar < CharactersCount; ++ichar)
{
BMFontBlockChar& srcChar = metadata.mChars[ichar];
CharEntry& dstChar = mAnsiChars[ichar];
dstChar.mOffset.x = srcChar.mOffsetX;
dstChar.mOffset.y = srcChar.mOffsetY;
dstChar.mRect.x = srcChar.mX;
dstChar.mRect.y = srcChar.mY;
dstChar.mRect.w = srcChar.mW;
dstChar.mRect.h = srcChar.mH;
dstChar.mOuterWidth = srcChar.mAdvanceX;
}
mLineHeight = metadata.mCommon.mLineHeight;
return true;
}
void Font::InitTexcoords()
{
if (!mAtlasBitmap.HasContent())
{
cxx_assert(false);
return;
}
const Point2D atlasDimensions = mAtlasBitmap.GetDimensions();
// compute texture coordinates
float tcx = 1.0f / atlasDimensions.x;
float tcy = 1.0f / atlasDimensions.y;
for (CharEntry& roller: mAnsiChars)
{
roller.mTexcoords.mU0 = (roller.mRect.x * tcx);
roller.mTexcoords.mV0 = (roller.mRect.y * tcy);
roller.mTexcoords.mU1 = (roller.mRect.x + roller.mRect.w) * tcx;
roller.mTexcoords.mV1 = (roller.mRect.y + roller.mRect.h) * tcy;
}
for (auto& roller: mWideChars)
{
CharEntry& charEntry = roller.second;
charEntry.mTexcoords.mU0 = (charEntry.mRect.x * tcx);
charEntry.mTexcoords.mV0 = (charEntry.mRect.y * tcy);
charEntry.mTexcoords.mU1 = (charEntry.mRect.x + charEntry.mRect.w) * tcx;
charEntry.mTexcoords.mV1 = (charEntry.mRect.y + charEntry.mRect.h) * tcy;
}
}