image_loader_svg.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. Error ImageLoaderSVG::create_image_from_utf8_buffer(Ref<Image> p_image, const PackedByteArray &p_buffer, float p_scale, bool p_upsample) {
  63. ERR_FAIL_COND_V_MSG(Math::is_zero_approx(p_scale), ERR_INVALID_PARAMETER, "ImageLoaderSVG: Can't load SVG with a scale of 0.");
  64. std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
  65. tvg::Result result = picture->load((const char *)p_buffer.ptr(), p_buffer.size(), "svg", true);
  66. if (result != tvg::Result::Success) {
  67. return ERR_INVALID_DATA;
  68. }
  69. float fw, fh;
  70. picture->size(&fw, &fh);
  71. uint32_t width = round(fw * p_scale);
  72. uint32_t height = round(fh * p_scale);
  73. const uint32_t max_dimension = 16384;
  74. if (width > max_dimension || height > max_dimension) {
  75. WARN_PRINT(vformat(
  76. 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."),
  77. width, height, p_scale, max_dimension, max_dimension));
  78. width = MIN(width, max_dimension);
  79. height = MIN(height, max_dimension);
  80. }
  81. picture->size(width, height);
  82. std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen();
  83. // Note: memalloc here, be sure to memfree before any return.
  84. uint32_t *buffer = (uint32_t *)memalloc(sizeof(uint32_t) * width * height);
  85. tvg::Result res = sw_canvas->target(buffer, width, width, height, tvg::SwCanvas::ARGB8888_STRAIGHT);
  86. if (res != tvg::Result::Success) {
  87. memfree(buffer);
  88. ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't set target on ThorVG canvas.");
  89. }
  90. res = sw_canvas->push(std::move(picture));
  91. if (res != tvg::Result::Success) {
  92. memfree(buffer);
  93. ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't insert ThorVG picture on canvas.");
  94. }
  95. res = sw_canvas->draw();
  96. if (res != tvg::Result::Success) {
  97. memfree(buffer);
  98. ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't draw ThorVG pictures on canvas.");
  99. }
  100. res = sw_canvas->sync();
  101. if (res != tvg::Result::Success) {
  102. memfree(buffer);
  103. ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't sync ThorVG canvas.");
  104. }
  105. Vector<uint8_t> image;
  106. image.resize(width * height * sizeof(uint32_t));
  107. for (uint32_t y = 0; y < height; y++) {
  108. for (uint32_t x = 0; x < width; x++) {
  109. uint32_t n = buffer[y * width + x];
  110. const size_t offset = sizeof(uint32_t) * width * y + sizeof(uint32_t) * x;
  111. image.write[offset + 0] = (n >> 16) & 0xff;
  112. image.write[offset + 1] = (n >> 8) & 0xff;
  113. image.write[offset + 2] = n & 0xff;
  114. image.write[offset + 3] = (n >> 24) & 0xff;
  115. }
  116. }
  117. res = sw_canvas->clear(true);
  118. memfree(buffer);
  119. p_image->set_data(width, height, false, Image::FORMAT_RGBA8, image);
  120. return OK;
  121. }
  122. 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) {
  123. if (p_color_map.size()) {
  124. _replace_color_property(p_color_map, "stop-color=\"", p_string);
  125. _replace_color_property(p_color_map, "fill=\"", p_string);
  126. _replace_color_property(p_color_map, "stroke=\"", p_string);
  127. }
  128. PackedByteArray bytes = p_string.to_utf8_buffer();
  129. return create_image_from_utf8_buffer(p_image, bytes, p_scale, p_upsample);
  130. }
  131. void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const {
  132. p_extensions->push_back("svg");
  133. }
  134. Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) {
  135. String svg = p_fileaccess->get_as_utf8_string();
  136. Error err;
  137. if (p_flags & FLAG_CONVERT_COLORS) {
  138. err = create_image_from_string(p_image, svg, p_scale, false, forced_color_map);
  139. } else {
  140. err = create_image_from_string(p_image, svg, p_scale, false, HashMap<Color, Color>());
  141. }
  142. if (err != OK) {
  143. return err;
  144. } else if (p_image->is_empty()) {
  145. return ERR_INVALID_DATA;
  146. }
  147. if (p_flags & FLAG_FORCE_LINEAR) {
  148. p_image->srgb_to_linear();
  149. }
  150. return OK;
  151. }