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