dynamic_font.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. /*************************************************************************/
  2. /* dynamic_font.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  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. #ifdef FREETYPE_ENABLED
  31. #include "dynamic_font.h"
  32. #include "core/os/file_access.h"
  33. #include "core/os/os.h"
  34. #include FT_STROKER_H
  35. #define __STDC_LIMIT_MACROS
  36. #include <stdint.h>
  37. bool DynamicFontData::CacheID::operator<(CacheID right) const {
  38. return key < right.key;
  39. }
  40. Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(CacheID p_cache_id) {
  41. if (size_cache.has(p_cache_id)) {
  42. return Ref<DynamicFontAtSize>(size_cache[p_cache_id]);
  43. }
  44. Ref<DynamicFontAtSize> dfas;
  45. dfas.instance();
  46. dfas->font = Ref<DynamicFontData>(this);
  47. size_cache[p_cache_id] = dfas.ptr();
  48. dfas->id = p_cache_id;
  49. dfas->_load();
  50. return dfas;
  51. }
  52. void DynamicFontData::set_font_ptr(const uint8_t *p_font_mem, int p_font_mem_size) {
  53. font_mem = p_font_mem;
  54. font_mem_size = p_font_mem_size;
  55. }
  56. void DynamicFontData::set_font_path(const String &p_path) {
  57. font_path = p_path;
  58. }
  59. String DynamicFontData::get_font_path() const {
  60. return font_path;
  61. }
  62. void DynamicFontData::set_force_autohinter(bool p_force) {
  63. force_autohinter = p_force;
  64. }
  65. void DynamicFontData::_bind_methods() {
  66. ClassDB::bind_method(D_METHOD("set_antialiased", "antialiased"), &DynamicFontData::set_antialiased);
  67. ClassDB::bind_method(D_METHOD("is_antialiased"), &DynamicFontData::is_antialiased);
  68. ClassDB::bind_method(D_METHOD("set_font_path", "path"), &DynamicFontData::set_font_path);
  69. ClassDB::bind_method(D_METHOD("get_font_path"), &DynamicFontData::get_font_path);
  70. ClassDB::bind_method(D_METHOD("set_hinting", "mode"), &DynamicFontData::set_hinting);
  71. ClassDB::bind_method(D_METHOD("get_hinting"), &DynamicFontData::get_hinting);
  72. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "antialiased"), "set_antialiased", "is_antialiased");
  73. ADD_PROPERTY(PropertyInfo(Variant::INT, "hinting", PROPERTY_HINT_ENUM, "None,Light,Normal"), "set_hinting", "get_hinting");
  74. BIND_ENUM_CONSTANT(HINTING_NONE);
  75. BIND_ENUM_CONSTANT(HINTING_LIGHT);
  76. BIND_ENUM_CONSTANT(HINTING_NORMAL);
  77. ADD_PROPERTY(PropertyInfo(Variant::STRING, "font_path", PROPERTY_HINT_FILE, "*.ttf,*.otf"), "set_font_path", "get_font_path");
  78. }
  79. DynamicFontData::DynamicFontData() {
  80. antialiased = true;
  81. force_autohinter = false;
  82. hinting = DynamicFontData::HINTING_NORMAL;
  83. font_mem = NULL;
  84. font_mem_size = 0;
  85. }
  86. DynamicFontData::~DynamicFontData() {
  87. }
  88. ////////////////////
  89. HashMap<String, Vector<uint8_t> > DynamicFontAtSize::_fontdata;
  90. Error DynamicFontAtSize::_load() {
  91. int error = FT_Init_FreeType(&library);
  92. ERR_EXPLAIN(TTR("Error initializing FreeType."));
  93. ERR_FAIL_COND_V(error != 0, ERR_CANT_CREATE);
  94. // FT_OPEN_STREAM is extremely slow only on Android.
  95. if (OS::get_singleton()->get_name() == "Android" && font->font_mem == NULL && font->font_path != String()) {
  96. // cache font only once for each font->font_path
  97. if (_fontdata.has(font->font_path)) {
  98. font->set_font_ptr(_fontdata[font->font_path].ptr(), _fontdata[font->font_path].size());
  99. } else {
  100. FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
  101. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  102. size_t len = f->get_len();
  103. _fontdata[font->font_path] = Vector<uint8_t>();
  104. Vector<uint8_t> &fontdata = _fontdata[font->font_path];
  105. fontdata.resize(len);
  106. f->get_buffer(fontdata.ptrw(), len);
  107. font->set_font_ptr(fontdata.ptr(), len);
  108. f->close();
  109. }
  110. }
  111. if (font->font_mem == NULL && font->font_path != String()) {
  112. FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
  113. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  114. memset(&stream, 0, sizeof(FT_StreamRec));
  115. stream.base = NULL;
  116. stream.size = f->get_len();
  117. stream.pos = 0;
  118. stream.descriptor.pointer = f;
  119. stream.read = _ft_stream_io;
  120. stream.close = _ft_stream_close;
  121. FT_Open_Args fargs;
  122. memset(&fargs, 0, sizeof(FT_Open_Args));
  123. fargs.flags = FT_OPEN_STREAM;
  124. fargs.stream = &stream;
  125. error = FT_Open_Face(library, &fargs, 0, &face);
  126. } else if (font->font_mem) {
  127. memset(&stream, 0, sizeof(FT_StreamRec));
  128. stream.base = (unsigned char *)font->font_mem;
  129. stream.size = font->font_mem_size;
  130. stream.pos = 0;
  131. FT_Open_Args fargs;
  132. memset(&fargs, 0, sizeof(FT_Open_Args));
  133. fargs.memory_base = (unsigned char *)font->font_mem;
  134. fargs.memory_size = font->font_mem_size;
  135. fargs.flags = FT_OPEN_MEMORY;
  136. fargs.stream = &stream;
  137. error = FT_Open_Face(library, &fargs, 0, &face);
  138. } else {
  139. ERR_EXPLAIN("DynamicFont uninitialized");
  140. ERR_FAIL_V(ERR_UNCONFIGURED);
  141. }
  142. //error = FT_New_Face( library, src_path.utf8().get_data(),0,&face );
  143. if (error == FT_Err_Unknown_File_Format) {
  144. ERR_EXPLAIN(TTR("Unknown font format."));
  145. FT_Done_FreeType(library);
  146. } else if (error) {
  147. ERR_EXPLAIN(TTR("Error loading font."));
  148. FT_Done_FreeType(library);
  149. }
  150. ERR_FAIL_COND_V(error, ERR_FILE_CANT_OPEN);
  151. /*error = FT_Set_Char_Size(face,0,64*size,512,512);
  152. if ( error ) {
  153. FT_Done_FreeType( library );
  154. ERR_EXPLAIN(TTR("Invalid font size."));
  155. ERR_FAIL_COND_V( error, ERR_INVALID_PARAMETER );
  156. }*/
  157. if (FT_HAS_COLOR(face)) {
  158. int best_match = 0;
  159. int diff = ABS(id.size - ((int64_t)face->available_sizes[0].width));
  160. scale_color_font = float(id.size) / face->available_sizes[0].width;
  161. for (int i = 1; i < face->num_fixed_sizes; i++) {
  162. int ndiff = ABS(id.size - ((int64_t)face->available_sizes[i].width));
  163. if (ndiff < diff) {
  164. best_match = i;
  165. diff = ndiff;
  166. scale_color_font = float(id.size) / face->available_sizes[i].width;
  167. }
  168. }
  169. FT_Select_Size(face, best_match);
  170. } else {
  171. FT_Set_Pixel_Sizes(face, 0, id.size * oversampling);
  172. }
  173. ascent = (face->size->metrics.ascender / 64.0) / oversampling * scale_color_font;
  174. descent = (-face->size->metrics.descender / 64.0) / oversampling * scale_color_font;
  175. linegap = 0;
  176. texture_flags = 0;
  177. if (id.mipmaps)
  178. texture_flags |= Texture::FLAG_MIPMAPS;
  179. if (id.filter)
  180. texture_flags |= Texture::FLAG_FILTER;
  181. valid = true;
  182. return OK;
  183. }
  184. float DynamicFontAtSize::font_oversampling = 1.0;
  185. float DynamicFontAtSize::get_height() const {
  186. return ascent + descent;
  187. }
  188. float DynamicFontAtSize::get_ascent() const {
  189. return ascent;
  190. }
  191. float DynamicFontAtSize::get_descent() const {
  192. return descent;
  193. }
  194. const Pair<const DynamicFontAtSize::Character *, DynamicFontAtSize *> DynamicFontAtSize::_find_char_with_font(CharType p_char, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const {
  195. const Character *chr = char_map.getptr(p_char);
  196. ERR_FAIL_COND_V(!chr, (Pair<const Character *, DynamicFontAtSize *>(NULL, NULL)));
  197. if (!chr->found) {
  198. //not found, try in fallbacks
  199. for (int i = 0; i < p_fallbacks.size(); i++) {
  200. DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr());
  201. if (!fb->valid)
  202. continue;
  203. fb->_update_char(p_char);
  204. const Character *fallback_chr = fb->char_map.getptr(p_char);
  205. ERR_CONTINUE(!fallback_chr);
  206. if (!fallback_chr->found)
  207. continue;
  208. return Pair<const Character *, DynamicFontAtSize *>(fallback_chr, fb);
  209. }
  210. //not found, try 0xFFFD to display 'not found'.
  211. const_cast<DynamicFontAtSize *>(this)->_update_char(0xFFFD);
  212. chr = char_map.getptr(0xFFFD);
  213. ERR_FAIL_COND_V(!chr, (Pair<const Character *, DynamicFontAtSize *>(NULL, NULL)));
  214. }
  215. return Pair<const Character *, DynamicFontAtSize *>(chr, const_cast<DynamicFontAtSize *>(this));
  216. }
  217. float DynamicFontAtSize::_get_kerning_advance(const DynamicFontAtSize *font, CharType p_char, CharType p_next) const {
  218. float advance = 0.0;
  219. if (p_next) {
  220. FT_Vector delta;
  221. FT_Get_Kerning(font->face, p_char, p_next, FT_KERNING_DEFAULT, &delta);
  222. advance = (delta.x / 64.0) / oversampling;
  223. }
  224. return advance;
  225. }
  226. Size2 DynamicFontAtSize::get_char_size(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const {
  227. if (!valid)
  228. return Size2(1, 1);
  229. const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
  230. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(p_char, p_fallbacks);
  231. const Character *ch = char_pair_with_font.first;
  232. DynamicFontAtSize *font = char_pair_with_font.second;
  233. ERR_FAIL_COND_V(!ch, Size2());
  234. Size2 ret(0, get_height());
  235. if (ch->found) {
  236. ret.x = ch->advance;
  237. }
  238. ret.x += _get_kerning_advance(font, p_char, p_next);
  239. return ret;
  240. }
  241. void DynamicFontAtSize::set_texture_flags(uint32_t p_flags) {
  242. texture_flags = p_flags;
  243. for (int i = 0; i < textures.size(); i++) {
  244. Ref<ImageTexture> &tex = textures.write[i].texture;
  245. if (!tex.is_null())
  246. tex->set_flags(p_flags);
  247. }
  248. }
  249. 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) const {
  250. if (!valid)
  251. return 0;
  252. const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
  253. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(p_char, p_fallbacks);
  254. const Character *ch = char_pair_with_font.first;
  255. DynamicFontAtSize *font = char_pair_with_font.second;
  256. ERR_FAIL_COND_V(!ch, 0.0);
  257. float advance = 0.0;
  258. if (ch->found) {
  259. ERR_FAIL_COND_V(ch->texture_idx < -1 || ch->texture_idx >= font->textures.size(), 0);
  260. if (!p_advance_only && ch->texture_idx != -1) {
  261. Point2 cpos = p_pos;
  262. cpos.x += ch->h_align;
  263. cpos.y -= font->get_ascent();
  264. cpos.y += ch->v_align;
  265. Color modulate = p_modulate;
  266. if (FT_HAS_COLOR(face)) {
  267. modulate.r = modulate.g = modulate.b = 1.0;
  268. }
  269. RID texture = font->textures[ch->texture_idx].texture->get_rid();
  270. 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);
  271. }
  272. advance = ch->advance;
  273. }
  274. advance += _get_kerning_advance(font, p_char, p_next);
  275. return advance;
  276. }
  277. unsigned long DynamicFontAtSize::_ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count) {
  278. FileAccess *f = (FileAccess *)stream->descriptor.pointer;
  279. if (f->get_position() != offset) {
  280. f->seek(offset);
  281. }
  282. if (count == 0)
  283. return 0;
  284. return f->get_buffer(buffer, count);
  285. }
  286. void DynamicFontAtSize::_ft_stream_close(FT_Stream stream) {
  287. FileAccess *f = (FileAccess *)stream->descriptor.pointer;
  288. f->close();
  289. memdelete(f);
  290. }
  291. DynamicFontAtSize::Character DynamicFontAtSize::Character::not_found() {
  292. Character ch;
  293. ch.texture_idx = -1;
  294. ch.advance = 0;
  295. ch.h_align = 0;
  296. ch.v_align = 0;
  297. ch.found = false;
  298. return ch;
  299. }
  300. DynamicFontAtSize::TexturePosition DynamicFontAtSize::_find_texture_pos_for_glyph(int p_color_size, Image::Format p_image_format, int p_width, int p_height) {
  301. TexturePosition ret;
  302. ret.index = -1;
  303. ret.x = 0;
  304. ret.y = 0;
  305. int mw = p_width;
  306. int mh = p_height;
  307. for (int i = 0; i < textures.size(); i++) {
  308. const CharTexture &ct = textures[i];
  309. if (ct.texture->get_format() != p_image_format)
  310. continue;
  311. if (mw > ct.texture_size || mh > ct.texture_size) //too big for this texture
  312. continue;
  313. ret.y = 0x7FFFFFFF;
  314. ret.x = 0;
  315. for (int j = 0; j < ct.texture_size - mw; j++) {
  316. int max_y = 0;
  317. for (int k = j; k < j + mw; k++) {
  318. int y = ct.offsets[k];
  319. if (y > max_y)
  320. max_y = y;
  321. }
  322. if (max_y < ret.y) {
  323. ret.y = max_y;
  324. ret.x = j;
  325. }
  326. }
  327. if (ret.y == 0x7FFFFFFF || ret.y + mh > ct.texture_size)
  328. continue; //fail, could not fit it here
  329. ret.index = i;
  330. break;
  331. }
  332. if (ret.index == -1) {
  333. //could not find texture to fit, create one
  334. ret.x = 0;
  335. ret.y = 0;
  336. int texsize = MAX(id.size * oversampling * 8, 256);
  337. if (mw > texsize)
  338. texsize = mw; //special case, adapt to it?
  339. if (mh > texsize)
  340. texsize = mh; //special case, adapt to it?
  341. texsize = next_power_of_2(texsize);
  342. texsize = MIN(texsize, 4096);
  343. CharTexture tex;
  344. tex.texture_size = texsize;
  345. tex.imgdata.resize(texsize * texsize * p_color_size); //grayscale alpha
  346. {
  347. //zero texture
  348. PoolVector<uint8_t>::Write w = tex.imgdata.write();
  349. ERR_FAIL_COND_V(texsize * texsize * p_color_size > tex.imgdata.size(), ret);
  350. for (int i = 0; i < texsize * texsize * p_color_size; i++) {
  351. w[i] = 0;
  352. }
  353. }
  354. tex.offsets.resize(texsize);
  355. for (int i = 0; i < texsize; i++) //zero offsets
  356. tex.offsets.write[i] = 0;
  357. textures.push_back(tex);
  358. ret.index = textures.size() - 1;
  359. }
  360. return ret;
  361. }
  362. DynamicFontAtSize::Character DynamicFontAtSize::_bitmap_to_character(FT_Bitmap bitmap, int yofs, int xofs, float advance) {
  363. int w = bitmap.width;
  364. int h = bitmap.rows;
  365. int mw = w + rect_margin * 2;
  366. int mh = h + rect_margin * 2;
  367. ERR_FAIL_COND_V(mw > 4096, Character::not_found());
  368. ERR_FAIL_COND_V(mh > 4096, Character::not_found());
  369. int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2;
  370. Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8;
  371. TexturePosition tex_pos = _find_texture_pos_for_glyph(color_size, require_format, mw, mh);
  372. ERR_FAIL_COND_V(tex_pos.index < 0, Character::not_found());
  373. //fit character in char texture
  374. CharTexture &tex = textures.write[tex_pos.index];
  375. {
  376. PoolVector<uint8_t>::Write wr = tex.imgdata.write();
  377. for (int i = 0; i < h; i++) {
  378. for (int j = 0; j < w; j++) {
  379. int ofs = ((i + tex_pos.y + rect_margin) * tex.texture_size + j + tex_pos.x + rect_margin) * color_size;
  380. ERR_FAIL_COND_V(ofs >= tex.imgdata.size(), Character::not_found());
  381. switch (bitmap.pixel_mode) {
  382. case FT_PIXEL_MODE_MONO: {
  383. int byte = i * bitmap.pitch + (j >> 3);
  384. int bit = 1 << (7 - (j % 8));
  385. wr[ofs + 0] = 255; //grayscale as 1
  386. wr[ofs + 1] = bitmap.buffer[byte] & bit ? 255 : 0;
  387. } break;
  388. case FT_PIXEL_MODE_GRAY:
  389. wr[ofs + 0] = 255; //grayscale as 1
  390. wr[ofs + 1] = bitmap.buffer[i * bitmap.pitch + j];
  391. break;
  392. case FT_PIXEL_MODE_BGRA: {
  393. int ofs_color = i * bitmap.pitch + (j << 2);
  394. wr[ofs + 2] = bitmap.buffer[ofs_color + 0];
  395. wr[ofs + 1] = bitmap.buffer[ofs_color + 1];
  396. wr[ofs + 0] = bitmap.buffer[ofs_color + 2];
  397. wr[ofs + 3] = bitmap.buffer[ofs_color + 3];
  398. } break;
  399. // TODO: FT_PIXEL_MODE_LCD
  400. default:
  401. ERR_EXPLAIN("Font uses unsupported pixel format: " + itos(bitmap.pixel_mode));
  402. ERR_FAIL_V(Character::not_found());
  403. break;
  404. }
  405. }
  406. }
  407. }
  408. //blit to image and texture
  409. {
  410. Ref<Image> img = memnew(Image(tex.texture_size, tex.texture_size, 0, require_format, tex.imgdata));
  411. if (tex.texture.is_null()) {
  412. tex.texture.instance();
  413. tex.texture->create_from_image(img, Texture::FLAG_VIDEO_SURFACE | texture_flags);
  414. } else {
  415. tex.texture->set_data(img); //update
  416. }
  417. }
  418. // update height array
  419. for (int k = tex_pos.x; k < tex_pos.x + mw; k++) {
  420. tex.offsets.write[k] = tex_pos.y + mh;
  421. }
  422. Character chr;
  423. chr.h_align = xofs * scale_color_font / oversampling;
  424. chr.v_align = ascent - (yofs * scale_color_font / oversampling); // + ascent - descent;
  425. chr.advance = advance * scale_color_font / oversampling;
  426. chr.texture_idx = tex_pos.index;
  427. chr.found = true;
  428. chr.rect_uv = Rect2(tex_pos.x + rect_margin, tex_pos.y + rect_margin, w, h);
  429. chr.rect = chr.rect_uv;
  430. chr.rect.position /= oversampling;
  431. chr.rect.size = chr.rect.size * scale_color_font / oversampling;
  432. return chr;
  433. }
  434. DynamicFontAtSize::Character DynamicFontAtSize::_make_outline_char(CharType p_char) {
  435. Character ret = Character::not_found();
  436. if (FT_Load_Char(face, p_char, FT_LOAD_NO_BITMAP | (font->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0)) != 0)
  437. return ret;
  438. FT_Stroker stroker;
  439. if (FT_Stroker_New(library, &stroker) != 0)
  440. return ret;
  441. FT_Stroker_Set(stroker, (int)(id.outline_size * oversampling * 64.0), FT_STROKER_LINECAP_BUTT, FT_STROKER_LINEJOIN_ROUND, 0);
  442. FT_Glyph glyph;
  443. FT_BitmapGlyph glyph_bitmap;
  444. if (FT_Get_Glyph(face->glyph, &glyph) != 0)
  445. goto cleanup_stroker;
  446. if (FT_Glyph_Stroke(&glyph, stroker, 1) != 0)
  447. goto cleanup_glyph;
  448. if (FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1) != 0)
  449. goto cleanup_glyph;
  450. glyph_bitmap = (FT_BitmapGlyph)glyph;
  451. ret = _bitmap_to_character(glyph_bitmap->bitmap, glyph_bitmap->top, glyph_bitmap->left, glyph->advance.x / 65536.0);
  452. cleanup_glyph:
  453. FT_Done_Glyph(glyph);
  454. cleanup_stroker:
  455. FT_Stroker_Done(stroker);
  456. return ret;
  457. }
  458. void DynamicFontAtSize::_update_char(CharType p_char) {
  459. if (char_map.has(p_char))
  460. return;
  461. _THREAD_SAFE_METHOD_
  462. Character character = Character::not_found();
  463. FT_GlyphSlot slot = face->glyph;
  464. if (FT_Get_Char_Index(face, p_char) == 0) {
  465. char_map[p_char] = character;
  466. return;
  467. }
  468. int ft_hinting;
  469. switch (font->hinting) {
  470. case DynamicFontData::HINTING_NONE:
  471. ft_hinting = FT_LOAD_NO_HINTING;
  472. break;
  473. case DynamicFontData::HINTING_LIGHT:
  474. ft_hinting = FT_LOAD_TARGET_LIGHT;
  475. break;
  476. default:
  477. ft_hinting = FT_LOAD_TARGET_NORMAL;
  478. break;
  479. }
  480. 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);
  481. if (error) {
  482. char_map[p_char] = character;
  483. return;
  484. }
  485. if (id.outline_size > 0) {
  486. character = _make_outline_char(p_char);
  487. } else {
  488. error = FT_Render_Glyph(face->glyph, font->antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
  489. if (!error)
  490. character = _bitmap_to_character(slot->bitmap, slot->bitmap_top, slot->bitmap_left, slot->advance.x / 64.0);
  491. }
  492. char_map[p_char] = character;
  493. }
  494. void DynamicFontAtSize::update_oversampling() {
  495. if (oversampling == font_oversampling || !valid)
  496. return;
  497. FT_Done_FreeType(library);
  498. textures.clear();
  499. char_map.clear();
  500. oversampling = font_oversampling;
  501. valid = false;
  502. _load();
  503. }
  504. DynamicFontAtSize::DynamicFontAtSize() {
  505. valid = false;
  506. rect_margin = 1;
  507. ascent = 1;
  508. descent = 1;
  509. linegap = 1;
  510. texture_flags = 0;
  511. oversampling = font_oversampling;
  512. scale_color_font = 1;
  513. }
  514. DynamicFontAtSize::~DynamicFontAtSize() {
  515. if (valid) {
  516. FT_Done_FreeType(library);
  517. }
  518. font->size_cache.erase(id);
  519. font.unref();
  520. }
  521. /////////////////////////
  522. void DynamicFont::_reload_cache() {
  523. ERR_FAIL_COND(cache_id.size < 1);
  524. if (!data.is_valid()) {
  525. data_at_size.unref();
  526. outline_data_at_size.unref();
  527. fallback_data_at_size.resize(0);
  528. fallback_outline_data_at_size.resize(0);
  529. return;
  530. }
  531. data_at_size = data->_get_dynamic_font_at_size(cache_id);
  532. if (outline_cache_id.outline_size > 0) {
  533. outline_data_at_size = data->_get_dynamic_font_at_size(outline_cache_id);
  534. fallback_outline_data_at_size.resize(fallback_data_at_size.size());
  535. } else {
  536. outline_data_at_size.unref();
  537. fallback_outline_data_at_size.resize(0);
  538. }
  539. for (int i = 0; i < fallbacks.size(); i++) {
  540. fallback_data_at_size.write[i] = fallbacks.write[i]->_get_dynamic_font_at_size(cache_id);
  541. if (outline_cache_id.outline_size > 0)
  542. fallback_outline_data_at_size.write[i] = fallbacks.write[i]->_get_dynamic_font_at_size(outline_cache_id);
  543. }
  544. emit_changed();
  545. _change_notify();
  546. }
  547. void DynamicFont::set_font_data(const Ref<DynamicFontData> &p_data) {
  548. data = p_data;
  549. _reload_cache();
  550. emit_changed();
  551. _change_notify();
  552. }
  553. Ref<DynamicFontData> DynamicFont::get_font_data() const {
  554. return data;
  555. }
  556. void DynamicFont::set_size(int p_size) {
  557. if (cache_id.size == p_size)
  558. return;
  559. cache_id.size = p_size;
  560. outline_cache_id.size = p_size;
  561. _reload_cache();
  562. }
  563. int DynamicFont::get_size() const {
  564. return cache_id.size;
  565. }
  566. void DynamicFont::set_outline_size(int p_size) {
  567. if (outline_cache_id.outline_size == p_size)
  568. return;
  569. ERR_FAIL_COND(p_size < 0 || p_size > UINT8_MAX);
  570. outline_cache_id.outline_size = p_size;
  571. _reload_cache();
  572. }
  573. int DynamicFont::get_outline_size() const {
  574. return outline_cache_id.outline_size;
  575. }
  576. void DynamicFont::set_outline_color(Color p_color) {
  577. if (p_color != outline_color) {
  578. outline_color = p_color;
  579. emit_changed();
  580. _change_notify();
  581. }
  582. }
  583. Color DynamicFont::get_outline_color() const {
  584. return outline_color;
  585. }
  586. bool DynamicFont::get_use_mipmaps() const {
  587. return cache_id.mipmaps;
  588. }
  589. void DynamicFont::set_use_mipmaps(bool p_enable) {
  590. if (cache_id.mipmaps == p_enable)
  591. return;
  592. cache_id.mipmaps = p_enable;
  593. outline_cache_id.mipmaps = p_enable;
  594. _reload_cache();
  595. }
  596. bool DynamicFont::get_use_filter() const {
  597. return cache_id.filter;
  598. }
  599. void DynamicFont::set_use_filter(bool p_enable) {
  600. if (cache_id.filter == p_enable)
  601. return;
  602. cache_id.filter = p_enable;
  603. outline_cache_id.filter = p_enable;
  604. _reload_cache();
  605. }
  606. bool DynamicFontData::is_antialiased() const {
  607. return antialiased;
  608. }
  609. void DynamicFontData::set_antialiased(bool p_antialiased) {
  610. if (antialiased == p_antialiased)
  611. return;
  612. antialiased = p_antialiased;
  613. }
  614. DynamicFontData::Hinting DynamicFontData::get_hinting() const {
  615. return hinting;
  616. }
  617. void DynamicFontData::set_hinting(Hinting p_hinting) {
  618. if (hinting == p_hinting)
  619. return;
  620. hinting = p_hinting;
  621. }
  622. int DynamicFont::get_spacing(int p_type) const {
  623. if (p_type == SPACING_TOP) {
  624. return spacing_top;
  625. } else if (p_type == SPACING_BOTTOM) {
  626. return spacing_bottom;
  627. } else if (p_type == SPACING_CHAR) {
  628. return spacing_char;
  629. } else if (p_type == SPACING_SPACE) {
  630. return spacing_space;
  631. }
  632. return 0;
  633. }
  634. void DynamicFont::set_spacing(int p_type, int p_value) {
  635. if (p_type == SPACING_TOP) {
  636. spacing_top = p_value;
  637. } else if (p_type == SPACING_BOTTOM) {
  638. spacing_bottom = p_value;
  639. } else if (p_type == SPACING_CHAR) {
  640. spacing_char = p_value;
  641. } else if (p_type == SPACING_SPACE) {
  642. spacing_space = p_value;
  643. }
  644. emit_changed();
  645. _change_notify();
  646. }
  647. float DynamicFont::get_height() const {
  648. if (!data_at_size.is_valid())
  649. return 1;
  650. return data_at_size->get_height() + spacing_top + spacing_bottom;
  651. }
  652. float DynamicFont::get_ascent() const {
  653. if (!data_at_size.is_valid())
  654. return 1;
  655. return data_at_size->get_ascent() + spacing_top;
  656. }
  657. float DynamicFont::get_descent() const {
  658. if (!data_at_size.is_valid())
  659. return 1;
  660. return data_at_size->get_descent() + spacing_bottom;
  661. }
  662. Size2 DynamicFont::get_char_size(CharType p_char, CharType p_next) const {
  663. if (!data_at_size.is_valid())
  664. return Size2(1, 1);
  665. Size2 ret = data_at_size->get_char_size(p_char, p_next, fallback_data_at_size);
  666. if (p_char == ' ')
  667. ret.width += spacing_space + spacing_char;
  668. else if (p_next)
  669. ret.width += spacing_char;
  670. return ret;
  671. }
  672. bool DynamicFont::is_distance_field_hint() const {
  673. return false;
  674. }
  675. bool DynamicFont::has_outline() const {
  676. return outline_cache_id.outline_size > 0;
  677. }
  678. 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 {
  679. const Ref<DynamicFontAtSize> &font_at_size = p_outline && outline_cache_id.outline_size > 0 ? outline_data_at_size : data_at_size;
  680. if (!font_at_size.is_valid())
  681. return 0;
  682. const Vector<Ref<DynamicFontAtSize> > &fallbacks = p_outline && outline_cache_id.outline_size > 0 ? fallback_outline_data_at_size : fallback_data_at_size;
  683. Color color = p_outline && outline_cache_id.outline_size > 0 ? p_modulate * outline_color : p_modulate;
  684. // If requested outline draw, but no outline is present, simply return advance without drawing anything
  685. bool advance_only = p_outline && outline_cache_id.outline_size == 0;
  686. return font_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, color, fallbacks, advance_only) + spacing_char;
  687. }
  688. void DynamicFont::set_fallback(int p_idx, const Ref<DynamicFontData> &p_data) {
  689. ERR_FAIL_COND(p_data.is_null());
  690. ERR_FAIL_INDEX(p_idx, fallbacks.size());
  691. fallbacks.write[p_idx] = p_data;
  692. fallback_data_at_size.write[p_idx] = fallbacks.write[p_idx]->_get_dynamic_font_at_size(cache_id);
  693. }
  694. void DynamicFont::add_fallback(const Ref<DynamicFontData> &p_data) {
  695. ERR_FAIL_COND(p_data.is_null());
  696. fallbacks.push_back(p_data);
  697. fallback_data_at_size.push_back(fallbacks.write[fallbacks.size() - 1]->_get_dynamic_font_at_size(cache_id)); //const..
  698. if (outline_cache_id.outline_size > 0)
  699. fallback_outline_data_at_size.push_back(fallbacks.write[fallbacks.size() - 1]->_get_dynamic_font_at_size(outline_cache_id));
  700. _change_notify();
  701. emit_changed();
  702. _change_notify();
  703. }
  704. int DynamicFont::get_fallback_count() const {
  705. return fallbacks.size();
  706. }
  707. Ref<DynamicFontData> DynamicFont::get_fallback(int p_idx) const {
  708. ERR_FAIL_INDEX_V(p_idx, fallbacks.size(), Ref<DynamicFontData>());
  709. return fallbacks[p_idx];
  710. }
  711. void DynamicFont::remove_fallback(int p_idx) {
  712. ERR_FAIL_INDEX(p_idx, fallbacks.size());
  713. fallbacks.remove(p_idx);
  714. fallback_data_at_size.remove(p_idx);
  715. emit_changed();
  716. _change_notify();
  717. }
  718. bool DynamicFont::_set(const StringName &p_name, const Variant &p_value) {
  719. String str = p_name;
  720. if (str.begins_with("fallback/")) {
  721. int idx = str.get_slicec('/', 1).to_int();
  722. Ref<DynamicFontData> fd = p_value;
  723. if (fd.is_valid()) {
  724. if (idx == fallbacks.size()) {
  725. add_fallback(fd);
  726. return true;
  727. } else if (idx >= 0 && idx < fallbacks.size()) {
  728. set_fallback(idx, fd);
  729. return true;
  730. } else {
  731. return false;
  732. }
  733. } else if (idx >= 0 && idx < fallbacks.size()) {
  734. remove_fallback(idx);
  735. return true;
  736. }
  737. }
  738. return false;
  739. }
  740. bool DynamicFont::_get(const StringName &p_name, Variant &r_ret) const {
  741. String str = p_name;
  742. if (str.begins_with("fallback/")) {
  743. int idx = str.get_slicec('/', 1).to_int();
  744. if (idx == fallbacks.size()) {
  745. r_ret = Ref<DynamicFontData>();
  746. return true;
  747. } else if (idx >= 0 && idx < fallbacks.size()) {
  748. r_ret = get_fallback(idx);
  749. return true;
  750. }
  751. }
  752. return false;
  753. }
  754. void DynamicFont::_get_property_list(List<PropertyInfo> *p_list) const {
  755. for (int i = 0; i < fallbacks.size(); i++) {
  756. p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"));
  757. }
  758. p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(fallbacks.size()), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"));
  759. }
  760. void DynamicFont::_bind_methods() {
  761. ClassDB::bind_method(D_METHOD("set_font_data", "data"), &DynamicFont::set_font_data);
  762. ClassDB::bind_method(D_METHOD("get_font_data"), &DynamicFont::get_font_data);
  763. ClassDB::bind_method(D_METHOD("set_size", "data"), &DynamicFont::set_size);
  764. ClassDB::bind_method(D_METHOD("get_size"), &DynamicFont::get_size);
  765. ClassDB::bind_method(D_METHOD("set_outline_size", "size"), &DynamicFont::set_outline_size);
  766. ClassDB::bind_method(D_METHOD("get_outline_size"), &DynamicFont::get_outline_size);
  767. ClassDB::bind_method(D_METHOD("set_outline_color", "color"), &DynamicFont::set_outline_color);
  768. ClassDB::bind_method(D_METHOD("get_outline_color"), &DynamicFont::get_outline_color);
  769. ClassDB::bind_method(D_METHOD("set_use_mipmaps", "enable"), &DynamicFont::set_use_mipmaps);
  770. ClassDB::bind_method(D_METHOD("get_use_mipmaps"), &DynamicFont::get_use_mipmaps);
  771. ClassDB::bind_method(D_METHOD("set_use_filter", "enable"), &DynamicFont::set_use_filter);
  772. ClassDB::bind_method(D_METHOD("get_use_filter"), &DynamicFont::get_use_filter);
  773. ClassDB::bind_method(D_METHOD("set_spacing", "type", "value"), &DynamicFont::set_spacing);
  774. ClassDB::bind_method(D_METHOD("get_spacing", "type"), &DynamicFont::get_spacing);
  775. ClassDB::bind_method(D_METHOD("add_fallback", "data"), &DynamicFont::add_fallback);
  776. ClassDB::bind_method(D_METHOD("set_fallback", "idx", "data"), &DynamicFont::set_fallback);
  777. ClassDB::bind_method(D_METHOD("get_fallback", "idx"), &DynamicFont::get_fallback);
  778. ClassDB::bind_method(D_METHOD("remove_fallback", "idx"), &DynamicFont::remove_fallback);
  779. ClassDB::bind_method(D_METHOD("get_fallback_count"), &DynamicFont::get_fallback_count);
  780. ADD_GROUP("Settings", "");
  781. ADD_PROPERTY(PropertyInfo(Variant::INT, "size"), "set_size", "get_size");
  782. ADD_PROPERTY(PropertyInfo(Variant::INT, "outline_size"), "set_outline_size", "get_outline_size");
  783. ADD_PROPERTY(PropertyInfo(Variant::COLOR, "outline_color"), "set_outline_color", "get_outline_color");
  784. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_mipmaps"), "set_use_mipmaps", "get_use_mipmaps");
  785. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_filter"), "set_use_filter", "get_use_filter");
  786. ADD_GROUP("Extra Spacing", "extra_spacing");
  787. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_top"), "set_spacing", "get_spacing", SPACING_TOP);
  788. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_bottom"), "set_spacing", "get_spacing", SPACING_BOTTOM);
  789. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_char"), "set_spacing", "get_spacing", SPACING_CHAR);
  790. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_space"), "set_spacing", "get_spacing", SPACING_SPACE);
  791. ADD_GROUP("Font", "");
  792. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font_data", PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"), "set_font_data", "get_font_data");
  793. BIND_ENUM_CONSTANT(SPACING_TOP);
  794. BIND_ENUM_CONSTANT(SPACING_BOTTOM);
  795. BIND_ENUM_CONSTANT(SPACING_CHAR);
  796. BIND_ENUM_CONSTANT(SPACING_SPACE);
  797. }
  798. Mutex *DynamicFont::dynamic_font_mutex = NULL;
  799. SelfList<DynamicFont>::List *DynamicFont::dynamic_fonts = NULL;
  800. DynamicFont::DynamicFont() :
  801. font_list(this) {
  802. cache_id.size = 16;
  803. outline_cache_id.size = 16;
  804. spacing_top = 0;
  805. spacing_bottom = 0;
  806. spacing_char = 0;
  807. spacing_space = 0;
  808. outline_color = Color(1, 1, 1);
  809. if (dynamic_font_mutex) {
  810. dynamic_font_mutex->lock();
  811. dynamic_fonts->add(&font_list);
  812. dynamic_font_mutex->unlock();
  813. }
  814. }
  815. DynamicFont::~DynamicFont() {
  816. if (dynamic_font_mutex) {
  817. dynamic_font_mutex->lock();
  818. dynamic_fonts->remove(&font_list);
  819. dynamic_font_mutex->unlock();
  820. }
  821. }
  822. void DynamicFont::initialize_dynamic_fonts() {
  823. dynamic_fonts = memnew(SelfList<DynamicFont>::List());
  824. dynamic_font_mutex = Mutex::create();
  825. }
  826. void DynamicFont::finish_dynamic_fonts() {
  827. memdelete(dynamic_font_mutex);
  828. dynamic_font_mutex = NULL;
  829. memdelete(dynamic_fonts);
  830. dynamic_fonts = NULL;
  831. }
  832. void DynamicFont::update_oversampling() {
  833. Vector<Ref<DynamicFont> > changed;
  834. if (dynamic_font_mutex)
  835. dynamic_font_mutex->lock();
  836. SelfList<DynamicFont> *E = dynamic_fonts->first();
  837. while (E) {
  838. if (E->self()->data_at_size.is_valid()) {
  839. E->self()->data_at_size->update_oversampling();
  840. if (E->self()->outline_data_at_size.is_valid()) {
  841. E->self()->outline_data_at_size->update_oversampling();
  842. }
  843. for (int i = 0; i < E->self()->fallback_data_at_size.size(); i++) {
  844. if (E->self()->fallback_data_at_size[i].is_valid()) {
  845. E->self()->fallback_data_at_size.write[i]->update_oversampling();
  846. if (E->self()->has_outline() && E->self()->fallback_outline_data_at_size[i].is_valid()) {
  847. E->self()->fallback_outline_data_at_size.write[i]->update_oversampling();
  848. }
  849. }
  850. }
  851. changed.push_back(Ref<DynamicFont>(E->self()));
  852. }
  853. E = E->next();
  854. }
  855. if (dynamic_font_mutex)
  856. dynamic_font_mutex->unlock();
  857. for (int i = 0; i < changed.size(); i++) {
  858. changed.write[i]->emit_changed();
  859. }
  860. }
  861. /////////////////////////
  862. RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String &p_original_path, Error *r_error) {
  863. if (r_error)
  864. *r_error = ERR_FILE_CANT_OPEN;
  865. Ref<DynamicFontData> dfont;
  866. dfont.instance();
  867. dfont->set_font_path(p_path);
  868. if (r_error)
  869. *r_error = OK;
  870. return dfont;
  871. }
  872. void ResourceFormatLoaderDynamicFont::get_recognized_extensions(List<String> *p_extensions) const {
  873. p_extensions->push_back("ttf");
  874. p_extensions->push_back("otf");
  875. }
  876. bool ResourceFormatLoaderDynamicFont::handles_type(const String &p_type) const {
  877. return (p_type == "DynamicFontData");
  878. }
  879. String ResourceFormatLoaderDynamicFont::get_resource_type(const String &p_path) const {
  880. String el = p_path.get_extension().to_lower();
  881. if (el == "ttf" || el == "otf")
  882. return "DynamicFontData";
  883. return "";
  884. }
  885. #endif