dynamic_font_stb.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /*************************************************************************/
  2. /* dynamic_font_stb.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. #include "dynamic_font_stb.h"
  31. #ifndef FREETYPE_ENABLED
  32. #define STB_TRUETYPE_IMPLEMENTATION
  33. #include "os/file_access.h"
  34. void DynamicFontData::lock() {
  35. fr = font_data.read();
  36. if (fr.ptr() != last_data_ptr) {
  37. last_data_ptr = fr.ptr();
  38. if (!stbtt_InitFont(&info, last_data_ptr, 0)) {
  39. valid = false;
  40. } else {
  41. valid = true;
  42. }
  43. last_data_ptr = fr.ptr();
  44. }
  45. }
  46. void DynamicFontData::unlock() {
  47. fr = PoolVector<uint8_t>::Read();
  48. }
  49. void DynamicFontData::set_font_data(const PoolVector<uint8_t> &p_font) {
  50. //clear caches and stuff
  51. ERR_FAIL_COND(font_data.size());
  52. font_data = p_font;
  53. lock();
  54. if (valid) {
  55. stbtt_GetFontVMetrics(&info, &ascent, &descent, &linegap);
  56. descent = -descent + linegap;
  57. for (int i = 32; i < 1024; i++) {
  58. for (int j = 32; j < 1024; j++) {
  59. int kern = stbtt_GetCodepointKernAdvance(&info, i, j);
  60. if (kern != 0) {
  61. KerningPairKey kpk;
  62. kpk.A = i;
  63. kpk.B = j;
  64. kerning_map[kpk] = kern;
  65. }
  66. }
  67. }
  68. }
  69. unlock();
  70. //clear existing stuff
  71. ERR_FAIL_COND(!valid);
  72. }
  73. Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(int p_size) {
  74. ERR_FAIL_COND_V(!valid, Ref<DynamicFontAtSize>());
  75. if (size_cache.has(p_size)) {
  76. return Ref<DynamicFontAtSize>(size_cache[p_size]);
  77. }
  78. Ref<DynamicFontAtSize> dfas;
  79. dfas.instance();
  80. dfas->font = Ref<DynamicFontData>(this);
  81. size_cache[p_size] = dfas.ptr();
  82. dfas->size = p_size;
  83. lock();
  84. dfas->scale = stbtt_ScaleForPixelHeight(&info, p_size);
  85. unlock();
  86. return dfas;
  87. }
  88. DynamicFontData::DynamicFontData() {
  89. last_data_ptr = NULL;
  90. valid = false;
  91. }
  92. DynamicFontData::~DynamicFontData() {
  93. }
  94. ////////////////////
  95. float DynamicFontAtSize::get_height() const {
  96. return (font->ascent + font->descent) * scale;
  97. }
  98. float DynamicFontAtSize::get_ascent() const {
  99. return font->ascent * scale;
  100. }
  101. float DynamicFontAtSize::get_descent() const {
  102. return font->descent * scale;
  103. }
  104. Size2 DynamicFontAtSize::get_char_size(CharType p_char, CharType p_next) const {
  105. const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
  106. const Character *c = char_map.getptr(p_char);
  107. ERR_FAIL_COND_V(!c, Size2());
  108. Size2 ret(c->advance, get_height());
  109. if (p_next) {
  110. DynamicFontData::KerningPairKey kpk;
  111. kpk.A = p_char;
  112. kpk.B = p_next;
  113. const Map<DynamicFontData::KerningPairKey, int>::Element *K = font->kerning_map.find(kpk);
  114. if (K) {
  115. ret.x += K->get() * scale;
  116. }
  117. }
  118. return ret;
  119. }
  120. float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const {
  121. const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
  122. const Character *c = char_map.getptr(p_char);
  123. if (!c) {
  124. return 0;
  125. }
  126. Point2 cpos = p_pos;
  127. cpos.x += c->h_align;
  128. cpos.y -= get_ascent();
  129. cpos.y += c->v_align;
  130. ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), 0);
  131. if (c->texture_idx != -1)
  132. 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);
  133. //textures[c->texture_idx].texture->draw(p_canvas_item,Vector2());
  134. float ret = c->advance;
  135. if (p_next) {
  136. DynamicFontData::KerningPairKey kpk;
  137. kpk.A = p_char;
  138. kpk.B = p_next;
  139. const Map<DynamicFontData::KerningPairKey, int>::Element *K = font->kerning_map.find(kpk);
  140. if (K) {
  141. ret += K->get() * scale;
  142. }
  143. }
  144. return ret;
  145. }
  146. void DynamicFontAtSize::_update_char(CharType p_char) {
  147. if (char_map.has(p_char))
  148. return;
  149. font->lock();
  150. int w, h, xofs, yofs;
  151. unsigned char *cpbitmap = stbtt_GetCodepointBitmap(&font->info, scale, scale, p_char, &w, &h, &xofs, &yofs);
  152. if (!cpbitmap) {
  153. //no glyph
  154. int advance;
  155. stbtt_GetCodepointHMetrics(&font->info, p_char, &advance, 0);
  156. //print_line("char has no bitmap: "+itos(p_char)+" but advance is "+itos(advance*scale));
  157. Character ch;
  158. ch.texture_idx = -1;
  159. ch.advance = advance * scale;
  160. ch.h_align = 0;
  161. ch.v_align = 0;
  162. char_map[p_char] = ch;
  163. font->unlock();
  164. return;
  165. }
  166. int mw = w + rect_margin * 2;
  167. int mh = h + rect_margin * 2;
  168. if (mw > 4096 || mh > 4096) {
  169. stbtt_FreeBitmap(cpbitmap, NULL);
  170. font->unlock();
  171. ERR_FAIL_COND(mw > 4096);
  172. ERR_FAIL_COND(mh > 4096);
  173. }
  174. //find a texture to fit this...
  175. int tex_index = -1;
  176. int tex_x = 0;
  177. int tex_y = 0;
  178. for (int i = 0; i < textures.size(); i++) {
  179. CharTexture &ct = textures[i];
  180. if (mw > ct.texture_size || mh > ct.texture_size) //too big for this texture
  181. continue;
  182. tex_y = 0x7FFFFFFF;
  183. tex_x = 0;
  184. for (int j = 0; j < ct.texture_size - mw; j++) {
  185. int max_y = 0;
  186. for (int k = j; k < j + mw; k++) {
  187. int y = ct.offsets[k];
  188. if (y > max_y)
  189. max_y = y;
  190. }
  191. if (max_y < tex_y) {
  192. tex_y = max_y;
  193. tex_x = j;
  194. }
  195. }
  196. if (tex_y == 0x7FFFFFFF || tex_y + mh > ct.texture_size)
  197. continue; //fail, could not fit it here
  198. tex_index = i;
  199. break;
  200. }
  201. //print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" X: "+itos(tex_x)+" Y: "+itos(tex_y));
  202. if (tex_index == -1) {
  203. //could not find texture to fit, create one
  204. tex_x = 0;
  205. tex_y = 0;
  206. int texsize = MAX(size * 8, 256);
  207. if (mw > texsize)
  208. texsize = mw; //special case, adapt to it?
  209. if (mh > texsize)
  210. texsize = mh; //special case, adapt to it?
  211. texsize = next_power_of_2(texsize);
  212. texsize = MIN(texsize, 4096);
  213. CharTexture tex;
  214. tex.texture_size = texsize;
  215. tex.imgdata.resize(texsize * texsize * 2); //grayscale alpha
  216. {
  217. //zero texture
  218. PoolVector<uint8_t>::Write w = tex.imgdata.write();
  219. ERR_FAIL_COND(texsize * texsize * 2 > tex.imgdata.size());
  220. for (int i = 0; i < texsize * texsize * 2; i++) {
  221. w[i] = 0;
  222. }
  223. }
  224. tex.offsets.resize(texsize);
  225. for (int i = 0; i < texsize; i++) //zero offsets
  226. tex.offsets[i] = 0;
  227. textures.push_back(tex);
  228. tex_index = textures.size() - 1;
  229. }
  230. //fit character in char texture
  231. CharTexture &tex = textures[tex_index];
  232. {
  233. PoolVector<uint8_t>::Write wr = tex.imgdata.write();
  234. for (int i = 0; i < h; i++) {
  235. for (int j = 0; j < w; j++) {
  236. int ofs = ((i + tex_y + rect_margin) * tex.texture_size + j + tex_x + rect_margin) * 2;
  237. ERR_FAIL_COND(ofs >= tex.imgdata.size());
  238. wr[ofs + 0] = 255; //grayscale as 1
  239. wr[ofs + 1] = cpbitmap[i * w + j]; //alpha as 0
  240. }
  241. }
  242. }
  243. //blit to image and texture
  244. {
  245. Image img(tex.texture_size, tex.texture_size, 0, Image::FORMAT_LA8, tex.imgdata);
  246. if (tex.texture.is_null()) {
  247. tex.texture.instance();
  248. tex.texture->create_from_image(img, Texture::FLAG_FILTER);
  249. } else {
  250. tex.texture->set_data(img); //update
  251. }
  252. }
  253. // update height array
  254. for (int k = tex_x; k < tex_x + mw; k++) {
  255. tex.offsets[k] = tex_y + mh;
  256. }
  257. int advance;
  258. stbtt_GetCodepointHMetrics(&font->info, p_char, &advance, 0);
  259. Character chr;
  260. chr.h_align = xofs;
  261. chr.v_align = yofs + get_ascent();
  262. chr.advance = advance * scale;
  263. chr.texture_idx = tex_index;
  264. chr.rect = Rect2(tex_x + rect_margin, tex_y + rect_margin, w, h);
  265. //print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" RECT: "+chr.rect+" X OFS: "+itos(xofs)+" Y OFS: "+itos(yofs));
  266. char_map[p_char] = chr;
  267. stbtt_FreeBitmap(cpbitmap, NULL);
  268. font->unlock();
  269. }
  270. DynamicFontAtSize::DynamicFontAtSize() {
  271. rect_margin = 1;
  272. }
  273. DynamicFontAtSize::~DynamicFontAtSize() {
  274. ERR_FAIL_COND(!font.ptr());
  275. font->size_cache.erase(size);
  276. }
  277. /////////////////////////
  278. void DynamicFont::_bind_methods() {
  279. ClassDB::bind_method(D_METHOD("set_font_data", "data"), &DynamicFont::set_font_data);
  280. ClassDB::bind_method(D_METHOD("get_font_data"), &DynamicFont::get_font_data);
  281. ClassDB::bind_method(D_METHOD("set_size", "data"), &DynamicFont::set_size);
  282. ClassDB::bind_method(D_METHOD("get_size"), &DynamicFont::get_size);
  283. ADD_PROPERTY(PropertyInfo(Variant::INT, "font/size"), "set_size", "get_size");
  284. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font/font", PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"), "set_font_data", "get_font_data");
  285. }
  286. void DynamicFont::set_font_data(const Ref<DynamicFontData> &p_data) {
  287. data = p_data;
  288. data_at_size = data->_get_dynamic_font_at_size(size);
  289. }
  290. Ref<DynamicFontData> DynamicFont::get_font_data() const {
  291. return data;
  292. }
  293. void DynamicFont::set_size(int p_size) {
  294. if (size == p_size)
  295. return;
  296. size = p_size;
  297. ERR_FAIL_COND(p_size < 1);
  298. if (!data.is_valid())
  299. return;
  300. data_at_size = data->_get_dynamic_font_at_size(size);
  301. }
  302. int DynamicFont::get_size() const {
  303. return size;
  304. }
  305. float DynamicFont::get_height() const {
  306. if (!data_at_size.is_valid())
  307. return 1;
  308. return data_at_size->get_height();
  309. }
  310. float DynamicFont::get_ascent() const {
  311. if (!data_at_size.is_valid())
  312. return 1;
  313. return data_at_size->get_ascent();
  314. }
  315. float DynamicFont::get_descent() const {
  316. if (!data_at_size.is_valid())
  317. return 1;
  318. return data_at_size->get_descent();
  319. }
  320. Size2 DynamicFont::get_char_size(CharType p_char, CharType p_next) const {
  321. if (!data_at_size.is_valid())
  322. return Size2(1, 1);
  323. return data_at_size->get_char_size(p_char, p_next);
  324. }
  325. bool DynamicFont::is_distance_field_hint() const {
  326. return false;
  327. }
  328. float DynamicFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const {
  329. if (!data_at_size.is_valid())
  330. return 0;
  331. return data_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate);
  332. }
  333. DynamicFont::DynamicFont() {
  334. size = 16;
  335. }
  336. DynamicFont::~DynamicFont() {
  337. }
  338. /////////////////////////
  339. RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String &p_original_path, Error *r_error) {
  340. if (r_error)
  341. *r_error = ERR_FILE_CANT_OPEN;
  342. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  343. ERR_FAIL_COND_V(!f, RES());
  344. PoolVector<uint8_t> data;
  345. data.resize(f->get_len());
  346. ERR_FAIL_COND_V(data.size() == 0, RES());
  347. {
  348. PoolVector<uint8_t>::Write w = data.write();
  349. f->get_buffer(w.ptr(), data.size());
  350. }
  351. Ref<DynamicFontData> dfd;
  352. dfd.instance();
  353. dfd->set_font_data(data);
  354. if (r_error)
  355. *r_error = OK;
  356. return dfd;
  357. }
  358. void ResourceFormatLoaderDynamicFont::get_recognized_extensions(List<String> *p_extensions) const {
  359. p_extensions->push_back("ttf");
  360. }
  361. bool ResourceFormatLoaderDynamicFont::handles_type(const String &p_type) const {
  362. return (p_type == "DynamicFontData");
  363. }
  364. String ResourceFormatLoaderDynamicFont::get_resource_type(const String &p_path) const {
  365. String el = p_path.extension().to_lower();
  366. if (el == "ttf")
  367. return "DynamicFontData";
  368. return "";
  369. }
  370. #endif