GradientPainting.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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, Optional<float> rotation_angle = {})
  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. AffineTransform rotation_transform;
  201. if (rotation_angle.has_value()) {
  202. auto angle_as_radians = rotation_angle.value() * (AK::Pi<float> / 180);
  203. rotation_transform.rotate_radians(angle_as_radians);
  204. }
  205. return Gradient {
  206. move(gradient_line),
  207. [=](int x, int y) {
  208. // FIXME: See if there's a more efficient calculation we do there :^)
  209. auto point = FloatPoint(x, y) - center_point;
  210. if (rotation_angle.has_value())
  211. point.transform_by(rotation_transform);
  212. auto gradient_x = point.x() / size.width();
  213. auto gradient_y = point.y() / size.height();
  214. return AK::sqrt(gradient_x * gradient_x + gradient_y * gradient_y) * max_visible_gradient;
  215. }
  216. };
  217. }
  218. void Painter::fill_rect_with_linear_gradient(IntRect const& rect, ReadonlySpan<ColorStop> color_stops, float angle, Optional<float> repeat_length)
  219. {
  220. auto a_rect = to_physical(rect);
  221. if (a_rect.intersected(clip_rect() * scale()).is_empty())
  222. return;
  223. auto linear_gradient = create_linear_gradient(a_rect, color_stops, angle, repeat_length);
  224. linear_gradient.paint(*this, a_rect);
  225. }
  226. static FloatPoint pixel_center(IntPoint point)
  227. {
  228. return point.to_type<float>().translated(0.5f, 0.5f);
  229. }
  230. void Painter::fill_rect_with_conic_gradient(IntRect const& rect, ReadonlySpan<ColorStop> color_stops, IntPoint center, float start_angle, Optional<float> repeat_length)
  231. {
  232. auto a_rect = to_physical(rect);
  233. if (a_rect.intersected(clip_rect() * scale()).is_empty())
  234. return;
  235. // Translate position/center to the center of the pixel (avoids some funky painting)
  236. auto center_point = pixel_center(center * scale());
  237. auto conic_gradient = create_conic_gradient(color_stops, center_point, start_angle, repeat_length);
  238. conic_gradient.paint(*this, a_rect);
  239. }
  240. void Painter::fill_rect_with_radial_gradient(IntRect const& rect, ReadonlySpan<ColorStop> color_stops, IntPoint center, IntSize size, Optional<float> repeat_length, Optional<float> rotation_angle)
  241. {
  242. auto a_rect = to_physical(rect);
  243. if (a_rect.intersected(clip_rect() * scale()).is_empty())
  244. return;
  245. auto radial_gradient = create_radial_gradient(a_rect, color_stops, center * scale(), size * scale(), repeat_length, rotation_angle);
  246. radial_gradient.paint(*this, a_rect);
  247. }
  248. // TODO: Figure out how to handle scale() here... Not important while not supported by fill_path()
  249. void LinearGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  250. {
  251. VERIFY(color_stops().size() > 2);
  252. auto linear_gradient = create_linear_gradient(physical_bounding_box, color_stops(), m_angle, repeat_length());
  253. paint(linear_gradient.sample_function());
  254. }
  255. void ConicGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  256. {
  257. VERIFY(color_stops().size() > 2);
  258. (void)physical_bounding_box;
  259. auto conic_gradient = create_conic_gradient(color_stops(), pixel_center(m_center), m_start_angle, repeat_length());
  260. paint(conic_gradient.sample_function());
  261. }
  262. void RadialGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  263. {
  264. VERIFY(color_stops().size() > 2);
  265. auto radial_gradient = create_radial_gradient(physical_bounding_box, color_stops(), m_center, m_size, repeat_length());
  266. paint(radial_gradient.sample_function());
  267. }
  268. // The following implements the gradient fill/stoke styles for the HTML canvas: https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles
  269. static auto make_sample_non_relative(IntPoint draw_location, auto sample)
  270. {
  271. return [=, sample = move(sample)](IntPoint point) { return sample(point.translated(draw_location)); };
  272. }
  273. static auto make_linear_gradient_between_two_points(FloatPoint p0, FloatPoint p1, ReadonlySpan<ColorStop> color_stops, Optional<float> repeat_length)
  274. {
  275. auto delta = p1 - 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(p1.distance_from(p0));
  280. auto rotated_start_point_x = p0.x() * cos_angle - p0.y() * -sin_angle;
  281. return 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. }
  288. void CanvasLinearGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  289. {
  290. // If x0 = x1 and y0 = y1, then the linear gradient must paint nothing.
  291. if (m_p0 == m_p1)
  292. return;
  293. if (color_stops().is_empty())
  294. return;
  295. if (color_stops().size() < 2)
  296. return paint([this](IntPoint) { return color_stops().first().color; });
  297. auto linear_gradient = make_linear_gradient_between_two_points(m_p0, m_p1, color_stops(), repeat_length());
  298. paint(make_sample_non_relative(physical_bounding_box.location(), linear_gradient.sample_function()));
  299. }
  300. void SVGLinearGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  301. {
  302. if (color_stops().is_empty())
  303. return;
  304. // If ‘x1’ = ‘x2’ and ‘y1’ = ‘y2’, then the area to be painted will be painted as
  305. // a single color using the color and opacity of the last gradient stop.
  306. if (m_p0 == m_p1)
  307. return paint([this](IntPoint) { return color_stops().last().color; });
  308. if (color_stops().size() < 2)
  309. return paint([this](IntPoint) { return color_stops().first().color; });
  310. // Note: The scaling is removed so enough points on the gradient line are generated.
  311. // Otherwise, if you scale a tiny path the gradient looks pixelated.
  312. FloatPoint scale { 1, 1 };
  313. auto sample_transform = gradient_transform().map([&](auto& transform) {
  314. if (auto inverse = transform.inverse(); inverse.has_value()) {
  315. scale = transform.scale();
  316. return Gfx::AffineTransform {}.scale(scale).multiply(*inverse);
  317. }
  318. return Gfx::AffineTransform {};
  319. });
  320. auto linear_gradient = make_linear_gradient_between_two_points(m_p0.scaled(scale), m_p1.scaled(scale), color_stops(), repeat_length());
  321. paint([&, sampler = linear_gradient.sample_function()](auto point) {
  322. point.translate_by(physical_bounding_box.location());
  323. if (sample_transform.has_value())
  324. point = sample_transform->map(point);
  325. return sampler(point);
  326. });
  327. }
  328. void CanvasConicGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  329. {
  330. if (color_stops().is_empty())
  331. return;
  332. if (color_stops().size() < 2)
  333. return paint([this](IntPoint) { return color_stops().first().color; });
  334. // Follows the same rendering rule as CSS 'conic-gradient' and it is equivalent to CSS
  335. // 'conic-gradient(from adjustedStartAnglerad at xpx ypx, angularColorStopList)'.
  336. // Here:
  337. // adjustedStartAngle is given by startAngle + π/2;
  338. auto conic_gradient = create_conic_gradient(color_stops(), m_center, m_start_angle + 90.0f, repeat_length(), UsePremultipliedAlpha::No);
  339. paint(make_sample_non_relative(physical_bounding_box.location(), conic_gradient.sample_function()));
  340. }
  341. void CanvasRadialGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  342. {
  343. // 1. If x0 = x1 and y0 = y1 and r0 = r1, then the radial gradient must paint nothing. Return.
  344. if (m_start_center == m_end_center && m_start_radius == m_end_radius)
  345. return;
  346. if (color_stops().is_empty())
  347. return;
  348. if (color_stops().size() < 2)
  349. return paint([this](IntPoint) { return color_stops().first().color; });
  350. auto start_radius = m_start_radius;
  351. auto start_center = m_start_center;
  352. auto end_radius = m_end_radius;
  353. auto end_center = m_end_center;
  354. if (end_radius == 0 && start_radius == 0)
  355. return;
  356. if (fabs(start_radius - end_radius) < 1)
  357. start_radius += 1;
  358. // Needed for the start circle > end circle case, but FIXME, this seems kind of hacky.
  359. bool reverse_gradient = end_radius < start_radius;
  360. if (reverse_gradient) {
  361. swap(end_radius, start_radius);
  362. swap(end_center, start_center);
  363. }
  364. // Spec steps: Useless for writing an actual implementation (give it a go :P):
  365. //
  366. // 2. Let x(ω) = (x1-x0)ω + x0
  367. // Let y(ω) = (y1-y0)ω + y0
  368. // Let r(ω) = (r1-r0)ω + r0
  369. // Let the color at ω be the color at that position on the gradient
  370. // (with the colors coming from the interpolation and extrapolation described above).
  371. //
  372. // 3. For all values of ω where r(ω) > 0, starting with the value of ω nearest to positive infinity and
  373. // ending with the value of ω nearest to negative infinity, draw the circumference of the circle with
  374. // radius r(ω) at position (x(ω), y(ω)), with the color at ω, but only painting on the parts of the
  375. // bitmap that have not yet been painted on by earlier circles in this step for this rendering of the gradient.
  376. auto center_delta = end_center - start_center;
  377. auto center_dist = end_center.distance_from(start_center);
  378. bool inner_contained = ((center_dist + start_radius) < end_radius);
  379. auto start_point = start_center;
  380. if (!inner_contained) {
  381. // The intersection point of the direct common tangents of the start/end circles.
  382. start_point = FloatPoint {
  383. (start_radius * end_center.x() - end_radius * start_center.x()) / (start_radius - end_radius),
  384. (start_radius * end_center.y() - end_radius * start_center.y()) / (start_radius - end_radius)
  385. };
  386. }
  387. // This is just an approximate upperbound (the gradient line class will shorten this if necessary).
  388. int gradient_length = AK::ceil(center_dist + end_radius + start_radius);
  389. GradientLine gradient_line(gradient_length, color_stops(), repeat_length(), UsePremultipliedAlpha::No);
  390. auto radius2 = end_radius * end_radius;
  391. center_delta = end_center - start_point;
  392. auto dx2_factor = (radius2 - center_delta.y() * center_delta.y());
  393. auto dy2_factor = (radius2 - center_delta.x() * center_delta.x());
  394. // If you can simplify this please do, this is "best guess" implementation due to lack of specification.
  395. // It was implemented to visually match chrome/firefox in all cases:
  396. // - Start circle inside end circle
  397. // - Start circle outside end circle
  398. // - Start circle radius == end circle radius
  399. // - Start circle larger than end circle (inside end circle)
  400. // - Start circle larger than end circle (outside end circle)
  401. // - Start circle or end circle radius == 0
  402. Gradient radial_gradient {
  403. move(gradient_line),
  404. [=](int x, int y) {
  405. auto get_gradient_location = [&] {
  406. FloatPoint point { x, y };
  407. auto dist = point.distance_from(start_point);
  408. if (dist == 0)
  409. return 0.0f;
  410. auto vec = (point - start_point) / dist;
  411. auto dx2 = vec.x() * vec.x();
  412. auto dy2 = vec.y() * vec.y();
  413. // This works out the distance to the nearest point on the end circle in the direction of the "vec" vector.
  414. // The "vec" vector points from the center of the start circle to the current point.
  415. auto root = sqrtf(dx2 * dx2_factor + dy2 * dy2_factor
  416. + 2 * vec.x() * vec.y() * center_delta.x() * center_delta.y());
  417. auto dot = vec.x() * center_delta.x() + vec.y() * center_delta.y();
  418. // Note: When reversed we always want the farthest point
  419. auto edge_dist = (((inner_contained || reverse_gradient ? root : -root) + dot) / (dx2 + dy2));
  420. auto start_offset = inner_contained ? start_radius : (edge_dist / end_radius) * start_radius;
  421. // FIXME: Returning nan is a hack for "Don't paint me!"
  422. if (edge_dist < 0)
  423. return AK::NaN<float>;
  424. if (edge_dist - start_offset < 0)
  425. return float(gradient_length);
  426. return ((dist - start_offset) / (edge_dist - start_offset));
  427. };
  428. auto loc = get_gradient_location();
  429. if (reverse_gradient)
  430. loc = 1.0f - loc;
  431. return loc * gradient_length;
  432. }
  433. };
  434. paint(make_sample_non_relative(physical_bounding_box.location(), radial_gradient.sample_function()));
  435. }
  436. }