forked from godotengine/godot
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtext_server_fb.cpp
4822 lines (4106 loc) · 160 KB
/
text_server_fb.cpp
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************************************************************/
/* text_server_fb.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "text_server_fb.h"
#ifdef GDEXTENSION
// Headers for building as GDExtension plug-in.
#include <godot_cpp/classes/file_access.hpp>
#include <godot_cpp/classes/os.hpp>
#include <godot_cpp/classes/project_settings.hpp>
#include <godot_cpp/classes/rendering_server.hpp>
#include <godot_cpp/classes/translation_server.hpp>
#include <godot_cpp/core/error_macros.hpp>
#define OT_TAG(m_c1, m_c2, m_c3, m_c4) ((int32_t)((((uint32_t)(m_c1) & 0xff) << 24) | (((uint32_t)(m_c2) & 0xff) << 16) | (((uint32_t)(m_c3) & 0xff) << 8) | ((uint32_t)(m_c4) & 0xff)))
using namespace godot;
#define GLOBAL_GET(m_var) ProjectSettings::get_singleton()->get_setting_with_override(m_var)
#elif defined(GODOT_MODULE)
// Headers for building as built-in module.
#include "core/config/project_settings.h"
#include "core/error/error_macros.h"
#include "core/string/print_string.h"
#include "core/string/translation_server.h"
#include "modules/modules_enabled.gen.h" // For freetype, msdfgen, svg.
#endif
// Thirdparty headers.
#ifdef MODULE_MSDFGEN_ENABLED
#ifdef _MSC_VER
#pragma warning(disable : 4458)
#endif
#include <core/EdgeHolder.h>
#include <core/ShapeDistanceFinder.h>
#include <core/contour-combiners.h>
#include <core/edge-selectors.h>
#include <msdfgen.h>
#ifdef _MSC_VER
#pragma warning(default : 4458)
#endif
#endif
#ifdef MODULE_FREETYPE_ENABLED
#include FT_SFNT_NAMES_H
#include FT_TRUETYPE_IDS_H
#ifdef MODULE_SVG_ENABLED
#include "thorvg_svg_in_ot.h"
#endif
#endif
/*************************************************************************/
bool TextServerFallback::_has_feature(Feature p_feature) const {
switch (p_feature) {
case FEATURE_SIMPLE_LAYOUT:
case FEATURE_FONT_BITMAP:
#ifdef MODULE_FREETYPE_ENABLED
case FEATURE_FONT_DYNAMIC:
#endif
#ifdef MODULE_MSDFGEN_ENABLED
case FEATURE_FONT_MSDF:
#endif
return true;
default: {
}
}
return false;
}
String TextServerFallback::_get_name() const {
#ifdef GDEXTENSION
return "Fallback (GDExtension)";
#elif defined(GODOT_MODULE)
return "Fallback (Built-in)";
#endif
}
int64_t TextServerFallback::_get_features() const {
int64_t interface_features = FEATURE_SIMPLE_LAYOUT | FEATURE_FONT_BITMAP;
#ifdef MODULE_FREETYPE_ENABLED
interface_features |= FEATURE_FONT_DYNAMIC;
#endif
#ifdef MODULE_MSDFGEN_ENABLED
interface_features |= FEATURE_FONT_MSDF;
#endif
return interface_features;
}
void TextServerFallback::_free_rid(const RID &p_rid) {
_THREAD_SAFE_METHOD_
if (font_owner.owns(p_rid)) {
MutexLock ftlock(ft_mutex);
FontFallback *fd = font_owner.get_or_null(p_rid);
{
MutexLock lock(fd->mutex);
font_owner.free(p_rid);
}
memdelete(fd);
} else if (font_var_owner.owns(p_rid)) {
MutexLock ftlock(ft_mutex);
FontFallbackLinkedVariation *fdv = font_var_owner.get_or_null(p_rid);
{
font_var_owner.free(p_rid);
}
memdelete(fdv);
} else if (shaped_owner.owns(p_rid)) {
ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_rid);
{
MutexLock lock(sd->mutex);
shaped_owner.free(p_rid);
}
memdelete(sd);
}
}
bool TextServerFallback::_has(const RID &p_rid) {
_THREAD_SAFE_METHOD_
return font_owner.owns(p_rid) || shaped_owner.owns(p_rid);
}
String TextServerFallback::_get_support_data_filename() const {
return "";
}
String TextServerFallback::_get_support_data_info() const {
return "Not supported";
}
bool TextServerFallback::_load_support_data(const String &p_filename) {
return false; // No extra data used.
}
bool TextServerFallback::_save_support_data(const String &p_filename) const {
return false; // No extra data used.
}
PackedByteArray TextServerFallback::_get_support_data() const {
return PackedByteArray(); // No extra data used.
}
bool TextServerFallback::_is_locale_right_to_left(const String &p_locale) const {
return false; // No RTL support.
}
_FORCE_INLINE_ void TextServerFallback::_insert_feature(const StringName &p_name, int32_t p_tag) {
feature_sets.insert(p_name, p_tag);
feature_sets_inv.insert(p_tag, p_name);
}
void TextServerFallback::_insert_feature_sets() {
// Registered OpenType variation tag.
_insert_feature("italic", OT_TAG('i', 't', 'a', 'l'));
_insert_feature("optical_size", OT_TAG('o', 'p', 's', 'z'));
_insert_feature("slant", OT_TAG('s', 'l', 'n', 't'));
_insert_feature("width", OT_TAG('w', 'd', 't', 'h'));
_insert_feature("weight", OT_TAG('w', 'g', 'h', 't'));
}
_FORCE_INLINE_ int32_t ot_tag_from_string(const char *p_str, int p_len) {
char tag[4];
uint32_t i;
if (!p_str || !p_len || !*p_str) {
return OT_TAG(0, 0, 0, 0);
}
if (p_len < 0 || p_len > 4) {
p_len = 4;
}
for (i = 0; i < (uint32_t)p_len && p_str[i]; i++) {
tag[i] = p_str[i];
}
for (; i < 4; i++) {
tag[i] = ' ';
}
return OT_TAG(tag[0], tag[1], tag[2], tag[3]);
}
int64_t TextServerFallback::_name_to_tag(const String &p_name) const {
if (feature_sets.has(p_name)) {
return feature_sets[p_name];
}
// No readable name, use tag string.
return ot_tag_from_string(p_name.replace("custom_", "").ascii().get_data(), -1);
}
_FORCE_INLINE_ void ot_tag_to_string(int32_t p_tag, char *p_buf) {
p_buf[0] = (char)(uint8_t)(p_tag >> 24);
p_buf[1] = (char)(uint8_t)(p_tag >> 16);
p_buf[2] = (char)(uint8_t)(p_tag >> 8);
p_buf[3] = (char)(uint8_t)(p_tag >> 0);
}
String TextServerFallback::_tag_to_name(int64_t p_tag) const {
if (feature_sets_inv.has(p_tag)) {
return feature_sets_inv[p_tag];
}
// No readable name, use tag string.
char name[5];
memset(name, 0, 5);
ot_tag_to_string(p_tag, name);
return String("custom_") + String(name);
}
/*************************************************************************/
/* Font Glyph Rendering */
/*************************************************************************/
_FORCE_INLINE_ TextServerFallback::FontTexturePosition TextServerFallback::find_texture_pos_for_glyph(FontForSizeFallback *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height, bool p_msdf) const {
FontTexturePosition ret;
int mw = p_width;
int mh = p_height;
ShelfPackTexture *ct = p_data->textures.ptrw();
for (int32_t i = 0; i < p_data->textures.size(); i++) {
if (ct[i].image.is_null()) {
continue;
}
if (p_image_format != ct[i].image->get_format()) {
continue;
}
if (mw > ct[i].texture_w || mh > ct[i].texture_h) { // Too big for this texture.
continue;
}
ret = ct[i].pack_rect(i, mh, mw);
if (ret.index != -1) {
break;
}
}
if (ret.index == -1) {
// Could not find texture to fit, create one.
int texsize = MAX(p_data->size.x * p_data->oversampling * 8, 256);
texsize = next_power_of_2(texsize);
if (p_msdf) {
texsize = MIN(texsize, 2048);
} else {
texsize = MIN(texsize, 1024);
}
if (mw > texsize) { // Special case, adapt to it?
texsize = next_power_of_2(mw);
}
if (mh > texsize) { // Special case, adapt to it?
texsize = next_power_of_2(mh);
}
ShelfPackTexture tex = ShelfPackTexture(texsize, texsize);
tex.image = Image::create_empty(texsize, texsize, false, p_image_format);
{
// Zero texture.
uint8_t *w = tex.image->ptrw();
ERR_FAIL_COND_V(texsize * texsize * p_color_size > tex.image->get_data_size(), ret);
// Initialize the texture to all-white pixels to prevent artifacts when the
// font is displayed at a non-default scale with filtering enabled.
if (p_color_size == 2) {
for (int i = 0; i < texsize * texsize * p_color_size; i += 2) { // FORMAT_LA8, BW font.
w[i + 0] = 255;
w[i + 1] = 0;
}
} else if (p_color_size == 4) {
for (int i = 0; i < texsize * texsize * p_color_size; i += 4) { // FORMAT_RGBA8, Color font, Multichannel(+True) SDF.
w[i + 0] = 255;
w[i + 1] = 255;
w[i + 2] = 255;
w[i + 3] = 0;
}
} else {
ERR_FAIL_V(ret);
}
}
p_data->textures.push_back(tex);
int32_t idx = p_data->textures.size() - 1;
ret = p_data->textures.write[idx].pack_rect(idx, mh, mw);
}
return ret;
}
#ifdef MODULE_MSDFGEN_ENABLED
struct MSContext {
msdfgen::Point2 position;
msdfgen::Shape *shape = nullptr;
msdfgen::Contour *contour = nullptr;
};
class DistancePixelConversion {
double invRange;
public:
_FORCE_INLINE_ explicit DistancePixelConversion(double range) :
invRange(1 / range) {}
_FORCE_INLINE_ void operator()(float *pixels, const msdfgen::MultiAndTrueDistance &distance) const {
pixels[0] = float(invRange * distance.r + .5);
pixels[1] = float(invRange * distance.g + .5);
pixels[2] = float(invRange * distance.b + .5);
pixels[3] = float(invRange * distance.a + .5);
}
};
struct MSDFThreadData {
msdfgen::Bitmap<float, 4> *output;
msdfgen::Shape *shape;
msdfgen::Projection *projection;
DistancePixelConversion *distancePixelConversion;
};
static msdfgen::Point2 ft_point2(const FT_Vector &vector) {
return msdfgen::Point2(vector.x / 60.0f, vector.y / 60.0f);
}
static int ft_move_to(const FT_Vector *to, void *user) {
MSContext *context = static_cast<MSContext *>(user);
if (!(context->contour && context->contour->edges.empty())) {
context->contour = &context->shape->addContour();
}
context->position = ft_point2(*to);
return 0;
}
static int ft_line_to(const FT_Vector *to, void *user) {
MSContext *context = static_cast<MSContext *>(user);
msdfgen::Point2 endpoint = ft_point2(*to);
if (endpoint != context->position) {
context->contour->addEdge(new msdfgen::LinearSegment(context->position, endpoint));
context->position = endpoint;
}
return 0;
}
static int ft_conic_to(const FT_Vector *control, const FT_Vector *to, void *user) {
MSContext *context = static_cast<MSContext *>(user);
context->contour->addEdge(new msdfgen::QuadraticSegment(context->position, ft_point2(*control), ft_point2(*to)));
context->position = ft_point2(*to);
return 0;
}
static int ft_cubic_to(const FT_Vector *control1, const FT_Vector *control2, const FT_Vector *to, void *user) {
MSContext *context = static_cast<MSContext *>(user);
context->contour->addEdge(new msdfgen::CubicSegment(context->position, ft_point2(*control1), ft_point2(*control2), ft_point2(*to)));
context->position = ft_point2(*to);
return 0;
}
void TextServerFallback::_generateMTSDF_threaded(void *p_td, uint32_t p_y) {
MSDFThreadData *td = static_cast<MSDFThreadData *>(p_td);
msdfgen::ShapeDistanceFinder<msdfgen::OverlappingContourCombiner<msdfgen::MultiAndTrueDistanceSelector>> distanceFinder(*td->shape);
int row = td->shape->inverseYAxis ? td->output->height() - p_y - 1 : p_y;
for (int col = 0; col < td->output->width(); ++col) {
int x = (p_y % 2) ? td->output->width() - col - 1 : col;
msdfgen::Point2 p = td->projection->unproject(msdfgen::Point2(x + .5, p_y + .5));
msdfgen::MultiAndTrueDistance distance = distanceFinder.distance(p);
td->distancePixelConversion->operator()(td->output->operator()(x, row), distance);
}
}
_FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_msdf(FontFallback *p_font_data, FontForSizeFallback *p_data, int p_pixel_range, int p_rect_margin, FT_Outline *p_outline, const Vector2 &p_advance) const {
msdfgen::Shape shape;
shape.contours.clear();
shape.inverseYAxis = false;
MSContext context = {};
context.shape = &shape;
FT_Outline_Funcs ft_functions;
ft_functions.move_to = &ft_move_to;
ft_functions.line_to = &ft_line_to;
ft_functions.conic_to = &ft_conic_to;
ft_functions.cubic_to = &ft_cubic_to;
ft_functions.shift = 0;
ft_functions.delta = 0;
int error = FT_Outline_Decompose(p_outline, &ft_functions, &context);
ERR_FAIL_COND_V_MSG(error, FontGlyph(), "FreeType: Outline decomposition error: '" + String(FT_Error_String(error)) + "'.");
if (!shape.contours.empty() && shape.contours.back().edges.empty()) {
shape.contours.pop_back();
}
if (FT_Outline_Get_Orientation(p_outline) == 1) {
for (int i = 0; i < (int)shape.contours.size(); ++i) {
shape.contours[i].reverse();
}
}
shape.inverseYAxis = true;
shape.normalize();
msdfgen::Shape::Bounds bounds = shape.getBounds(p_pixel_range);
FontGlyph chr;
chr.found = true;
chr.advance = p_advance;
if (shape.validate() && shape.contours.size() > 0) {
int w = (bounds.r - bounds.l);
int h = (bounds.t - bounds.b);
if (w == 0 || h == 0) {
chr.texture_idx = -1;
chr.uv_rect = Rect2();
chr.rect = Rect2();
return chr;
}
int mw = w + p_rect_margin * 4;
int mh = h + p_rect_margin * 4;
ERR_FAIL_COND_V(mw > 4096, FontGlyph());
ERR_FAIL_COND_V(mh > 4096, FontGlyph());
FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, 4, Image::FORMAT_RGBA8, mw, mh, true);
ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph());
ShelfPackTexture &tex = p_data->textures.write[tex_pos.index];
edgeColoringSimple(shape, 3.0); // Max. angle.
msdfgen::Bitmap<float, 4> image(w, h); // Texture size.
DistancePixelConversion distancePixelConversion(p_pixel_range);
msdfgen::Projection projection(msdfgen::Vector2(1.0, 1.0), msdfgen::Vector2(-bounds.l, -bounds.b));
msdfgen::MSDFGeneratorConfig config(true, msdfgen::ErrorCorrectionConfig());
MSDFThreadData td;
td.output = ℑ
td.shape = &shape;
td.projection = &projection;
td.distancePixelConversion = &distancePixelConversion;
WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_native_group_task(&TextServerFallback::_generateMTSDF_threaded, &td, h, -1, true, String("TextServerFBRenderMSDF"));
WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
msdfgen::msdfErrorCorrection(image, shape, projection, p_pixel_range, config);
{
uint8_t *wr = tex.image->ptrw();
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
int ofs = ((i + tex_pos.y + p_rect_margin * 2) * tex.texture_w + j + tex_pos.x + p_rect_margin * 2) * 4;
ERR_FAIL_COND_V(ofs >= tex.image->get_data_size(), FontGlyph());
wr[ofs + 0] = (uint8_t)(CLAMP(image(j, i)[0] * 256.f, 0.f, 255.f));
wr[ofs + 1] = (uint8_t)(CLAMP(image(j, i)[1] * 256.f, 0.f, 255.f));
wr[ofs + 2] = (uint8_t)(CLAMP(image(j, i)[2] * 256.f, 0.f, 255.f));
wr[ofs + 3] = (uint8_t)(CLAMP(image(j, i)[3] * 256.f, 0.f, 255.f));
}
}
}
tex.dirty = true;
chr.texture_idx = tex_pos.index;
chr.uv_rect = Rect2(tex_pos.x + p_rect_margin, tex_pos.y + p_rect_margin, w + p_rect_margin * 2, h + p_rect_margin * 2);
chr.rect.position = Vector2(bounds.l - p_rect_margin, -bounds.t - p_rect_margin);
chr.rect.size = chr.uv_rect.size;
}
return chr;
}
#endif
#ifdef MODULE_FREETYPE_ENABLED
_FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_bitmap(FontForSizeFallback *p_data, int p_rect_margin, FT_Bitmap p_bitmap, int p_yofs, int p_xofs, const Vector2 &p_advance, bool p_bgra) const {
FontGlyph chr;
chr.advance = p_advance * p_data->scale / p_data->oversampling;
chr.found = true;
int w = p_bitmap.width;
int h = p_bitmap.rows;
if (w == 0 || h == 0) {
chr.texture_idx = -1;
chr.uv_rect = Rect2();
chr.rect = Rect2();
return chr;
}
int color_size = 2;
switch (p_bitmap.pixel_mode) {
case FT_PIXEL_MODE_MONO:
case FT_PIXEL_MODE_GRAY: {
color_size = 2;
} break;
case FT_PIXEL_MODE_BGRA: {
color_size = 4;
} break;
case FT_PIXEL_MODE_LCD: {
color_size = 4;
w /= 3;
} break;
case FT_PIXEL_MODE_LCD_V: {
color_size = 4;
h /= 3;
} break;
}
int mw = w + p_rect_margin * 4;
int mh = h + p_rect_margin * 4;
ERR_FAIL_COND_V(mw > 4096, FontGlyph());
ERR_FAIL_COND_V(mh > 4096, FontGlyph());
Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8;
FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, color_size, require_format, mw, mh, false);
ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph());
// Fit character in char texture.
ShelfPackTexture &tex = p_data->textures.write[tex_pos.index];
{
uint8_t *wr = tex.image->ptrw();
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
int ofs = ((i + tex_pos.y + p_rect_margin * 2) * tex.texture_w + j + tex_pos.x + p_rect_margin * 2) * color_size;
ERR_FAIL_COND_V(ofs >= tex.image->get_data_size(), FontGlyph());
switch (p_bitmap.pixel_mode) {
case FT_PIXEL_MODE_MONO: {
int byte = i * p_bitmap.pitch + (j >> 3);
int bit = 1 << (7 - (j % 8));
wr[ofs + 0] = 255; // grayscale as 1
wr[ofs + 1] = (p_bitmap.buffer[byte] & bit) ? 255 : 0;
} break;
case FT_PIXEL_MODE_GRAY:
wr[ofs + 0] = 255; // grayscale as 1
wr[ofs + 1] = p_bitmap.buffer[i * p_bitmap.pitch + j];
break;
case FT_PIXEL_MODE_BGRA: {
int ofs_color = i * p_bitmap.pitch + (j << 2);
wr[ofs + 2] = p_bitmap.buffer[ofs_color + 0];
wr[ofs + 1] = p_bitmap.buffer[ofs_color + 1];
wr[ofs + 0] = p_bitmap.buffer[ofs_color + 2];
wr[ofs + 3] = p_bitmap.buffer[ofs_color + 3];
} break;
case FT_PIXEL_MODE_LCD: {
int ofs_color = i * p_bitmap.pitch + (j * 3);
if (p_bgra) {
wr[ofs + 0] = p_bitmap.buffer[ofs_color + 2];
wr[ofs + 1] = p_bitmap.buffer[ofs_color + 1];
wr[ofs + 2] = p_bitmap.buffer[ofs_color + 0];
wr[ofs + 3] = 255;
} else {
wr[ofs + 0] = p_bitmap.buffer[ofs_color + 0];
wr[ofs + 1] = p_bitmap.buffer[ofs_color + 1];
wr[ofs + 2] = p_bitmap.buffer[ofs_color + 2];
wr[ofs + 3] = 255;
}
} break;
case FT_PIXEL_MODE_LCD_V: {
int ofs_color = i * p_bitmap.pitch * 3 + j;
if (p_bgra) {
wr[ofs + 0] = p_bitmap.buffer[ofs_color + p_bitmap.pitch * 2];
wr[ofs + 1] = p_bitmap.buffer[ofs_color + p_bitmap.pitch];
wr[ofs + 2] = p_bitmap.buffer[ofs_color + 0];
wr[ofs + 3] = 255;
} else {
wr[ofs + 0] = p_bitmap.buffer[ofs_color + 0];
wr[ofs + 1] = p_bitmap.buffer[ofs_color + p_bitmap.pitch];
wr[ofs + 2] = p_bitmap.buffer[ofs_color + p_bitmap.pitch * 2];
wr[ofs + 3] = 255;
}
} break;
default:
ERR_FAIL_V_MSG(FontGlyph(), "Font uses unsupported pixel format: " + String::num_int64(p_bitmap.pixel_mode) + ".");
break;
}
}
}
}
tex.dirty = true;
chr.texture_idx = tex_pos.index;
chr.uv_rect = Rect2(tex_pos.x + p_rect_margin, tex_pos.y + p_rect_margin, w + p_rect_margin * 2, h + p_rect_margin * 2);
chr.rect.position = Vector2(p_xofs - p_rect_margin, -p_yofs - p_rect_margin) * p_data->scale / p_data->oversampling;
chr.rect.size = chr.uv_rect.size * p_data->scale / p_data->oversampling;
return chr;
}
#endif
/*************************************************************************/
/* Font Cache */
/*************************************************************************/
_FORCE_INLINE_ bool TextServerFallback::_ensure_glyph(FontFallback *p_font_data, const Vector2i &p_size, int32_t p_glyph, FontGlyph &r_glyph) const {
FontForSizeFallback *fd = nullptr;
ERR_FAIL_COND_V(!_ensure_cache_for_size(p_font_data, p_size, fd), false);
int32_t glyph_index = p_glyph & 0xffffff; // Remove subpixel shifts.
HashMap<int32_t, FontGlyph>::Iterator E = fd->glyph_map.find(p_glyph);
if (E) {
r_glyph = E->value;
return E->value.found;
}
if (glyph_index == 0) { // Non graphical or invalid glyph, do not render.
E = fd->glyph_map.insert(p_glyph, FontGlyph());
r_glyph = E->value;
return true;
}
#ifdef MODULE_FREETYPE_ENABLED
FontGlyph gl;
if (fd->face) {
FT_Int32 flags = FT_LOAD_DEFAULT;
bool outline = p_size.y > 0;
switch (p_font_data->hinting) {
case TextServer::HINTING_NONE:
flags |= FT_LOAD_NO_HINTING;
break;
case TextServer::HINTING_LIGHT:
flags |= FT_LOAD_TARGET_LIGHT;
break;
default:
flags |= FT_LOAD_TARGET_NORMAL;
break;
}
if (p_font_data->force_autohinter) {
flags |= FT_LOAD_FORCE_AUTOHINT;
}
if (outline || (p_font_data->disable_embedded_bitmaps && !FT_HAS_COLOR(fd->face))) {
flags |= FT_LOAD_NO_BITMAP;
} else if (FT_HAS_COLOR(fd->face)) {
flags |= FT_LOAD_COLOR;
}
glyph_index = FT_Get_Char_Index(fd->face, glyph_index);
FT_Fixed v, h;
FT_Get_Advance(fd->face, glyph_index, flags, &h);
FT_Get_Advance(fd->face, glyph_index, flags | FT_LOAD_VERTICAL_LAYOUT, &v);
int error = FT_Load_Glyph(fd->face, glyph_index, flags);
if (error) {
E = fd->glyph_map.insert(p_glyph, FontGlyph());
r_glyph = E->value;
return false;
}
if (!p_font_data->msdf) {
if ((p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && p_size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) {
FT_Pos xshift = (int)((p_glyph >> 27) & 3) << 4;
FT_Outline_Translate(&fd->face->glyph->outline, xshift, 0);
} else if ((p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && p_size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) {
FT_Pos xshift = (int)((p_glyph >> 27) & 3) << 5;
FT_Outline_Translate(&fd->face->glyph->outline, xshift, 0);
}
}
if (p_font_data->embolden != 0.f) {
FT_Pos strength = p_font_data->embolden * p_size.x * fd->oversampling * 4; // 26.6 fractional units (1 / 64).
FT_Outline_Embolden(&fd->face->glyph->outline, strength);
}
if (p_font_data->transform != Transform2D()) {
FT_Matrix mat = { FT_Fixed(p_font_data->transform[0][0] * 65536), FT_Fixed(p_font_data->transform[0][1] * 65536), FT_Fixed(p_font_data->transform[1][0] * 65536), FT_Fixed(p_font_data->transform[1][1] * 65536) }; // 16.16 fractional units (1 / 65536).
FT_Outline_Transform(&fd->face->glyph->outline, &mat);
}
FT_Render_Mode aa_mode = FT_RENDER_MODE_NORMAL;
bool bgra = false;
switch (p_font_data->antialiasing) {
case FONT_ANTIALIASING_NONE: {
aa_mode = FT_RENDER_MODE_MONO;
} break;
case FONT_ANTIALIASING_GRAY: {
aa_mode = FT_RENDER_MODE_NORMAL;
} break;
case FONT_ANTIALIASING_LCD: {
int aa_layout = (int)((p_glyph >> 24) & 7);
switch (aa_layout) {
case FONT_LCD_SUBPIXEL_LAYOUT_HRGB: {
aa_mode = FT_RENDER_MODE_LCD;
bgra = false;
} break;
case FONT_LCD_SUBPIXEL_LAYOUT_HBGR: {
aa_mode = FT_RENDER_MODE_LCD;
bgra = true;
} break;
case FONT_LCD_SUBPIXEL_LAYOUT_VRGB: {
aa_mode = FT_RENDER_MODE_LCD_V;
bgra = false;
} break;
case FONT_LCD_SUBPIXEL_LAYOUT_VBGR: {
aa_mode = FT_RENDER_MODE_LCD_V;
bgra = true;
} break;
default: {
aa_mode = FT_RENDER_MODE_NORMAL;
} break;
}
} break;
}
if (!outline) {
if (!p_font_data->msdf) {
error = FT_Render_Glyph(fd->face->glyph, aa_mode);
}
FT_GlyphSlot slot = fd->face->glyph;
if (!error) {
if (p_font_data->msdf) {
#ifdef MODULE_MSDFGEN_ENABLED
gl = rasterize_msdf(p_font_data, fd, p_font_data->msdf_range, rect_range, &slot->outline, Vector2((h + (1 << 9)) >> 10, (v + (1 << 9)) >> 10) / 64.0);
#else
fd->glyph_map[p_glyph] = FontGlyph();
ERR_FAIL_V_MSG(false, "Compiled without MSDFGEN support!");
#endif
} else {
gl = rasterize_bitmap(fd, rect_range, slot->bitmap, slot->bitmap_top, slot->bitmap_left, Vector2((h + (1 << 9)) >> 10, (v + (1 << 9)) >> 10) / 64.0, bgra);
}
}
} else {
FT_Stroker stroker;
if (FT_Stroker_New(ft_library, &stroker) != 0) {
fd->glyph_map[p_glyph] = FontGlyph();
ERR_FAIL_V_MSG(false, "FreeType: Failed to load glyph stroker.");
}
FT_Stroker_Set(stroker, (int)(fd->size.y * fd->oversampling * 16.0), FT_STROKER_LINECAP_BUTT, FT_STROKER_LINEJOIN_ROUND, 0);
FT_Glyph glyph;
FT_BitmapGlyph glyph_bitmap;
if (FT_Get_Glyph(fd->face->glyph, &glyph) != 0) {
goto cleanup_stroker;
}
if (FT_Glyph_Stroke(&glyph, stroker, 1) != 0) {
goto cleanup_glyph;
}
if (FT_Glyph_To_Bitmap(&glyph, aa_mode, nullptr, 1) != 0) {
goto cleanup_glyph;
}
glyph_bitmap = (FT_BitmapGlyph)glyph;
gl = rasterize_bitmap(fd, rect_range, glyph_bitmap->bitmap, glyph_bitmap->top, glyph_bitmap->left, Vector2(), bgra);
cleanup_glyph:
FT_Done_Glyph(glyph);
cleanup_stroker:
FT_Stroker_Done(stroker);
}
E = fd->glyph_map.insert(p_glyph, gl);
r_glyph = E->value;
return gl.found;
}
#endif
E = fd->glyph_map.insert(p_glyph, FontGlyph());
r_glyph = E->value;
return false;
}
_FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontFallback *p_font_data, const Vector2i &p_size, FontForSizeFallback *&r_cache_for_size, bool p_silent) const {
ERR_FAIL_COND_V(p_size.x <= 0, false);
HashMap<Vector2i, FontForSizeFallback *>::Iterator E = p_font_data->cache.find(p_size);
if (E) {
r_cache_for_size = E->value;
return true;
}
r_cache_for_size = nullptr;
FontForSizeFallback *fd = memnew(FontForSizeFallback);
fd->size = p_size;
if (p_font_data->data_ptr && (p_font_data->data_size > 0)) {
// Init dynamic font.
#ifdef MODULE_FREETYPE_ENABLED
int error = 0;
{
MutexLock ftlock(ft_mutex);
if (!ft_library) {
error = FT_Init_FreeType(&ft_library);
if (error != 0) {
memdelete(fd);
if (p_silent) {
return false;
} else {
ERR_FAIL_V_MSG(false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'.");
}
}
#ifdef MODULE_SVG_ENABLED
FT_Property_Set(ft_library, "ot-svg", "svg-hooks", get_tvg_svg_in_ot_hooks());
#endif
}
memset(&fd->stream, 0, sizeof(FT_StreamRec));
fd->stream.base = (unsigned char *)p_font_data->data_ptr;
fd->stream.size = p_font_data->data_size;
fd->stream.pos = 0;
FT_Open_Args fargs;
memset(&fargs, 0, sizeof(FT_Open_Args));
fargs.memory_base = (unsigned char *)p_font_data->data_ptr;
fargs.memory_size = p_font_data->data_size;
fargs.flags = FT_OPEN_MEMORY;
fargs.stream = &fd->stream;
int max_index = 0;
FT_Face tmp_face = nullptr;
error = FT_Open_Face(ft_library, &fargs, -1, &tmp_face);
if (tmp_face && error == 0) {
max_index = tmp_face->num_faces - 1;
}
if (tmp_face) {
FT_Done_Face(tmp_face);
}
error = FT_Open_Face(ft_library, &fargs, CLAMP(p_font_data->face_index, 0, max_index), &fd->face);
if (error) {
FT_Done_Face(fd->face);
fd->face = nullptr;
memdelete(fd);
if (p_silent) {
return false;
} else {
ERR_FAIL_V_MSG(false, "FreeType: Error loading font: '" + String(FT_Error_String(error)) + "'.");
}
}
}
if (p_font_data->msdf) {
fd->oversampling = 1.0;
fd->size.x = p_font_data->msdf_source_size;
} else if (p_font_data->oversampling <= 0.0) {
fd->oversampling = _font_get_global_oversampling();
} else {
fd->oversampling = p_font_data->oversampling;
}
if (FT_HAS_COLOR(fd->face) && fd->face->num_fixed_sizes > 0) {
int best_match = 0;
int diff = ABS(fd->size.x - ((int64_t)fd->face->available_sizes[0].width));
fd->scale = double(fd->size.x * fd->oversampling) / fd->face->available_sizes[0].width;
for (int i = 1; i < fd->face->num_fixed_sizes; i++) {
int ndiff = ABS(fd->size.x - ((int64_t)fd->face->available_sizes[i].width));
if (ndiff < diff) {
best_match = i;
diff = ndiff;
fd->scale = double(fd->size.x * fd->oversampling) / fd->face->available_sizes[i].width;
}
}
FT_Select_Size(fd->face, best_match);
} else {
FT_Set_Pixel_Sizes(fd->face, 0, Math::round(fd->size.x * fd->oversampling));
if (fd->face->size->metrics.y_ppem != 0) {
fd->scale = ((double)fd->size.x * fd->oversampling) / (double)fd->face->size->metrics.y_ppem;
}
}
fd->ascent = (fd->face->size->metrics.ascender / 64.0) / fd->oversampling * fd->scale;
fd->descent = (-fd->face->size->metrics.descender / 64.0) / fd->oversampling * fd->scale;
fd->underline_position = (-FT_MulFix(fd->face->underline_position, fd->face->size->metrics.y_scale) / 64.0) / fd->oversampling * fd->scale;
fd->underline_thickness = (FT_MulFix(fd->face->underline_thickness, fd->face->size->metrics.y_scale) / 64.0) / fd->oversampling * fd->scale;
if (!p_font_data->face_init) {
// When a font does not provide a `family_name`, FreeType tries to synthesize one based on other names.
// FreeType automatically converts non-ASCII characters to "?" in the synthesized name.
// To avoid that behavior, use the format-specific name directly if available.
if (FT_IS_SFNT(fd->face)) {
int name_count = FT_Get_Sfnt_Name_Count(fd->face);
for (int i = 0; i < name_count; i++) {
FT_SfntName sfnt_name;
if (FT_Get_Sfnt_Name(fd->face, i, &sfnt_name) != 0) {
continue;
}
if (sfnt_name.name_id != TT_NAME_ID_FONT_FAMILY && sfnt_name.name_id != TT_NAME_ID_TYPOGRAPHIC_FAMILY) {
continue;
}
if (!p_font_data->font_name.is_empty() && sfnt_name.language_id != TT_MS_LANGID_ENGLISH_UNITED_STATES) {
continue;
}
switch (sfnt_name.platform_id) {
case TT_PLATFORM_APPLE_UNICODE: {
p_font_data->font_name.parse_utf16((const char16_t *)sfnt_name.string, sfnt_name.string_len / 2, false);
} break;
case TT_PLATFORM_MICROSOFT: {
if (sfnt_name.encoding_id == TT_MS_ID_UNICODE_CS || sfnt_name.encoding_id == TT_MS_ID_UCS_4) {
p_font_data->font_name.parse_utf16((const char16_t *)sfnt_name.string, sfnt_name.string_len / 2, false);
}
} break;
}
}
}
if (p_font_data->font_name.is_empty() && fd->face->family_name != nullptr) {
p_font_data->font_name = String::utf8((const char *)fd->face->family_name);
}
if (fd->face->style_name != nullptr) {
p_font_data->style_name = String::utf8((const char *)fd->face->style_name);
}
p_font_data->weight = _font_get_weight_by_name(p_font_data->style_name.to_lower());
p_font_data->stretch = _font_get_stretch_by_name(p_font_data->style_name.to_lower());
p_font_data->style_flags = 0;
if ((fd->face->style_flags & FT_STYLE_FLAG_BOLD) || p_font_data->weight >= 700) {
p_font_data->style_flags.set_flag(FONT_BOLD);
}
if ((fd->face->style_flags & FT_STYLE_FLAG_ITALIC) || _is_ital_style(p_font_data->style_name.to_lower())) {
p_font_data->style_flags.set_flag(FONT_ITALIC);
}
if (fd->face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) {
p_font_data->style_flags.set_flag(FONT_FIXED_WIDTH);
}
// Read OpenType variations.
p_font_data->supported_varaitions.clear();
if (fd->face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
FT_MM_Var *amaster;
FT_Get_MM_Var(fd->face, &amaster);
for (FT_UInt i = 0; i < amaster->num_axis; i++) {
p_font_data->supported_varaitions[(int32_t)amaster->axis[i].tag] = Vector3i(amaster->axis[i].minimum / 65536, amaster->axis[i].maximum / 65536, amaster->axis[i].def / 65536);
}
FT_Done_MM_Var(ft_library, amaster);
}
p_font_data->face_init = true;
}
// Write variations.
if (fd->face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
FT_MM_Var *amaster;
FT_Get_MM_Var(fd->face, &amaster);
Vector<FT_Fixed> coords;
coords.resize(amaster->num_axis);
FT_Get_Var_Design_Coordinates(fd->face, coords.size(), coords.ptrw());
for (FT_UInt i = 0; i < amaster->num_axis; i++) {
// Reset to default.
int32_t var_tag = amaster->axis[i].tag;
double var_value = (double)amaster->axis[i].def / 65536.0;
coords.write[i] = amaster->axis[i].def;
if (p_font_data->variation_coordinates.has(var_tag)) {
var_value = p_font_data->variation_coordinates[var_tag];
coords.write[i] = CLAMP(var_value * 65536.0, amaster->axis[i].minimum, amaster->axis[i].maximum);
}
if (p_font_data->variation_coordinates.has(tag_to_name(var_tag))) {
var_value = p_font_data->variation_coordinates[tag_to_name(var_tag)];
coords.write[i] = CLAMP(var_value * 65536.0, amaster->axis[i].minimum, amaster->axis[i].maximum);
}
}
FT_Set_Var_Design_Coordinates(fd->face, coords.size(), coords.ptrw());
FT_Done_MM_Var(ft_library, amaster);
}
#else
memdelete(fd);
if (p_silent) {
return false;
} else {
ERR_FAIL_V_MSG(false, "FreeType: Can't load dynamic font, engine is compiled without FreeType support!");
}