Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/text_server_fb/thorvg_svg_in_ot.cpp
10277 views
1
/**************************************************************************/
2
/* thorvg_svg_in_ot.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
31
#include "thorvg_svg_in_ot.h"
32
33
#ifdef GDEXTENSION
34
// Headers for building as GDExtension plug-in.
35
36
#include <godot_cpp/classes/xml_parser.hpp>
37
#include <godot_cpp/core/mutex_lock.hpp>
38
#include <godot_cpp/godot.hpp>
39
#include <godot_cpp/templates/vector.hpp>
40
41
using namespace godot;
42
43
#elif defined(GODOT_MODULE)
44
// Headers for building as built-in module.
45
46
#include "core/error/error_macros.h"
47
#include "core/io/xml_parser.h"
48
#include "core/os/memory.h"
49
#include "core/os/os.h"
50
#include "core/string/ustring.h"
51
#include "core/typedefs.h"
52
#include "core/variant/variant.h"
53
54
#include "modules/modules_enabled.gen.h" // For svg, freetype.
55
#endif
56
57
#ifdef MODULE_SVG_ENABLED
58
#ifdef MODULE_FREETYPE_ENABLED
59
60
#include <freetype/otsvg.h>
61
#include <ft2build.h>
62
63
#include <cstdlib>
64
65
FT_Error tvg_svg_in_ot_init(FT_Pointer *p_state) {
66
*p_state = memnew(TVG_State);
67
68
return FT_Err_Ok;
69
}
70
71
void tvg_svg_in_ot_free(FT_Pointer *p_state) {
72
TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
73
memdelete(state);
74
}
75
76
static void construct_xml(Ref<XMLParser> &parser, double &r_embox_x, double &r_embox_y, String *p_xml, int64_t &r_tag_count) {
77
if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
78
*p_xml += vformat("<%s", parser->get_node_name());
79
bool is_svg_tag = parser->get_node_name() == "svg";
80
for (int i = 0; i < parser->get_attribute_count(); i++) {
81
String aname = parser->get_attribute_name(i);
82
String value = parser->get_attribute_value(i);
83
if (is_svg_tag && aname == "viewBox") {
84
PackedStringArray vb = value.split(" ");
85
if (vb.size() == 4) {
86
r_embox_x = vb[2].to_float();
87
r_embox_y = vb[3].to_float();
88
}
89
} else if (is_svg_tag && aname == "width") {
90
r_embox_x = value.to_float();
91
} else if (is_svg_tag && aname == "height") {
92
r_embox_y = value.to_float();
93
} else {
94
*p_xml += vformat(" %s=\"%s\"", aname, value);
95
}
96
}
97
98
if (parser->is_empty()) {
99
*p_xml += "/>";
100
} else {
101
*p_xml += ">";
102
if (r_tag_count >= 0) {
103
r_tag_count++;
104
}
105
}
106
} else if (parser->get_node_type() == XMLParser::NODE_TEXT) {
107
*p_xml += parser->get_node_data();
108
} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END) {
109
*p_xml += vformat("</%s>", parser->get_node_name());
110
if (r_tag_count > 0) {
111
r_tag_count--;
112
}
113
}
114
}
115
116
FT_Error tvg_svg_in_ot_preset_slot(FT_GlyphSlot p_slot, FT_Bool p_cache, FT_Pointer *p_state) {
117
TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
118
if (!state) {
119
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized.");
120
}
121
MutexLock lock(state->mutex);
122
123
FT_SVG_Document document = (FT_SVG_Document)p_slot->other;
124
FT_Size_Metrics metrics = document->metrics;
125
126
GL_State &gl_state = state->glyph_map[p_slot->glyph_index];
127
if (!gl_state.ready) {
128
Ref<XMLParser> parser;
129
parser.instantiate();
130
parser->_open_buffer((const uint8_t *)document->svg_document, document->svg_document_length);
131
132
String xml_body;
133
134
double embox_x = document->units_per_EM;
135
double embox_y = document->units_per_EM;
136
137
TVG_DocumentCache &cache = state->document_map[document->svg_document];
138
139
if (!cache.xml_body.is_empty()) {
140
// If we have a cached document, that means we have already parsed it.
141
// All node cache should be available.
142
143
xml_body = cache.xml_body;
144
embox_x = cache.embox_x;
145
embox_y = cache.embox_y;
146
147
ERR_FAIL_COND_V(!cache.node_caches.has(p_slot->glyph_index), FT_Err_Invalid_SVG_Document);
148
Vector<TVG_NodeCache> &ncs = cache.node_caches[p_slot->glyph_index];
149
150
uint64_t offset = 0;
151
for (TVG_NodeCache &nc : ncs) {
152
// Seek will call read() internally.
153
if (parser->seek(nc.document_offset) == OK) {
154
int64_t tag_count = 0;
155
String xml_node;
156
157
// We only parse the glyph node.
158
do {
159
construct_xml(parser, embox_x, embox_y, &xml_node, tag_count);
160
} while (tag_count != 0 && parser->read() == OK);
161
162
xml_body = xml_body.insert(nc.body_offset + offset, xml_node);
163
offset += xml_node.length();
164
}
165
}
166
} else {
167
String xml_node;
168
String xml_body_temp;
169
170
String *p_xml = &xml_body_temp;
171
int64_t tag_count = -1;
172
173
bool is_in_defs = false;
174
while (parser->read() == OK) {
175
if (parser->get_node_type() == XMLParser::NODE_ELEMENT && parser->get_node_name().to_lower() == "defs") {
176
is_in_defs = true;
177
} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name().to_lower() == "defs") {
178
is_in_defs = false;
179
}
180
if (!is_in_defs && parser->has_attribute("id")) {
181
const String &gl_name = parser->get_named_attribute_value("id");
182
if (gl_name.begins_with("glyph")) {
183
#ifdef GDEXTENSION
184
int dot_pos = gl_name.find(".");
185
#else
186
int dot_pos = gl_name.find_char('.');
187
#endif // GDEXTENSION
188
int64_t gl_idx = gl_name.substr(5, (dot_pos > 0) ? dot_pos - 5 : -1).to_int();
189
190
TVG_NodeCache node_cache = TVG_NodeCache();
191
node_cache.document_offset = parser->get_node_offset(),
192
node_cache.body_offset = (uint64_t)cache.xml_body.length();
193
cache.node_caches[gl_idx].push_back(node_cache);
194
195
if (p_slot->glyph_index != gl_idx) {
196
parser->skip_section();
197
continue;
198
}
199
tag_count = 0;
200
xml_node = "";
201
p_xml = &xml_node;
202
}
203
}
204
205
xml_body_temp = "";
206
construct_xml(parser, embox_x, embox_y, p_xml, tag_count);
207
208
if (xml_body_temp.length() > 0) {
209
xml_body += xml_body_temp;
210
cache.xml_body += xml_body_temp;
211
continue;
212
}
213
214
if (tag_count == 0) {
215
p_xml = &xml_body_temp;
216
tag_count = -1;
217
xml_body += xml_node;
218
}
219
}
220
221
cache.embox_x = embox_x;
222
cache.embox_y = embox_y;
223
}
224
225
std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
226
gl_state.xml_code = xml_body.utf8();
227
228
tvg::Result result = picture->load(gl_state.xml_code.get_data(), gl_state.xml_code.length(), "svg+xml", false);
229
if (result != tvg::Result::Success) {
230
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph metrics).");
231
}
232
233
float svg_width, svg_height;
234
picture->size(&svg_width, &svg_height);
235
double aspect_x = (svg_width > svg_height) ? svg_width / svg_height : 1.0;
236
double aspect_y = (svg_width < svg_height) ? svg_height / svg_width : 1.0;
237
238
result = picture->size(embox_x * aspect_x, embox_y * aspect_y);
239
if (result != tvg::Result::Success) {
240
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");
241
}
242
243
double scale = double(embox_x * aspect_x) / double(svg_width);
244
double yoff = double(document->metrics.ascender + document->metrics.descender) / double(document->metrics.ascender);
245
246
double x_svg_to_out = (double)metrics.x_ppem / embox_x / scale;
247
double y_svg_to_out = (double)metrics.y_ppem / embox_y / scale;
248
249
gl_state.m.e11 = (double)document->transform.xx / (1 << 16);
250
gl_state.m.e12 = -(double)document->transform.xy / (1 << 16);
251
gl_state.m.e21 = -(double)document->transform.yx / (1 << 16);
252
gl_state.m.e22 = (double)document->transform.yy / (1 << 16);
253
gl_state.m.e13 = (double)document->delta.x / 64 * embox_x / metrics.x_ppem * scale;
254
gl_state.m.e23 = -(double)document->delta.y / 64 * embox_y / metrics.y_ppem * scale;
255
gl_state.m.e31 = 0;
256
gl_state.m.e32 = 0;
257
gl_state.m.e33 = 1;
258
259
result = picture->size(embox_x * aspect_x * x_svg_to_out, embox_y * aspect_y * y_svg_to_out);
260
if (result != tvg::Result::Success) {
261
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");
262
}
263
264
result = picture->transform(gl_state.m);
265
if (result != tvg::Result::Success) {
266
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document.");
267
}
268
269
picture->size(&gl_state.w, &gl_state.h);
270
271
gl_state.x = (double(p_slot->metrics.horiAdvance) / 64.0 - gl_state.w) / 2.0;
272
gl_state.y = -Math::ceil(gl_state.h * yoff);
273
274
gl_state.ready = true;
275
}
276
277
p_slot->bitmap_left = (FT_Int)gl_state.x;
278
p_slot->bitmap_top = (FT_Int)-gl_state.y;
279
280
double tmpd = Math::ceil(gl_state.h);
281
p_slot->bitmap.rows = (unsigned int)tmpd;
282
tmpd = Math::ceil(gl_state.w);
283
p_slot->bitmap.width = (unsigned int)tmpd;
284
p_slot->bitmap.pitch = (int)p_slot->bitmap.width * 4;
285
286
p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
287
288
float metrics_width = (float)gl_state.w;
289
float metrics_height = (float)gl_state.h;
290
291
float horiBearingX = (float)gl_state.x;
292
float horiBearingY = (float)-gl_state.y;
293
294
float vertBearingX = p_slot->metrics.horiBearingX / 64.0f - p_slot->metrics.horiAdvance / 64.0f / 2;
295
float vertBearingY = (p_slot->metrics.vertAdvance / 64.0f - p_slot->metrics.height / 64.0f) / 2;
296
297
float tmpf = Math::round(metrics_width * 64);
298
p_slot->metrics.width = (FT_Pos)tmpf;
299
tmpf = Math::round(metrics_height * 64);
300
p_slot->metrics.height = (FT_Pos)tmpf;
301
302
p_slot->metrics.horiBearingX = (FT_Pos)(horiBearingX * 64);
303
p_slot->metrics.horiBearingY = (FT_Pos)(horiBearingY * 64);
304
p_slot->metrics.vertBearingX = (FT_Pos)(vertBearingX * 64);
305
p_slot->metrics.vertBearingY = (FT_Pos)(vertBearingY * 64);
306
307
if (p_slot->metrics.vertAdvance == 0) {
308
p_slot->metrics.vertAdvance = (FT_Pos)(metrics_height * 1.2f * 64);
309
}
310
311
return FT_Err_Ok;
312
}
313
314
FT_Error tvg_svg_in_ot_render(FT_GlyphSlot p_slot, FT_Pointer *p_state) {
315
TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
316
if (!state) {
317
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized.");
318
}
319
MutexLock lock(state->mutex);
320
321
if (!state->glyph_map.has(p_slot->glyph_index)) {
322
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG glyph not loaded.");
323
}
324
325
GL_State &gl_state = state->glyph_map[p_slot->glyph_index];
326
ERR_FAIL_COND_V_MSG(!gl_state.ready, FT_Err_Invalid_SVG_Document, "SVG glyph not ready.");
327
328
std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
329
tvg::Result res = picture->load(gl_state.xml_code.get_data(), gl_state.xml_code.length(), "svg+xml", false);
330
if (res != tvg::Result::Success) {
331
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph rendering).");
332
}
333
res = picture->size(gl_state.w, gl_state.h);
334
if (res != tvg::Result::Success) {
335
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");
336
}
337
res = picture->transform(gl_state.m);
338
if (res != tvg::Result::Success) {
339
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document.");
340
}
341
342
std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen();
343
res = 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);
344
if (res != tvg::Result::Success) {
345
ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to create SVG canvas.");
346
}
347
res = sw_canvas->push(std::move(picture));
348
if (res != tvg::Result::Success) {
349
ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to set SVG canvas source.");
350
}
351
res = sw_canvas->draw();
352
if (res != tvg::Result::Success) {
353
ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to draw to SVG canvas.");
354
}
355
res = sw_canvas->sync();
356
if (res != tvg::Result::Success) {
357
ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to sync SVG canvas.");
358
}
359
360
state->glyph_map.erase(p_slot->glyph_index);
361
362
p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
363
p_slot->bitmap.num_grays = 256;
364
p_slot->format = FT_GLYPH_FORMAT_BITMAP;
365
366
return FT_Err_Ok;
367
}
368
369
SVG_RendererHooks tvg_svg_in_ot_hooks = {
370
(SVG_Lib_Init_Func)tvg_svg_in_ot_init,
371
(SVG_Lib_Free_Func)tvg_svg_in_ot_free,
372
(SVG_Lib_Render_Func)tvg_svg_in_ot_render,
373
(SVG_Lib_Preset_Slot_Func)tvg_svg_in_ot_preset_slot,
374
};
375
376
SVG_RendererHooks *get_tvg_svg_in_ot_hooks() {
377
return &tvg_svg_in_ot_hooks;
378
}
379
380
#endif // MODULE_FREETYPE_ENABLED
381
#endif // MODULE_SVG_ENABLED
382
383