ElementImage.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 "ElementImage.h"
  29. #include "../../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../../Include/RmlUi/Core/ElementDocument.h"
  31. #include "../../../Include/RmlUi/Core/ElementUtilities.h"
  32. #include "../../../Include/RmlUi/Core/GeometryUtilities.h"
  33. #include "../../../Include/RmlUi/Core/PropertyIdSet.h"
  34. #include "../../../Include/RmlUi/Core/StyleSheet.h"
  35. #include "../../../Include/RmlUi/Core/URL.h"
  36. #include "../TextureDatabase.h"
  37. namespace Rml {
  38. // Constructs a new ElementImage.
  39. ElementImage::ElementImage(const String& tag) : Element(tag), dimensions(-1, -1), rect_source(RectSource::None), geometry(this)
  40. {
  41. dimensions_scale = 1.0f;
  42. geometry_dirty = false;
  43. texture_dirty = true;
  44. }
  45. ElementImage::~ElementImage()
  46. {
  47. }
  48. // Sizes the box to the element's inherent size.
  49. bool ElementImage::GetIntrinsicDimensions(Vector2f& _dimensions, float& _ratio)
  50. {
  51. // Check if we need to reload the texture.
  52. if (texture_dirty)
  53. LoadTexture();
  54. // Calculate the x dimension.
  55. if (HasAttribute("width"))
  56. dimensions.x = GetAttribute<float>("width", -1);
  57. else if (rect_source == RectSource::None)
  58. dimensions.x = (float)texture.GetDimensions(GetRenderInterface()).x;
  59. else
  60. dimensions.x = rect.Width();
  61. // Calculate the y dimension.
  62. if (HasAttribute("height"))
  63. dimensions.y = GetAttribute< float >("height", -1);
  64. else if (rect_source == RectSource::None)
  65. dimensions.y = (float)texture.GetDimensions(GetRenderInterface()).y;
  66. else
  67. dimensions.y = rect.Height();
  68. dimensions *= dimensions_scale;
  69. // Return the calculated dimensions. If this changes the size of the element, it will result in
  70. // a call to 'onresize' below which will regenerate the geometry.
  71. _dimensions = dimensions;
  72. _ratio = dimensions.x / dimensions.y;
  73. return true;
  74. }
  75. // Renders the element.
  76. void ElementImage::OnRender()
  77. {
  78. // Regenerate the geometry if required (this will be set if 'rect' changes but does not result in a resize).
  79. if (geometry_dirty)
  80. GenerateGeometry();
  81. // Render the geometry beginning at this element's content region.
  82. geometry.Render(GetAbsoluteOffset(Box::CONTENT));
  83. }
  84. // Called when attributes on the element are changed.
  85. void ElementImage::OnAttributeChange(const ElementAttributes& changed_attributes)
  86. {
  87. // Call through to the base element's OnAttributeChange().
  88. Element::OnAttributeChange(changed_attributes);
  89. bool dirty_layout = false;
  90. // Check for a changed 'src' attribute. If this changes, the old texture handle is released,
  91. // forcing a reload when the layout is regenerated.
  92. if (changed_attributes.find("src") != changed_attributes.end() ||
  93. changed_attributes.find("sprite") != changed_attributes.end())
  94. {
  95. texture_dirty = true;
  96. dirty_layout = true;
  97. }
  98. // Check for a changed 'width' attribute. If this changes, a layout is forced which will
  99. // recalculate the dimensions.
  100. if (changed_attributes.find("width") != changed_attributes.end() ||
  101. changed_attributes.find("height") != changed_attributes.end())
  102. {
  103. dirty_layout = true;
  104. }
  105. // Check for a change to the 'rect' attribute. If this changes, the coordinates are
  106. // recomputed and a layout forced. If a sprite is set to source, then that will override any attribute.
  107. if (changed_attributes.find("rect") != changed_attributes.end())
  108. {
  109. UpdateRect();
  110. // Rectangle has changed; this will most likely result in a size change, so we need to force a layout.
  111. dirty_layout = true;
  112. }
  113. if (dirty_layout)
  114. DirtyLayout();
  115. }
  116. void ElementImage::OnPropertyChange(const PropertyIdSet& changed_properties)
  117. {
  118. Element::OnPropertyChange(changed_properties);
  119. if (changed_properties.Contains(PropertyId::ImageColor) ||
  120. changed_properties.Contains(PropertyId::Opacity)) {
  121. GenerateGeometry();
  122. }
  123. }
  124. void ElementImage::OnChildAdd(Element* child)
  125. {
  126. // Load the texture once we have attached to the document so that it can immediately be found during the call to `Rml::GetTextureSourceList`. The
  127. // texture won't actually be loaded from the backend before it is shown. However, only do this if we have an active context so that the dp-ratio
  128. // can be retrieved. If there is no context now the texture loading will be deferred until the next layout update.
  129. if (child == this && texture_dirty && GetContext())
  130. {
  131. LoadTexture();
  132. }
  133. }
  134. // Regenerates the element's geometry.
  135. void ElementImage::OnResize()
  136. {
  137. GenerateGeometry();
  138. }
  139. void ElementImage::OnDpRatioChange()
  140. {
  141. texture_dirty = true;
  142. DirtyLayout();
  143. }
  144. void ElementImage::OnStyleSheetChange()
  145. {
  146. if (HasAttribute("sprite"))
  147. {
  148. texture_dirty = true;
  149. DirtyLayout();
  150. }
  151. }
  152. void ElementImage::GenerateGeometry()
  153. {
  154. // Release the old geometry before specifying the new vertices.
  155. geometry.Release(true);
  156. Vector< Vertex >& vertices = geometry.GetVertices();
  157. Vector< int >& indices = geometry.GetIndices();
  158. vertices.resize(4);
  159. indices.resize(6);
  160. // Generate the texture coordinates.
  161. Vector2f texcoords[2];
  162. if (rect_source != RectSource::None)
  163. {
  164. Vector2f texture_dimensions = Vector2f(Math::Max(texture.GetDimensions(GetRenderInterface()), Vector2i(1)));
  165. texcoords[0] = rect.TopLeft() / texture_dimensions;
  166. texcoords[1] = rect.BottomRight() / texture_dimensions;
  167. }
  168. else
  169. {
  170. texcoords[0] = Vector2f(0, 0);
  171. texcoords[1] = Vector2f(1, 1);
  172. }
  173. const ComputedValues& computed = GetComputedValues();
  174. float opacity = computed.opacity();
  175. Colourb quad_colour = computed.image_color();
  176. quad_colour.alpha = (byte)(opacity * (float)quad_colour.alpha);
  177. Vector2f quad_size = GetBox().GetSize(Box::CONTENT).Round();
  178. GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Vector2f(0, 0), quad_size, quad_colour, texcoords[0], texcoords[1]);
  179. geometry_dirty = false;
  180. }
  181. bool ElementImage::LoadTexture()
  182. {
  183. texture_dirty = false;
  184. geometry_dirty = true;
  185. dimensions_scale = 1.0f;
  186. const float dp_ratio = ElementUtilities::GetDensityIndependentPixelRatio(this);
  187. // Check for a sprite first, this takes precedence.
  188. const String sprite_name = GetAttribute< String >("sprite", "");
  189. if (!sprite_name.empty())
  190. {
  191. // Load sprite.
  192. bool valid_sprite = false;
  193. if (ElementDocument* document = GetOwnerDocument())
  194. {
  195. if (const StyleSheet* style_sheet = document->GetStyleSheet())
  196. {
  197. if (const Sprite* sprite = style_sheet->GetSprite(sprite_name))
  198. {
  199. rect = sprite->rectangle;
  200. rect_source = RectSource::Sprite;
  201. texture = sprite->sprite_sheet->texture;
  202. dimensions_scale = sprite->sprite_sheet->display_scale * dp_ratio;
  203. valid_sprite = true;
  204. }
  205. }
  206. }
  207. if (!valid_sprite)
  208. {
  209. texture = Texture();
  210. rect_source = RectSource::None;
  211. UpdateRect();
  212. Log::Message(Log::LT_WARNING, "Could not find sprite '%s' specified in img element %s", sprite_name.c_str(), GetAddress().c_str());
  213. return false;
  214. }
  215. }
  216. else
  217. {
  218. // Load image from source URL.
  219. const String source_name = GetAttribute< String >("src", "");
  220. if (source_name.empty())
  221. {
  222. texture = Texture();
  223. rect_source = RectSource::None;
  224. return false;
  225. }
  226. URL source_url;
  227. if (ElementDocument* document = GetOwnerDocument())
  228. source_url.SetURL(document->GetSourceURL());
  229. texture.Set(source_name, source_url.GetPath());
  230. dimensions_scale = dp_ratio;
  231. }
  232. // Set the texture onto our geometry object.
  233. geometry.SetTexture(&texture);
  234. return true;
  235. }
  236. void ElementImage::UpdateRect()
  237. {
  238. if(rect_source != RectSource::Sprite)
  239. {
  240. bool valid_rect = false;
  241. String rect_string = GetAttribute< String >("rect", "");
  242. if (!rect_string.empty())
  243. {
  244. StringList coords_list;
  245. StringUtilities::ExpandString(coords_list, rect_string, ' ');
  246. if (coords_list.size() != 4)
  247. {
  248. Log::Message(Log::LT_WARNING, "Element '%s' has an invalid 'rect' attribute; rect requires 4 space-separated values, found %zu.", GetAddress().c_str(), coords_list.size());
  249. }
  250. else
  251. {
  252. const Vector2f position = {FromString(coords_list[0], 0.f), FromString(coords_list[1], 0.f)};
  253. const Vector2f size = {FromString(coords_list[2], 0.f), FromString(coords_list[3], 0.f)};
  254. rect = Rectanglef::FromPositionSize(position, size);
  255. // We have new, valid coordinates; force the geometry to be regenerated.
  256. valid_rect = true;
  257. geometry_dirty = true;
  258. rect_source = RectSource::Attribute;
  259. }
  260. }
  261. if (!valid_rect)
  262. {
  263. rect = {};
  264. rect_source = RectSource::None;
  265. }
  266. }
  267. }
  268. } // namespace Rml