DecoratorTiled.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. Vector2f repeat_factor = Vector2f(1);
  104. switch (fit_mode)
  105. {
  106. case FILL:
  107. {
  108. final_tile_dimensions = surface_dimensions;
  109. }
  110. break;
  111. case CONTAIN:
  112. {
  113. Vector2f scale_factor = surface_dimensions / tile_dimensions;
  114. float min_factor = std::min(scale_factor.x, scale_factor.y);
  115. final_tile_dimensions = tile_dimensions * min_factor;
  116. offset_and_clip_tile = true;
  117. }
  118. break;
  119. case COVER:
  120. {
  121. Vector2f scale_factor = surface_dimensions / tile_dimensions;
  122. float max_factor = std::max(scale_factor.x, scale_factor.y);
  123. final_tile_dimensions = tile_dimensions * max_factor;
  124. offset_and_clip_tile = true;
  125. }
  126. break;
  127. case SCALE_NONE:
  128. {
  129. final_tile_dimensions = tile_dimensions;
  130. offset_and_clip_tile = true;
  131. }
  132. break;
  133. case SCALE_DOWN:
  134. {
  135. Vector2f scale_factor = surface_dimensions / tile_dimensions;
  136. float min_factor = std::min(scale_factor.x, scale_factor.y);
  137. if (min_factor < 1.0f)
  138. final_tile_dimensions = tile_dimensions * min_factor;
  139. else
  140. final_tile_dimensions = tile_dimensions;
  141. offset_and_clip_tile = true;
  142. }
  143. break;
  144. case REPEAT:
  145. final_tile_dimensions = surface_dimensions;
  146. repeat_factor = surface_dimensions / tile_dimensions;
  147. break;
  148. case REPEAT_X:
  149. final_tile_dimensions = Vector2f(surface_dimensions.x, tile_dimensions.y);
  150. repeat_factor.x = surface_dimensions.x / tile_dimensions.x;
  151. offset_and_clip_tile = true;
  152. break;
  153. case REPEAT_Y:
  154. final_tile_dimensions = Vector2f(tile_dimensions.x, surface_dimensions.y);
  155. repeat_factor.y = surface_dimensions.y / tile_dimensions.y;
  156. offset_and_clip_tile = true;
  157. break;
  158. }
  159. Vector2f tile_offset(0, 0);
  160. if (offset_and_clip_tile)
  161. {
  162. // Offset tile along each dimension.
  163. for (int i = 0; i < 2; i++)
  164. {
  165. switch (align[i].type)
  166. {
  167. case Style::LengthPercentage::Length: tile_offset[i] = align[i].value; break;
  168. case Style::LengthPercentage::Percentage:
  169. tile_offset[i] = (surface_dimensions[i] - final_tile_dimensions[i]) * align[i].value * 0.01f;
  170. break;
  171. }
  172. }
  173. tile_offset = tile_offset.Round();
  174. // Clip tile. See if our tile extends outside the boundary at either side, along each dimension.
  175. for (int i = 0; i < 2; i++)
  176. {
  177. // Left/right acts as top/bottom during the second iteration.
  178. float overshoot_left = std::max(-tile_offset[i], 0.0f);
  179. float overshoot_right = std::max(tile_offset[i] + final_tile_dimensions[i] - surface_dimensions[i], 0.0f);
  180. if (overshoot_left > 0.f || overshoot_right > 0.f)
  181. {
  182. float& left = scaled_texcoords[0][i];
  183. float& right = scaled_texcoords[1][i];
  184. float width = right - left;
  185. left += overshoot_left / final_tile_dimensions[i] * width;
  186. right -= overshoot_right / final_tile_dimensions[i] * width;
  187. final_tile_dimensions[i] -= overshoot_left + overshoot_right;
  188. tile_offset[i] += overshoot_left;
  189. }
  190. }
  191. }
  192. scaled_texcoords[0] *= repeat_factor;
  193. scaled_texcoords[1] *= repeat_factor;
  194. // Generate the vertices for the tiled surface.
  195. Vector2f tile_position = (surface_origin + tile_offset);
  196. Math::SnapToPixelGrid(tile_position, final_tile_dimensions);
  197. MeshUtilities::GenerateQuad(mesh, tile_position, final_tile_dimensions, quad_colour, scaled_texcoords[0], scaled_texcoords[1]);
  198. }
  199. void DecoratorTiled::ScaleTileDimensions(Vector2f& tile_dimensions, float axis_value, Axis axis_enum) const
  200. {
  201. int axis = static_cast<int>(axis_enum);
  202. if (tile_dimensions[axis] != axis_value)
  203. {
  204. tile_dimensions[1 - axis] = tile_dimensions[1 - axis] * (axis_value / tile_dimensions[axis]);
  205. tile_dimensions[axis] = axis_value;
  206. }
  207. }
  208. DecoratorTiledInstancer::DecoratorTiledInstancer(size_t num_tiles)
  209. {
  210. tile_property_ids.reserve(num_tiles);
  211. }
  212. void DecoratorTiledInstancer::RegisterTileProperty(const String& name, bool register_fit_modes)
  213. {
  214. TilePropertyIds ids = {};
  215. ids.src = RegisterProperty(CreateString("%s-src", name.c_str()), "").AddParser("string").GetId();
  216. String additional_modes;
  217. if (register_fit_modes)
  218. {
  219. String fit_name = CreateString("%s-fit", name.c_str());
  220. ids.fit = RegisterProperty(fit_name, "fill")
  221. .AddParser("keyword", "fill, contain, cover, scale-none, scale-down, repeat, repeat-x, repeat-y")
  222. .GetId();
  223. String align_x_name = CreateString("%s-align-x", name.c_str());
  224. ids.align_x = RegisterProperty(align_x_name, "center").AddParser("keyword", "left, center, right").AddParser("length_percent").GetId();
  225. String align_y_name = CreateString("%s-align-y", name.c_str());
  226. ids.align_y = RegisterProperty(align_y_name, "center").AddParser("keyword", "top, center, bottom").AddParser("length_percent").GetId();
  227. additional_modes += ", " + fit_name + ", " + align_x_name + ", " + align_y_name;
  228. }
  229. ids.orientation = RegisterProperty(CreateString("%s-orientation", name.c_str()), "none")
  230. .AddParser("keyword", "none, flip-horizontal, flip-vertical, rotate-180")
  231. .GetId();
  232. RegisterShorthand(name,
  233. CreateString(("%s-src, %s-orientation" + additional_modes).c_str(), name.c_str(), name.c_str(), name.c_str(), name.c_str(), name.c_str(),
  234. name.c_str()),
  235. ShorthandType::FallThrough);
  236. tile_property_ids.push_back(ids);
  237. }
  238. bool DecoratorTiledInstancer::GetTileProperties(DecoratorTiled::Tile* tiles, Texture* textures, size_t num_tiles_and_textures,
  239. const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) const
  240. {
  241. RMLUI_ASSERT(num_tiles_and_textures == tile_property_ids.size());
  242. String previous_texture_name;
  243. Texture previous_texture;
  244. for (size_t i = 0; i < num_tiles_and_textures; i++)
  245. {
  246. const TilePropertyIds& ids = tile_property_ids[i];
  247. const Property* src_property = properties.GetProperty(ids.src);
  248. const String texture_name = src_property->Get<String>();
  249. // Skip the tile if it has no source name.
  250. // Declaring the name 'auto' is the same as an empty string. This gives an easy way to skip certain
  251. // tiles in a shorthand since we can't always declare an empty string.
  252. if (texture_name.empty() || texture_name == "auto")
  253. continue;
  254. // We are required to set default values before instancing the tile, thus, all properties should always be
  255. // dereferencable. If the debugger captures a zero-dereference, check that all properties for every tile is set
  256. // and default values are set just before instancing.
  257. DecoratorTiled::Tile& tile = tiles[i];
  258. Texture& texture = textures[i];
  259. const Sprite* sprite = instancer_interface.GetSprite(texture_name);
  260. // A tile is always either a sprite or an image.
  261. if (sprite)
  262. {
  263. tile.position = sprite->rectangle.Position();
  264. tile.size = sprite->rectangle.Size();
  265. tile.display_scale = sprite->sprite_sheet->display_scale;
  266. texture = sprite->sprite_sheet->texture_source.GetTexture(instancer_interface.GetRenderManager());
  267. }
  268. else
  269. {
  270. // No sprite found, so assume that the name is an image source. Since the common use case is to specify the
  271. // same texture for all tiles, check the previous texture first before fetching from the global database.
  272. if (texture_name == previous_texture_name)
  273. {
  274. texture = previous_texture;
  275. }
  276. else
  277. {
  278. texture = instancer_interface.GetTexture(texture_name);
  279. if (!texture)
  280. return false;
  281. previous_texture_name = texture_name;
  282. previous_texture = texture;
  283. }
  284. }
  285. if (ids.fit != PropertyId::Invalid)
  286. {
  287. RMLUI_ASSERT(ids.align_x != PropertyId::Invalid && ids.align_y != PropertyId::Invalid);
  288. const Property& fit_property = *properties.GetProperty(ids.fit);
  289. tile.fit_mode = (DecoratorTiled::TileFitMode)fit_property.value.Get<int>();
  290. if (sprite &&
  291. (tile.fit_mode == DecoratorTiled::TileFitMode::REPEAT || tile.fit_mode == DecoratorTiled::TileFitMode::REPEAT_X ||
  292. tile.fit_mode == DecoratorTiled::TileFitMode::REPEAT_Y))
  293. {
  294. Log::Message(Log::LT_WARNING, "Decorator 'fit' value is '%s', which is incompatible with sprites", fit_property.ToString().c_str());
  295. return false;
  296. }
  297. const Property* align_properties[2] = {properties.GetProperty(ids.align_x), properties.GetProperty(ids.align_y)};
  298. for (int dimension = 0; dimension < 2; dimension++)
  299. {
  300. using Style::LengthPercentage;
  301. LengthPercentage& align = tile.align[dimension];
  302. const Property& property = *align_properties[dimension];
  303. if (property.unit == Unit::KEYWORD)
  304. {
  305. enum { TOP_LEFT, CENTER, BOTTOM_RIGHT };
  306. switch (property.Get<int>())
  307. {
  308. case TOP_LEFT: align = LengthPercentage(LengthPercentage::Percentage, 0.0f); break;
  309. case CENTER: align = LengthPercentage(LengthPercentage::Percentage, 50.0f); break;
  310. case BOTTOM_RIGHT: align = LengthPercentage(LengthPercentage::Percentage, 100.0f); break;
  311. }
  312. }
  313. else if (property.unit == Unit::PERCENT)
  314. {
  315. align = LengthPercentage(LengthPercentage::Percentage, property.Get<float>());
  316. }
  317. else if (property.unit == Unit::PX)
  318. {
  319. align = LengthPercentage(LengthPercentage::Length, property.Get<float>());
  320. }
  321. else
  322. {
  323. Log::Message(Log::LT_WARNING, "Decorator alignment value is '%s' which uses an unsupported unit (use px, %%, or keyword)",
  324. property.ToString().c_str());
  325. }
  326. }
  327. }
  328. if (ids.orientation != PropertyId::Invalid)
  329. {
  330. const Property& orientation_property = *properties.GetProperty(ids.orientation);
  331. tile.orientation = (DecoratorTiled::TileOrientation)orientation_property.value.Get<int>();
  332. }
  333. }
  334. return true;
  335. }
  336. } // namespace Rml