DecoratorNinePatch.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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-2023 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 "DecoratorNinePatch.h"
  29. #include "../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../Include/RmlUi/Core/Element.h"
  31. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  32. #include "../../Include/RmlUi/Core/Geometry.h"
  33. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  34. namespace Rml {
  35. DecoratorNinePatch::DecoratorNinePatch() {}
  36. DecoratorNinePatch::~DecoratorNinePatch() {}
  37. bool DecoratorNinePatch::Initialise(const Rectanglef& _rect_outer, const Rectanglef& _rect_inner, const Array<NumericValue, 4>* _edges,
  38. Texture _texture, float _display_scale)
  39. {
  40. rect_outer = _rect_outer;
  41. rect_inner = _rect_inner;
  42. display_scale = _display_scale;
  43. if (_edges)
  44. edges = MakeUnique<Array<NumericValue, 4>>(*_edges);
  45. int texture_index = AddTexture(_texture);
  46. return (texture_index >= 0);
  47. }
  48. DecoratorDataHandle DecoratorNinePatch::GenerateElementData(Element* element, BoxArea paint_area) const
  49. {
  50. const auto& computed = element->GetComputedValues();
  51. Texture texture = GetTexture();
  52. const Vector2f texture_dimensions(texture.GetDimensions());
  53. const RenderBox render_box = element->GetRenderBox(paint_area);
  54. const Vector2f surface_offset = render_box.GetFillOffset();
  55. const Vector2f surface_dimensions = render_box.GetFillSize();
  56. const ColourbPremultiplied quad_colour = computed.image_color().ToPremultiplied(computed.opacity());
  57. /* In the following, we operate on the four diagonal vertices in the grid, as they define the whole grid. */
  58. // Absolute texture coordinates 'px'
  59. Vector2f tex_pos[4] = {
  60. rect_outer.TopLeft(),
  61. rect_inner.TopLeft(),
  62. rect_inner.BottomRight(),
  63. rect_outer.BottomRight(),
  64. };
  65. // Normalized texture coordinates [0, 1]
  66. Vector2f tex_coords[4];
  67. for (int i = 0; i < 4; i++)
  68. tex_coords[i] = tex_pos[i] / texture_dimensions;
  69. // Natural size is determined from the raw pixel size multiplied by the dp-ratio and the sprite's
  70. // display scale (determined by eg. the inverse of spritesheet's 'src-scale').
  71. const float scale_raw_to_natural_dimensions = ElementUtilities::GetDensityIndependentPixelRatio(element) * display_scale;
  72. // Surface position in pixels [0, surface_dimensions]
  73. // Need to keep the corner patches at their natural size, but stretch the inner patches.
  74. Vector2f surface_pos[4];
  75. surface_pos[0] = {0, 0};
  76. surface_pos[1] = (tex_pos[1] - tex_pos[0]) * scale_raw_to_natural_dimensions;
  77. surface_pos[2] = surface_dimensions - (tex_pos[3] - tex_pos[2]) * scale_raw_to_natural_dimensions;
  78. surface_pos[3] = surface_dimensions;
  79. // Change the size of the edges if specified.
  80. if (edges)
  81. {
  82. float lengths[4]; // top, right, bottom, left
  83. lengths[0] = element->ResolveNumericValue((*edges)[0], (surface_pos[1].y - surface_pos[0].y));
  84. lengths[1] = element->ResolveNumericValue((*edges)[1], (surface_pos[3].x - surface_pos[2].x));
  85. lengths[2] = element->ResolveNumericValue((*edges)[2], (surface_pos[3].y - surface_pos[2].y));
  86. lengths[3] = element->ResolveNumericValue((*edges)[3], (surface_pos[1].x - surface_pos[0].x));
  87. surface_pos[1].y = lengths[0];
  88. surface_pos[2].x = surface_dimensions.x - lengths[1];
  89. surface_pos[2].y = surface_dimensions.y - lengths[2];
  90. surface_pos[1].x = lengths[3];
  91. }
  92. // In case the surface dimensions are less than the size of the corners, we need to scale down the corner rectangles, one dimension at a time.
  93. const Vector2f surface_center_size = surface_pos[2] - surface_pos[1];
  94. for (int i = 0; i < 2; i++)
  95. {
  96. if (surface_center_size[i] < 0.0f)
  97. {
  98. float top_left_size = tex_pos[1][i] - tex_pos[0][i];
  99. float bottom_right_size = tex_pos[3][i] - tex_pos[2][i];
  100. surface_pos[1][i] = top_left_size / (top_left_size + bottom_right_size) * surface_dimensions[i];
  101. surface_pos[2][i] = surface_pos[1][i];
  102. }
  103. }
  104. // Now offset all positions, relative to the border box.
  105. for (Vector2f& surface_pos_entry : surface_pos)
  106. surface_pos_entry += surface_offset;
  107. // Round the inner corners
  108. surface_pos[1] = surface_pos[1].Round();
  109. surface_pos[2] = surface_pos[2].Round();
  110. /* Now we have all the coordinates we need. Expand the diagonal vertices to the 16 individual vertices. */
  111. Mesh mesh;
  112. Vector<Vertex>& vertices = mesh.vertices;
  113. Vector<int>& indices = mesh.indices;
  114. vertices.resize(4 * 4);
  115. for (int y = 0; y < 4; y++)
  116. {
  117. for (int x = 0; x < 4; x++)
  118. {
  119. Vertex& vertex = vertices[y * 4 + x];
  120. vertex.colour = quad_colour;
  121. vertex.position = {surface_pos[x].x, surface_pos[y].y};
  122. vertex.tex_coord = {tex_coords[x].x, tex_coords[y].y};
  123. }
  124. }
  125. // Nine rectangles, two triangles per rectangle, three indices per triangle.
  126. indices.resize(9 * 2 * 3);
  127. // Fill in the indices one rectangle at a time.
  128. const int top_left_indices[9] = {0, 1, 2, 4, 5, 6, 8, 9, 10};
  129. for (int rectangle = 0; rectangle < 9; rectangle++)
  130. {
  131. int i = rectangle * 6;
  132. int top_left_index = top_left_indices[rectangle];
  133. indices[i] = top_left_index;
  134. indices[i + 1] = top_left_index + 4;
  135. indices[i + 2] = top_left_index + 1;
  136. indices[i + 3] = top_left_index + 1;
  137. indices[i + 4] = top_left_index + 4;
  138. indices[i + 5] = top_left_index + 5;
  139. }
  140. Geometry* data = new Geometry(element->GetRenderManager()->MakeGeometry(std::move(mesh)));
  141. return reinterpret_cast<DecoratorDataHandle>(data);
  142. }
  143. void DecoratorNinePatch::ReleaseElementData(DecoratorDataHandle element_data) const
  144. {
  145. delete reinterpret_cast<Geometry*>(element_data);
  146. }
  147. void DecoratorNinePatch::RenderElement(Element* element, DecoratorDataHandle element_data) const
  148. {
  149. Geometry* data = reinterpret_cast<Geometry*>(element_data);
  150. data->Render(element->GetAbsoluteOffset(BoxArea::Border), GetTexture());
  151. }
  152. DecoratorNinePatchInstancer::DecoratorNinePatchInstancer()
  153. {
  154. sprite_outer_id = RegisterProperty("outer", "").AddParser("string").GetId();
  155. sprite_inner_id = RegisterProperty("inner", "").AddParser("string").GetId();
  156. edge_ids[0] = RegisterProperty("edge-top", "0px").AddParser("number_length_percent").GetId();
  157. edge_ids[1] = RegisterProperty("edge-right", "0px").AddParser("number_length_percent").GetId();
  158. edge_ids[2] = RegisterProperty("edge-bottom", "0px").AddParser("number_length_percent").GetId();
  159. edge_ids[3] = RegisterProperty("edge-left", "0px").AddParser("number_length_percent").GetId();
  160. RegisterShorthand("edge", "edge-top, edge-right, edge-bottom, edge-left", ShorthandType::Box);
  161. RMLUI_ASSERT(sprite_outer_id != PropertyId::Invalid && sprite_inner_id != PropertyId::Invalid);
  162. RegisterShorthand("decorator", "outer, inner, edge?", ShorthandType::RecursiveCommaSeparated);
  163. }
  164. DecoratorNinePatchInstancer::~DecoratorNinePatchInstancer() {}
  165. SharedPtr<Decorator> DecoratorNinePatchInstancer::InstanceDecorator(const String& /*name*/, const PropertyDictionary& properties,
  166. const DecoratorInstancerInterface& instancer_interface)
  167. {
  168. bool edges_set = false;
  169. Array<NumericValue, 4> edges;
  170. for (int i = 0; i < 4; i++)
  171. {
  172. edges[i] = properties.GetProperty(edge_ids[i])->GetNumericValue();
  173. if (edges[i].number != 0.0f)
  174. {
  175. edges_set = true;
  176. }
  177. }
  178. const Sprite* sprite_outer = nullptr;
  179. const Sprite* sprite_inner = nullptr;
  180. {
  181. const String sprite_name = properties.GetProperty(sprite_outer_id)->Get<String>();
  182. sprite_outer = instancer_interface.GetSprite(sprite_name);
  183. if (!sprite_outer)
  184. {
  185. Log::Message(Log::LT_WARNING, "Could not find sprite named '%s' in ninepatch decorator.", sprite_name.c_str());
  186. return nullptr;
  187. }
  188. }
  189. {
  190. const String sprite_name = properties.GetProperty(sprite_inner_id)->Get<String>();
  191. sprite_inner = instancer_interface.GetSprite(sprite_name);
  192. if (!sprite_inner)
  193. {
  194. Log::Message(Log::LT_WARNING, "Could not find sprite named '%s' in ninepatch decorator.", sprite_name.c_str());
  195. return nullptr;
  196. }
  197. }
  198. if (sprite_outer->sprite_sheet != sprite_inner->sprite_sheet)
  199. {
  200. Log::Message(Log::LT_WARNING, "The outer and inner sprites in a ninepatch decorator must be from the same sprite sheet.");
  201. return nullptr;
  202. }
  203. auto decorator = MakeShared<DecoratorNinePatch>();
  204. if (!decorator->Initialise(sprite_outer->rectangle, sprite_inner->rectangle, (edges_set ? &edges : nullptr),
  205. sprite_outer->sprite_sheet->texture_source.GetTexture(instancer_interface.GetRenderManager()), sprite_outer->sprite_sheet->display_scale))
  206. {
  207. return nullptr;
  208. }
  209. return decorator;
  210. }
  211. } // namespace Rml