ElementProgress.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 "../../../Include/RmlUi/Core/Elements/ElementProgress.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/Factory.h"
  33. #include "../../../Include/RmlUi/Core/GeometryUtilities.h"
  34. #include "../../../Include/RmlUi/Core/Math.h"
  35. #include "../../../Include/RmlUi/Core/PropertyIdSet.h"
  36. #include "../../../Include/RmlUi/Core/StyleSheet.h"
  37. #include "../../../Include/RmlUi/Core/URL.h"
  38. #include <algorithm>
  39. namespace Rml {
  40. ElementProgress::ElementProgress(const String& tag) : Element(tag), direction(DefaultDirection), start_edge(DefaultStartEdge), fill(nullptr), rect_set(false), geometry(this)
  41. {
  42. if (tag == "progressbar")
  43. Log::Message(Log::LT_WARNING, "Deprecation notice: Element '<progressbar>' renamed to '<progress>', please adjust RML tags accordingly.");
  44. geometry_dirty = false;
  45. // Add the fill element as a non-DOM element.
  46. ElementPtr fill_element = Factory::InstanceElement(this, "*", "fill", XMLAttributes());
  47. RMLUI_ASSERT(fill_element);
  48. fill = AppendChild(std::move(fill_element), false);
  49. }
  50. ElementProgress::~ElementProgress()
  51. {
  52. }
  53. float ElementProgress::GetValue() const
  54. {
  55. const float max_value = GetMax();
  56. return Math::Clamp(GetAttribute< float >("value", 0.0f), 0.0f, max_value);
  57. }
  58. float ElementProgress::GetMax() const
  59. {
  60. const float max_value = GetAttribute< float >("max", 1.0f);
  61. return max_value <= 0.0f ? 1.0f : max_value;
  62. }
  63. void ElementProgress::SetMax(float max_value)
  64. {
  65. SetAttribute("max", max_value);
  66. }
  67. void ElementProgress::SetValue(float in_value)
  68. {
  69. SetAttribute("value", in_value);
  70. }
  71. bool ElementProgress::GetIntrinsicDimensions(Vector2f& dimensions, float& /*ratio*/)
  72. {
  73. dimensions.x = 256;
  74. dimensions.y = 16;
  75. return true;
  76. }
  77. void ElementProgress::OnRender()
  78. {
  79. // Some properties may change geometry without dirtying the layout, eg. opacity.
  80. if (geometry_dirty)
  81. GenerateGeometry();
  82. // Render the geometry at the fill element's content region.
  83. geometry.Render(fill->GetAbsoluteOffset());
  84. }
  85. void ElementProgress::OnAttributeChange(const ElementAttributes& changed_attributes)
  86. {
  87. Element::OnAttributeChange(changed_attributes);
  88. if (changed_attributes.find("value") != changed_attributes.end()
  89. || changed_attributes.find("max") != changed_attributes.end())
  90. {
  91. geometry_dirty = true;
  92. }
  93. if (changed_attributes.find("direction") != changed_attributes.end())
  94. {
  95. using DirectionNameList = Array<String, size_t(Direction::Count)>;
  96. static const DirectionNameList names = { "top", "right", "bottom", "left", "clockwise", "counter-clockwise" };
  97. direction = DefaultDirection;
  98. String name = StringUtilities::ToLower( GetAttribute< String >("direction", "") );
  99. auto it = std::find(names.begin(), names.end(), name);
  100. size_t index = size_t(it - names.begin());
  101. if (index < size_t(Direction::Count))
  102. direction = Direction(index);
  103. geometry_dirty = true;
  104. }
  105. if (changed_attributes.find("start-edge") != changed_attributes.end())
  106. {
  107. using StartEdgeNameList = Array<String, size_t(StartEdge::Count)>;
  108. static const StartEdgeNameList names = { "top", "right", "bottom", "left" };
  109. start_edge = DefaultStartEdge;
  110. String name = StringUtilities::ToLower(GetAttribute< String >("start-edge", ""));
  111. auto it = std::find(names.begin(), names.end(), name);
  112. size_t index = size_t(it - names.begin());
  113. if (index < size_t(StartEdge::Count))
  114. start_edge = StartEdge(index);
  115. geometry_dirty = true;
  116. }
  117. }
  118. void ElementProgress::OnPropertyChange(const PropertyIdSet& changed_properties)
  119. {
  120. Element::OnPropertyChange(changed_properties);
  121. if (changed_properties.Contains(PropertyId::ImageColor) ||
  122. changed_properties.Contains(PropertyId::Opacity)) {
  123. geometry_dirty = true;
  124. }
  125. if (changed_properties.Contains(PropertyId::FillImage)) {
  126. LoadTexture();
  127. }
  128. }
  129. void ElementProgress::OnResize()
  130. {
  131. const Vector2f element_size = GetBox().GetSize();
  132. // Build and set the 'fill' element's box. Here we are mainly interested in all the edge sizes set by the user.
  133. // The content size of the box is here scaled to fit inside the progress bar. Then, during 'CreateGeometry()',
  134. // the 'fill' element's content size is further shrunk according to 'value' along the proper direction.
  135. Box fill_box;
  136. ElementUtilities::BuildBox(fill_box, element_size, fill);
  137. const Vector2f margin_top_left(
  138. fill_box.GetEdge(Box::MARGIN, Box::LEFT),
  139. fill_box.GetEdge(Box::MARGIN, Box::TOP)
  140. );
  141. const Vector2f edge_size = fill_box.GetSize(Box::MARGIN) - fill_box.GetSize(Box::CONTENT);
  142. fill_offset = GetBox().GetPosition() + margin_top_left;
  143. fill_size = element_size - edge_size;
  144. fill_box.SetContent(fill_size);
  145. fill->SetBox(fill_box);
  146. geometry_dirty = true;
  147. }
  148. void ElementProgress::GenerateGeometry()
  149. {
  150. // Warn the user when using the old approach of adding the 'fill-image' property to the 'fill' element.
  151. if (fill->GetLocalProperty(PropertyId::FillImage))
  152. Log::Message(Log::LT_WARNING, "Breaking change: The 'fill-image' property now needs to be set on the <progress> element, instead of its inner <fill> element. Please update your RCSS source to fix progress bars in this document.");
  153. const float normalized_value = GetValue() / GetMax();
  154. Vector2f render_size = fill_size;
  155. {
  156. // Size and offset the fill element depending on the progress value.
  157. Vector2f offset = fill_offset;
  158. switch (direction) {
  159. case Direction::Top:
  160. render_size.y = fill_size.y * normalized_value;
  161. offset.y = fill_offset.y + fill_size.y - render_size.y;
  162. break;
  163. case Direction::Right:
  164. render_size.x = fill_size.x * normalized_value;
  165. break;
  166. case Direction::Bottom:
  167. render_size.y = fill_size.y * normalized_value;
  168. break;
  169. case Direction::Left:
  170. render_size.x = fill_size.x * normalized_value;
  171. offset.x = fill_offset.x + fill_size.x - render_size.x;
  172. break;
  173. case Direction::Clockwise:
  174. case Direction::CounterClockwise:
  175. // Circular progress bars cannot use a box to shape the fill element, instead we need to manually create the geometry from the image texture.
  176. // Thus, we leave the size and offset untouched as a canvas for the manual geometry.
  177. break;
  178. RMLUI_UNUSED_SWITCH_ENUM(Direction::Count);
  179. }
  180. Box fill_box = fill->GetBox();
  181. fill_box.SetContent(render_size);
  182. fill->SetBox(fill_box);
  183. fill->SetOffset(offset, this);
  184. }
  185. geometry.Release(true);
  186. geometry_dirty = false;
  187. // If we don't have a fill texture, then there is no need to generate manual geometry, and we are done here.
  188. // Instead, users can style the fill element eg. by decorators.
  189. if (!texture)
  190. return;
  191. // Otherwise, the 'fill-image' property is set, let's generate its geometry.
  192. auto& vertices = geometry.GetVertices();
  193. auto& indices = geometry.GetIndices();
  194. Vector2f texcoords[2];
  195. if (rect_set)
  196. {
  197. Vector2f texture_dimensions((float)texture.GetDimensions(GetRenderInterface()).x, (float)texture.GetDimensions(GetRenderInterface()).y);
  198. if (texture_dimensions.x == 0)
  199. texture_dimensions.x = 1;
  200. if (texture_dimensions.y == 0)
  201. texture_dimensions.y = 1;
  202. texcoords[0].x = rect.x / texture_dimensions.x;
  203. texcoords[0].y = rect.y / texture_dimensions.y;
  204. texcoords[1].x = (rect.x + rect.width) / texture_dimensions.x;
  205. texcoords[1].y = (rect.y + rect.height) / texture_dimensions.y;
  206. }
  207. else
  208. {
  209. texcoords[0] = Vector2f(0, 0);
  210. texcoords[1] = Vector2f(1, 1);
  211. }
  212. Colourb quad_colour;
  213. {
  214. const ComputedValues& computed = GetComputedValues();
  215. const float opacity = computed.opacity();
  216. quad_colour = computed.image_color();
  217. quad_colour.alpha = (byte)(opacity * (float)quad_colour.alpha);
  218. }
  219. switch (direction)
  220. {
  221. // For the top, right, bottom, left directions the fill element already describes where we should draw the fill,
  222. // we only need to generate the final texture coordinates here.
  223. case Direction::Top: texcoords[0].y = texcoords[0].y + (1.0f - normalized_value) * (texcoords[1].y - texcoords[0].y); break;
  224. case Direction::Right: texcoords[1].x = texcoords[0].x + normalized_value * (texcoords[1].x - texcoords[0].x); break;
  225. case Direction::Bottom: texcoords[1].y = texcoords[0].y + normalized_value * (texcoords[1].y - texcoords[0].y); break;
  226. case Direction::Left: texcoords[0].x = texcoords[0].x + (1.0f - normalized_value) * (texcoords[1].x - texcoords[0].x); break;
  227. case Direction::Clockwise:
  228. case Direction::CounterClockwise:
  229. {
  230. // The circular directions require custom geometry as a box is insufficient.
  231. // We divide the "circle" into eight parts, here called octants, such that each part can be represented by a triangle.
  232. // 'num_octants' tells us how many of these are completely or partially filled.
  233. const int num_octants = Math::Clamp(Math::RoundUpToInteger(8.f * normalized_value), 0, 8);
  234. const int num_vertices = 2 + num_octants;
  235. const int num_triangles = num_octants;
  236. const bool cw = (direction == Direction::Clockwise);
  237. if (num_octants == 0)
  238. break;
  239. vertices.resize(num_vertices);
  240. indices.resize(3 * num_triangles);
  241. RMLUI_ASSERT(int(start_edge) >= int(StartEdge::Top) && int(start_edge) <= int(StartEdge::Left));
  242. // The octant our "circle" expands from.
  243. const int start_octant = 2 * int(start_edge);
  244. // Positions along the unit square (clockwise, index 0 on top)
  245. const float x[8] = { 0, 1, 1, 1, 0, -1, -1, -1 };
  246. const float y[8] = { -1, -1, 0, 1, 1, 1, 0, -1 };
  247. // Set the position of the octant vertices to be rendered.
  248. for (int i = 0; i <= num_octants; i++)
  249. {
  250. int j = (cw ? i : 8 - i);
  251. j = ((j + start_octant) % 8);
  252. vertices[i].position = Vector2f(x[j], y[j]);
  253. }
  254. // Find the position of the vertex representing the partially filled triangle.
  255. if (normalized_value < 1.f)
  256. {
  257. using namespace Math;
  258. const float angle_offset = float(start_octant) / 8.f * 2.f * RMLUI_PI;
  259. const float angle = angle_offset + (cw ? 1.f : -1.f) * normalized_value * 2.f * RMLUI_PI;
  260. Vector2f pos(Sin(angle), -Cos(angle));
  261. // Project it from the circle towards the surrounding unit square.
  262. pos = pos / Max(AbsoluteValue(pos.x), AbsoluteValue(pos.y));
  263. vertices[num_octants].position = pos;
  264. }
  265. const int i_center = num_vertices - 1;
  266. vertices[i_center].position = Vector2f(0, 0);
  267. for (int i = 0; i < num_triangles; i++)
  268. {
  269. indices[i * 3 + 0] = i_center;
  270. indices[i * 3 + 2] = i;
  271. indices[i * 3 + 1] = i + 1;
  272. }
  273. for (int i = 0; i < num_vertices; i++)
  274. {
  275. // Transform position from [-1, 1] to [0, 1] and then to [0, size]
  276. const Vector2f pos = (Vector2f(1, 1) + vertices[i].position) * 0.5f;
  277. vertices[i].position = pos * render_size;
  278. vertices[i].tex_coord = texcoords[0] + pos * (texcoords[1] - texcoords[0]);
  279. vertices[i].colour = quad_colour;
  280. }
  281. }
  282. break;
  283. RMLUI_UNUSED_SWITCH_ENUM(Direction::Count);
  284. }
  285. const bool is_circular = (direction == Direction::Clockwise || direction == Direction::CounterClockwise);
  286. if(!is_circular)
  287. {
  288. vertices.resize(4);
  289. indices.resize(6);
  290. GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Vector2f(0), render_size, quad_colour, texcoords[0], texcoords[1]);
  291. }
  292. }
  293. bool ElementProgress::LoadTexture()
  294. {
  295. geometry_dirty = true;
  296. rect_set = false;
  297. String name;
  298. if (const Property* property = GetLocalProperty(PropertyId::FillImage))
  299. name = property->Get<String>();
  300. ElementDocument* document = GetOwnerDocument();
  301. bool texture_set = false;
  302. if(!name.empty() && document)
  303. {
  304. // Check for a sprite first, this takes precedence.
  305. if (const StyleSheet* style_sheet = document->GetStyleSheet())
  306. {
  307. if (const Sprite* sprite = style_sheet->GetSprite(name))
  308. {
  309. rect = sprite->rectangle;
  310. rect_set = true;
  311. texture = sprite->sprite_sheet->texture;
  312. texture_set = true;
  313. }
  314. }
  315. // Otherwise, treat it as a path
  316. if (!texture_set)
  317. {
  318. URL source_url;
  319. source_url.SetURL(document->GetSourceURL());
  320. texture.Set(name, source_url.GetPath());
  321. texture_set = true;
  322. }
  323. }
  324. if (!texture_set)
  325. {
  326. texture = {};
  327. rect = {};
  328. }
  329. // Set the texture onto our geometry object.
  330. geometry.SetTexture(&texture);
  331. return true;
  332. }
  333. } // namespace Rml