Path: blob/master/modules/text_server_adv/thorvg_svg_in_ot.cpp
10277 views
/**************************************************************************/1/* thorvg_svg_in_ot.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 "thorvg_svg_in_ot.h"3132#ifdef GDEXTENSION33// Headers for building as GDExtension plug-in.3435#include <godot_cpp/classes/xml_parser.hpp>36#include <godot_cpp/core/mutex_lock.hpp>37#include <godot_cpp/godot.hpp>38#include <godot_cpp/templates/vector.hpp>3940using namespace godot;4142#elif defined(GODOT_MODULE)43// Headers for building as built-in module.4445#include "core/error/error_macros.h"46#include "core/io/xml_parser.h"47#include "core/os/memory.h"48#include "core/os/os.h"49#include "core/string/ustring.h"50#include "core/typedefs.h"51#include "core/variant/variant.h"5253#include "modules/modules_enabled.gen.h" // For svg, freetype.54#endif5556#ifdef MODULE_SVG_ENABLED57#ifdef MODULE_FREETYPE_ENABLED5859#include <freetype/otsvg.h>60#include <ft2build.h>6162#include <cstdlib>6364FT_Error tvg_svg_in_ot_init(FT_Pointer *p_state) {65*p_state = memnew(TVG_State);6667return FT_Err_Ok;68}6970void tvg_svg_in_ot_free(FT_Pointer *p_state) {71TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);72memdelete(state);73}7475static void construct_xml(Ref<XMLParser> &parser, double &r_embox_x, double &r_embox_y, String *p_xml, int64_t &r_tag_count) {76if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {77*p_xml += vformat("<%s", parser->get_node_name());78bool is_svg_tag = parser->get_node_name() == "svg";79for (int i = 0; i < parser->get_attribute_count(); i++) {80String aname = parser->get_attribute_name(i);81String value = parser->get_attribute_value(i);82if (is_svg_tag && aname == "viewBox") {83PackedStringArray vb = value.split(" ");84if (vb.size() == 4) {85r_embox_x = vb[2].to_float();86r_embox_y = vb[3].to_float();87}88} else if (is_svg_tag && aname == "width") {89r_embox_x = value.to_float();90} else if (is_svg_tag && aname == "height") {91r_embox_y = value.to_float();92} else {93*p_xml += vformat(" %s=\"%s\"", aname, value);94}95}9697if (parser->is_empty()) {98*p_xml += "/>";99} else {100*p_xml += ">";101if (r_tag_count >= 0) {102r_tag_count++;103}104}105} else if (parser->get_node_type() == XMLParser::NODE_TEXT) {106*p_xml += parser->get_node_data();107} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END) {108*p_xml += vformat("</%s>", parser->get_node_name());109if (r_tag_count > 0) {110r_tag_count--;111}112}113}114115FT_Error tvg_svg_in_ot_preset_slot(FT_GlyphSlot p_slot, FT_Bool p_cache, FT_Pointer *p_state) {116TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);117if (!state) {118ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized.");119}120MutexLock lock(state->mutex);121122FT_SVG_Document document = (FT_SVG_Document)p_slot->other;123FT_Size_Metrics metrics = document->metrics;124125GL_State &gl_state = state->glyph_map[p_slot->glyph_index];126if (!gl_state.ready) {127Ref<XMLParser> parser;128parser.instantiate();129parser->_open_buffer((const uint8_t *)document->svg_document, document->svg_document_length);130131String xml_body;132133double embox_x = document->units_per_EM;134double embox_y = document->units_per_EM;135136TVG_DocumentCache &cache = state->document_map[document->svg_document];137138if (!cache.xml_body.is_empty()) {139// If we have a cached document, that means we have already parsed it.140// All node cache should be available.141142xml_body = cache.xml_body;143embox_x = cache.embox_x;144embox_y = cache.embox_y;145146ERR_FAIL_COND_V(!cache.node_caches.has(p_slot->glyph_index), FT_Err_Invalid_SVG_Document);147Vector<TVG_NodeCache> &ncs = cache.node_caches[p_slot->glyph_index];148149uint64_t offset = 0;150for (TVG_NodeCache &nc : ncs) {151// Seek will call read() internally.152if (parser->seek(nc.document_offset) == OK) {153int64_t tag_count = 0;154String xml_node;155156// We only parse the glyph node.157do {158construct_xml(parser, embox_x, embox_y, &xml_node, tag_count);159} while (tag_count != 0 && parser->read() == OK);160161xml_body = xml_body.insert(nc.body_offset + offset, xml_node);162offset += xml_node.length();163}164}165} else {166String xml_node;167String xml_body_temp;168169String *p_xml = &xml_body_temp;170int64_t tag_count = -1;171172bool is_in_defs = false;173while (parser->read() == OK) {174if (parser->get_node_type() == XMLParser::NODE_ELEMENT && parser->get_node_name().to_lower() == "defs") {175is_in_defs = true;176} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name().to_lower() == "defs") {177is_in_defs = false;178}179if (!is_in_defs && parser->has_attribute("id")) {180const String &gl_name = parser->get_named_attribute_value("id");181if (gl_name.begins_with("glyph")) {182#ifdef GDEXTENSION183int dot_pos = gl_name.find(".");184#else185int dot_pos = gl_name.find_char('.');186#endif // GDEXTENSION187int64_t gl_idx = gl_name.substr(5, (dot_pos > 0) ? dot_pos - 5 : -1).to_int();188189TVG_NodeCache node_cache = TVG_NodeCache();190node_cache.document_offset = parser->get_node_offset(),191node_cache.body_offset = (uint64_t)cache.xml_body.length();192cache.node_caches[gl_idx].push_back(node_cache);193194if (p_slot->glyph_index != gl_idx) {195parser->skip_section();196continue;197}198tag_count = 0;199xml_node = "";200p_xml = &xml_node;201}202}203204xml_body_temp = "";205construct_xml(parser, embox_x, embox_y, p_xml, tag_count);206207if (xml_body_temp.length() > 0) {208xml_body += xml_body_temp;209cache.xml_body += xml_body_temp;210continue;211}212213if (tag_count == 0) {214p_xml = &xml_body_temp;215tag_count = -1;216xml_body += xml_node;217}218}219220cache.embox_x = embox_x;221cache.embox_y = embox_y;222}223224std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();225gl_state.xml_code = xml_body.utf8();226227tvg::Result result = picture->load(gl_state.xml_code.get_data(), gl_state.xml_code.length(), "svg+xml", false);228if (result != tvg::Result::Success) {229ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph metrics).");230}231232float svg_width, svg_height;233picture->size(&svg_width, &svg_height);234double aspect_x = (svg_width > svg_height) ? svg_width / svg_height : 1.0;235double aspect_y = (svg_width < svg_height) ? svg_height / svg_width : 1.0;236237result = picture->size(embox_x * aspect_x, embox_y * aspect_y);238if (result != tvg::Result::Success) {239ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");240}241242double scale = double(embox_x * aspect_x) / double(svg_width);243double yoff = double(document->metrics.ascender + document->metrics.descender) / double(document->metrics.ascender);244245double x_svg_to_out = (double)metrics.x_ppem / embox_x / scale;246double y_svg_to_out = (double)metrics.y_ppem / embox_y / scale;247248gl_state.m.e11 = (double)document->transform.xx / (1 << 16);249gl_state.m.e12 = -(double)document->transform.xy / (1 << 16);250gl_state.m.e21 = -(double)document->transform.yx / (1 << 16);251gl_state.m.e22 = (double)document->transform.yy / (1 << 16);252gl_state.m.e13 = (double)document->delta.x / 64 * embox_x / metrics.x_ppem * scale;253gl_state.m.e23 = -(double)document->delta.y / 64 * embox_y / metrics.y_ppem * scale;254gl_state.m.e31 = 0;255gl_state.m.e32 = 0;256gl_state.m.e33 = 1;257258result = picture->size(embox_x * aspect_x * x_svg_to_out, embox_y * aspect_y * y_svg_to_out);259if (result != tvg::Result::Success) {260ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");261}262263result = picture->transform(gl_state.m);264if (result != tvg::Result::Success) {265ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document.");266}267268picture->size(&gl_state.w, &gl_state.h);269270gl_state.x = (double(p_slot->metrics.horiAdvance) / 64.0 - gl_state.w) / 2.0;271gl_state.y = -Math::ceil(gl_state.h * yoff);272273gl_state.ready = true;274}275276p_slot->bitmap_left = (FT_Int)gl_state.x;277p_slot->bitmap_top = (FT_Int)-gl_state.y;278279double tmpd = Math::ceil(gl_state.h);280p_slot->bitmap.rows = (unsigned int)tmpd;281tmpd = Math::ceil(gl_state.w);282p_slot->bitmap.width = (unsigned int)tmpd;283p_slot->bitmap.pitch = (int)p_slot->bitmap.width * 4;284285p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;286287float metrics_width = (float)gl_state.w;288float metrics_height = (float)gl_state.h;289290float horiBearingX = (float)gl_state.x;291float horiBearingY = (float)-gl_state.y;292293float vertBearingX = p_slot->metrics.horiBearingX / 64.0f - p_slot->metrics.horiAdvance / 64.0f / 2;294float vertBearingY = (p_slot->metrics.vertAdvance / 64.0f - p_slot->metrics.height / 64.0f) / 2;295296float tmpf = Math::round(metrics_width * 64);297p_slot->metrics.width = (FT_Pos)tmpf;298tmpf = Math::round(metrics_height * 64);299p_slot->metrics.height = (FT_Pos)tmpf;300301p_slot->metrics.horiBearingX = (FT_Pos)(horiBearingX * 64);302p_slot->metrics.horiBearingY = (FT_Pos)(horiBearingY * 64);303p_slot->metrics.vertBearingX = (FT_Pos)(vertBearingX * 64);304p_slot->metrics.vertBearingY = (FT_Pos)(vertBearingY * 64);305306if (p_slot->metrics.vertAdvance == 0) {307p_slot->metrics.vertAdvance = (FT_Pos)(metrics_height * 1.2f * 64);308}309310return FT_Err_Ok;311}312313FT_Error tvg_svg_in_ot_render(FT_GlyphSlot p_slot, FT_Pointer *p_state) {314TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);315if (!state) {316ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized.");317}318MutexLock lock(state->mutex);319320if (!state->glyph_map.has(p_slot->glyph_index)) {321ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG glyph not loaded.");322}323324GL_State &gl_state = state->glyph_map[p_slot->glyph_index];325ERR_FAIL_COND_V_MSG(!gl_state.ready, FT_Err_Invalid_SVG_Document, "SVG glyph not ready.");326327std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();328tvg::Result res = picture->load(gl_state.xml_code.get_data(), gl_state.xml_code.length(), "svg+xml", false);329if (res != tvg::Result::Success) {330ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph rendering).");331}332res = picture->size(gl_state.w, gl_state.h);333if (res != tvg::Result::Success) {334ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");335}336res = picture->transform(gl_state.m);337if (res != tvg::Result::Success) {338ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document.");339}340341std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen();342res = sw_canvas->target((uint32_t *)p_slot->bitmap.buffer, (int)p_slot->bitmap.width, (int)p_slot->bitmap.width, (int)p_slot->bitmap.rows, tvg::SwCanvas::ARGB8888S);343if (res != tvg::Result::Success) {344ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to create SVG canvas.");345}346res = sw_canvas->push(std::move(picture));347if (res != tvg::Result::Success) {348ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to set SVG canvas source.");349}350res = sw_canvas->draw();351if (res != tvg::Result::Success) {352ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to draw to SVG canvas.");353}354res = sw_canvas->sync();355if (res != tvg::Result::Success) {356ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to sync SVG canvas.");357}358359state->glyph_map.erase(p_slot->glyph_index);360361p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;362p_slot->bitmap.num_grays = 256;363p_slot->format = FT_GLYPH_FORMAT_BITMAP;364365return FT_Err_Ok;366}367368SVG_RendererHooks tvg_svg_in_ot_hooks = {369(SVG_Lib_Init_Func)tvg_svg_in_ot_init,370(SVG_Lib_Free_Func)tvg_svg_in_ot_free,371(SVG_Lib_Render_Func)tvg_svg_in_ot_render,372(SVG_Lib_Preset_Slot_Func)tvg_svg_in_ot_preset_slot,373};374375SVG_RendererHooks *get_tvg_svg_in_ot_hooks() {376return &tvg_svg_in_ot_hooks;377}378379#endif // MODULE_FREETYPE_ENABLED380#endif // MODULE_SVG_ENABLED381382383