SVGCache.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019- The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "SVGCache.h"
  29. #include "../../Include/RmlUi/Core/CallbackTexture.h"
  30. #include "../../Include/RmlUi/Core/ComputedValues.h"
  31. #include "../../Include/RmlUi/Core/Core.h"
  32. #include "../../Include/RmlUi/Core/Element.h"
  33. #include "../../Include/RmlUi/Core/ElementDocument.h"
  34. #include "../../Include/RmlUi/Core/FileInterface.h"
  35. #include "../../Include/RmlUi/Core/Geometry.h"
  36. #include "../../Include/RmlUi/Core/MeshUtilities.h"
  37. #include "../../Include/RmlUi/Core/RenderManager.h"
  38. #include "../../Include/RmlUi/Core/SystemInterface.h"
  39. #include "../../Include/RmlUi/Core/Texture.h"
  40. #include "../../Include/RmlUi/Core/Utilities.h"
  41. #include "../Core/ControlledLifetimeResource.h"
  42. #include <algorithm>
  43. #include <lunasvg.h>
  44. #ifdef RMLUI_SVG_DEBUG
  45. #define RMLUI_SVG_DEBUG_LOG(...) Rml::Log::Message(Rml::Log::LT_DEBUG, __VA_ARGS__)
  46. #else
  47. #define RMLUI_SVG_DEBUG_LOG(...)
  48. #endif
  49. namespace Rml {
  50. namespace SVG {
  51. struct SVGKey {
  52. String path;
  53. Vector2i dimensions;
  54. bool crop_to_content;
  55. ColourbPremultiplied colour;
  56. friend bool operator==(const SVGKey& lhs, const SVGKey& rhs)
  57. {
  58. return lhs.path == rhs.path && lhs.dimensions == rhs.dimensions && lhs.crop_to_content == rhs.crop_to_content && lhs.colour == rhs.colour;
  59. }
  60. };
  61. } // namespace SVG
  62. } // namespace Rml
  63. namespace std {
  64. template <>
  65. struct hash<::Rml::SVG::SVGKey> {
  66. size_t operator()(const ::Rml::SVG::SVGKey& key) const noexcept
  67. {
  68. size_t hash = 0;
  69. Rml::Utilities::HashCombine(hash, key.path);
  70. Rml::Utilities::HashCombine(hash, key.dimensions.x);
  71. Rml::Utilities::HashCombine(hash, key.dimensions.y);
  72. Rml::Utilities::HashCombine(hash, key.crop_to_content);
  73. static_assert(sizeof(uint32_t) == sizeof(key.colour), "Expecting color to be 4 bytes");
  74. Rml::Utilities::HashCombine(hash, *reinterpret_cast<const uint32_t*>(&key.colour[0]));
  75. return hash;
  76. }
  77. };
  78. } // namespace std
  79. namespace Rml {
  80. namespace SVG {
  81. static SharedPtr<SVGData> GetHandle(RenderManager& render_manager, String path, Vector2i dimensions, bool crop_to_content,
  82. ColourbPremultiplied colour);
  83. static void ReleaseHandle(SVGData* handle);
  84. struct SVGGeometry {
  85. ColourbPremultiplied colour;
  86. UniquePtr<Geometry> geometry;
  87. };
  88. struct SVGTexture {
  89. Vector2i render_dimensions;
  90. bool crop_to_content;
  91. CallbackTexture texture;
  92. // List of geometries using this texture, one entry for each unique color.
  93. Vector<SVGGeometry> geometries;
  94. };
  95. struct SVGDocument {
  96. Vector2f intrinsic_dimensions;
  97. UniquePtr<lunasvg::Document> svg_document;
  98. // List of textures using this document, one entry for each unique render dimension plus meta-data.
  99. Vector<SVGTexture> textures;
  100. };
  101. struct SVGCacheData {
  102. // A list of SVG documents mapped by their path. Owns all geometry and textures needed for rendering.
  103. UnorderedMap<String, SVGDocument> documents;
  104. // Handles are reference-counted lookup keys and views into the SVG document resources. Handles are responsible
  105. // for cleaning up the resources in the documents, when nothing refers to them any longer. When a handle is
  106. // destroyed, it also removes itself from the handle map.
  107. StableUnorderedMap<SVGKey, WeakPtr<SVGData>> handles;
  108. };
  109. static ControlledLifetimeResource<SVGCacheData> svg_cache_data;
  110. SVGData::SVGData(Geometry& geometry, Texture texture, Vector2f intrinsic_dimensions, const SVGKey& cache_key) :
  111. geometry(geometry), texture(texture), intrinsic_dimensions(intrinsic_dimensions), cache_key(cache_key)
  112. {}
  113. SVGData::~SVGData()
  114. {
  115. ReleaseHandle(this);
  116. }
  117. static Vector<SVGTexture>::iterator FindSVGTexture(SVGDocument& doc, Vector2i dimensions, bool crop_to_content)
  118. {
  119. return std::find_if(doc.textures.begin(), doc.textures.end(),
  120. [&](const auto& entry) { return entry.render_dimensions == dimensions && entry.crop_to_content == crop_to_content; });
  121. }
  122. static Vector<SVGGeometry>::iterator FindSVGGeometry(SVGTexture& per_size_data, const ColourbPremultiplied colour)
  123. {
  124. return std::find_if(per_size_data.geometries.begin(), per_size_data.geometries.end(),
  125. [&](const SVGGeometry& data) { return data.colour == colour; });
  126. }
  127. static const std::string& GetSourceOr(const lunasvg::Document* svg_document, const std::string& default_value)
  128. {
  129. const auto& documents = svg_cache_data->documents;
  130. auto it = std::find_if(documents.begin(), documents.end(),
  131. [svg_document](const auto& pair) { return pair.second.svg_document.get() == svg_document; });
  132. if (it != documents.end())
  133. return it->first;
  134. return default_value;
  135. }
  136. static SharedPtr<SVGData> GetHandle(RenderManager& render_manager, String move_from_path, const Vector2i dimensions, const bool crop_to_content,
  137. const ColourbPremultiplied colour)
  138. {
  139. SVGKey key{std::move(move_from_path), dimensions, crop_to_content, colour};
  140. const String& path = key.path;
  141. auto& documents = svg_cache_data->documents;
  142. auto& handles = svg_cache_data->handles;
  143. const auto it_handle = handles.find(key);
  144. if (it_handle != handles.cend())
  145. {
  146. RMLUI_SVG_DEBUG_LOG("Found handle, reusing: %s, (%d, %d), %s, %#x", path.c_str(), dimensions.x, dimensions.y,
  147. crop_to_content ? "crop_to_content" : "crop_none", *reinterpret_cast<const uint32_t*>(&colour[0]));
  148. SharedPtr<SVGData> result = it_handle->second.lock();
  149. RMLUI_ASSERTMSG(result, "Failed to lock handle in SVG cache");
  150. return result;
  151. }
  152. RMLUI_SVG_DEBUG_LOG("Making new handle: %s, (%d, %d), %s, %#x", path.c_str(), dimensions.x, dimensions.y,
  153. crop_to_content ? "crop_to_content" : "crop_none", *reinterpret_cast<const uint32_t*>(&colour[0]));
  154. // Find or create a document
  155. auto it_svg_document = documents.find(path);
  156. if (it_svg_document == documents.cend())
  157. {
  158. RMLUI_SVG_DEBUG_LOG("Loading SVG document from file %s", path.c_str());
  159. SVGDocument doc;
  160. String svg_data;
  161. if (path.empty() || !GetFileInterface()->LoadFile(path, svg_data))
  162. {
  163. Log::Message(Rml::Log::Type::LT_WARNING, "Could not load SVG file %s", path.c_str());
  164. return {};
  165. }
  166. // We use a reset-release approach here in case clients use a non-std unique_ptr (lunasvg uses std::unique_ptr)
  167. doc.svg_document.reset(lunasvg::Document::loadFromData(svg_data).release());
  168. if (!doc.svg_document)
  169. {
  170. Log::Message(Rml::Log::Type::LT_WARNING, "Could not load SVG data from file %s", path.c_str());
  171. return {};
  172. }
  173. doc.intrinsic_dimensions.x = Math::Max(float(doc.svg_document->width()), 1.0f);
  174. doc.intrinsic_dimensions.y = Math::Max(float(doc.svg_document->height()), 1.0f);
  175. const auto it_inserted = documents.insert_or_assign(path, std::move(doc));
  176. RMLUI_ASSERT(it_inserted.second);
  177. it_svg_document = it_inserted.first;
  178. }
  179. SVGDocument& doc = it_svg_document->second;
  180. Vector2f intrinsic_dimensions = doc.intrinsic_dimensions;
  181. if (crop_to_content)
  182. {
  183. const lunasvg::Box smallest_fit = doc.svg_document->boundingBox();
  184. intrinsic_dimensions.x = static_cast<float>(smallest_fit.w);
  185. intrinsic_dimensions.y = static_cast<float>(smallest_fit.h);
  186. }
  187. // Find or create texture
  188. auto it_size = FindSVGTexture(doc, dimensions, crop_to_content);
  189. if (it_size == doc.textures.cend())
  190. {
  191. RMLUI_SVG_DEBUG_LOG("Creating per-size data for (%d, %d), %s", dimensions.x, dimensions.y,
  192. crop_to_content ? "crop_to_content" : "crop_none");
  193. SVGTexture svg_texture;
  194. svg_texture.render_dimensions = dimensions;
  195. svg_texture.crop_to_content = crop_to_content;
  196. svg_texture.texture = {};
  197. // Callback for generating texture.
  198. auto texture_callback = [svg_document = doc.svg_document.get(), dimensions, crop_to_content](
  199. const CallbackTextureInterface& texture_interface) -> bool {
  200. RMLUI_ASSERT(svg_document);
  201. RMLUI_SVG_DEBUG_LOG("Generating texture: %s, (%d, %d), %s", GetSourceOr(svg_document, "").c_str(), dimensions.x, dimensions.y,
  202. crop_to_content ? "crop_to_content" : "crop_none");
  203. if (dimensions.x == 0 || dimensions.y == 0)
  204. return false;
  205. lunasvg::Bitmap bitmap;
  206. if (crop_to_content)
  207. {
  208. const lunasvg::Box smallest_fit = svg_document->boundingBox();
  209. lunasvg::Matrix matrix(dimensions.x / svg_document->width(), 0, 0, dimensions.y / svg_document->height(), 0, 0);
  210. matrix.scale(svg_document->width() / smallest_fit.w, svg_document->height() / smallest_fit.h);
  211. matrix.translate(-smallest_fit.x, -smallest_fit.y);
  212. bitmap = lunasvg::Bitmap(dimensions.x, dimensions.y);
  213. bitmap.clear(0x00000000);
  214. svg_document->render(bitmap, matrix);
  215. }
  216. else
  217. {
  218. bitmap = svg_document->renderToBitmap(dimensions.x, dimensions.y);
  219. }
  220. if (!bitmap.valid() || !bitmap.data())
  221. {
  222. Log::Message(Rml::Log::Type::LT_WARNING, "Could not render SVG to bitmap: %s", GetSourceOr(svg_document, "").c_str());
  223. return false;
  224. }
  225. // Swap red and blue channels, assuming LunaSVG v2.3.2 or newer, to convert to RmlUi's expected RGBA-ordering.
  226. const size_t bitmap_byte_size = bitmap.width() * bitmap.height() * 4;
  227. uint8_t* bitmap_data = bitmap.data();
  228. for (size_t i = 0; i < bitmap_byte_size; i += 4)
  229. std::swap(bitmap_data[i], bitmap_data[i + 2]);
  230. if (!texture_interface.GenerateTexture({reinterpret_cast<const Rml::byte*>(bitmap.data()), bitmap_byte_size},
  231. Vector2i{bitmap.width(), bitmap.height()}))
  232. {
  233. Log::Message(Rml::Log::Type::LT_WARNING, "Could not generate texture for SVG: %s", GetSourceOr(svg_document, "").c_str());
  234. return false;
  235. }
  236. return true;
  237. };
  238. svg_texture.texture = render_manager.MakeCallbackTexture(std::move(texture_callback));
  239. doc.textures.push_back(std::move(svg_texture));
  240. it_size = std::prev(doc.textures.end());
  241. }
  242. // Construct and insert per-color geometry
  243. SVGTexture& size_data = *it_size;
  244. RMLUI_ASSERTMSG(FindSVGGeometry(size_data, colour) == size_data.geometries.end(),
  245. "We found an existing color entry in the SVG document cache, this should have been found as a cache key map entry instead.");
  246. SVGGeometry colour_data;
  247. colour_data.colour = colour;
  248. Mesh mesh;
  249. MeshUtilities::GenerateQuad(mesh, Vector2f(0), Vector2f(size_data.render_dimensions), colour, Vector2f(0), Vector2f(1));
  250. colour_data.geometry = MakeUnique<Geometry>(render_manager.MakeGeometry(std::move(mesh)));
  251. size_data.geometries.push_back(std::move(colour_data));
  252. // Create and insert the handle
  253. const auto iterator_inserted = handles.emplace(std::move(key), WeakPtr<SVGData>());
  254. RMLUI_ASSERTMSG(iterator_inserted.second, "Could not insert entry into the SVG cache handle map, duplicate key.");
  255. const SVGKey& inserted_key = iterator_inserted.first->first;
  256. WeakPtr<SVGData>& inserted_weak_data_pointer = iterator_inserted.first->second;
  257. auto svg_handle = MakeShared<SVGData>(*size_data.geometries.back().geometry.get(), size_data.texture, intrinsic_dimensions, inserted_key);
  258. inserted_weak_data_pointer = svg_handle;
  259. return svg_handle;
  260. }
  261. static void ReleaseHandle(SVGData* handle)
  262. {
  263. // There are no longer any users of the cache entry uniquely identified by the handle address. Start from the
  264. // tip (i.e. per-color data) and remove that entry from its parent. Move up the cache ancestry and erase any
  265. // entries that no longer have any children.
  266. auto& documents = svg_cache_data->documents;
  267. auto& handles = svg_cache_data->handles;
  268. const SVGKey& key = handle->cache_key;
  269. auto it_handle = handles.find(key);
  270. RMLUI_ASSERT(it_handle != handles.cend());
  271. const auto it_document = documents.find(key.path);
  272. RMLUI_ASSERT(it_document != documents.cend());
  273. SVGDocument& svg_document = it_document->second;
  274. RMLUI_SVG_DEBUG_LOG("Releasing handle: %s, (%d, %d), %s, %#x", key.path.c_str(), key.dimensions.x, key.dimensions.y,
  275. key.crop_to_content ? "crop_to_content" : "crop_none", *reinterpret_cast<const uint32_t*>(&key.colour[0]));
  276. auto it_texture = FindSVGTexture(svg_document, key.dimensions, key.crop_to_content);
  277. RMLUI_ASSERT(it_texture != svg_document.textures.cend());
  278. SVGTexture& svg_texture = *it_texture;
  279. auto it_geometry = FindSVGGeometry(svg_texture, key.colour);
  280. RMLUI_ASSERT(it_geometry != svg_texture.geometries.cend());
  281. if (svg_texture.geometries.size() > 1)
  282. {
  283. RMLUI_SVG_DEBUG_LOG("Releasing handle from geometries, size: %zu", svg_texture.geometries.size());
  284. std::iter_swap(it_geometry, std::prev(svg_texture.geometries.end()));
  285. svg_texture.geometries.pop_back();
  286. }
  287. else if (svg_document.textures.size() > 1)
  288. {
  289. RMLUI_SVG_DEBUG_LOG("Releasing handle from textures, size: %zu", svg_document.textures.size());
  290. std::iter_swap(it_texture, std::prev(svg_document.textures.end()));
  291. svg_document.textures.pop_back();
  292. }
  293. else
  294. {
  295. RMLUI_SVG_DEBUG_LOG("Releasing document");
  296. documents.erase(it_document);
  297. }
  298. handles.erase(it_handle);
  299. #ifdef RMLUI_DEBUG
  300. size_t count_unique_entries = 0;
  301. for (auto& document : documents)
  302. {
  303. RMLUI_ASSERT(!document.second.textures.empty());
  304. for (auto& size_data : document.second.textures)
  305. {
  306. RMLUI_ASSERT(!size_data.geometries.empty());
  307. count_unique_entries += size_data.geometries.size();
  308. }
  309. }
  310. RMLUI_ASSERT(count_unique_entries == handles.size());
  311. #endif
  312. }
  313. void SVGCache::Initialize()
  314. {
  315. svg_cache_data.Initialize();
  316. }
  317. void SVGCache::Shutdown()
  318. {
  319. svg_cache_data.Shutdown();
  320. }
  321. SharedPtr<SVGData> SVGCache::GetHandle(const String& source, Element* element, const bool crop_to_content, const BoxArea area)
  322. {
  323. RenderManager* render_manager = element->GetRenderManager();
  324. if (!render_manager)
  325. return {};
  326. const ComputedValues& computed = element->GetComputedValues();
  327. const ColourbPremultiplied colour = computed.image_color().ToPremultiplied(computed.opacity());
  328. Vector2i dimensions(element->GetBox().GetSize(area).Round());
  329. if (dimensions.x == 0 || dimensions.y == 0)
  330. dimensions = {0, 0};
  331. String path;
  332. if (ElementDocument* document = element->GetOwnerDocument())
  333. {
  334. const String document_source_url = StringUtilities::Replace(document->GetSourceURL(), '|', ':');
  335. GetSystemInterface()->JoinPath(path, document_source_url, source);
  336. }
  337. return Rml::SVG::GetHandle(*render_manager, std::move(path), dimensions, crop_to_content, colour);
  338. }
  339. } // namespace SVG
  340. } // namespace Rml