dynamic_font.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. /*************************************************************************/
  2. /* dynamic_font.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 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 "os/file_access.h"
  33. #include "os/os.h"
  34. bool DynamicFontData::CacheID::operator<(CacheID right) const {
  35. if (size < right.size)
  36. return true;
  37. if (mipmaps != right.mipmaps)
  38. return right.mipmaps;
  39. if (filter != right.filter)
  40. return right.filter;
  41. return false;
  42. }
  43. Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(CacheID p_cache_id) {
  44. if (size_cache.has(p_cache_id)) {
  45. return Ref<DynamicFontAtSize>(size_cache[p_cache_id]);
  46. }
  47. Ref<DynamicFontAtSize> dfas;
  48. dfas.instance();
  49. dfas->font = Ref<DynamicFontData>(this);
  50. size_cache[p_cache_id] = dfas.ptr();
  51. dfas->id = p_cache_id;
  52. dfas->_load();
  53. return dfas;
  54. }
  55. void DynamicFontData::set_font_ptr(const uint8_t *p_font_mem, int p_font_mem_size) {
  56. font_mem = p_font_mem;
  57. font_mem_size = p_font_mem_size;
  58. }
  59. void DynamicFontData::set_font_path(const String &p_path) {
  60. font_path = p_path;
  61. }
  62. String DynamicFontData::get_font_path() const {
  63. return font_path;
  64. }
  65. void DynamicFontData::set_force_autohinter(bool p_force) {
  66. force_autohinter = p_force;
  67. }
  68. void DynamicFontData::_bind_methods() {
  69. ClassDB::bind_method(D_METHOD("set_font_path", "path"), &DynamicFontData::set_font_path);
  70. ClassDB::bind_method(D_METHOD("get_font_path"), &DynamicFontData::get_font_path);
  71. ADD_PROPERTY(PropertyInfo(Variant::STRING, "font_path", PROPERTY_HINT_FILE, "*.ttf,*.otf"), "set_font_path", "get_font_path");
  72. }
  73. DynamicFontData::DynamicFontData() {
  74. force_autohinter = false;
  75. font_mem = NULL;
  76. font_mem_size = 0;
  77. }
  78. DynamicFontData::~DynamicFontData() {
  79. }
  80. ////////////////////
  81. HashMap<String, Vector<uint8_t> > DynamicFontAtSize::_fontdata;
  82. Error DynamicFontAtSize::_load() {
  83. int error = FT_Init_FreeType(&library);
  84. ERR_EXPLAIN(TTR("Error initializing FreeType."));
  85. ERR_FAIL_COND_V(error != 0, ERR_CANT_CREATE);
  86. // FT_OPEN_STREAM is extremely slow only on Android.
  87. if (OS::get_singleton()->get_name() == "Android" && font->font_mem == NULL && font->font_path != String()) {
  88. // cache font only once for each font->font_path
  89. if (_fontdata.has(font->font_path)) {
  90. font->set_font_ptr(_fontdata[font->font_path].ptr(), _fontdata[font->font_path].size());
  91. } else {
  92. FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
  93. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  94. size_t len = f->get_len();
  95. _fontdata[font->font_path] = Vector<uint8_t>();
  96. Vector<uint8_t> &fontdata = _fontdata[font->font_path];
  97. fontdata.resize(len);
  98. f->get_buffer(fontdata.ptr(), len);
  99. font->set_font_ptr(fontdata.ptr(), len);
  100. f->close();
  101. }
  102. }
  103. if (font->font_mem == NULL && font->font_path != String()) {
  104. FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
  105. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  106. memset(&stream, 0, sizeof(FT_StreamRec));
  107. stream.base = NULL;
  108. stream.size = f->get_len();
  109. stream.pos = 0;
  110. stream.descriptor.pointer = f;
  111. stream.read = _ft_stream_io;
  112. stream.close = _ft_stream_close;
  113. FT_Open_Args fargs;
  114. memset(&fargs, 0, sizeof(FT_Open_Args));
  115. fargs.flags = FT_OPEN_STREAM;
  116. fargs.stream = &stream;
  117. error = FT_Open_Face(library, &fargs, 0, &face);
  118. } else if (font->font_mem) {
  119. memset(&stream, 0, sizeof(FT_StreamRec));
  120. stream.base = (unsigned char *)font->font_mem;
  121. stream.size = font->font_mem_size;
  122. stream.pos = 0;
  123. FT_Open_Args fargs;
  124. memset(&fargs, 0, sizeof(FT_Open_Args));
  125. fargs.memory_base = (unsigned char *)font->font_mem;
  126. fargs.memory_size = font->font_mem_size;
  127. fargs.flags = FT_OPEN_MEMORY;
  128. fargs.stream = &stream;
  129. error = FT_Open_Face(library, &fargs, 0, &face);
  130. } else {
  131. ERR_EXPLAIN("DynamicFont uninitialized");
  132. ERR_FAIL_V(ERR_UNCONFIGURED);
  133. }
  134. //error = FT_New_Face( library, src_path.utf8().get_data(),0,&face );
  135. if (error == FT_Err_Unknown_File_Format) {
  136. ERR_EXPLAIN(TTR("Unknown font format."));
  137. FT_Done_FreeType(library);
  138. } else if (error) {
  139. ERR_EXPLAIN(TTR("Error loading font."));
  140. FT_Done_FreeType(library);
  141. }
  142. ERR_FAIL_COND_V(error, ERR_FILE_CANT_OPEN);
  143. /*error = FT_Set_Char_Size(face,0,64*size,512,512);
  144. if ( error ) {
  145. FT_Done_FreeType( library );
  146. ERR_EXPLAIN(TTR("Invalid font size."));
  147. ERR_FAIL_COND_V( error, ERR_INVALID_PARAMETER );
  148. }*/
  149. error = FT_Set_Pixel_Sizes(face, 0, id.size);
  150. ascent = face->size->metrics.ascender >> 6;
  151. descent = -face->size->metrics.descender >> 6;
  152. linegap = 0;
  153. texture_flags = 0;
  154. if (id.mipmaps)
  155. texture_flags |= Texture::FLAG_MIPMAPS;
  156. if (id.filter)
  157. texture_flags |= Texture::FLAG_FILTER;
  158. //print_line("ASCENT: "+itos(ascent)+" descent "+itos(descent)+" hinted: "+itos(face->face_flags&FT_FACE_FLAG_HINTER));
  159. valid = true;
  160. return OK;
  161. }
  162. float DynamicFontAtSize::get_height() const {
  163. return ascent + descent;
  164. }
  165. float DynamicFontAtSize::get_ascent() const {
  166. return ascent;
  167. }
  168. float DynamicFontAtSize::get_descent() const {
  169. return descent;
  170. }
  171. Size2 DynamicFontAtSize::get_char_size(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const {
  172. if (!valid)
  173. return Size2(1, 1);
  174. const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
  175. const Character *c = char_map.getptr(p_char);
  176. ERR_FAIL_COND_V(!c, Size2());
  177. Size2 ret(0, get_height());
  178. if (!c->found) {
  179. //not found, try in fallbacks
  180. for (int i = 0; i < p_fallbacks.size(); i++) {
  181. DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr());
  182. if (!fb->valid)
  183. continue;
  184. fb->_update_char(p_char);
  185. const Character *ch = fb->char_map.getptr(p_char);
  186. ERR_CONTINUE(!ch);
  187. if (!ch->found)
  188. continue;
  189. c = ch;
  190. break;
  191. }
  192. //not found, try 0xFFFD to display 'not found'.
  193. if (!c->found) {
  194. const_cast<DynamicFontAtSize *>(this)->_update_char(0xFFFD);
  195. c = char_map.getptr(0xFFFD);
  196. ERR_FAIL_COND_V(!c, Size2());
  197. }
  198. }
  199. if (c->found) {
  200. ret.x = c->advance;
  201. }
  202. if (p_next) {
  203. FT_Vector delta;
  204. FT_Get_Kerning(face, p_char, p_next, FT_KERNING_DEFAULT, &delta);
  205. if (delta.x == 0) {
  206. for (int i = 0; i < p_fallbacks.size(); i++) {
  207. DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr());
  208. if (!fb->valid)
  209. continue;
  210. FT_Get_Kerning(fb->face, p_char, p_next, FT_KERNING_DEFAULT, &delta);
  211. if (delta.x == 0)
  212. continue;
  213. ret.x += delta.x >> 6;
  214. break;
  215. }
  216. } else {
  217. ret.x += delta.x >> 6;
  218. }
  219. }
  220. return ret;
  221. }
  222. void DynamicFontAtSize::set_texture_flags(uint32_t p_flags) {
  223. texture_flags = p_flags;
  224. for (int i = 0; i < textures.size(); i++) {
  225. Ref<ImageTexture> &tex = textures[i].texture;
  226. if (!tex.is_null())
  227. tex->set_flags(p_flags);
  228. }
  229. }
  230. 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) const {
  231. if (!valid)
  232. return 0;
  233. const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
  234. const Character *c = char_map.getptr(p_char);
  235. float advance = 0;
  236. if (!c->found) {
  237. //not found, try in fallbacks
  238. bool used_fallback = false;
  239. for (int i = 0; i < p_fallbacks.size(); i++) {
  240. DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr());
  241. if (!fb->valid)
  242. continue;
  243. fb->_update_char(p_char);
  244. const Character *ch = fb->char_map.getptr(p_char);
  245. ERR_CONTINUE(!ch);
  246. if (!ch->found)
  247. continue;
  248. Point2 cpos = p_pos;
  249. cpos.x += ch->h_align;
  250. cpos.y -= get_ascent();
  251. cpos.y += ch->v_align;
  252. ERR_FAIL_COND_V(ch->texture_idx < -1 || ch->texture_idx >= fb->textures.size(), 0);
  253. if (ch->texture_idx != -1)
  254. VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, ch->rect.size), fb->textures[ch->texture_idx].texture->get_rid(), ch->rect, p_modulate, false, RID(), false);
  255. advance = ch->advance;
  256. used_fallback = true;
  257. break;
  258. }
  259. //not found, try 0xFFFD to display 'not found'.
  260. if (!used_fallback) {
  261. const_cast<DynamicFontAtSize *>(this)->_update_char(0xFFFD);
  262. c = char_map.getptr(0xFFFD);
  263. }
  264. }
  265. if (c->found) {
  266. Point2 cpos = p_pos;
  267. cpos.x += c->h_align;
  268. cpos.y -= get_ascent();
  269. cpos.y += c->v_align;
  270. ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), 0);
  271. if (c->texture_idx != -1)
  272. VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, c->rect.size), textures[c->texture_idx].texture->get_rid(), c->rect, p_modulate, false, RID(), false);
  273. advance = c->advance;
  274. //textures[c->texture_idx].texture->draw(p_canvas_item,Vector2());
  275. }
  276. if (p_next) {
  277. FT_Vector delta;
  278. FT_Get_Kerning(face, p_char, p_next, FT_KERNING_DEFAULT, &delta);
  279. if (delta.x == 0) {
  280. for (int i = 0; i < p_fallbacks.size(); i++) {
  281. DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr());
  282. if (!fb->valid)
  283. continue;
  284. FT_Get_Kerning(fb->face, p_char, p_next, FT_KERNING_DEFAULT, &delta);
  285. if (delta.x == 0)
  286. continue;
  287. advance += delta.x >> 6;
  288. break;
  289. }
  290. } else {
  291. advance += delta.x >> 6;
  292. }
  293. }
  294. return advance;
  295. }
  296. unsigned long DynamicFontAtSize::_ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count) {
  297. FileAccess *f = (FileAccess *)stream->descriptor.pointer;
  298. if (f->get_position() != offset) {
  299. f->seek(offset);
  300. }
  301. if (count == 0)
  302. return 0;
  303. return f->get_buffer(buffer, count);
  304. }
  305. void DynamicFontAtSize::_ft_stream_close(FT_Stream stream) {
  306. FileAccess *f = (FileAccess *)stream->descriptor.pointer;
  307. f->close();
  308. memdelete(f);
  309. }
  310. void DynamicFontAtSize::_update_char(CharType p_char) {
  311. if (char_map.has(p_char))
  312. return;
  313. _THREAD_SAFE_METHOD_
  314. FT_GlyphSlot slot = face->glyph;
  315. if (FT_Get_Char_Index(face, p_char) == 0) {
  316. //not found
  317. Character ch;
  318. ch.texture_idx = -1;
  319. ch.advance = 0;
  320. ch.h_align = 0;
  321. ch.v_align = 0;
  322. ch.found = false;
  323. char_map[p_char] = ch;
  324. return;
  325. }
  326. int error = FT_Load_Char(face, p_char, FT_LOAD_RENDER | (font->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0));
  327. if (!error) {
  328. error = FT_Render_Glyph(face->glyph, ft_render_mode_normal);
  329. }
  330. if (error) {
  331. int advance = 0;
  332. //stbtt_GetCodepointHMetrics(&font->info, p_char, &advance, 0);
  333. //print_line("char has no bitmap: "+itos(p_char)+" but advance is "+itos(advance*scale));
  334. Character ch;
  335. ch.texture_idx = -1;
  336. ch.advance = advance;
  337. ch.h_align = 0;
  338. ch.v_align = 0;
  339. ch.found = false;
  340. char_map[p_char] = ch;
  341. return;
  342. }
  343. int w = slot->bitmap.width;
  344. int h = slot->bitmap.rows;
  345. //int p = slot->bitmap.pitch;
  346. int yofs = slot->bitmap_top;
  347. int xofs = slot->bitmap_left;
  348. int advance = slot->advance.x >> 6;
  349. int mw = w + rect_margin * 2;
  350. int mh = h + rect_margin * 2;
  351. if (mw > 4096 || mh > 4096) {
  352. ERR_FAIL_COND(mw > 4096);
  353. ERR_FAIL_COND(mh > 4096);
  354. }
  355. //find a texture to fit this...
  356. int tex_index = -1;
  357. int tex_x = 0;
  358. int tex_y = 0;
  359. for (int i = 0; i < textures.size(); i++) {
  360. CharTexture &ct = textures[i];
  361. if (mw > ct.texture_size || mh > ct.texture_size) //too big for this texture
  362. continue;
  363. tex_y = 0x7FFFFFFF;
  364. tex_x = 0;
  365. for (int j = 0; j < ct.texture_size - mw; j++) {
  366. int max_y = 0;
  367. for (int k = j; k < j + mw; k++) {
  368. int y = ct.offsets[k];
  369. if (y > max_y)
  370. max_y = y;
  371. }
  372. if (max_y < tex_y) {
  373. tex_y = max_y;
  374. tex_x = j;
  375. }
  376. }
  377. if (tex_y == 0x7FFFFFFF || tex_y + mh > ct.texture_size)
  378. continue; //fail, could not fit it here
  379. tex_index = i;
  380. break;
  381. }
  382. //print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" X: "+itos(tex_x)+" Y: "+itos(tex_y));
  383. if (tex_index == -1) {
  384. //could not find texture to fit, create one
  385. tex_x = 0;
  386. tex_y = 0;
  387. int texsize = MAX(id.size * 8, 256);
  388. if (mw > texsize)
  389. texsize = mw; //special case, adapt to it?
  390. if (mh > texsize)
  391. texsize = mh; //special case, adapt to it?
  392. texsize = next_power_of_2(texsize);
  393. texsize = MIN(texsize, 4096);
  394. CharTexture tex;
  395. tex.texture_size = texsize;
  396. tex.imgdata.resize(texsize * texsize * 2); //grayscale alpha
  397. {
  398. //zero texture
  399. PoolVector<uint8_t>::Write w = tex.imgdata.write();
  400. ERR_FAIL_COND(texsize * texsize * 2 > tex.imgdata.size());
  401. for (int i = 0; i < texsize * texsize * 2; i++) {
  402. w[i] = 0;
  403. }
  404. }
  405. tex.offsets.resize(texsize);
  406. for (int i = 0; i < texsize; i++) //zero offsets
  407. tex.offsets[i] = 0;
  408. textures.push_back(tex);
  409. tex_index = textures.size() - 1;
  410. }
  411. //fit character in char texture
  412. CharTexture &tex = textures[tex_index];
  413. {
  414. PoolVector<uint8_t>::Write wr = tex.imgdata.write();
  415. for (int i = 0; i < h; i++) {
  416. for (int j = 0; j < w; j++) {
  417. int ofs = ((i + tex_y + rect_margin) * tex.texture_size + j + tex_x + rect_margin) * 2;
  418. ERR_FAIL_COND(ofs >= tex.imgdata.size());
  419. switch (slot->bitmap.pixel_mode) {
  420. case FT_PIXEL_MODE_MONO: {
  421. int byte = i * slot->bitmap.pitch + (j >> 3);
  422. int bit = 1 << (7 - (j % 8));
  423. wr[ofs + 0] = 255; //grayscale as 1
  424. wr[ofs + 1] = slot->bitmap.buffer[byte] & bit ? 255 : 0;
  425. } break;
  426. case FT_PIXEL_MODE_GRAY:
  427. wr[ofs + 0] = 255; //grayscale as 1
  428. wr[ofs + 1] = slot->bitmap.buffer[i * slot->bitmap.pitch + j];
  429. break;
  430. // TODO: FT_PIXEL_MODE_LCD, FT_PIXEL_MODE_BGRA
  431. default:
  432. ERR_EXPLAIN("Font uses unsupported pixel format: " + itos(slot->bitmap.pixel_mode));
  433. ERR_FAIL();
  434. break;
  435. }
  436. }
  437. }
  438. }
  439. //blit to image and texture
  440. {
  441. Ref<Image> img = memnew(Image(tex.texture_size, tex.texture_size, 0, Image::FORMAT_LA8, tex.imgdata));
  442. if (tex.texture.is_null()) {
  443. tex.texture.instance();
  444. tex.texture->create_from_image(img, Texture::FLAG_VIDEO_SURFACE | texture_flags);
  445. } else {
  446. tex.texture->set_data(img); //update
  447. }
  448. }
  449. // update height array
  450. for (int k = tex_x; k < tex_x + mw; k++) {
  451. tex.offsets[k] = tex_y + mh;
  452. }
  453. Character chr;
  454. chr.h_align = xofs;
  455. chr.v_align = ascent - yofs; // + ascent - descent;
  456. chr.advance = advance;
  457. chr.texture_idx = tex_index;
  458. chr.found = true;
  459. chr.rect = Rect2(tex_x + rect_margin, tex_y + rect_margin, w, h);
  460. //print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" RECT: "+chr.rect+" X OFS: "+itos(xofs)+" Y OFS: "+itos(yofs));
  461. char_map[p_char] = chr;
  462. }
  463. DynamicFontAtSize::DynamicFontAtSize() {
  464. valid = false;
  465. rect_margin = 1;
  466. ascent = 1;
  467. descent = 1;
  468. linegap = 1;
  469. texture_flags = 0;
  470. }
  471. DynamicFontAtSize::~DynamicFontAtSize() {
  472. if (valid) {
  473. FT_Done_FreeType(library);
  474. font->size_cache.erase(id);
  475. }
  476. }
  477. /////////////////////////
  478. void DynamicFont::_reload_cache() {
  479. ERR_FAIL_COND(cache_id.size < 1);
  480. if (!data.is_valid())
  481. return;
  482. data_at_size = data->_get_dynamic_font_at_size(cache_id);
  483. for (int i = 0; i < fallbacks.size(); i++) {
  484. fallback_data_at_size[i] = fallbacks[i]->_get_dynamic_font_at_size(cache_id);
  485. }
  486. emit_changed();
  487. _change_notify();
  488. }
  489. void DynamicFont::set_font_data(const Ref<DynamicFontData> &p_data) {
  490. data = p_data;
  491. if (data.is_valid())
  492. data_at_size = data->_get_dynamic_font_at_size(cache_id);
  493. else
  494. data_at_size = Ref<DynamicFontAtSize>();
  495. emit_changed();
  496. }
  497. Ref<DynamicFontData> DynamicFont::get_font_data() const {
  498. return data;
  499. }
  500. void DynamicFont::set_size(int p_size) {
  501. if (cache_id.size == p_size)
  502. return;
  503. cache_id.size = p_size;
  504. _reload_cache();
  505. }
  506. int DynamicFont::get_size() const {
  507. return cache_id.size;
  508. }
  509. bool DynamicFont::get_use_mipmaps() const {
  510. return cache_id.mipmaps;
  511. }
  512. void DynamicFont::set_use_mipmaps(bool p_enable) {
  513. if (cache_id.mipmaps == p_enable)
  514. return;
  515. cache_id.mipmaps = p_enable;
  516. _reload_cache();
  517. }
  518. bool DynamicFont::get_use_filter() const {
  519. return cache_id.filter;
  520. }
  521. void DynamicFont::set_use_filter(bool p_enable) {
  522. if (cache_id.filter == p_enable)
  523. return;
  524. cache_id.filter = p_enable;
  525. _reload_cache();
  526. }
  527. int DynamicFont::get_spacing(int p_type) const {
  528. if (p_type == SPACING_TOP) {
  529. return spacing_top;
  530. } else if (p_type == SPACING_BOTTOM) {
  531. return spacing_bottom;
  532. } else if (p_type == SPACING_CHAR) {
  533. return spacing_char;
  534. } else if (p_type == SPACING_SPACE) {
  535. return spacing_space;
  536. }
  537. return 0;
  538. }
  539. void DynamicFont::set_spacing(int p_type, int p_value) {
  540. if (p_type == SPACING_TOP) {
  541. spacing_top = p_value;
  542. } else if (p_type == SPACING_BOTTOM) {
  543. spacing_bottom = p_value;
  544. } else if (p_type == SPACING_CHAR) {
  545. spacing_char = p_value;
  546. } else if (p_type == SPACING_SPACE) {
  547. spacing_space = p_value;
  548. }
  549. emit_changed();
  550. _change_notify();
  551. }
  552. float DynamicFont::get_height() const {
  553. if (!data_at_size.is_valid())
  554. return 1;
  555. return data_at_size->get_height() + spacing_top + spacing_bottom;
  556. }
  557. float DynamicFont::get_ascent() const {
  558. if (!data_at_size.is_valid())
  559. return 1;
  560. return data_at_size->get_ascent() + spacing_top;
  561. }
  562. float DynamicFont::get_descent() const {
  563. if (!data_at_size.is_valid())
  564. return 1;
  565. return data_at_size->get_descent() + spacing_bottom;
  566. }
  567. Size2 DynamicFont::get_char_size(CharType p_char, CharType p_next) const {
  568. if (!data_at_size.is_valid())
  569. return Size2(1, 1);
  570. Size2 ret = data_at_size->get_char_size(p_char, p_next, fallback_data_at_size);
  571. if (p_char == ' ')
  572. ret.width += spacing_space + spacing_char;
  573. else if (p_next)
  574. ret.width += spacing_char;
  575. return ret;
  576. }
  577. bool DynamicFont::is_distance_field_hint() const {
  578. return false;
  579. }
  580. float DynamicFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const {
  581. if (!data_at_size.is_valid())
  582. return 0;
  583. return data_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate, fallback_data_at_size) + spacing_char;
  584. }
  585. void DynamicFont::set_fallback(int p_idx, const Ref<DynamicFontData> &p_data) {
  586. ERR_FAIL_COND(p_data.is_null());
  587. ERR_FAIL_INDEX(p_idx, fallbacks.size());
  588. fallbacks[p_idx] = p_data;
  589. fallback_data_at_size[p_idx] = fallbacks[p_idx]->_get_dynamic_font_at_size(cache_id);
  590. }
  591. void DynamicFont::add_fallback(const Ref<DynamicFontData> &p_data) {
  592. ERR_FAIL_COND(p_data.is_null());
  593. fallbacks.push_back(p_data);
  594. fallback_data_at_size.push_back(fallbacks[fallbacks.size() - 1]->_get_dynamic_font_at_size(cache_id)); //const..
  595. _change_notify();
  596. emit_changed();
  597. _change_notify();
  598. }
  599. int DynamicFont::get_fallback_count() const {
  600. return fallbacks.size();
  601. }
  602. Ref<DynamicFontData> DynamicFont::get_fallback(int p_idx) const {
  603. ERR_FAIL_INDEX_V(p_idx, fallbacks.size(), Ref<DynamicFontData>());
  604. return fallbacks[p_idx];
  605. }
  606. void DynamicFont::remove_fallback(int p_idx) {
  607. ERR_FAIL_INDEX(p_idx, fallbacks.size());
  608. fallbacks.remove(p_idx);
  609. fallback_data_at_size.remove(p_idx);
  610. emit_changed();
  611. _change_notify();
  612. }
  613. bool DynamicFont::_set(const StringName &p_name, const Variant &p_value) {
  614. String str = p_name;
  615. if (str.begins_with("fallback/")) {
  616. int idx = str.get_slicec('/', 1).to_int();
  617. Ref<DynamicFontData> fd = p_value;
  618. if (fd.is_valid()) {
  619. if (idx == fallbacks.size()) {
  620. add_fallback(fd);
  621. return true;
  622. } else if (idx >= 0 && idx < fallbacks.size()) {
  623. set_fallback(idx, fd);
  624. return true;
  625. } else {
  626. return false;
  627. }
  628. } else if (idx >= 0 && idx < fallbacks.size()) {
  629. remove_fallback(idx);
  630. return true;
  631. }
  632. }
  633. return false;
  634. }
  635. bool DynamicFont::_get(const StringName &p_name, Variant &r_ret) const {
  636. String str = p_name;
  637. if (str.begins_with("fallback/")) {
  638. int idx = str.get_slicec('/', 1).to_int();
  639. if (idx == fallbacks.size()) {
  640. r_ret = Ref<DynamicFontData>();
  641. return true;
  642. } else if (idx >= 0 && idx < fallbacks.size()) {
  643. r_ret = get_fallback(idx);
  644. return true;
  645. }
  646. }
  647. return false;
  648. }
  649. void DynamicFont::_get_property_list(List<PropertyInfo> *p_list) const {
  650. for (int i = 0; i < fallbacks.size(); i++) {
  651. p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"));
  652. }
  653. p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(fallbacks.size()), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"));
  654. }
  655. void DynamicFont::_bind_methods() {
  656. ClassDB::bind_method(D_METHOD("set_font_data", "data"), &DynamicFont::set_font_data);
  657. ClassDB::bind_method(D_METHOD("get_font_data"), &DynamicFont::get_font_data);
  658. ClassDB::bind_method(D_METHOD("set_size", "data"), &DynamicFont::set_size);
  659. ClassDB::bind_method(D_METHOD("get_size"), &DynamicFont::get_size);
  660. ClassDB::bind_method(D_METHOD("set_use_mipmaps", "enable"), &DynamicFont::set_use_mipmaps);
  661. ClassDB::bind_method(D_METHOD("get_use_mipmaps"), &DynamicFont::get_use_mipmaps);
  662. ClassDB::bind_method(D_METHOD("set_use_filter", "enable"), &DynamicFont::set_use_filter);
  663. ClassDB::bind_method(D_METHOD("get_use_filter"), &DynamicFont::get_use_filter);
  664. ClassDB::bind_method(D_METHOD("set_spacing", "type", "value"), &DynamicFont::set_spacing);
  665. ClassDB::bind_method(D_METHOD("get_spacing", "type"), &DynamicFont::get_spacing);
  666. ClassDB::bind_method(D_METHOD("add_fallback", "data"), &DynamicFont::add_fallback);
  667. ClassDB::bind_method(D_METHOD("set_fallback", "idx", "data"), &DynamicFont::set_fallback);
  668. ClassDB::bind_method(D_METHOD("get_fallback", "idx"), &DynamicFont::get_fallback);
  669. ClassDB::bind_method(D_METHOD("remove_fallback", "idx"), &DynamicFont::remove_fallback);
  670. ClassDB::bind_method(D_METHOD("get_fallback_count"), &DynamicFont::get_fallback_count);
  671. ADD_GROUP("Settings", "");
  672. ADD_PROPERTY(PropertyInfo(Variant::INT, "size"), "set_size", "get_size");
  673. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_mipmaps"), "set_use_mipmaps", "get_use_mipmaps");
  674. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_filter"), "set_use_filter", "get_use_filter");
  675. ADD_GROUP("Extra Spacing", "extra_spacing");
  676. ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_top"), "set_spacing", "get_spacing", SPACING_TOP);
  677. ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_bottom"), "set_spacing", "get_spacing", SPACING_BOTTOM);
  678. ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_char"), "set_spacing", "get_spacing", SPACING_CHAR);
  679. ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_space"), "set_spacing", "get_spacing", SPACING_SPACE);
  680. ADD_GROUP("Font", "");
  681. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font_data", PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"), "set_font_data", "get_font_data");
  682. BIND_ENUM_CONSTANT(SPACING_TOP);
  683. BIND_ENUM_CONSTANT(SPACING_BOTTOM);
  684. BIND_ENUM_CONSTANT(SPACING_CHAR);
  685. BIND_ENUM_CONSTANT(SPACING_SPACE);
  686. }
  687. DynamicFont::DynamicFont() {
  688. spacing_top = 0;
  689. spacing_bottom = 0;
  690. spacing_char = 0;
  691. spacing_space = 0;
  692. }
  693. DynamicFont::~DynamicFont() {
  694. }
  695. /////////////////////////
  696. RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String &p_original_path, Error *r_error) {
  697. if (r_error)
  698. *r_error = ERR_FILE_CANT_OPEN;
  699. Ref<DynamicFontData> dfont;
  700. dfont.instance();
  701. dfont->set_font_path(p_path);
  702. if (r_error)
  703. *r_error = OK;
  704. return dfont;
  705. }
  706. void ResourceFormatLoaderDynamicFont::get_recognized_extensions(List<String> *p_extensions) const {
  707. p_extensions->push_back("ttf");
  708. p_extensions->push_back("otf");
  709. }
  710. bool ResourceFormatLoaderDynamicFont::handles_type(const String &p_type) const {
  711. return (p_type == "DynamicFontData");
  712. }
  713. String ResourceFormatLoaderDynamicFont::get_resource_type(const String &p_path) const {
  714. String el = p_path.get_extension().to_lower();
  715. if (el == "ttf" || el == "otf")
  716. return "DynamicFontData";
  717. return "";
  718. }
  719. #endif