GradientPainting.cpp 19 KB

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