DecoratorTiled.cpp 12 KB

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