Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/svg/image_loader_svg.cpp
10277 views
1
/**************************************************************************/
2
/* image_loader_svg.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 "image_loader_svg.h"
32
33
#include "core/os/memory.h"
34
#include "core/variant/variant.h"
35
36
#include <thorvg.h>
37
38
HashMap<Color, Color> ImageLoaderSVG::forced_color_map = HashMap<Color, Color>();
39
40
void ImageLoaderSVG::set_forced_color_map(const HashMap<Color, Color> &p_color_map) {
41
forced_color_map = p_color_map;
42
}
43
44
void ImageLoaderSVG::_replace_color_property(const HashMap<Color, Color> &p_color_map, const String &p_prefix, String &r_string) {
45
// Replace colors in the SVG based on what is passed in `p_color_map`.
46
// Used to change the colors of editor icons based on the used theme.
47
// The strings being replaced are typically of the form:
48
// fill="#5abbef"
49
// But can also be 3-letter codes, include alpha, be "none" or a named color
50
// string ("blue"). So we convert to Godot Color to compare with `p_color_map`.
51
52
const int prefix_len = p_prefix.length();
53
int pos = r_string.find(p_prefix);
54
while (pos != -1) {
55
pos += prefix_len; // Skip prefix.
56
int end_pos = r_string.find_char('"', pos);
57
ERR_FAIL_COND_MSG(end_pos == -1, vformat("Malformed SVG string after property \"%s\".", p_prefix));
58
const String color_code = r_string.substr(pos, end_pos - pos);
59
if (color_code != "none" && !color_code.begins_with("url(")) {
60
const Color color = Color(color_code); // Handles both HTML codes and named colors.
61
if (p_color_map.has(color)) {
62
r_string = r_string.left(pos) + "#" + p_color_map[color].to_html(false) + r_string.substr(end_pos);
63
}
64
}
65
// Search for other occurrences.
66
pos = r_string.find(p_prefix, pos);
67
}
68
}
69
70
Ref<Image> ImageLoaderSVG::load_mem_svg(const uint8_t *p_svg, int p_size, float p_scale) {
71
Ref<Image> img;
72
img.instantiate();
73
74
Error err = create_image_from_utf8_buffer(img, p_svg, p_size, p_scale, false);
75
ERR_FAIL_COND_V_MSG(err != OK, Ref<Image>(), vformat("ImageLoaderSVG: Failed to create SVG from buffer, error code %d.", err));
76
77
return img;
78
}
79
80
Error ImageLoaderSVG::create_image_from_utf8_buffer(Ref<Image> p_image, const uint8_t *p_buffer, int p_buffer_size, float p_scale, bool p_upsample) {
81
ERR_FAIL_COND_V_MSG(Math::is_zero_approx(p_scale), ERR_INVALID_PARAMETER, "ImageLoaderSVG: Can't load SVG with a scale of 0.");
82
83
std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
84
85
tvg::Result result = picture->load((const char *)p_buffer, p_buffer_size, "svg", true);
86
if (result != tvg::Result::Success) {
87
return ERR_INVALID_DATA;
88
}
89
float fw, fh;
90
picture->size(&fw, &fh);
91
92
uint32_t width = MAX(1, std::round(fw * p_scale));
93
uint32_t height = MAX(1, std::round(fh * p_scale));
94
95
const uint32_t max_dimension = 16384;
96
if (width > max_dimension || height > max_dimension) {
97
WARN_PRINT(vformat(
98
String::utf8("ImageLoaderSVG: Target canvas dimensions %d×%d (with scale %.2f) exceed the max supported dimensions %d×%d. The target canvas will be scaled down."),
99
width, height, p_scale, max_dimension, max_dimension));
100
width = MIN(width, max_dimension);
101
height = MIN(height, max_dimension);
102
}
103
104
picture->size(width, height);
105
106
std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen();
107
Vector<uint8_t> buffer;
108
buffer.resize(sizeof(uint32_t) * width * height);
109
110
tvg::Result res = sw_canvas->target((uint32_t *)buffer.ptrw(), width, width, height, tvg::SwCanvas::ABGR8888S);
111
if (res != tvg::Result::Success) {
112
ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't set target on ThorVG canvas.");
113
}
114
115
res = sw_canvas->push(std::move(picture));
116
if (res != tvg::Result::Success) {
117
ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't insert ThorVG picture on canvas.");
118
}
119
120
res = sw_canvas->draw();
121
if (res != tvg::Result::Success) {
122
ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't draw ThorVG pictures on canvas.");
123
}
124
125
res = sw_canvas->sync();
126
if (res != tvg::Result::Success) {
127
ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't sync ThorVG canvas.");
128
}
129
130
p_image->set_data(width, height, false, Image::FORMAT_RGBA8, buffer);
131
132
res = sw_canvas->clear(true);
133
134
return OK;
135
}
136
137
Error ImageLoaderSVG::create_image_from_utf8_buffer(Ref<Image> p_image, const PackedByteArray &p_buffer, float p_scale, bool p_upsample) {
138
return create_image_from_utf8_buffer(p_image, p_buffer.ptr(), p_buffer.size(), p_scale, p_upsample);
139
}
140
141
Error ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, String p_string, float p_scale, bool p_upsample, const HashMap<Color, Color> &p_color_map) {
142
if (p_color_map.size()) {
143
_replace_color_property(p_color_map, "stop-color=\"", p_string);
144
_replace_color_property(p_color_map, "fill=\"", p_string);
145
_replace_color_property(p_color_map, "stroke=\"", p_string);
146
}
147
148
PackedByteArray bytes = p_string.to_utf8_buffer();
149
150
return create_image_from_utf8_buffer(p_image, bytes, p_scale, p_upsample);
151
}
152
153
void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const {
154
p_extensions->push_back("svg");
155
}
156
157
Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) {
158
const uint64_t len = p_fileaccess->get_length() - p_fileaccess->get_position();
159
Vector<uint8_t> buffer;
160
buffer.resize(len);
161
p_fileaccess->get_buffer(buffer.ptrw(), buffer.size());
162
163
String svg;
164
Error err = svg.append_utf8((const char *)buffer.ptr(), buffer.size());
165
if (err != OK) {
166
return err;
167
}
168
169
if (p_flags & FLAG_CONVERT_COLORS) {
170
err = create_image_from_string(p_image, svg, p_scale, false, forced_color_map);
171
} else {
172
err = create_image_from_string(p_image, svg, p_scale, false, HashMap<Color, Color>());
173
}
174
175
if (err != OK) {
176
return err;
177
} else if (p_image->is_empty()) {
178
return ERR_INVALID_DATA;
179
}
180
181
if (p_flags & FLAG_FORCE_LINEAR) {
182
p_image->srgb_to_linear();
183
}
184
return OK;
185
}
186
187
ImageLoaderSVG::ImageLoaderSVG() {
188
Image::_svg_scalable_mem_loader_func = load_mem_svg;
189
}
190
191