DecoratorGradient.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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 "DecoratorGradient.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/Math.h"
  34. #include "../../Include/RmlUi/Core/MeshUtilities.h"
  35. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  36. #include "ComputeProperty.h"
  37. #include "DecoratorShader.h"
  38. namespace Rml {
  39. // Returns the point along the input line ('line_point', 'line_vector') closest to the input 'point'.
  40. static Vector2f IntersectionPointToLineNormal(const Vector2f point, const Vector2f line_point, const Vector2f line_vector)
  41. {
  42. const Vector2f delta = line_point - point;
  43. return line_point - delta.DotProduct(line_vector) * line_vector;
  44. }
  45. /// Convert all color stop positions to normalized numbers.
  46. /// @param[in] element The element to resolve lengths against.
  47. /// @param[in] gradient_line_length The length of the gradient line, along which color stops are placed.
  48. /// @param[in] soft_spacing The desired minimum distance between stops to avoid aliasing, in normalized number units.
  49. /// @param[in] unresolved_stops
  50. /// @return A list of resolved color stops, all in number units.
  51. static ColorStopList ResolveColorStops(Element* element, const float gradient_line_length, const float soft_spacing,
  52. const ColorStopList& unresolved_stops)
  53. {
  54. ColorStopList stops = unresolved_stops;
  55. const int num_stops = (int)stops.size();
  56. // Resolve all lengths, percentages, and angles to numbers. After this step all stops with a unit other than Number are considered as Auto.
  57. for (ColorStop& stop : stops)
  58. {
  59. if (Any(stop.position.unit & Unit::LENGTH))
  60. {
  61. const float resolved_position = element->ResolveLength(stop.position);
  62. stop.position = NumericValue(resolved_position / gradient_line_length, Unit::NUMBER);
  63. }
  64. else if (stop.position.unit == Unit::PERCENT)
  65. {
  66. stop.position = NumericValue(stop.position.number * 0.01f, Unit::NUMBER);
  67. }
  68. else if (Any(stop.position.unit & Unit::ANGLE))
  69. {
  70. stop.position = NumericValue(ComputeAngle(stop.position) * (1.f / (2.f * Math::RMLUI_PI)), Unit::NUMBER);
  71. }
  72. }
  73. // Resolve auto positions of the first and last color stops.
  74. auto resolve_edge_stop = [](ColorStop& stop, float auto_to_number) {
  75. if (stop.position.unit != Unit::NUMBER)
  76. stop.position = NumericValue(auto_to_number, Unit::NUMBER);
  77. };
  78. resolve_edge_stop(stops[0], 0.f);
  79. resolve_edge_stop(stops[num_stops - 1], 1.f);
  80. // Ensures that color stop positions are strictly increasing, and have at least 1px spacing to avoid aliasing.
  81. auto nudge_stop = [prev_position = stops[0].position.number](ColorStop& stop, bool update_prev = true) mutable {
  82. stop.position.number = Math::Max(stop.position.number, prev_position);
  83. if (update_prev)
  84. prev_position = stop.position.number;
  85. };
  86. int auto_begin_i = -1;
  87. // Evenly space stops with sequential auto indices, and nudge stop positions to ensure strictly increasing positions.
  88. for (int i = 1; i < num_stops; i++)
  89. {
  90. ColorStop& stop = stops[i];
  91. if (stop.position.unit != Unit::NUMBER)
  92. {
  93. // Mark the first of any consecutive auto stops.
  94. if (auto_begin_i < 0)
  95. auto_begin_i = i;
  96. }
  97. else if (auto_begin_i < 0)
  98. {
  99. // The stop has a definite position and there are no previous autos to handle, just ensure it is properly spaced.
  100. nudge_stop(stop);
  101. }
  102. else
  103. {
  104. // Space out all the previous auto stops, indices [auto_begin_i, i).
  105. nudge_stop(stop, false);
  106. const int num_auto_stops = i - auto_begin_i;
  107. const float t0 = stops[auto_begin_i - 1].position.number;
  108. const float t1 = stop.position.number;
  109. for (int j = 0; j < num_auto_stops; j++)
  110. {
  111. const float fraction_along_t0_t1 = float(j + 1) / float(num_auto_stops + 1);
  112. stops[j + auto_begin_i].position = NumericValue(t0 + (t1 - t0) * fraction_along_t0_t1, Unit::NUMBER);
  113. nudge_stop(stops[j + auto_begin_i]);
  114. }
  115. nudge_stop(stop);
  116. auto_begin_i = -1;
  117. }
  118. }
  119. // Ensures that stops are placed some minimum distance from each other to avoid aliasing, if possible.
  120. for (int i = 1; i < num_stops - 1; i++)
  121. {
  122. const float p0 = stops[i - 1].position.number;
  123. const float p1 = stops[i].position.number;
  124. const float p2 = stops[i + 1].position.number;
  125. float& new_position = stops[i].position.number;
  126. if (p1 - p0 < soft_spacing)
  127. {
  128. if (p2 - p0 < 2.f * soft_spacing)
  129. new_position = 0.5f * (p2 + p0);
  130. else
  131. new_position = p0 + soft_spacing;
  132. }
  133. }
  134. RMLUI_ASSERT(std::all_of(stops.begin(), stops.end(), [](auto&& stop) { return stop.position.unit == Unit::NUMBER; }));
  135. return stops;
  136. }
  137. DecoratorStraightGradient::DecoratorStraightGradient() {}
  138. DecoratorStraightGradient::~DecoratorStraightGradient() {}
  139. bool DecoratorStraightGradient::Initialise(const Direction in_direction, const Colourb in_start, const Colourb in_stop)
  140. {
  141. direction = in_direction;
  142. start = in_start;
  143. stop = in_stop;
  144. return true;
  145. }
  146. DecoratorDataHandle DecoratorStraightGradient::GenerateElementData(Element* element, BoxArea paint_area) const
  147. {
  148. const RenderBox render_box = element->GetRenderBox(paint_area);
  149. const ComputedValues& computed = element->GetComputedValues();
  150. const float opacity = computed.opacity();
  151. Mesh mesh;
  152. MeshUtilities::GenerateBackground(mesh, render_box, ColourbPremultiplied());
  153. ColourbPremultiplied colour_start = start.ToPremultiplied(opacity);
  154. ColourbPremultiplied colour_stop = stop.ToPremultiplied(opacity);
  155. const Vector2f offset = render_box.GetFillOffset();
  156. const Vector2f size = render_box.GetFillSize();
  157. Vector<Vertex>& vertices = mesh.vertices;
  158. if (direction == Direction::Horizontal)
  159. {
  160. for (int i = 0; i < (int)vertices.size(); i++)
  161. {
  162. const float t = Math::Clamp((vertices[i].position.x - offset.x) / size.x, 0.0f, 1.0f);
  163. vertices[i].colour = Math::RoundedLerp(t, colour_start, colour_stop);
  164. }
  165. }
  166. else if (direction == Direction::Vertical)
  167. {
  168. for (int i = 0; i < (int)vertices.size(); i++)
  169. {
  170. const float t = Math::Clamp((vertices[i].position.y - offset.y) / size.y, 0.0f, 1.0f);
  171. vertices[i].colour = Math::RoundedLerp(t, colour_start, colour_stop);
  172. }
  173. }
  174. Geometry* geometry = new Geometry(element->GetRenderManager()->MakeGeometry(std::move(mesh)));
  175. return reinterpret_cast<DecoratorDataHandle>(geometry);
  176. }
  177. void DecoratorStraightGradient::ReleaseElementData(DecoratorDataHandle element_data) const
  178. {
  179. delete reinterpret_cast<Geometry*>(element_data);
  180. }
  181. void DecoratorStraightGradient::RenderElement(Element* element, DecoratorDataHandle element_data) const
  182. {
  183. auto* data = reinterpret_cast<Geometry*>(element_data);
  184. data->Render(element->GetAbsoluteOffset(BoxArea::Border));
  185. }
  186. DecoratorStraightGradientInstancer::DecoratorStraightGradientInstancer()
  187. {
  188. ids.direction = RegisterProperty("direction", "horizontal").AddParser("keyword", "horizontal, vertical").GetId();
  189. ids.start = RegisterProperty("start-color", "#ffffff").AddParser("color").GetId();
  190. ids.stop = RegisterProperty("stop-color", "#ffffff").AddParser("color").GetId();
  191. RegisterShorthand("decorator", "direction, start-color, stop-color", ShorthandType::FallThrough);
  192. }
  193. DecoratorStraightGradientInstancer::~DecoratorStraightGradientInstancer() {}
  194. SharedPtr<Decorator> DecoratorStraightGradientInstancer::InstanceDecorator(const String& name, const PropertyDictionary& properties_,
  195. const DecoratorInstancerInterface& /*interface_*/)
  196. {
  197. using Direction = DecoratorStraightGradient::Direction;
  198. Direction direction;
  199. if (name == "horizontal-gradient")
  200. direction = Direction::Horizontal;
  201. else if (name == "vertical-gradient")
  202. direction = Direction::Vertical;
  203. else
  204. {
  205. direction = (Direction)properties_.GetProperty(ids.direction)->Get<int>();
  206. Log::Message(Log::LT_WARNING,
  207. "Decorator syntax 'gradient(horizontal|vertical ...)' is deprecated, please replace with 'horizontal-gradient(...)' or "
  208. "'vertical-gradient(...)'");
  209. }
  210. Colourb start = properties_.GetProperty(ids.start)->Get<Colourb>();
  211. Colourb stop = properties_.GetProperty(ids.stop)->Get<Colourb>();
  212. auto decorator = MakeShared<DecoratorStraightGradient>();
  213. if (decorator->Initialise(direction, start, stop))
  214. return decorator;
  215. return nullptr;
  216. }
  217. DecoratorLinearGradient::DecoratorLinearGradient() {}
  218. DecoratorLinearGradient::~DecoratorLinearGradient() {}
  219. bool DecoratorLinearGradient::Initialise(bool in_repeating, Corner in_corner, float in_angle, const ColorStopList& in_color_stops)
  220. {
  221. repeating = in_repeating;
  222. corner = in_corner;
  223. angle = in_angle;
  224. color_stops = in_color_stops;
  225. return !color_stops.empty();
  226. }
  227. DecoratorDataHandle DecoratorLinearGradient::GenerateElementData(Element* element, BoxArea paint_area) const
  228. {
  229. RenderManager* render_manager = element->GetRenderManager();
  230. if (!render_manager)
  231. return INVALID_DECORATORDATAHANDLE;
  232. RMLUI_ASSERT(!color_stops.empty());
  233. const RenderBox render_box = element->GetRenderBox(paint_area);
  234. LinearGradientShape gradient_shape = CalculateShape(render_box.GetFillSize());
  235. // One-pixel minimum color stop spacing to avoid aliasing.
  236. const float soft_spacing = 1.f / gradient_shape.length;
  237. ColorStopList resolved_stops = ResolveColorStops(element, gradient_shape.length, soft_spacing, color_stops);
  238. CompiledShader shader = render_manager->CompileShader("linear-gradient",
  239. Dictionary{
  240. {"p0", Variant(gradient_shape.p0)},
  241. {"p1", Variant(gradient_shape.p1)},
  242. {"length", Variant(gradient_shape.length)},
  243. {"repeating", Variant(repeating)},
  244. {"color_stop_list", Variant(std::move(resolved_stops))},
  245. });
  246. if (!shader)
  247. return INVALID_DECORATORDATAHANDLE;
  248. Mesh mesh;
  249. const ComputedValues& computed = element->GetComputedValues();
  250. const byte alpha = byte(computed.opacity() * 255.f);
  251. MeshUtilities::GenerateBackground(mesh, render_box, ColourbPremultiplied(alpha, alpha));
  252. const Vector2f render_offset = render_box.GetFillOffset();
  253. for (Vertex& vertex : mesh.vertices)
  254. vertex.tex_coord = vertex.position - render_offset;
  255. ShaderElementData* element_data =
  256. GetShaderElementDataPool().AllocateAndConstruct(render_manager->MakeGeometry(std::move(mesh)), std::move(shader));
  257. return reinterpret_cast<DecoratorDataHandle>(element_data);
  258. }
  259. void DecoratorLinearGradient::ReleaseElementData(DecoratorDataHandle handle) const
  260. {
  261. ShaderElementData* element_data = reinterpret_cast<ShaderElementData*>(handle);
  262. GetShaderElementDataPool().DestroyAndDeallocate(element_data);
  263. }
  264. void DecoratorLinearGradient::RenderElement(Element* element, DecoratorDataHandle handle) const
  265. {
  266. ShaderElementData* element_data = reinterpret_cast<ShaderElementData*>(handle);
  267. element_data->geometry.Render(element->GetAbsoluteOffset(BoxArea::Border), {}, element_data->shader);
  268. }
  269. DecoratorLinearGradient::LinearGradientShape DecoratorLinearGradient::CalculateShape(Vector2f dim) const
  270. {
  271. using uint = unsigned int;
  272. const Vector2f corners[(int)Corner::Count] = {Vector2f(dim.x, 0), dim, Vector2f(0, dim.y), Vector2f(0, 0)};
  273. const Vector2f center = 0.5f * dim;
  274. uint quadrant = 0;
  275. Vector2f line_vector;
  276. if (corner == Corner::None)
  277. {
  278. // Find the target quadrant and unit vector for the given angle.
  279. quadrant = uint(Math::NormaliseAngle(angle) * (4.f / (2.f * Math::RMLUI_PI))) % 4u;
  280. line_vector = Vector2f(Math::Sin(angle), -Math::Cos(angle));
  281. }
  282. else
  283. {
  284. // Quadrant given by the corner, need to find the vector perpendicular to the line connecting the neighboring corners.
  285. quadrant = uint(corner);
  286. const Vector2f v_neighbors = (corners[(quadrant + 1u) % 4u] - corners[(quadrant + 3u) % 4u]).Normalise();
  287. line_vector = {v_neighbors.y, -v_neighbors.x};
  288. }
  289. const uint quadrant_opposite = (quadrant + 2u) % 4u;
  290. const Vector2f starting_point = IntersectionPointToLineNormal(corners[quadrant_opposite], center, line_vector);
  291. const Vector2f ending_point = IntersectionPointToLineNormal(corners[quadrant], center, line_vector);
  292. const float length = Math::Absolute(dim.x * line_vector.x) + Math::Absolute(-dim.y * line_vector.y);
  293. return LinearGradientShape{starting_point, ending_point, length};
  294. }
  295. DecoratorLinearGradientInstancer::DecoratorLinearGradientInstancer()
  296. {
  297. ids.angle = RegisterProperty("angle", "180deg").AddParser("angle").GetId();
  298. ids.direction_to = RegisterProperty("to", "unspecified").AddParser("keyword", "unspecified, to").GetId();
  299. // See Direction enum for keyword values.
  300. ids.direction_x = RegisterProperty("direction-x", "unspecified").AddParser("keyword", "unspecified=0, left=8, right=2").GetId();
  301. ids.direction_y = RegisterProperty("direction-y", "unspecified").AddParser("keyword", "unspecified=0, top=1, bottom=4").GetId();
  302. ids.color_stop_list = RegisterProperty("color-stops", "").AddParser("color_stop_list").GetId();
  303. RegisterShorthand("direction", "angle, to, direction-x, direction-y, direction-x", ShorthandType::FallThrough);
  304. RegisterShorthand("decorator", "direction?, color-stops#", ShorthandType::RecursiveCommaSeparated);
  305. }
  306. DecoratorLinearGradientInstancer::~DecoratorLinearGradientInstancer() {}
  307. SharedPtr<Decorator> DecoratorLinearGradientInstancer::InstanceDecorator(const String& name, const PropertyDictionary& properties_,
  308. const DecoratorInstancerInterface& /*interface_*/)
  309. {
  310. const Property* p_angle = properties_.GetProperty(ids.angle);
  311. const Property* p_direction_to = properties_.GetProperty(ids.direction_to);
  312. const Property* p_direction_x = properties_.GetProperty(ids.direction_x);
  313. const Property* p_direction_y = properties_.GetProperty(ids.direction_y);
  314. const Property* p_color_stop_list = properties_.GetProperty(ids.color_stop_list);
  315. if (!p_angle || !p_direction_to || !p_direction_x || !p_direction_y || !p_color_stop_list)
  316. return nullptr;
  317. using Corner = DecoratorLinearGradient::Corner;
  318. Corner corner = Corner::None;
  319. float angle = 0.f;
  320. if (p_direction_to->Get<bool>())
  321. {
  322. const Direction direction = (Direction)(p_direction_x->Get<int>() | p_direction_y->Get<int>());
  323. switch (direction)
  324. {
  325. case Direction::Top: angle = 0.f; break;
  326. case Direction::Right: angle = 0.5f * Math::RMLUI_PI; break;
  327. case Direction::Bottom: angle = Math::RMLUI_PI; break;
  328. case Direction::Left: angle = 1.5f * Math::RMLUI_PI; break;
  329. case Direction::TopLeft: corner = Corner::TopLeft; break;
  330. case Direction::TopRight: corner = Corner::TopRight; break;
  331. case Direction::BottomRight: corner = Corner::BottomRight; break;
  332. case Direction::BottomLeft: corner = Corner::BottomLeft; break;
  333. case Direction::None:
  334. default: return nullptr; break;
  335. }
  336. }
  337. else
  338. {
  339. angle = ComputeAngle(p_angle->GetNumericValue());
  340. }
  341. if (p_color_stop_list->unit != Unit::COLORSTOPLIST)
  342. return nullptr;
  343. const ColorStopList& color_stop_list = p_color_stop_list->value.GetReference<ColorStopList>();
  344. const bool repeating = (name == "repeating-linear-gradient");
  345. auto decorator = MakeShared<DecoratorLinearGradient>();
  346. if (decorator->Initialise(repeating, corner, angle, color_stop_list))
  347. return decorator;
  348. return nullptr;
  349. }
  350. DecoratorRadialGradient::DecoratorRadialGradient() {}
  351. DecoratorRadialGradient::~DecoratorRadialGradient() {}
  352. bool DecoratorRadialGradient::Initialise(bool in_repeating, Shape in_shape, SizeType in_size_type, Vector2Numeric in_size, Vector2Numeric in_position,
  353. const ColorStopList& in_color_stops)
  354. {
  355. repeating = in_repeating;
  356. shape = in_shape;
  357. size_type = in_size_type;
  358. size = in_size;
  359. position = in_position;
  360. color_stops = in_color_stops;
  361. return !color_stops.empty();
  362. }
  363. DecoratorDataHandle DecoratorRadialGradient::GenerateElementData(Element* element, BoxArea paint_area) const
  364. {
  365. RenderManager* render_manager = element->GetRenderManager();
  366. if (!render_manager)
  367. return INVALID_DECORATORDATAHANDLE;
  368. RMLUI_ASSERT(!color_stops.empty() && (shape == Shape::Circle || shape == Shape::Ellipse));
  369. const RenderBox render_box = element->GetRenderBox(paint_area);
  370. const Vector2f dimensions = render_box.GetFillSize();
  371. RadialGradientShape gradient_shape = CalculateRadialGradientShape(element, dimensions);
  372. // One-pixel minimum color stop spacing to avoid aliasing.
  373. const float soft_spacing = 1.f / Math::Min(gradient_shape.radius.x, gradient_shape.radius.y);
  374. ColorStopList resolved_stops = ResolveColorStops(element, gradient_shape.radius.x, soft_spacing, color_stops);
  375. CompiledShader shader = render_manager->CompileShader("radial-gradient",
  376. Dictionary{
  377. {"center", Variant(gradient_shape.center)},
  378. {"radius", Variant(gradient_shape.radius)},
  379. {"repeating", Variant(repeating)},
  380. {"color_stop_list", Variant(std::move(resolved_stops))},
  381. });
  382. if (!shader)
  383. return INVALID_DECORATORDATAHANDLE;
  384. Mesh mesh;
  385. const ComputedValues& computed = element->GetComputedValues();
  386. const byte alpha = byte(computed.opacity() * 255.f);
  387. MeshUtilities::GenerateBackground(mesh, render_box, ColourbPremultiplied(alpha, alpha));
  388. const Vector2f render_offset = render_box.GetFillOffset();
  389. for (Vertex& vertex : mesh.vertices)
  390. vertex.tex_coord = vertex.position - render_offset;
  391. ShaderElementData* element_data =
  392. GetShaderElementDataPool().AllocateAndConstruct(render_manager->MakeGeometry(std::move(mesh)), std::move(shader));
  393. return reinterpret_cast<DecoratorDataHandle>(element_data);
  394. }
  395. void DecoratorRadialGradient::ReleaseElementData(DecoratorDataHandle handle) const
  396. {
  397. ShaderElementData* element_data = reinterpret_cast<ShaderElementData*>(handle);
  398. GetShaderElementDataPool().DestroyAndDeallocate(element_data);
  399. }
  400. void DecoratorRadialGradient::RenderElement(Element* element, DecoratorDataHandle handle) const
  401. {
  402. ShaderElementData* element_data = reinterpret_cast<ShaderElementData*>(handle);
  403. element_data->geometry.Render(element->GetAbsoluteOffset(BoxArea::Border), {}, element_data->shader);
  404. }
  405. DecoratorRadialGradient::RadialGradientShape DecoratorRadialGradient::CalculateRadialGradientShape(Element* element, Vector2f dimensions) const
  406. {
  407. RadialGradientShape result;
  408. result.center.x = element->ResolveNumericValue(position.x, dimensions.x);
  409. result.center.y = element->ResolveNumericValue(position.y, dimensions.y);
  410. const bool is_circle = (shape == Shape::Circle);
  411. auto Abs = [](Vector2f v) { return Vector2f{Math::Absolute(v.x), Math::Absolute(v.y)}; };
  412. auto d = dimensions;
  413. auto c = result.center;
  414. Vector2f r;
  415. switch (size_type)
  416. {
  417. case SizeType::ClosestSide:
  418. {
  419. r = Abs(Math::Min(c, d - c));
  420. result.radius = (is_circle ? Vector2f(Math::Min(r.x, r.y)) : r);
  421. }
  422. break;
  423. case SizeType::FarthestSide:
  424. {
  425. r = Abs(Math::Max(c, d - c));
  426. result.radius = (is_circle ? Vector2f(Math::Max(r.x, r.y)) : r);
  427. }
  428. break;
  429. case SizeType::ClosestCorner:
  430. case SizeType::FarthestCorner:
  431. {
  432. if (size_type == SizeType::ClosestCorner)
  433. r = Abs(Math::Min(c, d - c)); // Same as closest-side.
  434. else
  435. r = Abs(Math::Max(c, d - c)); // Same as farthest-side.
  436. if (is_circle)
  437. {
  438. result.radius = Vector2f(r.Magnitude());
  439. }
  440. else
  441. {
  442. r = Math::Max(r, Vector2f(1)); // In case r.x ~= 0
  443. result.radius.x = Math::SquareRoot(2.f * r.x * r.x);
  444. result.radius.y = result.radius.x * (r.y / r.x);
  445. }
  446. }
  447. break;
  448. case SizeType::LengthPercentage:
  449. {
  450. result.radius.x = element->ResolveNumericValue(size.x, d.x);
  451. result.radius.y = (is_circle ? result.radius.x : element->ResolveNumericValue(size.y, d.y));
  452. result.radius = Abs(result.radius);
  453. }
  454. break;
  455. }
  456. result.radius = Math::Max(result.radius, Vector2f(1.f));
  457. return result;
  458. }
  459. DecoratorRadialGradientInstancer::DecoratorRadialGradientInstancer()
  460. {
  461. ids.ending_shape = RegisterProperty("ending-shape", "unspecified").AddParser("keyword", "circle, ellipse, unspecified").GetId();
  462. ids.size_x = RegisterProperty("size-x", "farthest-corner")
  463. .AddParser("keyword", "closest-side, farthest-side, closest-corner, farthest-corner")
  464. .AddParser("length_percent")
  465. .GetId();
  466. ids.size_y = RegisterProperty("size-y", "unspecified").AddParser("keyword", "unspecified").AddParser("length_percent").GetId();
  467. RegisterProperty("at", "unspecified").AddParser("keyword", "at, unspecified");
  468. ids.position_x = RegisterProperty("position-x", "center").AddParser("keyword", "left, center, right").AddParser("length_percent").GetId();
  469. ids.position_y = RegisterProperty("position-y", "center").AddParser("keyword", "top, center, bottom").AddParser("length_percent").GetId();
  470. ids.color_stop_list = RegisterProperty("color-stops", "").AddParser("color_stop_list").GetId();
  471. RegisterShorthand("shape", "ending-shape, size-x, size-y, at, position-x, position-y, position-x", ShorthandType::FallThrough);
  472. RegisterShorthand("decorator", "shape?, color-stops#", ShorthandType::RecursiveCommaSeparated);
  473. }
  474. DecoratorRadialGradientInstancer::~DecoratorRadialGradientInstancer() {}
  475. SharedPtr<Decorator> DecoratorRadialGradientInstancer::InstanceDecorator(const String& name, const PropertyDictionary& properties_,
  476. const DecoratorInstancerInterface& /*interface_*/)
  477. {
  478. const Property* p_ending_shape = properties_.GetProperty(ids.ending_shape);
  479. const Property* p_size_x = properties_.GetProperty(ids.size_x);
  480. const Property* p_size_y = properties_.GetProperty(ids.size_y);
  481. Array<const Property*, 2> p_position = {properties_.GetProperty(ids.position_x), properties_.GetProperty(ids.position_y)};
  482. const Property* p_color_stop_list = properties_.GetProperty(ids.color_stop_list);
  483. if (!p_ending_shape || !p_size_x || !p_size_y || !p_position[0] || !p_position[1] || !p_color_stop_list)
  484. return nullptr;
  485. using SizeType = DecoratorRadialGradient::SizeType;
  486. using Shape = DecoratorRadialGradient::Shape;
  487. Shape shape = (Shape)p_ending_shape->Get<int>();
  488. if (shape == Shape::Unspecified)
  489. {
  490. const bool circle_sized = (Any(p_size_x->unit & Unit::LENGTH_PERCENT) && p_size_y->unit == Unit::KEYWORD);
  491. shape = (circle_sized ? Shape::Circle : Shape::Ellipse);
  492. }
  493. if (shape == Shape::Circle && (p_size_x->unit == Unit::PERCENT || p_size_y->unit != Unit::KEYWORD))
  494. return nullptr;
  495. SizeType size_type = {};
  496. Vector2Numeric size;
  497. if (p_size_x->unit == Unit::KEYWORD)
  498. {
  499. size_type = (SizeType)p_size_x->Get<int>();
  500. }
  501. else
  502. {
  503. size_type = SizeType::LengthPercentage;
  504. size.x = p_size_x->GetNumericValue();
  505. size.y = (p_size_y->unit == Unit::KEYWORD ? size.x : p_size_y->GetNumericValue());
  506. }
  507. const Vector2Numeric position = ComputePosition(p_position);
  508. const bool repeating = (name == "repeating-radial-gradient");
  509. if (p_color_stop_list->unit != Unit::COLORSTOPLIST)
  510. return nullptr;
  511. const ColorStopList& color_stop_list = p_color_stop_list->value.GetReference<ColorStopList>();
  512. auto decorator = MakeShared<DecoratorRadialGradient>();
  513. if (decorator->Initialise(repeating, shape, size_type, size, position, color_stop_list))
  514. return decorator;
  515. return nullptr;
  516. }
  517. DecoratorConicGradient::DecoratorConicGradient() {}
  518. DecoratorConicGradient::~DecoratorConicGradient() {}
  519. bool DecoratorConicGradient::Initialise(bool in_repeating, float in_angle, Vector2Numeric in_position, const ColorStopList& in_color_stops)
  520. {
  521. repeating = in_repeating;
  522. angle = in_angle;
  523. position = in_position;
  524. color_stops = in_color_stops;
  525. return !color_stops.empty();
  526. }
  527. DecoratorDataHandle DecoratorConicGradient::GenerateElementData(Element* element, BoxArea paint_area) const
  528. {
  529. RenderManager* render_manager = element->GetRenderManager();
  530. if (!render_manager)
  531. return INVALID_DECORATORDATAHANDLE;
  532. RMLUI_ASSERT(!color_stops.empty());
  533. const RenderBox render_box = element->GetRenderBox(paint_area);
  534. const Vector2f dimensions = render_box.GetFillSize();
  535. const Vector2f center =
  536. Vector2f{element->ResolveNumericValue(position.x, dimensions.x), element->ResolveNumericValue(position.y, dimensions.y)}.Round();
  537. ColorStopList resolved_stops = ResolveColorStops(element, 1.f, 0.f, color_stops);
  538. CompiledShader shader = render_manager->CompileShader("conic-gradient",
  539. Dictionary{
  540. {"angle", Variant(angle)},
  541. {"center", Variant(center)},
  542. {"repeating", Variant(repeating)},
  543. {"color_stop_list", Variant(std::move(resolved_stops))},
  544. });
  545. if (!shader)
  546. return INVALID_DECORATORDATAHANDLE;
  547. Mesh mesh;
  548. const ComputedValues& computed = element->GetComputedValues();
  549. const byte alpha = byte(computed.opacity() * 255.f);
  550. MeshUtilities::GenerateBackground(mesh, render_box, ColourbPremultiplied(alpha, alpha));
  551. const Vector2f render_offset = render_box.GetFillOffset();
  552. for (Vertex& vertex : mesh.vertices)
  553. vertex.tex_coord = vertex.position - render_offset;
  554. ShaderElementData* element_data =
  555. GetShaderElementDataPool().AllocateAndConstruct(render_manager->MakeGeometry(std::move(mesh)), std::move(shader));
  556. return reinterpret_cast<DecoratorDataHandle>(element_data);
  557. }
  558. void DecoratorConicGradient::ReleaseElementData(DecoratorDataHandle handle) const
  559. {
  560. ShaderElementData* element_data = reinterpret_cast<ShaderElementData*>(handle);
  561. GetShaderElementDataPool().DestroyAndDeallocate(element_data);
  562. }
  563. void DecoratorConicGradient::RenderElement(Element* element, DecoratorDataHandle handle) const
  564. {
  565. ShaderElementData* element_data = reinterpret_cast<ShaderElementData*>(handle);
  566. element_data->geometry.Render(element->GetAbsoluteOffset(BoxArea::Border), {}, element_data->shader);
  567. }
  568. DecoratorConicGradientInstancer::DecoratorConicGradientInstancer()
  569. {
  570. RegisterProperty("from", "from").AddParser("keyword", "from");
  571. ids.angle = RegisterProperty("angle", "0deg").AddParser("angle").GetId();
  572. RegisterProperty("at", "unspecified").AddParser("keyword", "at, unspecified");
  573. ids.position_x = RegisterProperty("position-x", "center").AddParser("keyword", "left, center, right").AddParser("length_percent").GetId();
  574. ids.position_y = RegisterProperty("position-y", "center").AddParser("keyword", "top, center, bottom").AddParser("length_percent").GetId();
  575. ids.color_stop_list = RegisterProperty("color-stops", "").AddParser("color_stop_list", "angle").GetId();
  576. RegisterShorthand("shape", "from, angle, at, position-x, position-y, position-x", ShorthandType::FallThrough);
  577. RegisterShorthand("decorator", "shape?, color-stops#", ShorthandType::RecursiveCommaSeparated);
  578. }
  579. DecoratorConicGradientInstancer::~DecoratorConicGradientInstancer() {}
  580. SharedPtr<Decorator> DecoratorConicGradientInstancer::InstanceDecorator(const String& name, const PropertyDictionary& properties_,
  581. const DecoratorInstancerInterface& /*interface_*/)
  582. {
  583. const Property* p_angle = properties_.GetProperty(ids.angle);
  584. Array<const Property*, 2> p_position = {properties_.GetProperty(ids.position_x), properties_.GetProperty(ids.position_y)};
  585. const Property* p_color_stop_list = properties_.GetProperty(ids.color_stop_list);
  586. if (!p_angle || !p_position[0] || !p_position[1] || !p_color_stop_list)
  587. return nullptr;
  588. const float angle = ComputeAngle(p_angle->GetNumericValue());
  589. const Vector2Numeric position = ComputePosition(p_position);
  590. const bool repeating = (name == "repeating-conic-gradient");
  591. if (p_color_stop_list->unit != Unit::COLORSTOPLIST)
  592. return nullptr;
  593. const ColorStopList& color_stop_list = p_color_stop_list->value.GetReference<ColorStopList>();
  594. auto decorator = MakeShared<DecoratorConicGradient>();
  595. if (decorator->Initialise(repeating, angle, position, color_stop_list))
  596. return decorator;
  597. return nullptr;
  598. }
  599. } // namespace Rml