SVGCache.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 source_id;
  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.source_id == rhs.source_id && lhs.dimensions == rhs.dimensions && lhs.crop_to_content == rhs.crop_to_content &&
  59. lhs.colour == rhs.colour;
  60. }
  61. };
  62. } // namespace SVG
  63. } // namespace Rml
  64. namespace std {
  65. template <>
  66. struct hash<::Rml::SVG::SVGKey> {
  67. size_t operator()(const ::Rml::SVG::SVGKey& key) const noexcept
  68. {
  69. size_t hash = 0;
  70. Rml::Utilities::HashCombine(hash, key.source_id);
  71. Rml::Utilities::HashCombine(hash, key.dimensions.x);
  72. Rml::Utilities::HashCombine(hash, key.dimensions.y);
  73. Rml::Utilities::HashCombine(hash, key.crop_to_content);
  74. static_assert(sizeof(uint32_t) == sizeof(key.colour), "Expecting color to be 4 bytes");
  75. Rml::Utilities::HashCombine(hash, *reinterpret_cast<const uint32_t*>(&key.colour[0]));
  76. return hash;
  77. }
  78. };
  79. } // namespace std
  80. namespace Rml {
  81. namespace SVG {
  82. static SharedPtr<SVGData> GetHandle(RenderManager& render_manager, String source_id, const String& source, SVGCache::SourceType source_type,
  83. Vector2i dimensions, bool crop_to_content, ColourbPremultiplied colour);
  84. static void ReleaseHandle(SVGData* handle);
  85. struct SVGGeometry {
  86. ColourbPremultiplied colour;
  87. UniquePtr<Geometry> geometry;
  88. };
  89. struct SVGTexture {
  90. Vector2i render_dimensions;
  91. bool crop_to_content;
  92. CallbackTexture texture;
  93. // List of geometries using this texture, one entry for each unique color.
  94. Vector<SVGGeometry> geometries;
  95. };
  96. struct SVGDocument {
  97. Vector2f intrinsic_dimensions;
  98. UniquePtr<lunasvg::Document> svg_document;
  99. // List of textures using this document, one entry for each unique render dimension plus meta-data.
  100. Vector<SVGTexture> textures;
  101. };
  102. struct SVGCacheData {
  103. // A list of SVG documents mapped by their path. Owns all geometry and textures needed for rendering.
  104. UnorderedMap<String, SVGDocument> documents;
  105. // Handles are reference-counted lookup keys and views into the SVG document resources. Handles are responsible
  106. // for cleaning up the resources in the documents, when nothing refers to them any longer. When a handle is
  107. // destroyed, it also removes itself from the handle map.
  108. StableUnorderedMap<SVGKey, WeakPtr<SVGData>> handles;
  109. };
  110. static ControlledLifetimeResource<SVGCacheData> svg_cache_data;
  111. SVGData::SVGData(Geometry& geometry, Texture texture, Vector2f intrinsic_dimensions, const SVGKey& cache_key) :
  112. geometry(geometry), texture(texture), intrinsic_dimensions(intrinsic_dimensions), cache_key(cache_key)
  113. {}
  114. SVGData::~SVGData()
  115. {
  116. ReleaseHandle(this);
  117. }
  118. static Vector<SVGTexture>::iterator FindSVGTexture(SVGDocument& doc, Vector2i dimensions, bool crop_to_content)
  119. {
  120. return std::find_if(doc.textures.begin(), doc.textures.end(),
  121. [&](const auto& entry) { return entry.render_dimensions == dimensions && entry.crop_to_content == crop_to_content; });
  122. }
  123. static Vector<SVGGeometry>::iterator FindSVGGeometry(SVGTexture& per_size_data, const ColourbPremultiplied colour)
  124. {
  125. return std::find_if(per_size_data.geometries.begin(), per_size_data.geometries.end(),
  126. [&](const SVGGeometry& data) { return data.colour == colour; });
  127. }
  128. static const String& GetSourceOr(const lunasvg::Document* svg_document, const String& default_value)
  129. {
  130. const auto& documents = svg_cache_data->documents;
  131. auto it = std::find_if(documents.begin(), documents.end(),
  132. [svg_document](const auto& pair) { return pair.second.svg_document.get() == svg_document; });
  133. if (it != documents.end())
  134. return it->first;
  135. return default_value;
  136. }
  137. static SharedPtr<SVGData> GetHandle(RenderManager& render_manager, String move_from_id, const String& source, SVGCache::SourceType source_type,
  138. const Vector2i dimensions, const bool crop_to_content, const ColourbPremultiplied colour)
  139. {
  140. SVGKey key{std::move(move_from_id), dimensions, crop_to_content, colour};
  141. const String& source_id = key.source_id;
  142. auto& documents = svg_cache_data->documents;
  143. auto& handles = svg_cache_data->handles;
  144. const auto it_handle = handles.find(key);
  145. if (it_handle != handles.cend())
  146. {
  147. RMLUI_SVG_DEBUG_LOG("Found handle, reusing: %s, (%d, %d), %s, %#x", source_id.c_str(), dimensions.x, dimensions.y,
  148. crop_to_content ? "crop_to_content" : "crop_none", *reinterpret_cast<const uint32_t*>(&colour[0]));
  149. SharedPtr<SVGData> result = it_handle->second.lock();
  150. RMLUI_ASSERTMSG(result, "Failed to lock handle in SVG cache");
  151. return result;
  152. }
  153. RMLUI_SVG_DEBUG_LOG("Making new handle: %s, (%d, %d), %s, %#x", source_id.c_str(), dimensions.x, dimensions.y,
  154. crop_to_content ? "crop_to_content" : "crop_none", *reinterpret_cast<const uint32_t*>(&colour[0]));
  155. // Find or create a document
  156. auto it_svg_document = documents.find(source_id);
  157. if (it_svg_document == documents.cend())
  158. {
  159. SVGDocument doc;
  160. if (source_type == SVGCache::SourceType::File)
  161. {
  162. RMLUI_SVG_DEBUG_LOG("Loading SVG document from file %s", source.c_str());
  163. String svg_data;
  164. if (source.empty() || !GetFileInterface()->LoadFile(source, svg_data))
  165. {
  166. Log::Message(Rml::Log::Type::LT_WARNING, "Could not load SVG file %s", source.c_str());
  167. return {};
  168. }
  169. // We use a reset-release approach here in case clients use a non-std unique_ptr (lunasvg uses std::unique_ptr)
  170. doc.svg_document.reset(lunasvg::Document::loadFromData(svg_data).release());
  171. }
  172. else
  173. {
  174. RMLUI_SVG_DEBUG_LOG("Loading SVG document from element %s contents", source_id.c_str());
  175. // We use a reset-release approach here in case clients use a non-std unique_ptr (lunasvg uses std::unique_ptr)
  176. doc.svg_document.reset(lunasvg::Document::loadFromData(source).release());
  177. }
  178. if (!doc.svg_document)
  179. {
  180. Log::Message(Rml::Log::Type::LT_WARNING, "Could not load SVG data for item %s", source_id.c_str());
  181. return {};
  182. }
  183. doc.intrinsic_dimensions.x = Math::Max(float(doc.svg_document->width()), 1.0f);
  184. doc.intrinsic_dimensions.y = Math::Max(float(doc.svg_document->height()), 1.0f);
  185. const auto it_inserted = documents.insert_or_assign(source_id, std::move(doc));
  186. RMLUI_ASSERT(it_inserted.second);
  187. it_svg_document = it_inserted.first;
  188. }
  189. SVGDocument& doc = it_svg_document->second;
  190. Vector2f intrinsic_dimensions = doc.intrinsic_dimensions;
  191. if (crop_to_content)
  192. {
  193. const lunasvg::Box smallest_fit = doc.svg_document->boundingBox();
  194. intrinsic_dimensions.x = static_cast<float>(smallest_fit.w);
  195. intrinsic_dimensions.y = static_cast<float>(smallest_fit.h);
  196. }
  197. // Find or create texture
  198. auto it_size = FindSVGTexture(doc, dimensions, crop_to_content);
  199. if (it_size == doc.textures.cend())
  200. {
  201. RMLUI_SVG_DEBUG_LOG("Creating per-size data for (%d, %d), %s", dimensions.x, dimensions.y,
  202. crop_to_content ? "crop_to_content" : "crop_none");
  203. SVGTexture svg_texture;
  204. svg_texture.render_dimensions = dimensions;
  205. svg_texture.crop_to_content = crop_to_content;
  206. svg_texture.texture = {};
  207. // Callback for generating texture.
  208. auto texture_callback = [svg_document = doc.svg_document.get(), dimensions, crop_to_content](
  209. const CallbackTextureInterface& texture_interface) -> bool {
  210. RMLUI_ASSERT(svg_document);
  211. RMLUI_SVG_DEBUG_LOG("Generating texture: %s, (%d, %d), %s", GetSourceOr(svg_document, "").c_str(), dimensions.x, dimensions.y,
  212. crop_to_content ? "crop_to_content" : "crop_none");
  213. if (dimensions.x == 0 || dimensions.y == 0)
  214. return false;
  215. lunasvg::Bitmap bitmap;
  216. if (crop_to_content)
  217. {
  218. const lunasvg::Box smallest_fit = svg_document->boundingBox();
  219. lunasvg::Matrix matrix(dimensions.x / svg_document->width(), 0, 0, dimensions.y / svg_document->height(), 0, 0);
  220. matrix.scale(svg_document->width() / smallest_fit.w, svg_document->height() / smallest_fit.h);
  221. matrix.translate(-smallest_fit.x, -smallest_fit.y);
  222. bitmap = lunasvg::Bitmap(dimensions.x, dimensions.y);
  223. bitmap.clear(0x00000000);
  224. svg_document->render(bitmap, matrix);
  225. }
  226. else
  227. {
  228. bitmap = svg_document->renderToBitmap(dimensions.x, dimensions.y);
  229. }
  230. if (!bitmap.valid() || !bitmap.data())
  231. {
  232. Log::Message(Rml::Log::Type::LT_WARNING, "Could not render SVG to bitmap: %s", GetSourceOr(svg_document, "").c_str());
  233. return false;
  234. }
  235. // Swap red and blue channels, assuming LunaSVG v2.3.2 or newer, to convert to RmlUi's expected RGBA-ordering.
  236. const size_t bitmap_byte_size = bitmap.width() * bitmap.height() * 4;
  237. uint8_t* bitmap_data = bitmap.data();
  238. for (size_t i = 0; i < bitmap_byte_size; i += 4)
  239. std::swap(bitmap_data[i], bitmap_data[i + 2]);
  240. if (!texture_interface.GenerateTexture({reinterpret_cast<const Rml::byte*>(bitmap.data()), bitmap_byte_size},
  241. Vector2i{bitmap.width(), bitmap.height()}))
  242. {
  243. Log::Message(Rml::Log::Type::LT_WARNING, "Could not generate texture for SVG: %s", GetSourceOr(svg_document, "").c_str());
  244. return false;
  245. }
  246. return true;
  247. };
  248. svg_texture.texture = render_manager.MakeCallbackTexture(std::move(texture_callback));
  249. doc.textures.push_back(std::move(svg_texture));
  250. it_size = std::prev(doc.textures.end());
  251. }
  252. // Construct and insert per-color geometry
  253. SVGTexture& size_data = *it_size;
  254. RMLUI_ASSERTMSG(FindSVGGeometry(size_data, colour) == size_data.geometries.end(),
  255. "We found an existing color entry in the SVG document cache, this should have been found as a cache key map entry instead.");
  256. SVGGeometry colour_data;
  257. colour_data.colour = colour;
  258. Mesh mesh;
  259. MeshUtilities::GenerateQuad(mesh, Vector2f(0), Vector2f(size_data.render_dimensions), colour, Vector2f(0), Vector2f(1));
  260. colour_data.geometry = MakeUnique<Geometry>(render_manager.MakeGeometry(std::move(mesh)));
  261. size_data.geometries.push_back(std::move(colour_data));
  262. // Create and insert the handle
  263. const auto iterator_inserted = handles.emplace(std::move(key), WeakPtr<SVGData>());
  264. RMLUI_ASSERTMSG(iterator_inserted.second, "Could not insert entry into the SVG cache handle map, duplicate key.");
  265. const SVGKey& inserted_key = iterator_inserted.first->first;
  266. WeakPtr<SVGData>& inserted_weak_data_pointer = iterator_inserted.first->second;
  267. auto svg_handle = MakeShared<SVGData>(*size_data.geometries.back().geometry.get(), size_data.texture, intrinsic_dimensions, inserted_key);
  268. inserted_weak_data_pointer = svg_handle;
  269. return svg_handle;
  270. }
  271. static void ReleaseHandle(SVGData* handle)
  272. {
  273. // There are no longer any users of the cache entry uniquely identified by the handle address. Start from the
  274. // tip (i.e. per-color data) and remove that entry from its parent. Move up the cache ancestry and erase any
  275. // entries that no longer have any children.
  276. auto& documents = svg_cache_data->documents;
  277. auto& handles = svg_cache_data->handles;
  278. const SVGKey& key = handle->cache_key;
  279. auto it_handle = handles.find(key);
  280. RMLUI_ASSERT(it_handle != handles.cend());
  281. const auto it_document = documents.find(key.source_id);
  282. RMLUI_ASSERT(it_document != documents.cend());
  283. SVGDocument& svg_document = it_document->second;
  284. RMLUI_SVG_DEBUG_LOG("Releasing handle: %s, (%d, %d), %s, %#x", key.path.c_str(), key.dimensions.x, key.dimensions.y,
  285. key.crop_to_content ? "crop_to_content" : "crop_none", *reinterpret_cast<const uint32_t*>(&key.colour[0]));
  286. auto it_texture = FindSVGTexture(svg_document, key.dimensions, key.crop_to_content);
  287. RMLUI_ASSERT(it_texture != svg_document.textures.cend());
  288. SVGTexture& svg_texture = *it_texture;
  289. auto it_geometry = FindSVGGeometry(svg_texture, key.colour);
  290. RMLUI_ASSERT(it_geometry != svg_texture.geometries.cend());
  291. if (svg_texture.geometries.size() > 1)
  292. {
  293. RMLUI_SVG_DEBUG_LOG("Releasing handle from geometries, size: %zu", svg_texture.geometries.size());
  294. std::iter_swap(it_geometry, std::prev(svg_texture.geometries.end()));
  295. svg_texture.geometries.pop_back();
  296. }
  297. else if (svg_document.textures.size() > 1)
  298. {
  299. RMLUI_SVG_DEBUG_LOG("Releasing handle from textures, size: %zu", svg_document.textures.size());
  300. std::iter_swap(it_texture, std::prev(svg_document.textures.end()));
  301. svg_document.textures.pop_back();
  302. }
  303. else
  304. {
  305. RMLUI_SVG_DEBUG_LOG("Releasing document");
  306. documents.erase(it_document);
  307. }
  308. handles.erase(it_handle);
  309. #ifdef RMLUI_DEBUG
  310. size_t count_unique_entries = 0;
  311. for (auto& document : documents)
  312. {
  313. RMLUI_ASSERT(!document.second.textures.empty());
  314. for (auto& size_data : document.second.textures)
  315. {
  316. RMLUI_ASSERT(!size_data.geometries.empty());
  317. count_unique_entries += size_data.geometries.size();
  318. }
  319. }
  320. RMLUI_ASSERT(count_unique_entries == handles.size());
  321. #endif
  322. }
  323. void SVGCache::Initialize()
  324. {
  325. svg_cache_data.Initialize();
  326. }
  327. void SVGCache::Shutdown()
  328. {
  329. svg_cache_data.Shutdown();
  330. }
  331. SharedPtr<SVGData> SVGCache::GetHandle(const String& source_id, const String& source, SourceType source_type, Element* element,
  332. const bool crop_to_content, const BoxArea area)
  333. {
  334. RenderManager* render_manager = element->GetRenderManager();
  335. if (!render_manager)
  336. return {};
  337. const ComputedValues& computed = element->GetComputedValues();
  338. const ColourbPremultiplied colour = computed.image_color().ToPremultiplied(computed.opacity());
  339. Vector2i dimensions(element->GetBox().GetSize(area).Round());
  340. if (dimensions.x == 0 || dimensions.y == 0)
  341. dimensions = {0, 0};
  342. if (source_type == File)
  343. {
  344. String path;
  345. if (ElementDocument* document = element->GetOwnerDocument())
  346. {
  347. const String document_source_url = StringUtilities::Replace(document->GetSourceURL(), '|', ':');
  348. GetSystemInterface()->JoinPath(path, document_source_url, source_id);
  349. }
  350. return Rml::SVG::GetHandle(*render_manager, path, path, source_type, dimensions, crop_to_content, colour);
  351. }
  352. return Rml::SVG::GetHandle(*render_manager, source_id, source, source_type, dimensions, crop_to_content, colour);
  353. }
  354. } // namespace SVG
  355. } // namespace Rml