image_loader_svg.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. #include "image_loader_svg.h"
  31. #include "core/os/memory.h"
  32. #include "core/variant/variant.h"
  33. #include <thorvg.h>
  34. HashMap<Color, Color> ImageLoaderSVG::forced_color_map = HashMap<Color, Color>();
  35. void ImageLoaderSVG::set_forced_color_map(const HashMap<Color, Color> &p_color_map) {
  36. forced_color_map = p_color_map;
  37. }
  38. void ImageLoaderSVG::_replace_color_property(const HashMap<Color, Color> &p_color_map, const String &p_prefix, String &r_string) {
  39. // Replace colors in the SVG based on what is passed in `p_color_map`.
  40. // Used to change the colors of editor icons based on the used theme.
  41. // The strings being replaced are typically of the form:
  42. // fill="#5abbef"
  43. // But can also be 3-letter codes, include alpha, be "none" or a named color
  44. // string ("blue"). So we convert to Godot Color to compare with `p_color_map`.
  45. const int prefix_len = p_prefix.length();
  46. int pos = r_string.find(p_prefix);
  47. while (pos != -1) {
  48. pos += prefix_len; // Skip prefix.
  49. int end_pos = r_string.find("\"", pos);
  50. ERR_FAIL_COND_MSG(end_pos == -1, vformat("Malformed SVG string after property \"%s\".", p_prefix));
  51. const String color_code = r_string.substr(pos, end_pos - pos);
  52. if (color_code != "none" && !color_code.begins_with("url(")) {
  53. const Color color = Color(color_code); // Handles both HTML codes and named colors.
  54. if (p_color_map.has(color)) {
  55. r_string = r_string.left(pos) + "#" + p_color_map[color].to_html(false) + r_string.substr(end_pos);
  56. }
  57. }
  58. // Search for other occurrences.
  59. pos = r_string.find(p_prefix, pos);
  60. }
  61. }
  62. Ref<Image> ImageLoaderSVG::load_mem_svg(const uint8_t *p_svg, int p_size, float p_scale) {
  63. Ref<Image> img;
  64. img.instantiate();
  65. Error err = create_image_from_utf8_buffer(img, p_svg, p_size, p_scale, false);
  66. ERR_FAIL_COND_V(err, Ref<Image>());
  67. return img;
  68. }
  69. 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) {
  70. ERR_FAIL_COND_V_MSG(Math::is_zero_approx(p_scale), ERR_INVALID_PARAMETER, "ImageLoaderSVG: Can't load SVG with a scale of 0.");
  71. std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
  72. tvg::Result result = picture->load((const char *)p_buffer, p_buffer_size, "svg", true);
  73. if (result != tvg::Result::Success) {
  74. return ERR_INVALID_DATA;
  75. }
  76. float fw, fh;
  77. picture->size(&fw, &fh);
  78. uint32_t width = MAX(1, round(fw * p_scale));
  79. uint32_t height = MAX(1, round(fh * p_scale));
  80. const uint32_t max_dimension = 16384;
  81. if (width > max_dimension || height > max_dimension) {
  82. WARN_PRINT(vformat(
  83. 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."),
  84. width, height, p_scale, max_dimension, max_dimension));
  85. width = MIN(width, max_dimension);
  86. height = MIN(height, max_dimension);
  87. }
  88. picture->size(width, height);
  89. std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen();
  90. // Note: memalloc here, be sure to memfree before any return.
  91. uint32_t *buffer = (uint32_t *)memalloc(sizeof(uint32_t) * width * height);
  92. tvg::Result res = sw_canvas->target(buffer, width, width, height, tvg::SwCanvas::ARGB8888S);
  93. if (res != tvg::Result::Success) {
  94. memfree(buffer);
  95. ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't set target on ThorVG canvas.");
  96. }
  97. res = sw_canvas->push(std::move(picture));
  98. if (res != tvg::Result::Success) {
  99. memfree(buffer);
  100. ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't insert ThorVG picture on canvas.");
  101. }
  102. res = sw_canvas->draw();
  103. if (res != tvg::Result::Success) {
  104. memfree(buffer);
  105. ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't draw ThorVG pictures on canvas.");
  106. }
  107. res = sw_canvas->sync();
  108. if (res != tvg::Result::Success) {
  109. memfree(buffer);
  110. ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't sync ThorVG canvas.");
  111. }
  112. Vector<uint8_t> image;
  113. image.resize(width * height * sizeof(uint32_t));
  114. for (uint32_t y = 0; y < height; y++) {
  115. for (uint32_t x = 0; x < width; x++) {
  116. uint32_t n = buffer[y * width + x];
  117. const size_t offset = sizeof(uint32_t) * width * y + sizeof(uint32_t) * x;
  118. image.write[offset + 0] = (n >> 16) & 0xff;
  119. image.write[offset + 1] = (n >> 8) & 0xff;
  120. image.write[offset + 2] = n & 0xff;
  121. image.write[offset + 3] = (n >> 24) & 0xff;
  122. }
  123. }
  124. res = sw_canvas->clear(true);
  125. memfree(buffer);
  126. p_image->set_data(width, height, false, Image::FORMAT_RGBA8, image);
  127. return OK;
  128. }
  129. Error ImageLoaderSVG::create_image_from_utf8_buffer(Ref<Image> p_image, const PackedByteArray &p_buffer, float p_scale, bool p_upsample) {
  130. return create_image_from_utf8_buffer(p_image, p_buffer.ptr(), p_buffer.size(), p_scale, p_upsample);
  131. }
  132. 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) {
  133. if (p_color_map.size()) {
  134. _replace_color_property(p_color_map, "stop-color=\"", p_string);
  135. _replace_color_property(p_color_map, "fill=\"", p_string);
  136. _replace_color_property(p_color_map, "stroke=\"", p_string);
  137. }
  138. PackedByteArray bytes = p_string.to_utf8_buffer();
  139. return create_image_from_utf8_buffer(p_image, bytes, p_scale, p_upsample);
  140. }
  141. void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const {
  142. p_extensions->push_back("svg");
  143. }
  144. Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) {
  145. String svg = p_fileaccess->get_as_utf8_string();
  146. Error err;
  147. if (p_flags & FLAG_CONVERT_COLORS) {
  148. err = create_image_from_string(p_image, svg, p_scale, false, forced_color_map);
  149. } else {
  150. err = create_image_from_string(p_image, svg, p_scale, false, HashMap<Color, Color>());
  151. }
  152. if (err != OK) {
  153. return err;
  154. } else if (p_image->is_empty()) {
  155. return ERR_INVALID_DATA;
  156. }
  157. if (p_flags & FLAG_FORCE_LINEAR) {
  158. p_image->srgb_to_linear();
  159. }
  160. return OK;
  161. }
  162. ImageLoaderSVG::ImageLoaderSVG() {
  163. Image::_svg_scalable_mem_loader_func = load_mem_svg;
  164. }