dynamic_font.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  1. /**************************************************************************/
  2. /* dynamic_font.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "modules/modules_enabled.gen.h" // For freetype.
  31. #ifdef MODULE_FREETYPE_ENABLED
  32. #include "dynamic_font.h"
  33. #include "core/os/file_access.h"
  34. #include "core/os/os.h"
  35. #include FT_STROKER_H
  36. #define __STDC_LIMIT_MACROS
  37. #include <stdint.h>
  38. bool DynamicFontData::CacheID::operator<(CacheID right) const {
  39. return key < right.key;
  40. }
  41. Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(CacheID p_cache_id) {
  42. if (size_cache.has(p_cache_id)) {
  43. return Ref<DynamicFontAtSize>(size_cache[p_cache_id]);
  44. }
  45. Ref<DynamicFontAtSize> dfas;
  46. dfas.instance();
  47. dfas->font = Ref<DynamicFontData>(this);
  48. dfas->oversampling = (override_oversampling > 0) ? override_oversampling : DynamicFontAtSize::font_oversampling;
  49. size_cache[p_cache_id] = dfas.ptr();
  50. dfas->id = p_cache_id;
  51. dfas->_load();
  52. return dfas;
  53. }
  54. void DynamicFontData::set_font_ptr(const uint8_t *p_font_mem, int p_font_mem_size) {
  55. font_mem = p_font_mem;
  56. font_mem_size = p_font_mem_size;
  57. }
  58. void DynamicFontData::set_font_path(const String &p_path) {
  59. font_path = p_path;
  60. }
  61. String DynamicFontData::get_font_path() const {
  62. return font_path;
  63. }
  64. void DynamicFontData::set_force_autohinter(bool p_force) {
  65. force_autohinter = p_force;
  66. }
  67. float DynamicFontData::get_override_oversampling() const {
  68. return override_oversampling;
  69. }
  70. void DynamicFontData::set_override_oversampling(float p_oversampling) {
  71. if (override_oversampling == p_oversampling) {
  72. return;
  73. }
  74. override_oversampling = p_oversampling;
  75. DynamicFont::update_oversampling();
  76. }
  77. void DynamicFontData::_bind_methods() {
  78. ClassDB::bind_method(D_METHOD("set_antialiased", "antialiased"), &DynamicFontData::set_antialiased);
  79. ClassDB::bind_method(D_METHOD("is_antialiased"), &DynamicFontData::is_antialiased);
  80. ClassDB::bind_method(D_METHOD("set_font_path", "path"), &DynamicFontData::set_font_path);
  81. ClassDB::bind_method(D_METHOD("get_font_path"), &DynamicFontData::get_font_path);
  82. ClassDB::bind_method(D_METHOD("set_hinting", "mode"), &DynamicFontData::set_hinting);
  83. ClassDB::bind_method(D_METHOD("get_hinting"), &DynamicFontData::get_hinting);
  84. ClassDB::bind_method(D_METHOD("get_override_oversampling"), &DynamicFontData::get_override_oversampling);
  85. ClassDB::bind_method(D_METHOD("set_override_oversampling", "oversampling"), &DynamicFontData::set_override_oversampling);
  86. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "antialiased"), "set_antialiased", "is_antialiased");
  87. ADD_PROPERTY(PropertyInfo(Variant::INT, "hinting", PROPERTY_HINT_ENUM, "None,Light,Normal"), "set_hinting", "get_hinting");
  88. ADD_PROPERTY(PropertyInfo(Variant::REAL, "override_oversampling"), "set_override_oversampling", "get_override_oversampling");
  89. BIND_ENUM_CONSTANT(HINTING_NONE);
  90. BIND_ENUM_CONSTANT(HINTING_LIGHT);
  91. BIND_ENUM_CONSTANT(HINTING_NORMAL);
  92. // Only WOFF1 is supported as WOFF2 requires a Brotli decompression library to be linked.
  93. ADD_PROPERTY(PropertyInfo(Variant::STRING, "font_path", PROPERTY_HINT_FILE, "*.ttf,*.otf,*.woff,*.woff2"), "set_font_path", "get_font_path");
  94. }
  95. DynamicFontData::DynamicFontData() {
  96. antialiased = true;
  97. force_autohinter = false;
  98. hinting = DynamicFontData::HINTING_NORMAL;
  99. font_mem = nullptr;
  100. font_mem_size = 0;
  101. override_oversampling = 0.0;
  102. }
  103. DynamicFontData::~DynamicFontData() {
  104. }
  105. ////////////////////
  106. Error DynamicFontAtSize::_load() {
  107. int error = FT_Init_FreeType(&library);
  108. ERR_FAIL_COND_V_MSG(error != 0, ERR_CANT_CREATE, "Error initializing FreeType.");
  109. if (font->font_mem == nullptr && font->font_path != String()) {
  110. FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
  111. if (!f) {
  112. FT_Done_FreeType(library);
  113. ERR_FAIL_V_MSG(ERR_CANT_OPEN, "Cannot open font file '" + font->font_path + "'.");
  114. }
  115. uint64_t len = f->get_len();
  116. font->_fontdata = Vector<uint8_t>();
  117. font->_fontdata.resize(len);
  118. f->get_buffer(font->_fontdata.ptrw(), len);
  119. font->set_font_ptr(font->_fontdata.ptr(), len);
  120. f->close();
  121. memdelete(f);
  122. }
  123. if (font->font_mem) {
  124. memset(&stream, 0, sizeof(FT_StreamRec));
  125. stream.base = (unsigned char *)font->font_mem;
  126. stream.size = font->font_mem_size;
  127. stream.pos = 0;
  128. FT_Open_Args fargs;
  129. memset(&fargs, 0, sizeof(FT_Open_Args));
  130. fargs.memory_base = (unsigned char *)font->font_mem;
  131. fargs.memory_size = font->font_mem_size;
  132. fargs.flags = FT_OPEN_MEMORY;
  133. fargs.stream = &stream;
  134. error = FT_Open_Face(library, &fargs, 0, &face);
  135. } else {
  136. FT_Done_FreeType(library);
  137. ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "DynamicFont uninitialized.");
  138. }
  139. //error = FT_New_Face( library, src_path.utf8().get_data(),0,&face );
  140. if (error == FT_Err_Unknown_File_Format) {
  141. FT_Done_FreeType(library);
  142. ERR_FAIL_V_MSG(ERR_FILE_CANT_OPEN, "Unknown font format.");
  143. } else if (error) {
  144. FT_Done_FreeType(library);
  145. ERR_FAIL_V_MSG(ERR_FILE_CANT_OPEN, "Error loading font.");
  146. }
  147. if (FT_HAS_COLOR(face) && face->num_fixed_sizes > 0) {
  148. int best_match = 0;
  149. int diff = ABS(id.size - ((int64_t)face->available_sizes[0].width));
  150. scale_color_font = float(id.size * oversampling) / face->available_sizes[0].width;
  151. for (int i = 1; i < face->num_fixed_sizes; i++) {
  152. int ndiff = ABS(id.size - ((int64_t)face->available_sizes[i].width));
  153. if (ndiff < diff) {
  154. best_match = i;
  155. diff = ndiff;
  156. scale_color_font = float(id.size * oversampling) / face->available_sizes[i].width;
  157. }
  158. }
  159. FT_Select_Size(face, best_match);
  160. } else {
  161. FT_Set_Pixel_Sizes(face, 0, id.size * oversampling);
  162. }
  163. ascent = (face->size->metrics.ascender / 64.0) / oversampling * scale_color_font;
  164. descent = (-face->size->metrics.descender / 64.0) / oversampling * scale_color_font;
  165. linegap = 0;
  166. texture_flags = 0;
  167. if (id.mipmaps) {
  168. texture_flags |= Texture::FLAG_MIPMAPS;
  169. }
  170. if (id.filter) {
  171. texture_flags |= Texture::FLAG_FILTER;
  172. }
  173. valid = true;
  174. return OK;
  175. }
  176. float DynamicFontAtSize::font_oversampling = 1.0;
  177. float DynamicFontAtSize::get_height() const {
  178. return ascent + descent;
  179. }
  180. float DynamicFontAtSize::get_ascent() const {
  181. return ascent;
  182. }
  183. float DynamicFontAtSize::get_descent() const {
  184. return descent;
  185. }
  186. const Pair<const DynamicFontAtSize::Character *, DynamicFontAtSize *> DynamicFontAtSize::_find_char_with_font(int32_t p_char, const Vector<Ref<DynamicFontAtSize>> &p_fallbacks) const {
  187. const Character *chr = char_map.getptr(p_char);
  188. ERR_FAIL_COND_V(!chr, (Pair<const Character *, DynamicFontAtSize *>(NULL, NULL)));
  189. if (!chr->found) {
  190. //not found, try in fallbacks
  191. for (int i = 0; i < p_fallbacks.size(); i++) {
  192. DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr());
  193. if (!fb->valid) {
  194. continue;
  195. }
  196. fb->_update_char(p_char);
  197. const Character *fallback_chr = fb->char_map.getptr(p_char);
  198. ERR_CONTINUE(!fallback_chr);
  199. if (!fallback_chr->found) {
  200. continue;
  201. }
  202. return Pair<const Character *, DynamicFontAtSize *>(fallback_chr, fb);
  203. }
  204. //not found, try 0xFFFD to display 'not found'.
  205. const_cast<DynamicFontAtSize *>(this)->_update_char(0xFFFD);
  206. chr = char_map.getptr(0xFFFD);
  207. ERR_FAIL_COND_V(!chr, (Pair<const Character *, DynamicFontAtSize *>(NULL, NULL)));
  208. }
  209. return Pair<const Character *, DynamicFontAtSize *>(chr, const_cast<DynamicFontAtSize *>(this));
  210. }
  211. float DynamicFontAtSize::_get_kerning_advance(const DynamicFontAtSize *font, int32_t p_char, int32_t p_next) const {
  212. float advance = 0.0;
  213. if (p_next) {
  214. FT_Vector delta;
  215. FT_Get_Kerning(font->face, FT_Get_Char_Index(font->face, p_char), FT_Get_Char_Index(font->face, p_next), FT_KERNING_DEFAULT, &delta);
  216. advance = (delta.x / 64.0) / oversampling;
  217. }
  218. return advance;
  219. }
  220. Size2 DynamicFontAtSize::get_char_size(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize>> &p_fallbacks) const {
  221. if (!valid) {
  222. return Size2(1, 1);
  223. }
  224. int32_t c = p_char;
  225. bool skip_kerning = false;
  226. if (((p_char & 0xfffffc00) == 0xd800) && (p_next & 0xfffffc00) == 0xdc00) { // decode surrogate pair.
  227. c = (p_char << 10UL) + p_next - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  228. skip_kerning = true;
  229. }
  230. if ((p_char & 0xfffffc00) == 0xdc00) { // skip trail surrogate.
  231. return Size2();
  232. }
  233. const_cast<DynamicFontAtSize *>(this)->_update_char(c);
  234. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(c, p_fallbacks);
  235. const Character *ch = char_pair_with_font.first;
  236. DynamicFontAtSize *font = char_pair_with_font.second;
  237. ERR_FAIL_COND_V(!ch, Size2());
  238. Size2 ret(0, get_height());
  239. if (ch->found) {
  240. ret.x = ch->advance;
  241. }
  242. if (!skip_kerning) {
  243. ret.x += _get_kerning_advance(font, p_char, p_next);
  244. }
  245. return ret;
  246. }
  247. String DynamicFontAtSize::get_available_chars() const {
  248. if (!valid) {
  249. return "";
  250. }
  251. String chars;
  252. FT_UInt gindex;
  253. FT_ULong charcode = FT_Get_First_Char(face, &gindex);
  254. while (gindex != 0) {
  255. if (charcode != 0) {
  256. chars += CharType(charcode);
  257. }
  258. charcode = FT_Get_Next_Char(face, charcode, &gindex);
  259. }
  260. return chars;
  261. }
  262. void DynamicFontAtSize::set_texture_flags(uint32_t p_flags) {
  263. texture_flags = p_flags;
  264. for (int i = 0; i < textures.size(); i++) {
  265. Ref<ImageTexture> &tex = textures.write[i].texture;
  266. if (!tex.is_null()) {
  267. tex->set_flags(p_flags);
  268. }
  269. }
  270. }
  271. RID DynamicFontAtSize::get_char_texture(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize>> &p_fallbacks) const {
  272. if (!valid) {
  273. return RID();
  274. }
  275. int32_t c = p_char;
  276. if (((p_char & 0xfffffc00) == 0xd800) && (p_next & 0xfffffc00) == 0xdc00) { // decode surrogate pair.
  277. c = (p_char << 10UL) + p_next - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  278. }
  279. if ((p_char & 0xfffffc00) == 0xdc00) { // skip trail surrogate.
  280. return RID();
  281. }
  282. const_cast<DynamicFontAtSize *>(this)->_update_char(c);
  283. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(c, p_fallbacks);
  284. const Character *ch = char_pair_with_font.first;
  285. DynamicFontAtSize *font = char_pair_with_font.second;
  286. ERR_FAIL_COND_V(!ch, RID());
  287. if (ch->found) {
  288. ERR_FAIL_COND_V(ch->texture_idx < -1 || ch->texture_idx >= font->textures.size(), RID());
  289. if (ch->texture_idx != -1) {
  290. return font->textures[ch->texture_idx].texture->get_rid();
  291. }
  292. }
  293. return RID();
  294. }
  295. Size2 DynamicFontAtSize::get_char_texture_size(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize>> &p_fallbacks) const {
  296. if (!valid) {
  297. return Size2();
  298. }
  299. int32_t c = p_char;
  300. if (((p_char & 0xfffffc00) == 0xd800) && (p_next & 0xfffffc00) == 0xdc00) { // decode surrogate pair.
  301. c = (p_char << 10UL) + p_next - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  302. }
  303. if ((p_char & 0xfffffc00) == 0xdc00) { // skip trail surrogate.
  304. return Size2();
  305. }
  306. const_cast<DynamicFontAtSize *>(this)->_update_char(c);
  307. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(c, p_fallbacks);
  308. const Character *ch = char_pair_with_font.first;
  309. DynamicFontAtSize *font = char_pair_with_font.second;
  310. ERR_FAIL_COND_V(!ch, Size2());
  311. if (ch->found) {
  312. ERR_FAIL_COND_V(ch->texture_idx < -1 || ch->texture_idx >= font->textures.size(), Size2());
  313. if (ch->texture_idx != -1) {
  314. return font->textures[ch->texture_idx].texture->get_size();
  315. }
  316. }
  317. return Size2();
  318. }
  319. Vector2 DynamicFontAtSize::get_char_tx_offset(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize>> &p_fallbacks) const {
  320. if (!valid) {
  321. return Vector2();
  322. }
  323. int32_t c = p_char;
  324. if (((p_char & 0xfffffc00) == 0xd800) && (p_next & 0xfffffc00) == 0xdc00) { // decode surrogate pair.
  325. c = (p_char << 10UL) + p_next - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  326. }
  327. if ((p_char & 0xfffffc00) == 0xdc00) { // skip trail surrogate.
  328. return Vector2();
  329. }
  330. const_cast<DynamicFontAtSize *>(this)->_update_char(c);
  331. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(c, p_fallbacks);
  332. const Character *ch = char_pair_with_font.first;
  333. DynamicFontAtSize *font = char_pair_with_font.second;
  334. ERR_FAIL_COND_V(!ch, Vector2());
  335. if (ch->found) {
  336. Point2 cpos;
  337. cpos.x += ch->h_align;
  338. cpos.y -= font->get_ascent();
  339. cpos.y += ch->v_align;
  340. return cpos;
  341. }
  342. return Vector2();
  343. }
  344. Size2 DynamicFontAtSize::get_char_tx_size(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize>> &p_fallbacks) const {
  345. if (!valid) {
  346. return Size2();
  347. }
  348. int32_t c = p_char;
  349. if (((p_char & 0xfffffc00) == 0xd800) && (p_next & 0xfffffc00) == 0xdc00) { // decode surrogate pair.
  350. c = (p_char << 10UL) + p_next - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  351. }
  352. if ((p_char & 0xfffffc00) == 0xdc00) { // skip trail surrogate.
  353. return Size2();
  354. }
  355. const_cast<DynamicFontAtSize *>(this)->_update_char(c);
  356. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(c, p_fallbacks);
  357. const Character *ch = char_pair_with_font.first;
  358. ERR_FAIL_COND_V(!ch, Size2());
  359. if (ch->found) {
  360. return ch->rect.size;
  361. }
  362. return Size2();
  363. }
  364. Rect2 DynamicFontAtSize::get_char_tx_uv_rect(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize>> &p_fallbacks) const {
  365. if (!valid) {
  366. return Rect2();
  367. }
  368. int32_t c = p_char;
  369. if (((p_char & 0xfffffc00) == 0xd800) && (p_next & 0xfffffc00) == 0xdc00) { // decode surrogate pair.
  370. c = (p_char << 10UL) + p_next - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  371. }
  372. if ((p_char & 0xfffffc00) == 0xdc00) { // skip trail surrogate.
  373. return Rect2();
  374. }
  375. const_cast<DynamicFontAtSize *>(this)->_update_char(c);
  376. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(c, p_fallbacks);
  377. const Character *ch = char_pair_with_font.first;
  378. ERR_FAIL_COND_V(!ch, Rect2());
  379. if (ch->found) {
  380. return ch->rect_uv;
  381. }
  382. return Rect2();
  383. }
  384. float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate, const Vector<Ref<DynamicFontAtSize>> &p_fallbacks, bool p_advance_only, bool p_outline) const {
  385. if (!valid) {
  386. return 0;
  387. }
  388. int32_t c = p_char;
  389. bool skip_kerning = false;
  390. if (((p_char & 0xfffffc00) == 0xd800) && (p_next & 0xfffffc00) == 0xdc00) { // decode surrogate pair.
  391. c = (p_char << 10UL) + p_next - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  392. skip_kerning = true;
  393. }
  394. if ((p_char & 0xfffffc00) == 0xdc00) { // skip trail surrogate.
  395. return 0;
  396. }
  397. const_cast<DynamicFontAtSize *>(this)->_update_char(c);
  398. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(c, p_fallbacks);
  399. const Character *ch = char_pair_with_font.first;
  400. DynamicFontAtSize *font = char_pair_with_font.second;
  401. ERR_FAIL_COND_V(!ch, 0.0);
  402. float advance = 0.0;
  403. // use normal character size if there's no outline character
  404. if (p_outline && !ch->found) {
  405. FT_GlyphSlot slot = face->glyph;
  406. int error = FT_Load_Char(face, c, FT_HAS_COLOR(face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT);
  407. if (!error) {
  408. error = FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
  409. if (!error) {
  410. Character character = Character::not_found();
  411. character = const_cast<DynamicFontAtSize *>(this)->_bitmap_to_character(slot->bitmap, slot->bitmap_top, slot->bitmap_left, slot->advance.x / 64.0);
  412. advance = character.advance;
  413. }
  414. }
  415. }
  416. if (ch->found) {
  417. ERR_FAIL_COND_V(ch->texture_idx < -1 || ch->texture_idx >= font->textures.size(), 0);
  418. if (!p_advance_only && ch->texture_idx != -1) {
  419. Point2 cpos = p_pos;
  420. cpos.x += ch->h_align;
  421. cpos.y -= font->get_ascent();
  422. cpos.y += ch->v_align;
  423. Color modulate = p_modulate;
  424. if (font->textures[ch->texture_idx].texture->get_format() == Image::FORMAT_RGBA8) {
  425. modulate.r = modulate.g = modulate.b = 1.0;
  426. }
  427. RID texture = font->textures[ch->texture_idx].texture->get_rid();
  428. VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, ch->rect.size), texture, ch->rect_uv, modulate, false, RID(), false);
  429. }
  430. advance = ch->advance;
  431. }
  432. if (!skip_kerning) {
  433. advance += _get_kerning_advance(font, p_char, p_next);
  434. }
  435. return advance;
  436. }
  437. Dictionary DynamicFontAtSize::get_char_contours(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize>> &p_fallbacks) const {
  438. if (!valid) {
  439. return Dictionary();
  440. }
  441. int32_t c = p_char;
  442. if (((p_char & 0xfffffc00) == 0xd800) && (p_next & 0xfffffc00) == 0xdc00) { // decode surrogate pair.
  443. c = (p_char << 10UL) + p_next - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  444. }
  445. if ((p_char & 0xfffffc00) == 0xdc00) { // skip trail surrogate.
  446. return Dictionary();
  447. }
  448. const_cast<DynamicFontAtSize *>(this)->_update_char(c);
  449. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(c, p_fallbacks);
  450. const Character *ch = char_pair_with_font.first;
  451. DynamicFontAtSize *font = char_pair_with_font.second;
  452. if (ch->found) {
  453. PoolVector3Array points;
  454. PoolIntArray contours;
  455. int error = FT_Load_Char(font->face, c, FT_LOAD_NO_BITMAP | (font->font->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0));
  456. ERR_FAIL_COND_V(error, Dictionary());
  457. double scale = (1.0 / 64.0) / oversampling * scale_color_font;
  458. for (short i = 0; i < font->face->glyph->outline.n_points; i++) {
  459. points.push_back(Vector3(font->face->glyph->outline.points[i].x * scale, -font->face->glyph->outline.points[i].y * scale, FT_CURVE_TAG(font->face->glyph->outline.tags[i])));
  460. }
  461. for (short i = 0; i < font->face->glyph->outline.n_contours; i++) {
  462. contours.push_back(font->face->glyph->outline.contours[i]);
  463. }
  464. bool orientation = (FT_Outline_Get_Orientation(&font->face->glyph->outline) == FT_ORIENTATION_FILL_RIGHT);
  465. Dictionary out;
  466. out["points"] = points;
  467. out["contours"] = contours;
  468. out["orientation"] = orientation;
  469. return out;
  470. } else {
  471. return Dictionary();
  472. }
  473. }
  474. DynamicFontAtSize::Character DynamicFontAtSize::Character::not_found() {
  475. Character ch;
  476. ch.texture_idx = -1;
  477. ch.advance = 0;
  478. ch.h_align = 0;
  479. ch.v_align = 0;
  480. ch.found = false;
  481. return ch;
  482. }
  483. DynamicFontAtSize::TexturePosition DynamicFontAtSize::_find_texture_pos_for_glyph(int p_color_size, Image::Format p_image_format, int p_width, int p_height) {
  484. TexturePosition ret;
  485. ret.index = -1;
  486. ret.x = 0;
  487. ret.y = 0;
  488. int mw = p_width;
  489. int mh = p_height;
  490. for (int i = 0; i < textures.size(); i++) {
  491. const CharTexture &ct = textures[i];
  492. if (ct.texture->get_format() != p_image_format) {
  493. continue;
  494. }
  495. if (mw > ct.texture_size || mh > ct.texture_size) { //too big for this texture
  496. continue;
  497. }
  498. ret.y = 0x7FFFFFFF;
  499. ret.x = 0;
  500. for (int j = 0; j < ct.texture_size - mw; j++) {
  501. int max_y = 0;
  502. for (int k = j; k < j + mw; k++) {
  503. int y = ct.offsets[k];
  504. if (y > max_y) {
  505. max_y = y;
  506. }
  507. }
  508. if (max_y < ret.y) {
  509. ret.y = max_y;
  510. ret.x = j;
  511. }
  512. }
  513. if (ret.y == 0x7FFFFFFF || ret.y + mh > ct.texture_size) {
  514. continue; //fail, could not fit it here
  515. }
  516. ret.index = i;
  517. break;
  518. }
  519. if (ret.index == -1) {
  520. //could not find texture to fit, create one
  521. ret.x = 0;
  522. ret.y = 0;
  523. int texsize = MAX(id.size * oversampling * 8, 256);
  524. if (mw > texsize) {
  525. texsize = mw; //special case, adapt to it?
  526. }
  527. if (mh > texsize) {
  528. texsize = mh; //special case, adapt to it?
  529. }
  530. texsize = next_power_of_2(texsize);
  531. texsize = MIN(texsize, 4096);
  532. CharTexture tex;
  533. tex.texture_size = texsize;
  534. tex.imgdata.resize(texsize * texsize * p_color_size); //grayscale alpha
  535. {
  536. //zero texture
  537. PoolVector<uint8_t>::Write w = tex.imgdata.write();
  538. ERR_FAIL_COND_V(texsize * texsize * p_color_size > tex.imgdata.size(), ret);
  539. // Initialize the texture to all-white pixels to prevent artifacts when the
  540. // font is displayed at a non-default scale with filtering enabled.
  541. if (p_color_size == 2) {
  542. for (int i = 0; i < texsize * texsize * p_color_size; i += 2) {
  543. w[i + 0] = 255;
  544. w[i + 1] = 0;
  545. }
  546. } else {
  547. for (int i = 0; i < texsize * texsize * p_color_size; i += 4) {
  548. w[i + 0] = 255;
  549. w[i + 1] = 255;
  550. w[i + 2] = 255;
  551. w[i + 3] = 0;
  552. }
  553. }
  554. }
  555. tex.offsets.resize(texsize);
  556. for (int i = 0; i < texsize; i++) { //zero offsets
  557. tex.offsets.write[i] = 0;
  558. }
  559. textures.push_back(tex);
  560. ret.index = textures.size() - 1;
  561. }
  562. return ret;
  563. }
  564. DynamicFontAtSize::Character DynamicFontAtSize::_bitmap_to_character(FT_Bitmap bitmap, int yofs, int xofs, float advance) {
  565. int w = bitmap.width;
  566. int h = bitmap.rows;
  567. int mw = w + rect_margin * 2;
  568. int mh = h + rect_margin * 2;
  569. ERR_FAIL_COND_V(mw > 4096, Character::not_found());
  570. ERR_FAIL_COND_V(mh > 4096, Character::not_found());
  571. int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2;
  572. Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8;
  573. TexturePosition tex_pos = _find_texture_pos_for_glyph(color_size, require_format, mw, mh);
  574. ERR_FAIL_COND_V(tex_pos.index < 0, Character::not_found());
  575. //fit character in char texture
  576. CharTexture &tex = textures.write[tex_pos.index];
  577. {
  578. PoolVector<uint8_t>::Write wr = tex.imgdata.write();
  579. for (int i = 0; i < h; i++) {
  580. for (int j = 0; j < w; j++) {
  581. int ofs = ((i + tex_pos.y + rect_margin) * tex.texture_size + j + tex_pos.x + rect_margin) * color_size;
  582. ERR_FAIL_COND_V(ofs >= tex.imgdata.size(), Character::not_found());
  583. switch (bitmap.pixel_mode) {
  584. case FT_PIXEL_MODE_MONO: {
  585. int byte = i * bitmap.pitch + (j >> 3);
  586. int bit = 1 << (7 - (j % 8));
  587. wr[ofs + 0] = 255; //grayscale as 1
  588. wr[ofs + 1] = (bitmap.buffer[byte] & bit) ? 255 : 0;
  589. } break;
  590. case FT_PIXEL_MODE_GRAY:
  591. wr[ofs + 0] = 255; //grayscale as 1
  592. wr[ofs + 1] = bitmap.buffer[i * bitmap.pitch + j];
  593. break;
  594. case FT_PIXEL_MODE_BGRA: {
  595. int ofs_color = i * bitmap.pitch + (j << 2);
  596. wr[ofs + 2] = bitmap.buffer[ofs_color + 0];
  597. wr[ofs + 1] = bitmap.buffer[ofs_color + 1];
  598. wr[ofs + 0] = bitmap.buffer[ofs_color + 2];
  599. wr[ofs + 3] = bitmap.buffer[ofs_color + 3];
  600. } break;
  601. // TODO: FT_PIXEL_MODE_LCD
  602. default:
  603. ERR_FAIL_V_MSG(Character::not_found(), "Font uses unsupported pixel format: " + itos(bitmap.pixel_mode) + ".");
  604. break;
  605. }
  606. }
  607. }
  608. }
  609. //blit to image and texture
  610. {
  611. Ref<Image> img = memnew(Image(tex.texture_size, tex.texture_size, 0, require_format, tex.imgdata));
  612. if (tex.texture.is_null()) {
  613. tex.texture.instance();
  614. tex.texture->create_from_image(img, Texture::FLAG_VIDEO_SURFACE | texture_flags);
  615. } else {
  616. tex.texture->set_data(img); //update
  617. }
  618. }
  619. // update height array
  620. for (int k = tex_pos.x; k < tex_pos.x + mw; k++) {
  621. tex.offsets.write[k] = tex_pos.y + mh;
  622. }
  623. Character chr;
  624. chr.h_align = xofs * scale_color_font / oversampling;
  625. chr.v_align = ascent - (yofs * scale_color_font / oversampling); // + ascent - descent;
  626. chr.advance = advance * scale_color_font / oversampling;
  627. chr.texture_idx = tex_pos.index;
  628. chr.found = true;
  629. chr.rect_uv = Rect2(tex_pos.x + rect_margin, tex_pos.y + rect_margin, w, h);
  630. chr.rect = chr.rect_uv;
  631. chr.rect.position /= oversampling;
  632. chr.rect.size = chr.rect.size * scale_color_font / oversampling;
  633. return chr;
  634. }
  635. DynamicFontAtSize::Character DynamicFontAtSize::_make_outline_char(int32_t p_char) {
  636. Character ret = Character::not_found();
  637. if (FT_Load_Char(face, p_char, FT_LOAD_NO_BITMAP | (font->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0)) != 0) {
  638. return ret;
  639. }
  640. FT_Stroker stroker;
  641. if (FT_Stroker_New(library, &stroker) != 0) {
  642. return ret;
  643. }
  644. FT_Stroker_Set(stroker, (int)(id.outline_size * oversampling * 64.0), FT_STROKER_LINECAP_BUTT, FT_STROKER_LINEJOIN_ROUND, 0);
  645. FT_Glyph glyph;
  646. FT_BitmapGlyph glyph_bitmap;
  647. if (FT_Get_Glyph(face->glyph, &glyph) != 0) {
  648. goto cleanup_stroker;
  649. }
  650. if (FT_Glyph_Stroke(&glyph, stroker, 1) != 0) {
  651. goto cleanup_glyph;
  652. }
  653. if (FT_Glyph_To_Bitmap(&glyph, font->antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO, nullptr, 1) != 0) {
  654. goto cleanup_glyph;
  655. }
  656. glyph_bitmap = (FT_BitmapGlyph)glyph;
  657. ret = _bitmap_to_character(glyph_bitmap->bitmap, glyph_bitmap->top, glyph_bitmap->left, glyph->advance.x / 65536.0);
  658. cleanup_glyph:
  659. FT_Done_Glyph(glyph);
  660. cleanup_stroker:
  661. FT_Stroker_Done(stroker);
  662. return ret;
  663. }
  664. void DynamicFontAtSize::_update_char(int32_t p_char) {
  665. if (char_map.has(p_char)) {
  666. return;
  667. }
  668. _THREAD_SAFE_METHOD_
  669. Character character = Character::not_found();
  670. FT_GlyphSlot slot = face->glyph;
  671. if (FT_Get_Char_Index(face, p_char) == 0) {
  672. char_map[p_char] = character;
  673. return;
  674. }
  675. int ft_hinting;
  676. switch (font->hinting) {
  677. case DynamicFontData::HINTING_NONE:
  678. ft_hinting = FT_LOAD_NO_HINTING;
  679. break;
  680. case DynamicFontData::HINTING_LIGHT:
  681. ft_hinting = FT_LOAD_TARGET_LIGHT;
  682. break;
  683. default:
  684. ft_hinting = FT_LOAD_TARGET_NORMAL;
  685. break;
  686. }
  687. int error = FT_Load_Char(face, p_char, FT_HAS_COLOR(face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (font->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting);
  688. if (error) {
  689. char_map[p_char] = character;
  690. return;
  691. }
  692. if (id.outline_size > 0) {
  693. character = _make_outline_char(p_char);
  694. } else {
  695. error = FT_Render_Glyph(face->glyph, font->antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
  696. if (!error) {
  697. character = _bitmap_to_character(slot->bitmap, slot->bitmap_top, slot->bitmap_left, slot->advance.x / 64.0);
  698. }
  699. }
  700. char_map[p_char] = character;
  701. }
  702. void DynamicFontAtSize::update_oversampling() {
  703. if (!valid) {
  704. return;
  705. }
  706. float new_oversampling = (font.is_valid() && font->override_oversampling > 0) ? font->override_oversampling : font_oversampling;
  707. if (oversampling == new_oversampling) {
  708. return;
  709. }
  710. FT_Done_FreeType(library);
  711. textures.clear();
  712. char_map.clear();
  713. oversampling = new_oversampling;
  714. valid = false;
  715. _load();
  716. }
  717. DynamicFontAtSize::DynamicFontAtSize() {
  718. valid = false;
  719. rect_margin = 1;
  720. ascent = 1;
  721. descent = 1;
  722. linegap = 1;
  723. texture_flags = 0;
  724. oversampling = font_oversampling;
  725. scale_color_font = 1;
  726. }
  727. DynamicFontAtSize::~DynamicFontAtSize() {
  728. if (valid) {
  729. FT_Done_FreeType(library);
  730. }
  731. font->size_cache.erase(id);
  732. font.unref();
  733. }
  734. /////////////////////////
  735. void DynamicFont::_reload_cache(const char *p_triggering_property) {
  736. ERR_FAIL_COND(cache_id.size < 1);
  737. if (!data.is_valid()) {
  738. data_at_size.unref();
  739. outline_data_at_size.unref();
  740. fallbacks.resize(0);
  741. fallback_data_at_size.resize(0);
  742. fallback_outline_data_at_size.resize(0);
  743. return;
  744. }
  745. data_at_size = data->_get_dynamic_font_at_size(cache_id);
  746. if (outline_cache_id.outline_size > 0) {
  747. outline_data_at_size = data->_get_dynamic_font_at_size(outline_cache_id);
  748. fallback_outline_data_at_size.resize(fallback_data_at_size.size());
  749. } else {
  750. outline_data_at_size.unref();
  751. fallback_outline_data_at_size.resize(0);
  752. }
  753. for (int i = 0; i < fallbacks.size(); i++) {
  754. fallback_data_at_size.write[i] = fallbacks.write[i]->_get_dynamic_font_at_size(cache_id);
  755. if (outline_cache_id.outline_size > 0) {
  756. fallback_outline_data_at_size.write[i] = fallbacks.write[i]->_get_dynamic_font_at_size(outline_cache_id);
  757. }
  758. }
  759. emit_changed();
  760. _change_notify(p_triggering_property);
  761. }
  762. void DynamicFont::set_font_data(const Ref<DynamicFontData> &p_data) {
  763. data = p_data;
  764. _reload_cache(); // not passing the prop name as clearing the font data also clears fallbacks
  765. }
  766. Ref<DynamicFontData> DynamicFont::get_font_data() const {
  767. return data;
  768. }
  769. void DynamicFont::set_size(int p_size) {
  770. if (cache_id.size == p_size) {
  771. return;
  772. }
  773. cache_id.size = p_size;
  774. outline_cache_id.size = p_size;
  775. _reload_cache("size");
  776. }
  777. int DynamicFont::get_size() const {
  778. return cache_id.size;
  779. }
  780. void DynamicFont::set_outline_size(int p_size) {
  781. if (outline_cache_id.outline_size == p_size) {
  782. return;
  783. }
  784. ERR_FAIL_COND(p_size < 0 || p_size > UINT8_MAX);
  785. outline_cache_id.outline_size = p_size;
  786. _reload_cache("outline_size");
  787. }
  788. int DynamicFont::get_outline_size() const {
  789. return outline_cache_id.outline_size;
  790. }
  791. void DynamicFont::set_outline_color(Color p_color) {
  792. if (p_color != outline_color) {
  793. outline_color = p_color;
  794. emit_changed();
  795. _change_notify("outline_color");
  796. }
  797. }
  798. Color DynamicFont::get_outline_color() const {
  799. return outline_color;
  800. }
  801. bool DynamicFont::get_use_mipmaps() const {
  802. return cache_id.mipmaps;
  803. }
  804. void DynamicFont::set_use_mipmaps(bool p_enable) {
  805. if (cache_id.mipmaps == p_enable) {
  806. return;
  807. }
  808. cache_id.mipmaps = p_enable;
  809. outline_cache_id.mipmaps = p_enable;
  810. _reload_cache();
  811. }
  812. bool DynamicFont::get_use_filter() const {
  813. return cache_id.filter;
  814. }
  815. void DynamicFont::set_use_filter(bool p_enable) {
  816. if (cache_id.filter == p_enable) {
  817. return;
  818. }
  819. cache_id.filter = p_enable;
  820. outline_cache_id.filter = p_enable;
  821. _reload_cache();
  822. }
  823. bool DynamicFontData::is_antialiased() const {
  824. return antialiased;
  825. }
  826. void DynamicFontData::set_antialiased(bool p_antialiased) {
  827. if (antialiased == p_antialiased) {
  828. return;
  829. }
  830. antialiased = p_antialiased;
  831. }
  832. DynamicFontData::Hinting DynamicFontData::get_hinting() const {
  833. return hinting;
  834. }
  835. void DynamicFontData::set_hinting(Hinting p_hinting) {
  836. if (hinting == p_hinting) {
  837. return;
  838. }
  839. hinting = p_hinting;
  840. }
  841. int DynamicFont::get_spacing(int p_type) const {
  842. if (p_type == SPACING_TOP) {
  843. return spacing_top;
  844. } else if (p_type == SPACING_BOTTOM) {
  845. return spacing_bottom;
  846. } else if (p_type == SPACING_CHAR) {
  847. return spacing_char;
  848. } else if (p_type == SPACING_SPACE) {
  849. return spacing_space;
  850. }
  851. return 0;
  852. }
  853. void DynamicFont::set_spacing(int p_type, int p_value) {
  854. if (p_type == SPACING_TOP) {
  855. spacing_top = p_value;
  856. _change_notify("extra_spacing_top");
  857. } else if (p_type == SPACING_BOTTOM) {
  858. spacing_bottom = p_value;
  859. _change_notify("extra_spacing_bottom");
  860. } else if (p_type == SPACING_CHAR) {
  861. spacing_char = p_value;
  862. _change_notify("extra_spacing_char");
  863. } else if (p_type == SPACING_SPACE) {
  864. spacing_space = p_value;
  865. _change_notify("extra_spacing_space");
  866. }
  867. emit_changed();
  868. }
  869. float DynamicFont::get_height() const {
  870. if (!data_at_size.is_valid()) {
  871. return 1;
  872. }
  873. return data_at_size->get_height() + spacing_top + spacing_bottom;
  874. }
  875. float DynamicFont::get_ascent() const {
  876. if (!data_at_size.is_valid()) {
  877. return 1;
  878. }
  879. return data_at_size->get_ascent() + spacing_top;
  880. }
  881. float DynamicFont::get_descent() const {
  882. if (!data_at_size.is_valid()) {
  883. return 1;
  884. }
  885. return data_at_size->get_descent() + spacing_bottom;
  886. }
  887. Size2 DynamicFont::get_char_size(CharType p_char, CharType p_next) const {
  888. if (!data_at_size.is_valid()) {
  889. return Size2(1, 1);
  890. }
  891. Size2 ret = data_at_size->get_char_size(p_char, p_next, fallback_data_at_size);
  892. if (p_char == ' ') {
  893. ret.width += spacing_space + spacing_char;
  894. } else if (p_next) {
  895. ret.width += spacing_char;
  896. }
  897. return ret;
  898. }
  899. String DynamicFont::get_available_chars() const {
  900. if (!data_at_size.is_valid()) {
  901. return "";
  902. }
  903. String chars = data_at_size->get_available_chars();
  904. for (int i = 0; i < fallback_data_at_size.size(); i++) {
  905. String fallback_chars = fallback_data_at_size[i]->get_available_chars();
  906. for (int j = 0; j < fallback_chars.length(); j++) {
  907. if (chars.find_char(fallback_chars[j]) == -1) {
  908. chars += fallback_chars[j];
  909. }
  910. }
  911. }
  912. return chars;
  913. }
  914. bool DynamicFont::is_distance_field_hint() const {
  915. return false;
  916. }
  917. bool DynamicFont::has_outline() const {
  918. return outline_cache_id.outline_size > 0;
  919. }
  920. RID DynamicFont::get_char_texture(CharType p_char, CharType p_next, bool p_outline) const {
  921. if (!data_at_size.is_valid()) {
  922. return RID();
  923. }
  924. if (p_outline) {
  925. if (outline_data_at_size.is_valid() && outline_cache_id.outline_size > 0) {
  926. return outline_data_at_size->get_char_texture(p_char, p_next, fallback_outline_data_at_size);
  927. }
  928. return RID();
  929. } else {
  930. return data_at_size->get_char_texture(p_char, p_next, fallback_data_at_size);
  931. }
  932. }
  933. Size2 DynamicFont::get_char_texture_size(CharType p_char, CharType p_next, bool p_outline) const {
  934. if (!data_at_size.is_valid()) {
  935. return Size2();
  936. }
  937. if (p_outline) {
  938. if (outline_data_at_size.is_valid() && outline_cache_id.outline_size > 0) {
  939. return outline_data_at_size->get_char_texture_size(p_char, p_next, fallback_outline_data_at_size);
  940. }
  941. return Size2();
  942. } else {
  943. return data_at_size->get_char_texture_size(p_char, p_next, fallback_data_at_size);
  944. }
  945. }
  946. Vector2 DynamicFont::get_char_tx_offset(CharType p_char, CharType p_next, bool p_outline) const {
  947. if (!data_at_size.is_valid()) {
  948. return Vector2();
  949. }
  950. if (p_outline) {
  951. if (outline_data_at_size.is_valid() && outline_cache_id.outline_size > 0) {
  952. return outline_data_at_size->get_char_tx_offset(p_char, p_next, fallback_outline_data_at_size);
  953. }
  954. return Vector2();
  955. } else {
  956. return data_at_size->get_char_tx_offset(p_char, p_next, fallback_data_at_size);
  957. }
  958. }
  959. Size2 DynamicFont::get_char_tx_size(CharType p_char, CharType p_next, bool p_outline) const {
  960. if (!data_at_size.is_valid()) {
  961. return Size2();
  962. }
  963. if (p_outline) {
  964. if (outline_data_at_size.is_valid() && outline_cache_id.outline_size > 0) {
  965. return outline_data_at_size->get_char_tx_size(p_char, p_next, fallback_outline_data_at_size);
  966. }
  967. return Size2();
  968. } else {
  969. return data_at_size->get_char_tx_size(p_char, p_next, fallback_data_at_size);
  970. }
  971. }
  972. Rect2 DynamicFont::get_char_tx_uv_rect(CharType p_char, CharType p_next, bool p_outline) const {
  973. if (!data_at_size.is_valid()) {
  974. return Rect2();
  975. }
  976. if (p_outline) {
  977. if (outline_data_at_size.is_valid() && outline_cache_id.outline_size > 0) {
  978. return outline_data_at_size->get_char_tx_uv_rect(p_char, p_next, fallback_outline_data_at_size);
  979. }
  980. return Rect2();
  981. } else {
  982. return data_at_size->get_char_tx_uv_rect(p_char, p_next, fallback_data_at_size);
  983. }
  984. }
  985. float DynamicFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate, bool p_outline) const {
  986. if (!data_at_size.is_valid()) {
  987. return 0;
  988. }
  989. int spacing = spacing_char;
  990. if (p_char == ' ') {
  991. spacing += spacing_space;
  992. }
  993. if (p_outline) {
  994. if (outline_data_at_size.is_valid() && outline_cache_id.outline_size > 0) {
  995. outline_data_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate * outline_color, fallback_outline_data_at_size, false, true); // Draw glyph outline.
  996. }
  997. return data_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate, fallback_data_at_size, true, false) + spacing; // Return advance of the base glyph.
  998. } else {
  999. return data_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate, fallback_data_at_size, false, false) + spacing; // Draw base glyph and return advance.
  1000. }
  1001. }
  1002. Dictionary DynamicFont::get_char_contours(CharType p_char, CharType p_next) const {
  1003. if (!data_at_size.is_valid()) {
  1004. return Dictionary();
  1005. }
  1006. return data_at_size->get_char_contours(p_char, p_next, fallback_data_at_size);
  1007. }
  1008. void DynamicFont::set_fallback(int p_idx, const Ref<DynamicFontData> &p_data) {
  1009. ERR_FAIL_COND(p_data.is_null());
  1010. ERR_FAIL_INDEX(p_idx, fallbacks.size());
  1011. fallbacks.write[p_idx] = p_data;
  1012. fallback_data_at_size.write[p_idx] = fallbacks.write[p_idx]->_get_dynamic_font_at_size(cache_id);
  1013. }
  1014. void DynamicFont::add_fallback(const Ref<DynamicFontData> &p_data) {
  1015. ERR_FAIL_COND(p_data.is_null());
  1016. fallbacks.push_back(p_data);
  1017. fallback_data_at_size.push_back(fallbacks.write[fallbacks.size() - 1]->_get_dynamic_font_at_size(cache_id)); //const..
  1018. if (outline_cache_id.outline_size > 0) {
  1019. fallback_outline_data_at_size.push_back(fallbacks.write[fallbacks.size() - 1]->_get_dynamic_font_at_size(outline_cache_id));
  1020. }
  1021. emit_changed();
  1022. _change_notify();
  1023. }
  1024. int DynamicFont::get_fallback_count() const {
  1025. return fallbacks.size();
  1026. }
  1027. Ref<DynamicFontData> DynamicFont::get_fallback(int p_idx) const {
  1028. ERR_FAIL_INDEX_V(p_idx, fallbacks.size(), Ref<DynamicFontData>());
  1029. return fallbacks[p_idx];
  1030. }
  1031. void DynamicFont::remove_fallback(int p_idx) {
  1032. ERR_FAIL_INDEX(p_idx, fallbacks.size());
  1033. fallbacks.remove(p_idx);
  1034. fallback_data_at_size.remove(p_idx);
  1035. emit_changed();
  1036. _change_notify();
  1037. }
  1038. bool DynamicFont::_set(const StringName &p_name, const Variant &p_value) {
  1039. String str = p_name;
  1040. if (str.begins_with("fallback/")) {
  1041. int idx = str.get_slicec('/', 1).to_int();
  1042. Ref<DynamicFontData> fd = p_value;
  1043. if (fd.is_valid()) {
  1044. if (idx == fallbacks.size()) {
  1045. add_fallback(fd);
  1046. return true;
  1047. } else if (idx >= 0 && idx < fallbacks.size()) {
  1048. set_fallback(idx, fd);
  1049. return true;
  1050. } else {
  1051. return false;
  1052. }
  1053. } else if (idx >= 0 && idx < fallbacks.size()) {
  1054. remove_fallback(idx);
  1055. return true;
  1056. }
  1057. }
  1058. return false;
  1059. }
  1060. bool DynamicFont::_get(const StringName &p_name, Variant &r_ret) const {
  1061. String str = p_name;
  1062. if (str.begins_with("fallback/")) {
  1063. int idx = str.get_slicec('/', 1).to_int();
  1064. if (idx == fallbacks.size()) {
  1065. r_ret = Ref<DynamicFontData>();
  1066. return true;
  1067. } else if (idx >= 0 && idx < fallbacks.size()) {
  1068. r_ret = get_fallback(idx);
  1069. return true;
  1070. }
  1071. }
  1072. return false;
  1073. }
  1074. void DynamicFont::_get_property_list(List<PropertyInfo> *p_list) const {
  1075. for (int i = 0; i < fallbacks.size(); i++) {
  1076. p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"));
  1077. }
  1078. p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(fallbacks.size()), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"));
  1079. }
  1080. void DynamicFont::_bind_methods() {
  1081. ClassDB::bind_method(D_METHOD("set_font_data", "data"), &DynamicFont::set_font_data);
  1082. ClassDB::bind_method(D_METHOD("get_font_data"), &DynamicFont::get_font_data);
  1083. ClassDB::bind_method(D_METHOD("get_available_chars"), &DynamicFont::get_available_chars);
  1084. ClassDB::bind_method(D_METHOD("set_size", "data"), &DynamicFont::set_size);
  1085. ClassDB::bind_method(D_METHOD("get_size"), &DynamicFont::get_size);
  1086. ClassDB::bind_method(D_METHOD("set_outline_size", "size"), &DynamicFont::set_outline_size);
  1087. ClassDB::bind_method(D_METHOD("get_outline_size"), &DynamicFont::get_outline_size);
  1088. ClassDB::bind_method(D_METHOD("set_outline_color", "color"), &DynamicFont::set_outline_color);
  1089. ClassDB::bind_method(D_METHOD("get_outline_color"), &DynamicFont::get_outline_color);
  1090. ClassDB::bind_method(D_METHOD("set_use_mipmaps", "enable"), &DynamicFont::set_use_mipmaps);
  1091. ClassDB::bind_method(D_METHOD("get_use_mipmaps"), &DynamicFont::get_use_mipmaps);
  1092. ClassDB::bind_method(D_METHOD("set_use_filter", "enable"), &DynamicFont::set_use_filter);
  1093. ClassDB::bind_method(D_METHOD("get_use_filter"), &DynamicFont::get_use_filter);
  1094. ClassDB::bind_method(D_METHOD("set_spacing", "type", "value"), &DynamicFont::set_spacing);
  1095. ClassDB::bind_method(D_METHOD("get_spacing", "type"), &DynamicFont::get_spacing);
  1096. ClassDB::bind_method(D_METHOD("add_fallback", "data"), &DynamicFont::add_fallback);
  1097. ClassDB::bind_method(D_METHOD("set_fallback", "idx", "data"), &DynamicFont::set_fallback);
  1098. ClassDB::bind_method(D_METHOD("get_fallback", "idx"), &DynamicFont::get_fallback);
  1099. ClassDB::bind_method(D_METHOD("remove_fallback", "idx"), &DynamicFont::remove_fallback);
  1100. ClassDB::bind_method(D_METHOD("get_fallback_count"), &DynamicFont::get_fallback_count);
  1101. ADD_GROUP("Settings", "");
  1102. ADD_PROPERTY(PropertyInfo(Variant::INT, "size", PROPERTY_HINT_RANGE, "1,1024,1"), "set_size", "get_size");
  1103. ADD_PROPERTY(PropertyInfo(Variant::INT, "outline_size", PROPERTY_HINT_RANGE, "0,255,1"), "set_outline_size", "get_outline_size");
  1104. ADD_PROPERTY(PropertyInfo(Variant::COLOR, "outline_color"), "set_outline_color", "get_outline_color");
  1105. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_mipmaps"), "set_use_mipmaps", "get_use_mipmaps");
  1106. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_filter"), "set_use_filter", "get_use_filter");
  1107. ADD_GROUP("Extra Spacing", "extra_spacing");
  1108. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_top"), "set_spacing", "get_spacing", SPACING_TOP);
  1109. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_bottom"), "set_spacing", "get_spacing", SPACING_BOTTOM);
  1110. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_char"), "set_spacing", "get_spacing", SPACING_CHAR);
  1111. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_space"), "set_spacing", "get_spacing", SPACING_SPACE);
  1112. ADD_GROUP("Font", "");
  1113. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font_data", PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"), "set_font_data", "get_font_data");
  1114. BIND_ENUM_CONSTANT(SPACING_TOP);
  1115. BIND_ENUM_CONSTANT(SPACING_BOTTOM);
  1116. BIND_ENUM_CONSTANT(SPACING_CHAR);
  1117. BIND_ENUM_CONSTANT(SPACING_SPACE);
  1118. }
  1119. Mutex DynamicFont::dynamic_font_mutex;
  1120. SelfList<DynamicFont>::List *DynamicFont::dynamic_fonts = nullptr;
  1121. DynamicFont::DynamicFont() :
  1122. font_list(this) {
  1123. cache_id.size = 16;
  1124. outline_cache_id.size = 16;
  1125. spacing_top = 0;
  1126. spacing_bottom = 0;
  1127. spacing_char = 0;
  1128. spacing_space = 0;
  1129. outline_color = Color(1, 1, 1);
  1130. dynamic_font_mutex.lock();
  1131. dynamic_fonts->add(&font_list);
  1132. dynamic_font_mutex.unlock();
  1133. }
  1134. DynamicFont::~DynamicFont() {
  1135. dynamic_font_mutex.lock();
  1136. dynamic_fonts->remove(&font_list);
  1137. dynamic_font_mutex.unlock();
  1138. }
  1139. void DynamicFont::initialize_dynamic_fonts() {
  1140. dynamic_fonts = memnew(SelfList<DynamicFont>::List());
  1141. }
  1142. void DynamicFont::finish_dynamic_fonts() {
  1143. memdelete(dynamic_fonts);
  1144. dynamic_fonts = nullptr;
  1145. }
  1146. void DynamicFont::update_oversampling() {
  1147. Vector<Ref<DynamicFont>> changed;
  1148. dynamic_font_mutex.lock();
  1149. SelfList<DynamicFont> *E = dynamic_fonts->first();
  1150. while (E) {
  1151. if (E->self()->data_at_size.is_valid()) {
  1152. E->self()->data_at_size->update_oversampling();
  1153. if (E->self()->outline_data_at_size.is_valid()) {
  1154. E->self()->outline_data_at_size->update_oversampling();
  1155. }
  1156. for (int i = 0; i < E->self()->fallback_data_at_size.size(); i++) {
  1157. if (E->self()->fallback_data_at_size[i].is_valid()) {
  1158. E->self()->fallback_data_at_size.write[i]->update_oversampling();
  1159. if (E->self()->has_outline() && E->self()->fallback_outline_data_at_size[i].is_valid()) {
  1160. E->self()->fallback_outline_data_at_size.write[i]->update_oversampling();
  1161. }
  1162. }
  1163. }
  1164. changed.push_back(Ref<DynamicFont>(E->self()));
  1165. }
  1166. E = E->next();
  1167. }
  1168. dynamic_font_mutex.unlock();
  1169. for (int i = 0; i < changed.size(); i++) {
  1170. changed.write[i]->emit_changed();
  1171. }
  1172. }
  1173. /////////////////////////
  1174. RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String &p_original_path, Error *r_error) {
  1175. if (r_error) {
  1176. *r_error = ERR_FILE_CANT_OPEN;
  1177. }
  1178. Ref<DynamicFontData> dfont;
  1179. dfont.instance();
  1180. dfont->set_font_path(p_path);
  1181. if (r_error) {
  1182. *r_error = OK;
  1183. }
  1184. return dfont;
  1185. }
  1186. void ResourceFormatLoaderDynamicFont::get_recognized_extensions(List<String> *p_extensions) const {
  1187. p_extensions->push_back("ttf");
  1188. p_extensions->push_back("otf");
  1189. p_extensions->push_back("woff");
  1190. p_extensions->push_back("woff2");
  1191. }
  1192. bool ResourceFormatLoaderDynamicFont::handles_type(const String &p_type) const {
  1193. return (p_type == "DynamicFontData");
  1194. }
  1195. String ResourceFormatLoaderDynamicFont::get_resource_type(const String &p_path) const {
  1196. String el = p_path.get_extension().to_lower();
  1197. if (el == "ttf" || el == "otf" || el == "woff" || el == "woff2") {
  1198. return "DynamicFontData";
  1199. }
  1200. return "";
  1201. }
  1202. #endif