resource_importer_imagefont.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /**************************************************************************/
  2. /* resource_importer_imagefont.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "resource_importer_imagefont.h"
  31. #include "core/io/image_loader.h"
  32. #include "core/io/resource_saver.h"
  33. String ResourceImporterImageFont::get_importer_name() const {
  34. return "font_data_image";
  35. }
  36. String ResourceImporterImageFont::get_visible_name() const {
  37. return "Font Data (Image Font)";
  38. }
  39. void ResourceImporterImageFont::get_recognized_extensions(List<String> *p_extensions) const {
  40. if (p_extensions) {
  41. ImageLoader::get_recognized_extensions(p_extensions);
  42. }
  43. }
  44. String ResourceImporterImageFont::get_save_extension() const {
  45. return "fontdata";
  46. }
  47. String ResourceImporterImageFont::get_resource_type() const {
  48. return "FontFile";
  49. }
  50. bool ResourceImporterImageFont::get_option_visibility(const String &p_path, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
  51. return true;
  52. }
  53. void ResourceImporterImageFont::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {
  54. r_options->push_back(ImportOption(PropertyInfo(Variant::PACKED_STRING_ARRAY, "character_ranges"), Vector<String>()));
  55. r_options->push_back(ImportOption(PropertyInfo(Variant::PACKED_STRING_ARRAY, "kerning_pairs"), Vector<String>()));
  56. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "columns", PROPERTY_HINT_RANGE, "1,1024,1,or_greater"), 1));
  57. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "rows", PROPERTY_HINT_RANGE, "1,1024,1,or_greater"), 1));
  58. r_options->push_back(ImportOption(PropertyInfo(Variant::RECT2I, "image_margin"), Rect2i()));
  59. r_options->push_back(ImportOption(PropertyInfo(Variant::RECT2I, "character_margin"), Rect2i()));
  60. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "ascent"), 0));
  61. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "descent"), 0));
  62. r_options->push_back(ImportOption(PropertyInfo(Variant::ARRAY, "fallbacks", PROPERTY_HINT_ARRAY_TYPE, MAKE_RESOURCE_TYPE_HINT("Font")), Array()));
  63. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "compress"), true));
  64. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "scaling_mode", PROPERTY_HINT_ENUM, "Disabled,Enabled (Integer),Enabled (Fractional)"), TextServer::FIXED_SIZE_SCALE_ENABLED));
  65. }
  66. Error ResourceImporterImageFont::import(ResourceUID::ID p_source_id, const String &p_source_file, const String &p_save_path, const HashMap<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
  67. print_verbose("Importing image font from: " + p_source_file);
  68. int columns = p_options["columns"];
  69. int rows = p_options["rows"];
  70. int ascent = p_options["ascent"];
  71. int descent = p_options["descent"];
  72. Vector<String> ranges = p_options["character_ranges"];
  73. Vector<String> kern = p_options["kerning_pairs"];
  74. Array fallbacks = p_options["fallbacks"];
  75. Rect2i img_margin = p_options["image_margin"];
  76. Rect2i char_margin = p_options["character_margin"];
  77. TextServer::FixedSizeScaleMode smode = (TextServer::FixedSizeScaleMode)p_options["scaling_mode"].operator int();
  78. Ref<Image> img;
  79. img.instantiate();
  80. Error err = ImageLoader::load_image(p_source_file, img);
  81. ERR_FAIL_COND_V_MSG(err != OK, ERR_FILE_CANT_READ, vformat("Can't load font texture: \"%s\".", p_source_file));
  82. ERR_FAIL_COND_V_MSG(columns <= 0, ERR_FILE_CANT_READ, vformat("Columns (%d) must be positive.", columns));
  83. ERR_FAIL_COND_V_MSG(rows <= 0, ERR_FILE_CANT_READ, vformat("Rows (%d) must be positive.", rows));
  84. int count = columns * rows;
  85. int chr_cell_width = (img->get_width() - img_margin.position.x - img_margin.size.x) / columns;
  86. int chr_cell_height = (img->get_height() - img_margin.position.y - img_margin.size.y) / rows;
  87. ERR_FAIL_COND_V_MSG(chr_cell_width <= 0 || chr_cell_height <= 0, ERR_FILE_CANT_READ, "Image margin too big.");
  88. int chr_width = chr_cell_width - char_margin.position.x - char_margin.size.x;
  89. int chr_height = chr_cell_height - char_margin.position.y - char_margin.size.y;
  90. ERR_FAIL_COND_V_MSG(chr_width <= 0 || chr_height <= 0, ERR_FILE_CANT_READ, "Character margin too big.");
  91. Ref<FontFile> font;
  92. font.instantiate();
  93. font->set_antialiasing(TextServer::FONT_ANTIALIASING_NONE);
  94. font->set_generate_mipmaps(false);
  95. font->set_multichannel_signed_distance_field(false);
  96. font->set_fixed_size(chr_height);
  97. font->set_subpixel_positioning(TextServer::SUBPIXEL_POSITIONING_DISABLED);
  98. font->set_keep_rounding_remainders(true);
  99. font->set_force_autohinter(false);
  100. font->set_allow_system_fallback(false);
  101. font->set_hinting(TextServer::HINTING_NONE);
  102. font->set_oversampling(1.0f);
  103. font->set_fallbacks(fallbacks);
  104. font->set_texture_image(0, Vector2i(chr_height, 0), 0, img);
  105. font->set_fixed_size_scale_mode(smode);
  106. int32_t pos = 0;
  107. for (const String &range : ranges) {
  108. int32_t start = -1;
  109. int32_t end = -1;
  110. int chr_adv = 0;
  111. Vector2i chr_off;
  112. {
  113. enum RangeParseStep {
  114. STEP_START_BEGIN,
  115. STEP_START_READ_HEX,
  116. STEP_START_READ_DEC,
  117. STEP_END_BEGIN,
  118. STEP_END_READ_HEX,
  119. STEP_END_READ_DEC,
  120. STEP_ADVANCE_BEGIN,
  121. STEP_OFF_X_BEGIN,
  122. STEP_OFF_Y_BEGIN,
  123. STEP_FINISHED,
  124. };
  125. RangeParseStep step = STEP_START_BEGIN;
  126. String token;
  127. for (int c = 0; c < range.length(); c++) {
  128. switch (step) {
  129. case STEP_START_BEGIN:
  130. case STEP_END_BEGIN: {
  131. // Read range start/end first symbol.
  132. if (range[c] == 'U' || range[c] == 'u') {
  133. if ((c <= range.length() - 2) && range[c + 1] == '+') {
  134. token = String();
  135. if (step == STEP_START_BEGIN) {
  136. step = STEP_START_READ_HEX;
  137. } else {
  138. step = STEP_END_READ_HEX;
  139. }
  140. c++; // Skip "+".
  141. continue;
  142. }
  143. } else if (range[c] == '0' && (c <= range.length() - 2) && (range[c + 1] == 'x' || range[c + 1] == 'X')) {
  144. // Read hexadecimal value, start.
  145. token = String();
  146. if (step == STEP_START_BEGIN) {
  147. step = STEP_START_READ_HEX;
  148. } else {
  149. step = STEP_END_READ_HEX;
  150. }
  151. c++; // Skip "x".
  152. continue;
  153. } else if (range[c] == '\'' || range[c] == '\"') {
  154. if ((c <= range.length() - 3) && (range[c + 2] == '\'' || range[c + 2] == '\"')) {
  155. token = String();
  156. if (step == STEP_START_BEGIN) {
  157. start = range.unicode_at(c + 1);
  158. step = STEP_END_BEGIN;
  159. } else {
  160. end = range.unicode_at(c + 1);
  161. step = STEP_ADVANCE_BEGIN;
  162. }
  163. c = c + 2; // Skip the rest or token.
  164. continue;
  165. }
  166. } else if (is_digit(range[c])) {
  167. // Read decimal value, start.
  168. token = String();
  169. token += range[c];
  170. if (step == STEP_START_BEGIN) {
  171. step = STEP_START_READ_DEC;
  172. } else {
  173. step = STEP_END_READ_DEC;
  174. }
  175. continue;
  176. }
  177. [[fallthrough]];
  178. }
  179. case STEP_ADVANCE_BEGIN:
  180. case STEP_OFF_X_BEGIN:
  181. case STEP_OFF_Y_BEGIN: {
  182. // Read advance and offset.
  183. if (range[c] == ' ') {
  184. int next = range.find_char(' ', c + 1);
  185. if (next < c) {
  186. next = range.length();
  187. }
  188. if (step == STEP_OFF_X_BEGIN) {
  189. chr_off.x = range.substr(c + 1, next - (c + 1)).to_int();
  190. step = STEP_OFF_Y_BEGIN;
  191. } else if (step == STEP_OFF_Y_BEGIN) {
  192. chr_off.y = range.substr(c + 1, next - (c + 1)).to_int();
  193. step = STEP_FINISHED;
  194. } else {
  195. chr_adv = range.substr(c + 1, next - (c + 1)).to_int();
  196. step = STEP_OFF_X_BEGIN;
  197. }
  198. c = next - 1;
  199. continue;
  200. }
  201. } break;
  202. case STEP_START_READ_HEX:
  203. case STEP_END_READ_HEX: {
  204. // Read hexadecimal value.
  205. if (is_hex_digit(range[c])) {
  206. token += range[c];
  207. } else {
  208. if (step == STEP_START_READ_HEX) {
  209. start = token.hex_to_int();
  210. step = STEP_END_BEGIN;
  211. } else {
  212. end = token.hex_to_int();
  213. step = STEP_ADVANCE_BEGIN;
  214. c--;
  215. }
  216. }
  217. } break;
  218. case STEP_START_READ_DEC:
  219. case STEP_END_READ_DEC: {
  220. // Read decimal value.
  221. if (is_digit(range[c])) {
  222. token += range[c];
  223. } else {
  224. if (step == STEP_START_READ_DEC) {
  225. start = token.to_int();
  226. step = STEP_END_BEGIN;
  227. } else {
  228. end = token.to_int();
  229. step = STEP_ADVANCE_BEGIN;
  230. c--;
  231. }
  232. }
  233. } break;
  234. default: {
  235. WARN_PRINT(vformat("Invalid character \"%d\" in the range: \"%s\"", c, range));
  236. } break;
  237. }
  238. }
  239. if (step == STEP_START_READ_HEX) {
  240. start = token.hex_to_int();
  241. } else if (step == STEP_START_READ_DEC) {
  242. start = token.to_int();
  243. } else if (step == STEP_END_READ_HEX) {
  244. end = token.hex_to_int();
  245. } else if (step == STEP_END_READ_DEC) {
  246. end = token.to_int();
  247. }
  248. if (end == -1) {
  249. end = start;
  250. }
  251. if (start == -1) {
  252. WARN_PRINT(vformat("Invalid range: \"%s\"", range));
  253. continue;
  254. }
  255. }
  256. for (int32_t idx = MIN(start, end); idx <= MAX(start, end); idx++) {
  257. ERR_FAIL_COND_V_MSG(pos >= count, ERR_CANT_CREATE, "Too many characters in range, should be " + itos(columns * rows));
  258. int x = pos % columns;
  259. int y = pos / columns;
  260. font->set_glyph_advance(0, chr_height, idx, Vector2(chr_width + chr_adv, 0));
  261. font->set_glyph_offset(0, Vector2i(chr_height, 0), idx, Vector2i(0, -0.5 * chr_height) + chr_off);
  262. font->set_glyph_size(0, Vector2i(chr_height, 0), idx, Vector2(chr_width, chr_height));
  263. font->set_glyph_uv_rect(0, Vector2i(chr_height, 0), idx, Rect2(img_margin.position.x + chr_cell_width * x + char_margin.position.x, img_margin.position.y + chr_cell_height * y + char_margin.position.y, chr_width, chr_height));
  264. font->set_glyph_texture_idx(0, Vector2i(chr_height, 0), idx, 0);
  265. pos++;
  266. }
  267. }
  268. for (const String &kp : kern) {
  269. const Vector<String> &kp_tokens = kp.split(" ");
  270. if (kp_tokens.size() != 3) {
  271. WARN_PRINT(vformat("Invalid kerning pairs string: \"%s\"", kp));
  272. continue;
  273. }
  274. String from_tokens;
  275. for (int i = 0; i < kp_tokens[0].length(); i++) {
  276. if (i <= kp_tokens[0].length() - 6 && kp_tokens[0][i] == '\\' && kp_tokens[0][i + 1] == 'u' && is_hex_digit(kp_tokens[0][i + 2]) && is_hex_digit(kp_tokens[0][i + 3]) && is_hex_digit(kp_tokens[0][i + 4]) && is_hex_digit(kp_tokens[0][i + 5])) {
  277. char32_t charcode = kp_tokens[0].substr(i + 2, 4).hex_to_int();
  278. from_tokens += charcode;
  279. i += 5;
  280. } else {
  281. from_tokens += kp_tokens[0][i];
  282. }
  283. }
  284. String to_tokens;
  285. for (int i = 0; i < kp_tokens[1].length(); i++) {
  286. if (i <= kp_tokens[1].length() - 6 && kp_tokens[1][i] == '\\' && kp_tokens[1][i + 1] == 'u' && is_hex_digit(kp_tokens[1][i + 2]) && is_hex_digit(kp_tokens[1][i + 3]) && is_hex_digit(kp_tokens[1][i + 4]) && is_hex_digit(kp_tokens[1][i + 5])) {
  287. char32_t charcode = kp_tokens[1].substr(i + 2, 4).hex_to_int();
  288. to_tokens += charcode;
  289. i += 5;
  290. } else {
  291. to_tokens += kp_tokens[1][i];
  292. }
  293. }
  294. int offset = kp_tokens[2].to_int();
  295. for (int a = 0; a < from_tokens.length(); a++) {
  296. for (int b = 0; b < to_tokens.length(); b++) {
  297. font->set_kerning(0, chr_height, Vector2i(from_tokens.unicode_at(a), to_tokens.unicode_at(b)), Vector2(offset, 0));
  298. }
  299. }
  300. }
  301. if (ascent > 0) {
  302. font->set_cache_ascent(0, chr_height, ascent);
  303. } else {
  304. font->set_cache_ascent(0, chr_height, 0.5 * chr_height);
  305. }
  306. if (descent > 0) {
  307. font->set_cache_descent(0, chr_height, descent);
  308. } else {
  309. font->set_cache_descent(0, chr_height, 0.5 * chr_height);
  310. }
  311. int flg = 0;
  312. if ((bool)p_options["compress"]) {
  313. flg |= ResourceSaver::SaverFlags::FLAG_COMPRESS;
  314. }
  315. print_verbose("Saving to: " + p_save_path + ".fontdata");
  316. err = ResourceSaver::save(font, p_save_path + ".fontdata", flg);
  317. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save font to file \"" + p_save_path + ".res\".");
  318. print_verbose("Done saving to: " + p_save_path + ".fontdata");
  319. return OK;
  320. }
  321. ResourceImporterImageFont::ResourceImporterImageFont() {
  322. }