GradientPainting.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. /*
  2. * Copyright (c) 2022-2023, MacDue <macdue@dueutil.tech>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Math.h>
  7. #include <LibGfx/Gradients.h>
  8. #include <LibGfx/PaintStyle.h>
  9. #if defined(AK_COMPILER_GCC)
  10. # pragma GCC optimize("O3")
  11. #endif
  12. namespace Gfx {
  13. // Note: This file implements the CSS/Canvas gradients for LibWeb according to the spec.
  14. // Please do not make ad-hoc changes that may break spec compliance!
  15. float color_stop_step(ColorStop const& previous_stop, ColorStop const& next_stop, float position)
  16. {
  17. if (position < previous_stop.position)
  18. return 0;
  19. if (position > next_stop.position)
  20. return 1;
  21. // For any given point between the two color stops,
  22. // determine the point’s location as a percentage of the distance between the two color stops.
  23. // Let this percentage be P.
  24. auto stop_length = next_stop.position - previous_stop.position;
  25. // FIXME: Avoids NaNs... Still not quite correct?
  26. if (stop_length <= 0)
  27. return 1;
  28. auto p = (position - previous_stop.position) / stop_length;
  29. if (!next_stop.transition_hint.has_value())
  30. return p;
  31. if (*next_stop.transition_hint >= 1)
  32. return 0;
  33. if (*next_stop.transition_hint <= 0)
  34. return 1;
  35. // Let C, the color weighting at that point, be equal to P^(logH(.5)).
  36. auto c = AK::pow(p, AK::log<float>(0.5) / AK::log(*next_stop.transition_hint));
  37. // The color at that point is then a linear blend between the colors of the two color stops,
  38. // blending (1 - C) of the first stop and C of the second stop.
  39. return c;
  40. }
  41. class GradientLine {
  42. public:
  43. GradientLine(int gradient_length, ReadonlySpan<ColorStop> color_stops, Optional<float> repeat_length, AlphaType alpha_type = AlphaType::Premultiplied)
  44. : m_repeat_mode(repeat_length.has_value() ? RepeatMode::Repeat : RepeatMode::None)
  45. , m_start_offset(round_to<int>((repeating() ? color_stops.first().position : 0.0f) * gradient_length))
  46. , m_color_stops(color_stops)
  47. , m_alpha_type(alpha_type)
  48. {
  49. // Avoid generating excessive amounts of colors when the not enough shades to fill that length.
  50. auto necessary_length = min<int>((color_stops.size() - 1) * 255, gradient_length);
  51. m_sample_scale = float(necessary_length) / gradient_length;
  52. // Note: color_count will be < gradient_length for repeating gradients.
  53. auto color_count = round_to<int>(repeat_length.value_or(1.0f) * necessary_length);
  54. m_gradient_line_colors.resize(color_count);
  55. for (int loc = 0; loc < color_count; loc++) {
  56. auto relative_loc = float(loc + m_start_offset) / necessary_length;
  57. Color gradient_color = color_blend(color_stops[0].color, color_stops[1].color,
  58. color_stop_step(color_stops[0], color_stops[1], relative_loc));
  59. for (size_t i = 1; i < color_stops.size() - 1; i++) {
  60. gradient_color = color_blend(gradient_color, color_stops[i + 1].color,
  61. color_stop_step(color_stops[i], color_stops[i + 1], relative_loc));
  62. }
  63. m_gradient_line_colors[loc] = gradient_color;
  64. if (gradient_color.alpha() < 255)
  65. m_requires_blending = true;
  66. }
  67. }
  68. Color color_blend(Color a, Color b, float amount) const
  69. {
  70. // Note: color.mixed_with() performs premultiplied alpha mixing when necessary as defined in:
  71. // https://drafts.csswg.org/css-images/#coloring-gradient-line
  72. if (m_alpha_type == AlphaType::Premultiplied)
  73. return a.mixed_with(b, amount);
  74. return a.interpolate(b, amount);
  75. }
  76. Color get_color(i64 index) const
  77. {
  78. if (index < 0)
  79. return m_color_stops.first().color;
  80. if (index >= static_cast<i64>(m_gradient_line_colors.size()))
  81. return m_color_stops.last().color;
  82. return m_gradient_line_colors[index];
  83. }
  84. Color sample_color(float loc) const
  85. {
  86. if (!isfinite(loc))
  87. return Color();
  88. if (m_sample_scale != 1.0f)
  89. loc *= m_sample_scale;
  90. auto repeat_wrap_if_required = [&](i64 loc) {
  91. if (m_repeat_mode != RepeatMode::None) {
  92. auto current_loc = loc + m_start_offset;
  93. auto gradient_len = static_cast<i64>(m_gradient_line_colors.size());
  94. if (m_repeat_mode == RepeatMode::Repeat) {
  95. auto color_loc = current_loc % gradient_len;
  96. return color_loc < 0 ? gradient_len + color_loc : color_loc;
  97. } else if (m_repeat_mode == RepeatMode::Reflect) {
  98. auto color_loc = AK::abs(current_loc % gradient_len);
  99. auto repeats = current_loc / gradient_len;
  100. return (repeats & 1) ? gradient_len - color_loc : color_loc;
  101. }
  102. }
  103. return loc;
  104. };
  105. auto int_loc = static_cast<i64>(floor(loc));
  106. auto blend = loc - int_loc;
  107. auto color = get_color(repeat_wrap_if_required(int_loc));
  108. // Blend between the two neighboring colors (this fixes some nasty aliasing issues at small angles)
  109. if (blend >= 0.004f)
  110. color = color_blend(color, get_color(repeat_wrap_if_required(int_loc + 1)), blend);
  111. return color;
  112. }
  113. bool repeating() const
  114. {
  115. return m_repeat_mode != RepeatMode::None;
  116. }
  117. enum class RepeatMode {
  118. None,
  119. Repeat,
  120. Reflect
  121. };
  122. void set_repeat_mode(RepeatMode repeat_mode)
  123. {
  124. // Note: A gradient can be set to repeating without a repeat length.
  125. // The repeat length is used for CSS gradients but not for SVG gradients.
  126. m_repeat_mode = repeat_mode;
  127. }
  128. private:
  129. RepeatMode m_repeat_mode { RepeatMode::None };
  130. int m_start_offset { 0 };
  131. float m_sample_scale { 1 };
  132. ReadonlySpan<ColorStop> m_color_stops {};
  133. AlphaType m_alpha_type { AlphaType::Premultiplied };
  134. Vector<Color, 1024> m_gradient_line_colors;
  135. bool m_requires_blending = false;
  136. };
  137. template<typename TransformFunction>
  138. struct Gradient {
  139. Gradient(GradientLine gradient_line, TransformFunction transform_function)
  140. : m_gradient_line(move(gradient_line))
  141. , m_transform_function(move(transform_function))
  142. {
  143. }
  144. template<typename CoordinateType = int>
  145. auto sample_function()
  146. {
  147. return [this](Point<CoordinateType> point) {
  148. return m_gradient_line.sample_color(m_transform_function(point.x(), point.y()));
  149. };
  150. }
  151. GradientLine& gradient_line()
  152. {
  153. return m_gradient_line;
  154. }
  155. private:
  156. GradientLine m_gradient_line;
  157. TransformFunction m_transform_function;
  158. };
  159. static auto create_conic_gradient(ReadonlySpan<ColorStop> color_stops, FloatPoint center_point, float start_angle, Optional<float> repeat_length, AlphaType alpha_type = AlphaType::Premultiplied)
  160. {
  161. // FIXME: Do we need/want sub-degree accuracy for the gradient line?
  162. GradientLine gradient_line(360, color_stops, repeat_length, alpha_type);
  163. float normalized_start_angle = (360.0f - start_angle) + 90.0f;
  164. // The flooring can make gradients that want soft edges look worse, so only floor if we have hard edges.
  165. // Which makes sure the hard edge stay hard edges :^)
  166. bool should_floor_angles = false;
  167. for (size_t i = 0; i < color_stops.size() - 1; i++) {
  168. if (color_stops[i + 1].position - color_stops[i].position <= 0.01f) {
  169. should_floor_angles = true;
  170. break;
  171. }
  172. }
  173. return Gradient {
  174. move(gradient_line),
  175. [=](int x, int y) {
  176. auto point = FloatPoint { x, y } - center_point;
  177. // FIXME: We could probably get away with some approximation here:
  178. auto loc = fmod((AK::to_degrees(AK::atan2(point.y(), point.x())) + 360.0f + normalized_start_angle), 360.0f);
  179. return should_floor_angles ? floor(loc) : loc;
  180. }
  181. };
  182. }
  183. // The following implements the gradient fill/stoke styles for the HTML canvas: https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles
  184. static auto make_sample_non_relative(IntPoint draw_location, auto sample)
  185. {
  186. return [=, sample = move(sample)](IntPoint point) { return sample(point.translated(draw_location)); };
  187. }
  188. static auto make_linear_gradient_between_two_points(FloatPoint p0, FloatPoint p1, ReadonlySpan<ColorStop> color_stops, Optional<float> repeat_length)
  189. {
  190. auto delta = p1 - p0;
  191. auto angle = AK::atan2(delta.y(), delta.x());
  192. float sin_angle, cos_angle;
  193. AK::sincos(angle, sin_angle, cos_angle);
  194. int gradient_length = ceilf(p1.distance_from(p0));
  195. auto rotated_start_point_x = p0.x() * cos_angle - p0.y() * -sin_angle;
  196. return Gradient {
  197. GradientLine(gradient_length, color_stops, repeat_length, AlphaType::Unpremultiplied),
  198. [=](int x, int y) {
  199. return (x * cos_angle - y * -sin_angle) - rotated_start_point_x;
  200. }
  201. };
  202. }
  203. void CanvasLinearGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  204. {
  205. // If x0 = x1 and y0 = y1, then the linear gradient must paint nothing.
  206. if (m_p0 == m_p1)
  207. return;
  208. if (color_stops().is_empty())
  209. return;
  210. if (color_stops().size() < 2)
  211. return paint([this](IntPoint) { return color_stops().first().color; });
  212. auto linear_gradient = make_linear_gradient_between_two_points(m_p0, m_p1, color_stops(), repeat_length());
  213. paint(make_sample_non_relative(physical_bounding_box.location(), linear_gradient.sample_function()));
  214. }
  215. static GradientLine::RepeatMode svg_spread_method_to_repeat_mode(SVGGradientPaintStyle::SpreadMethod spread_method)
  216. {
  217. switch (spread_method) {
  218. case SVGGradientPaintStyle::SpreadMethod::Pad:
  219. return GradientLine::RepeatMode::None;
  220. case SVGGradientPaintStyle::SpreadMethod::Reflect:
  221. return GradientLine::RepeatMode::Reflect;
  222. case SVGGradientPaintStyle::SpreadMethod::Repeat:
  223. return GradientLine::RepeatMode::Repeat;
  224. default:
  225. VERIFY_NOT_REACHED();
  226. }
  227. }
  228. void SVGGradientPaintStyle::set_gradient_transform(AffineTransform transform)
  229. {
  230. // Note: The scaling is removed so enough points on the gradient line are generated.
  231. // Otherwise, if you scale a tiny path the gradient looks pixelated.
  232. m_scale = 1.0f;
  233. if (auto inverse = transform.inverse(); inverse.has_value()) {
  234. auto transform_scale = transform.scale();
  235. m_scale = max(transform_scale.x(), transform_scale.y());
  236. m_inverse_transform = AffineTransform {}.scale(m_scale, m_scale).multiply(*inverse);
  237. } else {
  238. m_inverse_transform = OptionalNone {};
  239. }
  240. }
  241. void SVGLinearGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  242. {
  243. if (color_stops().is_empty())
  244. return;
  245. // If ‘x1’ = ‘x2’ and ‘y1’ = ‘y2’, then the area to be painted will be painted as
  246. // a single color using the color and opacity of the last gradient stop.
  247. if (m_p0 == m_p1)
  248. return paint([this](IntPoint) { return color_stops().last().color; });
  249. if (color_stops().size() < 2)
  250. return paint([this](IntPoint) { return color_stops().first().color; });
  251. float scale = gradient_transform_scale();
  252. auto linear_gradient = make_linear_gradient_between_two_points(
  253. m_p0.scaled(scale, scale), m_p1.scaled(scale, scale),
  254. color_stops(), repeat_length());
  255. linear_gradient.gradient_line().set_repeat_mode(
  256. svg_spread_method_to_repeat_mode(spread_method()));
  257. paint([&, sampler = linear_gradient.sample_function<float>()](IntPoint target_point) {
  258. auto point = target_point.translated(physical_bounding_box.location()).to_type<float>();
  259. if (auto inverse_transform = scale_adjusted_inverse_gradient_transform(); inverse_transform.has_value())
  260. point = inverse_transform->map(point);
  261. return sampler(point);
  262. });
  263. }
  264. void CanvasConicGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  265. {
  266. if (color_stops().is_empty())
  267. return;
  268. if (color_stops().size() < 2)
  269. return paint([this](IntPoint) { return color_stops().first().color; });
  270. // Follows the same rendering rule as CSS 'conic-gradient' and it is equivalent to CSS
  271. // 'conic-gradient(from adjustedStartAnglerad at xpx ypx, angularColorStopList)'.
  272. // Here:
  273. // adjustedStartAngle is given by startAngle + π/2;
  274. auto conic_gradient = create_conic_gradient(color_stops(), m_center, m_start_angle + 90.0f, repeat_length(), AlphaType::Unpremultiplied);
  275. paint(make_sample_non_relative(physical_bounding_box.location(), conic_gradient.sample_function()));
  276. }
  277. static auto create_radial_gradient_between_two_circles(Gfx::FloatPoint start_center, float start_radius, Gfx::FloatPoint end_center, float end_radius, ReadonlySpan<ColorStop> color_stops, Optional<float> repeat_length)
  278. {
  279. bool reverse_gradient = end_radius < start_radius;
  280. if (reverse_gradient) {
  281. swap(end_radius, start_radius);
  282. swap(end_center, start_center);
  283. }
  284. // FIXME: Handle the start_radius == end_radius special case separately.
  285. // This hack is not quite correct.
  286. if (end_radius - start_radius < 1)
  287. end_radius += 1;
  288. // Spec steps: Useless for writing an actual implementation (give it a go :P):
  289. //
  290. // 2. Let x(ω) = (x1-x0)ω + x0
  291. // Let y(ω) = (y1-y0)ω + y0
  292. // Let r(ω) = (r1-r0)ω + r0
  293. // Let the color at ω be the color at that position on the gradient
  294. // (with the colors coming from the interpolation and extrapolation described above).
  295. //
  296. // 3. For all values of ω where r(ω) > 0, starting with the value of ω nearest to positive infinity and
  297. // ending with the value of ω nearest to negative infinity, draw the circumference of the circle with
  298. // radius r(ω) at position (x(ω), y(ω)), with the color at ω, but only painting on the parts of the
  299. // bitmap that have not yet been painted on by earlier circles in this step for this rendering of the gradient.
  300. auto center_dist = end_center.distance_from(start_center);
  301. bool inner_contained = ((center_dist + start_radius) < end_radius);
  302. auto start_point = start_center;
  303. if (start_radius != 0) {
  304. // Set the start point to the focal point.
  305. auto f = end_radius / (end_radius - start_radius);
  306. auto one_minus_f = 1 - f;
  307. start_point = start_center.scaled(f) + end_center.scaled(one_minus_f);
  308. }
  309. // This is just an approximate upperbound (the gradient line class will shorten this if necessary).
  310. int gradient_length = AK::ceil(center_dist + end_radius + start_radius);
  311. GradientLine gradient_line(gradient_length, color_stops, repeat_length, AlphaType::Unpremultiplied);
  312. // If you can simplify this please do, this is "best guess" implementation due to lack of specification.
  313. // It was implemented to visually match chrome/firefox in all cases:
  314. // - Start circle inside end circle
  315. // - Start circle outside end circle
  316. // - Start circle radius == end circle radius
  317. // - Start circle larger than end circle (inside end circle)
  318. // - Start circle larger than end circle (outside end circle)
  319. // - Start circle or end circle radius == 0
  320. auto circle_distance_finder = [=](auto radius, auto center) {
  321. auto radius2 = radius * radius;
  322. auto delta = center - start_point;
  323. auto delta_xy = delta.x() * delta.y();
  324. auto dx2_factor = radius2 - delta.y() * delta.y();
  325. auto dy2_factor = radius2 - delta.x() * delta.x();
  326. return [=](bool positive_root, auto vec) {
  327. // This works out the distance to the nearest point on the circle
  328. // in the direction of the "vec" vector.
  329. auto dx2 = vec.x() * vec.x();
  330. auto dy2 = vec.y() * vec.y();
  331. auto root = sqrtf(dx2 * dx2_factor + dy2 * dy2_factor
  332. + 2 * vec.x() * vec.y() * delta_xy);
  333. auto dot = vec.x() * delta.x() + vec.y() * delta.y();
  334. return ((positive_root ? root : -root) + dot) / (dx2 + dy2);
  335. };
  336. };
  337. auto end_circle_dist = circle_distance_finder(end_radius, end_center);
  338. auto start_circle_dist = [=, dist = circle_distance_finder(start_radius, start_center)](bool positive_root, auto vec) {
  339. if (start_center == start_point)
  340. return start_radius;
  341. return dist(positive_root, vec);
  342. };
  343. return Gradient {
  344. move(gradient_line),
  345. [=](float x, float y) {
  346. auto loc = [&] {
  347. FloatPoint point { x, y };
  348. // Add a little to avoid division by zero at the focal point.
  349. if (point == start_point)
  350. point += FloatPoint { 0.001f, 0.001f };
  351. // The "vec" (unit) vector points from the focal point to the current point.
  352. auto dist = point.distance_from(start_point);
  353. auto vec = (point - start_point) / dist;
  354. bool use_positive_root = inner_contained || reverse_gradient;
  355. auto dist_end = end_circle_dist(use_positive_root, vec);
  356. auto dist_start = start_circle_dist(use_positive_root, vec);
  357. // FIXME: Returning nan is a hack for "Don't paint me!"
  358. if (dist_end < 0)
  359. return AK::NaN<float>;
  360. if (dist_end - dist_start < 0)
  361. return float(gradient_length);
  362. return (dist - dist_start) / (dist_end - dist_start);
  363. }();
  364. if (reverse_gradient)
  365. loc = 1.0f - loc;
  366. return loc * gradient_length;
  367. }
  368. };
  369. }
  370. void CanvasRadialGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  371. {
  372. // 1. If x0 = x1 and y0 = y1 and r0 = r1, then the radial gradient must paint nothing. Return.
  373. if (m_start_center == m_end_center && m_start_radius == m_end_radius)
  374. return;
  375. if (color_stops().is_empty())
  376. return;
  377. if (color_stops().size() < 2)
  378. return paint([this](IntPoint) { return color_stops().first().color; });
  379. if (m_end_radius == 0 && m_start_radius == 0)
  380. return;
  381. auto radial_gradient = create_radial_gradient_between_two_circles(m_start_center, m_start_radius, m_end_center, m_end_radius, color_stops(), repeat_length());
  382. paint(make_sample_non_relative(physical_bounding_box.location(), radial_gradient.sample_function()));
  383. }
  384. void SVGRadialGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  385. {
  386. // FIXME: Ensure this handles all the edge cases of SVG gradients.
  387. if (color_stops().is_empty())
  388. return;
  389. if (color_stops().size() < 2 || (m_end_radius == 0 && m_start_radius == 0))
  390. return paint([this](IntPoint) { return color_stops().last().color; });
  391. float scale = gradient_transform_scale();
  392. auto radial_gradient = create_radial_gradient_between_two_circles(
  393. m_start_center.scaled(scale, scale), m_start_radius * scale, m_end_center.scaled(scale, scale), m_end_radius * scale,
  394. color_stops(), repeat_length());
  395. radial_gradient.gradient_line().set_repeat_mode(
  396. svg_spread_method_to_repeat_mode(spread_method()));
  397. paint([&, sampler = radial_gradient.sample_function<float>()](IntPoint target_point) {
  398. auto point = target_point.translated(physical_bounding_box.location()).to_type<float>();
  399. if (auto inverse_transform = scale_adjusted_inverse_gradient_transform(); inverse_transform.has_value())
  400. point = inverse_transform->map(point);
  401. return sampler(point);
  402. });
  403. }
  404. }