GradientPainting.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. #include <LibGfx/Painter.h>
  10. #if defined(AK_COMPILER_GCC)
  11. # pragma GCC optimize("O3")
  12. #endif
  13. namespace Gfx {
  14. // Note: This file implements the CSS/Canvas gradients for LibWeb according to the spec.
  15. // Please do not make ad-hoc changes that may break spec compliance!
  16. static float color_stop_step(ColorStop const& previous_stop, ColorStop const& next_stop, float position)
  17. {
  18. if (position < previous_stop.position)
  19. return 0;
  20. if (position > next_stop.position)
  21. return 1;
  22. // For any given point between the two color stops,
  23. // determine the point’s location as a percentage of the distance between the two color stops.
  24. // Let this percentage be P.
  25. auto stop_length = next_stop.position - previous_stop.position;
  26. // FIXME: Avoids NaNs... Still not quite correct?
  27. if (stop_length <= 0)
  28. return 1;
  29. auto p = (position - previous_stop.position) / stop_length;
  30. if (!next_stop.transition_hint.has_value())
  31. return p;
  32. if (*next_stop.transition_hint >= 1)
  33. return 0;
  34. if (*next_stop.transition_hint <= 0)
  35. return 1;
  36. // Let C, the color weighting at that point, be equal to P^(logH(.5)).
  37. auto c = AK::pow(p, AK::log<float>(0.5) / AK::log(*next_stop.transition_hint));
  38. // The color at that point is then a linear blend between the colors of the two color stops,
  39. // blending (1 - C) of the first stop and C of the second stop.
  40. return c;
  41. }
  42. enum class UsePremultipliedAlpha {
  43. Yes,
  44. No
  45. };
  46. class GradientLine {
  47. public:
  48. GradientLine(int gradient_length, Span<ColorStop const> color_stops, Optional<float> repeat_length, UsePremultipliedAlpha use_premultiplied_alpha = UsePremultipliedAlpha::Yes)
  49. : m_repeating { repeat_length.has_value() }
  50. , m_start_offset { round_to<int>((m_repeating ? color_stops.first().position : 0.0f) * gradient_length) }
  51. {
  52. // Avoid generating excessive amounts of colors when the not enough shades to fill that length.
  53. auto necessary_length = min<int>((color_stops.size() - 1) * 255, gradient_length);
  54. m_sample_scale = float(necessary_length) / gradient_length;
  55. // Note: color_count will be < gradient_length for repeating gradients.
  56. auto color_count = round_to<int>(repeat_length.value_or(1.0f) * necessary_length);
  57. m_gradient_line_colors.resize(color_count);
  58. auto color_blend = [&](Color a, Color b, float amount) {
  59. // Note: color.mixed_with() performs premultiplied alpha mixing when necessary as defined in:
  60. // https://drafts.csswg.org/css-images/#coloring-gradient-line
  61. if (use_premultiplied_alpha == UsePremultipliedAlpha::Yes)
  62. return a.mixed_with(b, amount);
  63. return a.interpolate(b, amount);
  64. };
  65. for (int loc = 0; loc < color_count; loc++) {
  66. auto relative_loc = float(loc + m_start_offset) / necessary_length;
  67. Color gradient_color = color_blend(color_stops[0].color, color_stops[1].color,
  68. color_stop_step(color_stops[0], color_stops[1], relative_loc));
  69. for (size_t i = 1; i < color_stops.size() - 1; i++) {
  70. gradient_color = color_blend(gradient_color, color_stops[i + 1].color,
  71. color_stop_step(color_stops[i], color_stops[i + 1], relative_loc));
  72. }
  73. m_gradient_line_colors[loc] = gradient_color;
  74. if (gradient_color.alpha() < 255)
  75. m_requires_blending = true;
  76. }
  77. }
  78. Color get_color(i64 index) const
  79. {
  80. return m_gradient_line_colors[clamp(index, 0, m_gradient_line_colors.size() - 1)];
  81. }
  82. Color sample_color(float loc) const
  83. {
  84. if (!isfinite(loc))
  85. return Color();
  86. if (m_sample_scale != 1.0f)
  87. loc *= m_sample_scale;
  88. auto repeat_wrap_if_required = [&](i64 loc) {
  89. if (m_repeating)
  90. return (loc + m_start_offset) % static_cast<i64>(m_gradient_line_colors.size());
  91. return loc;
  92. };
  93. auto int_loc = static_cast<i64>(floor(loc));
  94. auto blend = loc - int_loc;
  95. auto color = get_color(repeat_wrap_if_required(int_loc));
  96. // Blend between the two neighbouring colors (this fixes some nasty aliasing issues at small angles)
  97. if (blend >= 0.004f)
  98. color = color.mixed_with(get_color(repeat_wrap_if_required(int_loc + 1)), blend);
  99. return color;
  100. }
  101. void paint_into_physical_rect(Painter& painter, IntRect rect, auto location_transform)
  102. {
  103. auto clipped_rect = rect.intersected(painter.clip_rect() * painter.scale());
  104. auto start_offset = clipped_rect.location() - rect.location();
  105. for (int y = 0; y < clipped_rect.height(); y++) {
  106. for (int x = 0; x < clipped_rect.width(); x++) {
  107. auto pixel = sample_color(location_transform(x + start_offset.x(), y + start_offset.y()));
  108. painter.set_physical_pixel(clipped_rect.location().translated(x, y), pixel, m_requires_blending);
  109. }
  110. }
  111. }
  112. private:
  113. bool m_repeating;
  114. int m_start_offset;
  115. float m_sample_scale { 1 };
  116. Vector<Color, 1024> m_gradient_line_colors;
  117. bool m_requires_blending = false;
  118. };
  119. template<typename TransformFunction>
  120. struct Gradient {
  121. Gradient(GradientLine gradient_line, TransformFunction transform_function)
  122. : m_gradient_line(move(gradient_line))
  123. , m_transform_function(move(transform_function))
  124. {
  125. }
  126. void paint(Painter& painter, IntRect rect)
  127. {
  128. m_gradient_line.paint_into_physical_rect(painter, rect, m_transform_function);
  129. }
  130. PaintStyle::SamplerFunction sample_function()
  131. {
  132. return [this](IntPoint point) {
  133. return m_gradient_line.sample_color(m_transform_function(point.x(), point.y()));
  134. };
  135. }
  136. private:
  137. GradientLine m_gradient_line;
  138. TransformFunction m_transform_function;
  139. };
  140. static auto create_linear_gradient(IntRect const& physical_rect, Span<ColorStop const> const& color_stops, float angle, Optional<float> repeat_length)
  141. {
  142. float normalized_angle = normalized_gradient_angle_radians(angle);
  143. float sin_angle, cos_angle;
  144. AK::sincos(normalized_angle, sin_angle, cos_angle);
  145. // Full length of the gradient
  146. auto gradient_length = calculate_gradient_length(physical_rect.size(), sin_angle, cos_angle);
  147. IntPoint offset { cos_angle * (gradient_length / 2), sin_angle * (gradient_length / 2) };
  148. auto center = physical_rect.translated(-physical_rect.location()).center();
  149. auto start_point = center - offset;
  150. // Rotate gradient line to be horizontal
  151. auto rotated_start_point_x = start_point.x() * cos_angle - start_point.y() * -sin_angle;
  152. GradientLine gradient_line(gradient_length, color_stops, repeat_length);
  153. return Gradient {
  154. move(gradient_line),
  155. [=](int x, int y) {
  156. return (x * cos_angle - (physical_rect.height() - y) * -sin_angle) - rotated_start_point_x;
  157. }
  158. };
  159. }
  160. static auto create_conic_gradient(Span<ColorStop const> const& color_stops, FloatPoint center_point, float start_angle, Optional<float> repeat_length, UsePremultipliedAlpha use_premultiplied_alpha = UsePremultipliedAlpha::Yes)
  161. {
  162. // FIXME: Do we need/want sub-degree accuracy for the gradient line?
  163. GradientLine gradient_line(360, color_stops, repeat_length, use_premultiplied_alpha);
  164. float normalized_start_angle = (360.0f - start_angle) + 90.0f;
  165. // The flooring can make gradients that want soft edges look worse, so only floor if we have hard edges.
  166. // Which makes sure the hard edge stay hard edges :^)
  167. bool should_floor_angles = false;
  168. for (size_t i = 0; i < color_stops.size() - 1; i++) {
  169. if (color_stops[i + 1].position - color_stops[i].position <= 0.01f) {
  170. should_floor_angles = true;
  171. break;
  172. }
  173. }
  174. return Gradient {
  175. move(gradient_line),
  176. [=](int x, int y) {
  177. auto point = FloatPoint { x, y } - center_point;
  178. // FIXME: We could probably get away with some approximation here:
  179. auto loc = fmod((AK::atan2(point.y(), point.x()) * 180.0f / AK::Pi<float> + 360.0f + normalized_start_angle), 360.0f);
  180. return should_floor_angles ? floor(loc) : loc;
  181. }
  182. };
  183. }
  184. static auto create_radial_gradient(IntRect const& physical_rect, Span<ColorStop const> const& color_stops, IntPoint center, IntSize size, Optional<float> repeat_length)
  185. {
  186. // A conservative guesstimate on how many colors we need to generate:
  187. auto max_dimension = max(physical_rect.width(), physical_rect.height());
  188. auto max_visible_gradient = max(max_dimension / 2, min(size.width(), max_dimension));
  189. GradientLine gradient_line(max_visible_gradient, color_stops, repeat_length);
  190. auto center_point = FloatPoint { center }.translated(0.5, 0.5);
  191. return Gradient {
  192. move(gradient_line),
  193. [=](int x, int y) {
  194. // FIXME: See if there's a more efficient calculation we do there :^)
  195. auto point = FloatPoint(x, y) - center_point;
  196. auto gradient_x = point.x() / size.width();
  197. auto gradient_y = point.y() / size.height();
  198. return AK::sqrt(gradient_x * gradient_x + gradient_y * gradient_y) * max_visible_gradient;
  199. }
  200. };
  201. }
  202. void Painter::fill_rect_with_linear_gradient(IntRect const& rect, Span<ColorStop const> const& color_stops, float angle, Optional<float> repeat_length)
  203. {
  204. auto a_rect = to_physical(rect);
  205. if (a_rect.intersected(clip_rect() * scale()).is_empty())
  206. return;
  207. auto linear_gradient = create_linear_gradient(a_rect, color_stops, angle, repeat_length);
  208. linear_gradient.paint(*this, a_rect);
  209. }
  210. static FloatPoint pixel_center(IntPoint point)
  211. {
  212. return point.to_type<float>().translated(0.5f, 0.5f);
  213. }
  214. void Painter::fill_rect_with_conic_gradient(IntRect const& rect, Span<ColorStop const> const& color_stops, IntPoint center, float start_angle, Optional<float> repeat_length)
  215. {
  216. auto a_rect = to_physical(rect);
  217. if (a_rect.intersected(clip_rect() * scale()).is_empty())
  218. return;
  219. // Translate position/center to the center of the pixel (avoids some funky painting)
  220. auto center_point = pixel_center(center * scale());
  221. auto conic_gradient = create_conic_gradient(color_stops, center_point, start_angle, repeat_length);
  222. conic_gradient.paint(*this, a_rect);
  223. }
  224. void Painter::fill_rect_with_radial_gradient(IntRect const& rect, Span<ColorStop const> const& color_stops, IntPoint center, IntSize size, Optional<float> repeat_length)
  225. {
  226. auto a_rect = to_physical(rect);
  227. if (a_rect.intersected(clip_rect() * scale()).is_empty())
  228. return;
  229. auto radial_gradient = create_radial_gradient(a_rect, color_stops, center * scale(), size * scale(), repeat_length);
  230. radial_gradient.paint(*this, a_rect);
  231. }
  232. // TODO: Figure out how to handle scale() here... Not important while not supported by fill_path()
  233. void LinearGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  234. {
  235. VERIFY(color_stops().size() > 2);
  236. auto linear_gradient = create_linear_gradient(physical_bounding_box, color_stops(), m_angle, repeat_length());
  237. paint(linear_gradient.sample_function());
  238. }
  239. void ConicGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  240. {
  241. VERIFY(color_stops().size() > 2);
  242. (void)physical_bounding_box;
  243. auto conic_gradient = create_conic_gradient(color_stops(), pixel_center(m_center), m_start_angle, repeat_length());
  244. paint(conic_gradient.sample_function());
  245. }
  246. void RadialGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  247. {
  248. VERIFY(color_stops().size() > 2);
  249. auto radial_gradient = create_radial_gradient(physical_bounding_box, color_stops(), m_center, m_size, repeat_length());
  250. paint(radial_gradient.sample_function());
  251. }
  252. // The following implements the gradient fill/stoke styles for the HTML canvas: https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles
  253. static auto make_sample_non_relative(IntPoint draw_location, auto sample)
  254. {
  255. return [=, sample = move(sample)](IntPoint point) { return sample(point.translated(draw_location)); };
  256. }
  257. void CanvasLinearGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  258. {
  259. // If x0 = x1 and y0 = y1, then the linear gradient must paint nothing.
  260. if (m_p0 == m_p1)
  261. return;
  262. if (color_stops().is_empty())
  263. return;
  264. if (color_stops().size() < 2)
  265. return paint([this](IntPoint) { return color_stops().first().color; });
  266. auto delta = m_p1 - m_p0;
  267. auto angle = AK::atan2(delta.y(), delta.x());
  268. float sin_angle, cos_angle;
  269. AK::sincos(angle, sin_angle, cos_angle);
  270. int gradient_length = ceilf(m_p1.distance_from(m_p0));
  271. auto rotated_start_point_x = m_p0.x() * cos_angle - m_p0.y() * -sin_angle;
  272. Gradient linear_gradient {
  273. GradientLine(gradient_length, color_stops(), repeat_length(), UsePremultipliedAlpha::No),
  274. [=](int x, int y) {
  275. return (x * cos_angle - y * -sin_angle) - rotated_start_point_x;
  276. }
  277. };
  278. paint(make_sample_non_relative(physical_bounding_box.location(), linear_gradient.sample_function()));
  279. }
  280. void CanvasConicGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  281. {
  282. if (color_stops().is_empty())
  283. return;
  284. if (color_stops().size() < 2)
  285. return paint([this](IntPoint) { return color_stops().first().color; });
  286. // Follows the same rendering rule as CSS 'conic-gradient' and it is equivalent to CSS
  287. // 'conic-gradient(from adjustedStartAnglerad at xpx ypx, angularColorStopList)'.
  288. // Here:
  289. // adjustedStartAngle is given by startAngle + π/2;
  290. auto conic_gradient = create_conic_gradient(color_stops(), m_center, m_start_angle + 90.0f, repeat_length(), UsePremultipliedAlpha::No);
  291. paint(make_sample_non_relative(physical_bounding_box.location(), conic_gradient.sample_function()));
  292. }
  293. void CanvasRadialGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  294. {
  295. // 1. If x0 = x1 and y0 = y1 and r0 = r1, then the radial gradient must paint nothing. Return.
  296. if (m_start_center == m_end_center && m_start_radius == m_end_radius)
  297. return;
  298. if (color_stops().is_empty())
  299. return;
  300. if (color_stops().size() < 2)
  301. return paint([this](IntPoint) { return color_stops().first().color; });
  302. auto start_radius = m_start_radius;
  303. auto start_center = m_start_center;
  304. auto end_radius = m_end_radius;
  305. auto end_center = m_end_center;
  306. if (end_radius == 0 && start_radius == 0)
  307. return;
  308. if (fabs(start_radius - end_radius) < 1)
  309. start_radius += 1;
  310. // Needed for the start circle > end circle case, but FIXME, this seems kind of hacky.
  311. bool reverse_gradient = end_radius < start_radius;
  312. if (reverse_gradient) {
  313. swap(end_radius, start_radius);
  314. swap(end_center, start_center);
  315. }
  316. // Spec steps: Useless for writing an actual implementation (give it a go :P):
  317. //
  318. // 2. Let x(ω) = (x1-x0)ω + x0
  319. // Let y(ω) = (y1-y0)ω + y0
  320. // Let r(ω) = (r1-r0)ω + r0
  321. // Let the color at ω be the color at that position on the gradient
  322. // (with the colors coming from the interpolation and extrapolation described above).
  323. //
  324. // 3. For all values of ω where r(ω) > 0, starting with the value of ω nearest to positive infinity and
  325. // ending with the value of ω nearest to negative infinity, draw the circumference of the circle with
  326. // radius r(ω) at position (x(ω), y(ω)), with the color at ω, but only painting on the parts of the
  327. // bitmap that have not yet been painted on by earlier circles in this step for this rendering of the gradient.
  328. auto center_delta = end_center - start_center;
  329. auto center_dist = end_center.distance_from(start_center);
  330. bool inner_contained = ((center_dist + start_radius) < end_radius);
  331. auto start_point = start_center;
  332. if (!inner_contained) {
  333. // The intersection point of the direct common tangents of the start/end circles.
  334. start_point = FloatPoint {
  335. (start_radius * end_center.x() - end_radius * start_center.x()) / (start_radius - end_radius),
  336. (start_radius * end_center.y() - end_radius * start_center.y()) / (start_radius - end_radius)
  337. };
  338. }
  339. // This is just an approximate upperbound (the gradient line class will shorten this if necessary).
  340. int gradient_length = center_dist + end_radius + start_radius;
  341. GradientLine gradient_line(gradient_length, color_stops(), repeat_length(), UsePremultipliedAlpha::No);
  342. auto radius2 = end_radius * end_radius;
  343. center_delta = end_center - start_point;
  344. auto dx2_factor = (radius2 - center_delta.y() * center_delta.y());
  345. auto dy2_factor = (radius2 - center_delta.x() * center_delta.x());
  346. // If you can simplify this please do, this is "best guess" implementation due to lack of specification.
  347. // It was implemented to visually match chrome/firefox in all cases:
  348. // - Start circle inside end circle
  349. // - Start circle outside end circle
  350. // - Start circle radius == end circle radius
  351. // - Start circle larger than end circle (inside end circle)
  352. // - Start circle larger than end circle (outside end circle)
  353. // - Start cirlce or end circle radius == 0
  354. Gradient radial_gradient {
  355. move(gradient_line),
  356. [=](int x, int y) {
  357. auto get_gradient_location = [&] {
  358. FloatPoint point { x, y };
  359. auto dist = point.distance_from(start_point);
  360. if (dist == 0)
  361. return 0.0f;
  362. auto vec = (point - start_point) / dist;
  363. auto dx2 = vec.x() * vec.x();
  364. auto dy2 = vec.y() * vec.y();
  365. // This works out the distance to the nearest point on the end circle in the direction of the "vec" vector.
  366. // The "vec" vector points from the center of the start circle to the current point.
  367. auto root = sqrtf(dx2 * dx2_factor + dy2 * dy2_factor
  368. + 2 * vec.x() * vec.y() * center_delta.x() * center_delta.y());
  369. auto dot = vec.x() * center_delta.x() + vec.y() * center_delta.y();
  370. // Note: When reversed we always want the farthest point
  371. auto edge_dist = (((inner_contained || reverse_gradient ? root : -root) + dot) / (dx2 + dy2));
  372. auto start_offset = inner_contained ? start_radius : (edge_dist / end_radius) * start_radius;
  373. // FIXME: Returning nan is a hack for "Don't paint me!"
  374. if (edge_dist < 0)
  375. return AK::NaN<float>;
  376. if (edge_dist - start_offset < 0)
  377. return float(gradient_length);
  378. return ((dist - start_offset) / (edge_dist - start_offset));
  379. };
  380. auto loc = get_gradient_location();
  381. if (reverse_gradient)
  382. loc = 1.0f - loc;
  383. return loc * gradient_length;
  384. }
  385. };
  386. paint(make_sample_non_relative(physical_bounding_box.location(), radial_gradient.sample_function()));
  387. }
  388. }