DecoratorTiled.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 "DecoratorTiled.h"
  29. #include "../../Include/RmlUi/Core/Element.h"
  30. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  31. #include "../../Include/RmlUi/Core/GeometryUtilities.h"
  32. #include "../../Include/RmlUi/Core/Math.h"
  33. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  34. #include "../../Include/RmlUi/Core/Spritesheet.h"
  35. #include <algorithm>
  36. namespace Rml {
  37. DecoratorTiled::DecoratorTiled() {}
  38. DecoratorTiled::~DecoratorTiled() {}
  39. static const Vector2f oriented_texcoords[4][2] = {
  40. {Vector2f(0, 0), Vector2f(1, 1)}, // ORIENTATION_NONE
  41. {Vector2f(1, 0), Vector2f(0, 1)}, // FLIP_HORIZONTAL
  42. {Vector2f(0, 1), Vector2f(1, 0)}, // FLIP_VERTICAL
  43. {Vector2f(1, 1), Vector2f(0, 0)} // ROTATE_180
  44. };
  45. DecoratorTiled::Tile::Tile() : display_scale(1), position(0, 0), size(0, 0)
  46. {
  47. texture_index = -1;
  48. fit_mode = FILL;
  49. orientation = ORIENTATION_NONE;
  50. }
  51. void DecoratorTiled::Tile::CalculateDimensions(const Texture& texture) const
  52. {
  53. if (!tile_data_calculated)
  54. {
  55. tile_data_calculated = true;
  56. tile_data = {};
  57. const Vector2f texture_dimensions(texture.GetDimensions());
  58. if (texture_dimensions.x == 0 || texture_dimensions.y == 0)
  59. {
  60. tile_data.size = Vector2f(0, 0);
  61. tile_data.texcoords[0] = Vector2f(0, 0);
  62. tile_data.texcoords[1] = Vector2f(0, 0);
  63. }
  64. else
  65. {
  66. // Need to scale the coordinates to normalized units and 'size' to absolute size (pixels)
  67. if (size.x == 0 && size.y == 0 && position.x == 0 && position.y == 0)
  68. tile_data.size = texture_dimensions;
  69. else
  70. tile_data.size = size;
  71. const Vector2f size_relative = tile_data.size / texture_dimensions;
  72. tile_data.size = Vector2f(Math::Absolute(tile_data.size.x), Math::Absolute(tile_data.size.y));
  73. tile_data.texcoords[0] = position / texture_dimensions;
  74. tile_data.texcoords[1] = size_relative + tile_data.texcoords[0];
  75. }
  76. }
  77. }
  78. Vector2f DecoratorTiled::Tile::GetNaturalDimensions(Element* element) const
  79. {
  80. if (!tile_data_calculated)
  81. return Vector2f(0, 0);
  82. const float scale_raw_to_natural_dimensions = ElementUtilities::GetDensityIndependentPixelRatio(element) * display_scale;
  83. const Vector2f raw_dimensions = tile_data.size;
  84. return raw_dimensions * scale_raw_to_natural_dimensions;
  85. }
  86. void DecoratorTiled::Tile::GenerateGeometry(Vector<Vertex>& vertices, Vector<int>& indices, const ComputedValues& computed,
  87. const Vector2f surface_origin, const Vector2f surface_dimensions, const Vector2f tile_dimensions) const
  88. {
  89. if (surface_dimensions.x <= 0 || surface_dimensions.y <= 0)
  90. return;
  91. const ColourbPremultiplied quad_colour = computed.image_color().ToPremultiplied(computed.opacity());
  92. if (!tile_data_calculated)
  93. return;
  94. // Generate the oriented texture coordinates for the tiles.
  95. Vector2f scaled_texcoords[2];
  96. for (int i = 0; i < 2; i++)
  97. {
  98. scaled_texcoords[i] = tile_data.texcoords[0] + oriented_texcoords[orientation][i] * (tile_data.texcoords[1] - tile_data.texcoords[0]);
  99. }
  100. Vector2f final_tile_dimensions;
  101. bool offset_and_clip_tile = false;
  102. switch (fit_mode)
  103. {
  104. case FILL:
  105. {
  106. final_tile_dimensions = surface_dimensions;
  107. }
  108. break;
  109. case CONTAIN:
  110. {
  111. Vector2f scale_factor = surface_dimensions / tile_dimensions;
  112. float min_factor = std::min(scale_factor.x, scale_factor.y);
  113. final_tile_dimensions = tile_dimensions * min_factor;
  114. offset_and_clip_tile = true;
  115. }
  116. break;
  117. case COVER:
  118. {
  119. Vector2f scale_factor = surface_dimensions / tile_dimensions;
  120. float max_factor = std::max(scale_factor.x, scale_factor.y);
  121. final_tile_dimensions = tile_dimensions * max_factor;
  122. offset_and_clip_tile = true;
  123. }
  124. break;
  125. case SCALE_NONE:
  126. {
  127. final_tile_dimensions = tile_dimensions;
  128. offset_and_clip_tile = true;
  129. }
  130. break;
  131. case SCALE_DOWN:
  132. {
  133. Vector2f scale_factor = surface_dimensions / tile_dimensions;
  134. float min_factor = std::min(scale_factor.x, scale_factor.y);
  135. if (min_factor < 1.0f)
  136. final_tile_dimensions = tile_dimensions * min_factor;
  137. else
  138. final_tile_dimensions = tile_dimensions;
  139. offset_and_clip_tile = true;
  140. }
  141. break;
  142. }
  143. Vector2f tile_offset(0, 0);
  144. if (offset_and_clip_tile)
  145. {
  146. // Offset tile along each dimension.
  147. for (int i = 0; i < 2; i++)
  148. {
  149. switch (align[i].type)
  150. {
  151. case Style::LengthPercentage::Length: tile_offset[i] = align[i].value; break;
  152. case Style::LengthPercentage::Percentage:
  153. tile_offset[i] = (surface_dimensions[i] - final_tile_dimensions[i]) * align[i].value * 0.01f;
  154. break;
  155. }
  156. }
  157. tile_offset = tile_offset.Round();
  158. // Clip tile. See if our tile extends outside the boundary at either side, along each dimension.
  159. for (int i = 0; i < 2; i++)
  160. {
  161. // Left/right acts as top/bottom during the second iteration.
  162. float overshoot_left = std::max(-tile_offset[i], 0.0f);
  163. float overshoot_right = std::max(tile_offset[i] + final_tile_dimensions[i] - surface_dimensions[i], 0.0f);
  164. if (overshoot_left > 0.f || overshoot_right > 0.f)
  165. {
  166. float& left = scaled_texcoords[0][i];
  167. float& right = scaled_texcoords[1][i];
  168. float width = right - left;
  169. left += overshoot_left / final_tile_dimensions[i] * width;
  170. right -= overshoot_right / final_tile_dimensions[i] * width;
  171. final_tile_dimensions[i] -= overshoot_left + overshoot_right;
  172. tile_offset[i] += overshoot_left;
  173. }
  174. }
  175. }
  176. // Resize the vertex and index arrays to fit the new geometry.
  177. int index_offset = (int)vertices.size();
  178. vertices.resize(vertices.size() + 4);
  179. Vertex* new_vertices = &vertices[0] + index_offset;
  180. size_t num_indices = indices.size();
  181. indices.resize(indices.size() + 6);
  182. int* new_indices = &indices[0] + num_indices;
  183. // Generate the vertices for the tiled surface.
  184. Vector2f tile_position = (surface_origin + tile_offset);
  185. Math::SnapToPixelGrid(tile_position, final_tile_dimensions);
  186. GeometryUtilities::GenerateQuad(new_vertices, new_indices, tile_position, final_tile_dimensions, quad_colour, scaled_texcoords[0],
  187. scaled_texcoords[1], index_offset);
  188. }
  189. void DecoratorTiled::ScaleTileDimensions(Vector2f& tile_dimensions, float axis_value, Axis axis_enum) const
  190. {
  191. int axis = static_cast<int>(axis_enum);
  192. if (tile_dimensions[axis] != axis_value)
  193. {
  194. tile_dimensions[1 - axis] = tile_dimensions[1 - axis] * (axis_value / tile_dimensions[axis]);
  195. tile_dimensions[axis] = axis_value;
  196. }
  197. }
  198. DecoratorTiledInstancer::DecoratorTiledInstancer(size_t num_tiles)
  199. {
  200. tile_property_ids.reserve(num_tiles);
  201. }
  202. void DecoratorTiledInstancer::RegisterTileProperty(const String& name, bool register_fit_modes)
  203. {
  204. TilePropertyIds ids = {};
  205. ids.src = RegisterProperty(CreateString(32, "%s-src", name.c_str()), "").AddParser("string").GetId();
  206. String additional_modes;
  207. if (register_fit_modes)
  208. {
  209. String fit_name = CreateString(32, "%s-fit", name.c_str());
  210. ids.fit = RegisterProperty(fit_name, "fill").AddParser("keyword", "fill, contain, cover, scale-none, scale-down").GetId();
  211. String align_x_name = CreateString(32, "%s-align-x", name.c_str());
  212. ids.align_x = RegisterProperty(align_x_name, "center").AddParser("keyword", "left, center, right").AddParser("length_percent").GetId();
  213. String align_y_name = CreateString(32, "%s-align-y", name.c_str());
  214. ids.align_y = RegisterProperty(align_y_name, "center").AddParser("keyword", "top, center, bottom").AddParser("length_percent").GetId();
  215. additional_modes += ", " + fit_name + ", " + align_x_name + ", " + align_y_name;
  216. }
  217. ids.orientation = RegisterProperty(CreateString(32, "%s-orientation", name.c_str()), "none")
  218. .AddParser("keyword", "none, flip-horizontal, flip-vertical, rotate-180")
  219. .GetId();
  220. RegisterShorthand(name,
  221. CreateString(256, ("%s-src, %s-orientation" + additional_modes).c_str(), name.c_str(), name.c_str(), name.c_str(), name.c_str(), name.c_str(),
  222. name.c_str()),
  223. ShorthandType::FallThrough);
  224. tile_property_ids.push_back(ids);
  225. }
  226. bool DecoratorTiledInstancer::GetTileProperties(DecoratorTiled::Tile* tiles, Texture* textures, size_t num_tiles_and_textures,
  227. const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) const
  228. {
  229. RMLUI_ASSERT(num_tiles_and_textures == tile_property_ids.size());
  230. String previous_texture_name;
  231. Texture previous_texture;
  232. for (size_t i = 0; i < num_tiles_and_textures; i++)
  233. {
  234. const TilePropertyIds& ids = tile_property_ids[i];
  235. const Property* src_property = properties.GetProperty(ids.src);
  236. const String texture_name = src_property->Get<String>();
  237. // Skip the tile if it has no source name.
  238. // Declaring the name 'auto' is the same as an empty string. This gives an easy way to skip certain
  239. // tiles in a shorthand since we can't always declare an empty string.
  240. if (texture_name.empty() || texture_name == "auto")
  241. continue;
  242. // We are required to set default values before instancing the tile, thus, all properties should always be
  243. // dereferencable. If the debugger captures a zero-dereference, check that all properties for every tile is set
  244. // and default values are set just before instancing.
  245. DecoratorTiled::Tile& tile = tiles[i];
  246. Texture& texture = textures[i];
  247. // A tile is always either a sprite or an image.
  248. if (const Sprite* sprite = instancer_interface.GetSprite(texture_name))
  249. {
  250. tile.position = sprite->rectangle.Position();
  251. tile.size = sprite->rectangle.Size();
  252. tile.display_scale = sprite->sprite_sheet->display_scale;
  253. texture = sprite->sprite_sheet->texture;
  254. }
  255. else
  256. {
  257. // No sprite found, so assume that the name is an image source. Since the common use case is to specify the
  258. // same texture for all tiles, check the previous texture first before fetching from the global database.
  259. if (texture_name == previous_texture_name)
  260. {
  261. texture = previous_texture;
  262. }
  263. else
  264. {
  265. texture = instancer_interface.GetTexture(texture_name);
  266. if (!texture)
  267. return false;
  268. previous_texture_name = texture_name;
  269. previous_texture = texture;
  270. }
  271. }
  272. if (ids.fit != PropertyId::Invalid)
  273. {
  274. RMLUI_ASSERT(ids.align_x != PropertyId::Invalid && ids.align_y != PropertyId::Invalid);
  275. const Property& fit_property = *properties.GetProperty(ids.fit);
  276. tile.fit_mode = (DecoratorTiled::TileFitMode)fit_property.value.Get<int>();
  277. const Property* align_properties[2] = {properties.GetProperty(ids.align_x), properties.GetProperty(ids.align_y)};
  278. for (int dimension = 0; dimension < 2; dimension++)
  279. {
  280. using Style::LengthPercentage;
  281. LengthPercentage& align = tile.align[dimension];
  282. const Property& property = *align_properties[dimension];
  283. if (property.unit == Unit::KEYWORD)
  284. {
  285. enum { TOP_LEFT, CENTER, BOTTOM_RIGHT };
  286. switch (property.Get<int>())
  287. {
  288. case TOP_LEFT: align = LengthPercentage(LengthPercentage::Percentage, 0.0f); break;
  289. case CENTER: align = LengthPercentage(LengthPercentage::Percentage, 50.0f); break;
  290. case BOTTOM_RIGHT: align = LengthPercentage(LengthPercentage::Percentage, 100.0f); break;
  291. }
  292. }
  293. else if (property.unit == Unit::PERCENT)
  294. {
  295. align = LengthPercentage(LengthPercentage::Percentage, property.Get<float>());
  296. }
  297. else if (property.unit == Unit::PX)
  298. {
  299. align = LengthPercentage(LengthPercentage::Length, property.Get<float>());
  300. }
  301. else
  302. {
  303. Log::Message(Log::LT_WARNING, "Decorator alignment value is '%s' which uses an unsupported unit (use px, %%, or keyword)",
  304. property.ToString().c_str());
  305. }
  306. }
  307. }
  308. if (ids.orientation != PropertyId::Invalid)
  309. {
  310. const Property& orientation_property = *properties.GetProperty(ids.orientation);
  311. tile.orientation = (DecoratorTiled::TileOrientation)orientation_property.value.Get<int>();
  312. }
  313. }
  314. return true;
  315. }
  316. } // namespace Rml