font.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. /*************************************************************************/
  2. /* 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. #include "font.h"
  31. #include "core/io/resource_loader.h"
  32. #include "core/os/file_access.h"
  33. void Font::draw_halign(RID p_canvas_item, const Point2 &p_pos, HAlign p_align, float p_width, const String &p_text, const Color &p_modulate) const {
  34. float length = get_string_size(p_text).width;
  35. if (length >= p_width) {
  36. draw(p_canvas_item, p_pos, p_text, p_modulate, p_width);
  37. return;
  38. }
  39. float ofs = 0.f;
  40. switch (p_align) {
  41. case HALIGN_LEFT: {
  42. ofs = 0;
  43. } break;
  44. case HALIGN_CENTER: {
  45. ofs = Math::floor((p_width - length) / 2.0);
  46. } break;
  47. case HALIGN_RIGHT: {
  48. ofs = p_width - length;
  49. } break;
  50. default: {
  51. ERR_PRINT("Unknown halignment type");
  52. } break;
  53. }
  54. draw(p_canvas_item, p_pos + Point2(ofs, 0), p_text, p_modulate, p_width);
  55. }
  56. void Font::draw(RID p_canvas_item, const Point2 &p_pos, const String &p_text, const Color &p_modulate, int p_clip_w) const {
  57. Vector2 ofs;
  58. for (int i = 0; i < p_text.length(); i++) {
  59. int width = get_char_size(p_text[i]).width;
  60. if (p_clip_w >= 0 && (ofs.x + width) > p_clip_w)
  61. break; //clip
  62. ofs.x += draw_char(p_canvas_item, p_pos + ofs, p_text[i], p_text[i + 1], p_modulate);
  63. }
  64. }
  65. void Font::update_changes() {
  66. emit_changed();
  67. }
  68. void Font::_bind_methods() {
  69. ClassDB::bind_method(D_METHOD("draw", "canvas_item", "position", "string", "modulate", "clip_w"), &Font::draw, DEFVAL(Color(1, 1, 1)), DEFVAL(-1));
  70. ClassDB::bind_method(D_METHOD("get_ascent"), &Font::get_ascent);
  71. ClassDB::bind_method(D_METHOD("get_descent"), &Font::get_descent);
  72. ClassDB::bind_method(D_METHOD("get_height"), &Font::get_height);
  73. ClassDB::bind_method(D_METHOD("is_distance_field_hint"), &Font::is_distance_field_hint);
  74. ClassDB::bind_method(D_METHOD("get_string_size", "string"), &Font::get_string_size);
  75. ClassDB::bind_method(D_METHOD("draw_char", "canvas_item", "position", "char", "next", "modulate"), &Font::draw_char, DEFVAL(-1), DEFVAL(Color(1, 1, 1)));
  76. ClassDB::bind_method(D_METHOD("update_changes"), &Font::update_changes);
  77. }
  78. Font::Font() {
  79. }
  80. /////////////////////////////////////////////////////////////////
  81. void BitmapFont::_set_chars(const PoolVector<int> &p_chars) {
  82. int len = p_chars.size();
  83. //char 1 charsize 1 texture, 4 rect, 2 align, advance 1
  84. ERR_FAIL_COND(len % 9);
  85. if (!len)
  86. return; //none to do
  87. int chars = len / 9;
  88. PoolVector<int>::Read r = p_chars.read();
  89. for (int i = 0; i < chars; i++) {
  90. const int *data = &r[i * 9];
  91. add_char(data[0], data[1], Rect2(data[2], data[3], data[4], data[5]), Size2(data[6], data[7]), data[8]);
  92. }
  93. }
  94. PoolVector<int> BitmapFont::_get_chars() const {
  95. PoolVector<int> chars;
  96. const CharType *key = NULL;
  97. while ((key = char_map.next(key))) {
  98. const Character *c = char_map.getptr(*key);
  99. chars.push_back(*key);
  100. chars.push_back(c->texture_idx);
  101. chars.push_back(c->rect.position.x);
  102. chars.push_back(c->rect.position.y);
  103. chars.push_back(c->rect.size.x);
  104. chars.push_back(c->rect.size.y);
  105. chars.push_back(c->h_align);
  106. chars.push_back(c->v_align);
  107. chars.push_back(c->advance);
  108. }
  109. return chars;
  110. }
  111. void BitmapFont::_set_kernings(const PoolVector<int> &p_kernings) {
  112. int len = p_kernings.size();
  113. ERR_FAIL_COND(len % 3);
  114. if (!len)
  115. return;
  116. PoolVector<int>::Read r = p_kernings.read();
  117. for (int i = 0; i < len / 3; i++) {
  118. const int *data = &r[i * 3];
  119. add_kerning_pair(data[0], data[1], data[2]);
  120. }
  121. }
  122. PoolVector<int> BitmapFont::_get_kernings() const {
  123. PoolVector<int> kernings;
  124. for (Map<KerningPairKey, int>::Element *E = kerning_map.front(); E; E = E->next()) {
  125. kernings.push_back(E->key().A);
  126. kernings.push_back(E->key().B);
  127. kernings.push_back(E->get());
  128. }
  129. return kernings;
  130. }
  131. void BitmapFont::_set_textures(const Vector<Variant> &p_textures) {
  132. for (int i = 0; i < p_textures.size(); i++) {
  133. Ref<Texture> tex = p_textures[i];
  134. ERR_CONTINUE(!tex.is_valid());
  135. add_texture(tex);
  136. }
  137. }
  138. Vector<Variant> BitmapFont::_get_textures() const {
  139. Vector<Variant> rtextures;
  140. for (int i = 0; i < textures.size(); i++)
  141. rtextures.push_back(textures[i].get_ref_ptr());
  142. return rtextures;
  143. }
  144. Error BitmapFont::create_from_fnt(const String &p_file) {
  145. //fnt format used by angelcode bmfont
  146. //http://www.angelcode.com/products/bmfont/
  147. FileAccess *f = FileAccess::open(p_file, FileAccess::READ);
  148. if (!f) {
  149. ERR_EXPLAIN("Can't open font: " + p_file);
  150. ERR_FAIL_V(ERR_FILE_NOT_FOUND);
  151. }
  152. clear();
  153. while (true) {
  154. String line = f->get_line();
  155. int delimiter = line.find(" ");
  156. String type = line.substr(0, delimiter);
  157. int pos = delimiter + 1;
  158. Map<String, String> keys;
  159. while (pos < line.size() && line[pos] == ' ')
  160. pos++;
  161. while (pos < line.size()) {
  162. int eq = line.find("=", pos);
  163. if (eq == -1)
  164. break;
  165. String key = line.substr(pos, eq - pos);
  166. int end = -1;
  167. String value;
  168. if (line[eq + 1] == '"') {
  169. end = line.find("\"", eq + 2);
  170. if (end == -1)
  171. break;
  172. value = line.substr(eq + 2, end - 1 - eq - 1);
  173. pos = end + 1;
  174. } else {
  175. end = line.find(" ", eq + 1);
  176. if (end == -1)
  177. end = line.size();
  178. value = line.substr(eq + 1, end - eq);
  179. pos = end;
  180. }
  181. while (pos < line.size() && line[pos] == ' ')
  182. pos++;
  183. keys[key] = value;
  184. }
  185. if (type == "info") {
  186. if (keys.has("face"))
  187. set_name(keys["face"]);
  188. /*
  189. if (keys.has("size"))
  190. font->set_height(keys["size"].to_int());
  191. */
  192. } else if (type == "common") {
  193. if (keys.has("lineHeight"))
  194. set_height(keys["lineHeight"].to_int());
  195. if (keys.has("base"))
  196. set_ascent(keys["base"].to_int());
  197. } else if (type == "page") {
  198. if (keys.has("file")) {
  199. String file = keys["file"];
  200. file = p_file.get_base_dir() + "/" + file;
  201. Ref<Texture> tex = ResourceLoader::load(file);
  202. if (tex.is_null()) {
  203. ERR_PRINT("Can't load font texture!");
  204. } else {
  205. add_texture(tex);
  206. }
  207. }
  208. } else if (type == "char") {
  209. CharType idx = 0;
  210. if (keys.has("id"))
  211. idx = keys["id"].to_int();
  212. Rect2 rect;
  213. if (keys.has("x"))
  214. rect.position.x = keys["x"].to_int();
  215. if (keys.has("y"))
  216. rect.position.y = keys["y"].to_int();
  217. if (keys.has("width"))
  218. rect.size.width = keys["width"].to_int();
  219. if (keys.has("height"))
  220. rect.size.height = keys["height"].to_int();
  221. Point2 ofs;
  222. if (keys.has("xoffset"))
  223. ofs.x = keys["xoffset"].to_int();
  224. if (keys.has("yoffset"))
  225. ofs.y = keys["yoffset"].to_int();
  226. int texture = 0;
  227. if (keys.has("page"))
  228. texture = keys["page"].to_int();
  229. int advance = -1;
  230. if (keys.has("xadvance"))
  231. advance = keys["xadvance"].to_int();
  232. add_char(idx, texture, rect, ofs, advance);
  233. } else if (type == "kerning") {
  234. CharType first = 0, second = 0;
  235. int k = 0;
  236. if (keys.has("first"))
  237. first = keys["first"].to_int();
  238. if (keys.has("second"))
  239. second = keys["second"].to_int();
  240. if (keys.has("amount"))
  241. k = keys["amount"].to_int();
  242. add_kerning_pair(first, second, -k);
  243. }
  244. if (f->eof_reached())
  245. break;
  246. }
  247. memdelete(f);
  248. return OK;
  249. }
  250. void BitmapFont::set_height(float p_height) {
  251. height = p_height;
  252. }
  253. float BitmapFont::get_height() const {
  254. return height;
  255. }
  256. void BitmapFont::set_ascent(float p_ascent) {
  257. ascent = p_ascent;
  258. }
  259. float BitmapFont::get_ascent() const {
  260. return ascent;
  261. }
  262. float BitmapFont::get_descent() const {
  263. return height - ascent;
  264. }
  265. void BitmapFont::add_texture(const Ref<Texture> &p_texture) {
  266. ERR_FAIL_COND(p_texture.is_null());
  267. textures.push_back(p_texture);
  268. }
  269. int BitmapFont::get_texture_count() const {
  270. return textures.size();
  271. };
  272. Ref<Texture> BitmapFont::get_texture(int p_idx) const {
  273. ERR_FAIL_INDEX_V(p_idx, textures.size(), Ref<Texture>());
  274. return textures[p_idx];
  275. };
  276. int BitmapFont::get_character_count() const {
  277. return char_map.size();
  278. };
  279. Vector<CharType> BitmapFont::get_char_keys() const {
  280. Vector<CharType> chars;
  281. chars.resize(char_map.size());
  282. const CharType *ct = NULL;
  283. int count = 0;
  284. while ((ct = char_map.next(ct))) {
  285. chars[count++] = *ct;
  286. };
  287. return chars;
  288. };
  289. BitmapFont::Character BitmapFont::get_character(CharType p_char) const {
  290. if (!char_map.has(p_char)) {
  291. ERR_FAIL_V(Character());
  292. };
  293. return char_map[p_char];
  294. };
  295. void BitmapFont::add_char(CharType p_char, int p_texture_idx, const Rect2 &p_rect, const Size2 &p_align, float p_advance) {
  296. if (p_advance < 0)
  297. p_advance = p_rect.size.width;
  298. Character c;
  299. c.rect = p_rect;
  300. c.texture_idx = p_texture_idx;
  301. c.v_align = p_align.y;
  302. c.advance = p_advance;
  303. c.h_align = p_align.x;
  304. char_map[p_char] = c;
  305. }
  306. void BitmapFont::add_kerning_pair(CharType p_A, CharType p_B, int p_kerning) {
  307. KerningPairKey kpk;
  308. kpk.A = p_A;
  309. kpk.B = p_B;
  310. if (p_kerning == 0 && kerning_map.has(kpk)) {
  311. kerning_map.erase(kpk);
  312. } else {
  313. kerning_map[kpk] = p_kerning;
  314. }
  315. }
  316. Vector<BitmapFont::KerningPairKey> BitmapFont::get_kerning_pair_keys() const {
  317. Vector<BitmapFont::KerningPairKey> ret;
  318. ret.resize(kerning_map.size());
  319. int i = 0;
  320. for (Map<KerningPairKey, int>::Element *E = kerning_map.front(); E; E = E->next()) {
  321. ret[i++] = E->key();
  322. }
  323. return ret;
  324. }
  325. int BitmapFont::get_kerning_pair(CharType p_A, CharType p_B) const {
  326. KerningPairKey kpk;
  327. kpk.A = p_A;
  328. kpk.B = p_B;
  329. const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk);
  330. if (E)
  331. return E->get();
  332. return 0;
  333. }
  334. void BitmapFont::set_distance_field_hint(bool p_distance_field) {
  335. distance_field_hint = p_distance_field;
  336. emit_changed();
  337. }
  338. bool BitmapFont::is_distance_field_hint() const {
  339. return distance_field_hint;
  340. }
  341. void BitmapFont::clear() {
  342. height = 1;
  343. ascent = 0;
  344. char_map.clear();
  345. textures.clear();
  346. kerning_map.clear();
  347. distance_field_hint = false;
  348. }
  349. Size2 Font::get_string_size(const String &p_string) const {
  350. float w = 0;
  351. int l = p_string.length();
  352. if (l == 0)
  353. return Size2(0, get_height());
  354. const CharType *sptr = &p_string[0];
  355. for (int i = 0; i < l; i++) {
  356. w += get_char_size(sptr[i], sptr[i + 1]).width;
  357. }
  358. return Size2(w, get_height());
  359. }
  360. void BitmapFont::set_fallback(const Ref<BitmapFont> &p_fallback) {
  361. fallback = p_fallback;
  362. }
  363. Ref<BitmapFont> BitmapFont::get_fallback() const {
  364. return fallback;
  365. }
  366. float BitmapFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const {
  367. const Character *c = char_map.getptr(p_char);
  368. if (!c) {
  369. if (fallback.is_valid())
  370. return fallback->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate);
  371. return 0;
  372. }
  373. Point2 cpos = p_pos;
  374. cpos.x += c->h_align;
  375. cpos.y -= ascent;
  376. cpos.y += c->v_align;
  377. ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), 0);
  378. if (c->texture_idx != -1)
  379. VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, c->rect.size), textures[c->texture_idx]->get_rid(), c->rect, p_modulate, false, RID(), false);
  380. return get_char_size(p_char, p_next).width;
  381. }
  382. Size2 BitmapFont::get_char_size(CharType p_char, CharType p_next) const {
  383. const Character *c = char_map.getptr(p_char);
  384. if (!c) {
  385. if (fallback.is_valid())
  386. return fallback->get_char_size(p_char, p_next);
  387. return Size2();
  388. }
  389. Size2 ret(c->advance, c->rect.size.y);
  390. if (p_next) {
  391. KerningPairKey kpk;
  392. kpk.A = p_char;
  393. kpk.B = p_next;
  394. const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk);
  395. if (E) {
  396. ret.width -= E->get();
  397. }
  398. }
  399. return ret;
  400. }
  401. void BitmapFont::_bind_methods() {
  402. ClassDB::bind_method(D_METHOD("create_from_fnt", "path"), &BitmapFont::create_from_fnt);
  403. ClassDB::bind_method(D_METHOD("set_height", "px"), &BitmapFont::set_height);
  404. ClassDB::bind_method(D_METHOD("set_ascent", "px"), &BitmapFont::set_ascent);
  405. ClassDB::bind_method(D_METHOD("add_kerning_pair", "char_a", "char_b", "kerning"), &BitmapFont::add_kerning_pair);
  406. ClassDB::bind_method(D_METHOD("get_kerning_pair", "char_a", "char_b"), &BitmapFont::get_kerning_pair);
  407. ClassDB::bind_method(D_METHOD("add_texture", "texture"), &BitmapFont::add_texture);
  408. ClassDB::bind_method(D_METHOD("add_char", "character", "texture", "rect", "align", "advance"), &BitmapFont::add_char, DEFVAL(Point2()), DEFVAL(-1));
  409. ClassDB::bind_method(D_METHOD("get_texture_count"), &BitmapFont::get_texture_count);
  410. ClassDB::bind_method(D_METHOD("get_texture", "idx"), &BitmapFont::get_texture);
  411. ClassDB::bind_method(D_METHOD("get_char_size", "char", "next"), &BitmapFont::get_char_size, DEFVAL(0));
  412. ClassDB::bind_method(D_METHOD("set_distance_field_hint", "enable"), &BitmapFont::set_distance_field_hint);
  413. ClassDB::bind_method(D_METHOD("clear"), &BitmapFont::clear);
  414. ClassDB::bind_method(D_METHOD("_set_chars"), &BitmapFont::_set_chars);
  415. ClassDB::bind_method(D_METHOD("_get_chars"), &BitmapFont::_get_chars);
  416. ClassDB::bind_method(D_METHOD("_set_kernings"), &BitmapFont::_set_kernings);
  417. ClassDB::bind_method(D_METHOD("_get_kernings"), &BitmapFont::_get_kernings);
  418. ClassDB::bind_method(D_METHOD("_set_textures"), &BitmapFont::_set_textures);
  419. ClassDB::bind_method(D_METHOD("_get_textures"), &BitmapFont::_get_textures);
  420. ClassDB::bind_method(D_METHOD("set_fallback", "fallback"), &BitmapFont::set_fallback);
  421. ClassDB::bind_method(D_METHOD("get_fallback"), &BitmapFont::get_fallback);
  422. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "textures", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_textures", "_get_textures");
  423. ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY, "chars", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_chars", "_get_chars");
  424. ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY, "kernings", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_kernings", "_get_kernings");
  425. ADD_PROPERTY(PropertyInfo(Variant::REAL, "height", PROPERTY_HINT_RANGE, "-1024,1024,1"), "set_height", "get_height");
  426. ADD_PROPERTY(PropertyInfo(Variant::REAL, "ascent", PROPERTY_HINT_RANGE, "-1024,1024,1"), "set_ascent", "get_ascent");
  427. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "distance_field"), "set_distance_field_hint", "is_distance_field_hint");
  428. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "fallback", PROPERTY_HINT_RESOURCE_TYPE, "BitmapFont"), "set_fallback", "get_fallback");
  429. }
  430. BitmapFont::BitmapFont() {
  431. clear();
  432. }
  433. BitmapFont::~BitmapFont() {
  434. clear();
  435. }