DecoratorGradient.cpp 27 KB

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