AntiAliasingPainter.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. * Copyright (c) 2022, Ben Maxwell <macdue@dueutil.tech>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #if defined(__GNUC__) && !defined(__clang__)
  8. # pragma GCC optimize("O3")
  9. #endif
  10. #include "FillPathImplementation.h"
  11. #include <AK/Function.h>
  12. #include <LibGfx/AntiAliasingPainter.h>
  13. #include <LibGfx/Path.h>
  14. // Base algorithm from https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm,
  15. // because there seems to be no other known method for drawing AA'd lines (?)
  16. template<Gfx::AntiAliasingPainter::AntiAliasPolicy policy>
  17. void Gfx::AntiAliasingPainter::draw_anti_aliased_line(FloatPoint const& actual_from, FloatPoint const& actual_to, Color color, float thickness, Gfx::Painter::LineStyle style, Color)
  18. {
  19. // FIXME: Implement this :P
  20. VERIFY(style == Painter::LineStyle::Solid);
  21. auto corrected_thickness = thickness > 1 ? thickness - 1 : thickness;
  22. auto size = IntSize(corrected_thickness, corrected_thickness);
  23. auto plot = [&](int x, int y, float c) {
  24. m_underlying_painter.fill_rect(IntRect::centered_on({ x, y }, size), color.with_alpha(color.alpha() * c));
  25. };
  26. auto integer_part = [](float x) { return floorf(x); };
  27. auto round = [&](float x) { return integer_part(x + 0.5f); };
  28. auto fractional_part = [&](float x) { return x - floorf(x); };
  29. auto one_minus_fractional_part = [&](float x) { return 1.0f - fractional_part(x); };
  30. auto draw_line = [&](float x0, float y0, float x1, float y1) {
  31. bool steep = fabsf(y1 - y0) > fabsf(x1 - x0);
  32. if (steep) {
  33. swap(x0, y0);
  34. swap(x1, y1);
  35. }
  36. if (x0 > x1) {
  37. swap(x0, x1);
  38. swap(y0, y1);
  39. }
  40. float dx = x1 - x0;
  41. float dy = y1 - y0;
  42. float gradient;
  43. if (dx == 0.0f)
  44. gradient = 1.0f;
  45. else
  46. gradient = dy / dx;
  47. // Handle first endpoint.
  48. int x_end = round(x0);
  49. int y_end = y0 + gradient * (x_end - x0);
  50. float x_gap = one_minus_fractional_part(x0 + 0.5f);
  51. int xpxl1 = x_end; // This will be used in the main loop.
  52. int ypxl1 = integer_part(y_end);
  53. if (steep) {
  54. plot(ypxl1, xpxl1, one_minus_fractional_part(y_end) * x_gap);
  55. plot(ypxl1 + 1, xpxl1, fractional_part(y_end) * x_gap);
  56. } else {
  57. plot(xpxl1, ypxl1, one_minus_fractional_part(y_end) * x_gap);
  58. plot(xpxl1, ypxl1 + 1, fractional_part(y_end) * x_gap);
  59. }
  60. float intery = y_end + gradient; // First y-intersection for the main loop.
  61. // Handle second endpoint.
  62. x_end = round(x1);
  63. y_end = y1 + gradient * (x_end - x1);
  64. x_gap = fractional_part(x1 + 0.5f);
  65. int xpxl2 = x_end; // This will be used in the main loop
  66. int ypxl2 = integer_part(y_end);
  67. if (steep) {
  68. plot(ypxl2, xpxl2, one_minus_fractional_part(y_end) * x_gap);
  69. plot(ypxl2 + 1, xpxl2, fractional_part(y_end) * x_gap);
  70. } else {
  71. plot(xpxl2, ypxl2, one_minus_fractional_part(y_end) * x_gap);
  72. plot(xpxl2, ypxl2 + 1, fractional_part(y_end) * x_gap);
  73. }
  74. // Main loop.
  75. if (steep) {
  76. for (int x = xpxl1 + 1; x <= xpxl2 - 1; ++x) {
  77. if constexpr (policy == AntiAliasPolicy::OnlyEnds) {
  78. plot(integer_part(intery), x, 1);
  79. } else {
  80. plot(integer_part(intery), x, one_minus_fractional_part(intery));
  81. }
  82. plot(integer_part(intery) + 1, x, fractional_part(intery));
  83. intery += gradient;
  84. }
  85. } else {
  86. for (int x = xpxl1 + 1; x <= xpxl2 - 1; ++x) {
  87. if constexpr (policy == AntiAliasPolicy::OnlyEnds) {
  88. plot(x, integer_part(intery), 1);
  89. } else {
  90. plot(x, integer_part(intery), one_minus_fractional_part(intery));
  91. }
  92. plot(x, integer_part(intery) + 1, fractional_part(intery));
  93. intery += gradient;
  94. }
  95. }
  96. };
  97. auto mapped_from = m_transform.map(actual_from);
  98. auto mapped_to = m_transform.map(actual_to);
  99. draw_line(mapped_from.x(), mapped_from.y(), mapped_to.x(), mapped_to.y());
  100. }
  101. void Gfx::AntiAliasingPainter::draw_aliased_line(FloatPoint const& actual_from, FloatPoint const& actual_to, Color color, float thickness, Gfx::Painter::LineStyle style, Color alternate_color)
  102. {
  103. draw_anti_aliased_line<AntiAliasPolicy::OnlyEnds>(actual_from, actual_to, color, thickness, style, alternate_color);
  104. }
  105. void Gfx::AntiAliasingPainter::draw_line(FloatPoint const& actual_from, FloatPoint const& actual_to, Color color, float thickness, Gfx::Painter::LineStyle style, Color alternate_color)
  106. {
  107. draw_anti_aliased_line<AntiAliasPolicy::Full>(actual_from, actual_to, color, thickness, style, alternate_color);
  108. }
  109. void Gfx::AntiAliasingPainter::fill_path(Path& path, Color color, Painter::WindingRule rule)
  110. {
  111. Detail::fill_path<Detail::FillPathMode::AllowFloatingPoints>(*this, path, color, rule);
  112. }
  113. void Gfx::AntiAliasingPainter::stroke_path(Path const& path, Color color, float thickness)
  114. {
  115. FloatPoint cursor;
  116. for (auto& segment : path.segments()) {
  117. switch (segment.type()) {
  118. case Segment::Type::Invalid:
  119. VERIFY_NOT_REACHED();
  120. case Segment::Type::MoveTo:
  121. cursor = segment.point();
  122. break;
  123. case Segment::Type::LineTo:
  124. draw_line(cursor, segment.point(), color, thickness);
  125. cursor = segment.point();
  126. break;
  127. case Segment::Type::QuadraticBezierCurveTo: {
  128. auto& through = static_cast<QuadraticBezierCurveSegment const&>(segment).through();
  129. draw_quadratic_bezier_curve(through, cursor, segment.point(), color, thickness);
  130. cursor = segment.point();
  131. break;
  132. }
  133. case Segment::Type::CubicBezierCurveTo: {
  134. auto& curve = static_cast<CubicBezierCurveSegment const&>(segment);
  135. auto& through_0 = curve.through_0();
  136. auto& through_1 = curve.through_1();
  137. draw_cubic_bezier_curve(through_0, through_1, cursor, segment.point(), color, thickness);
  138. cursor = segment.point();
  139. break;
  140. }
  141. case Segment::Type::EllipticalArcTo:
  142. auto& arc = static_cast<EllipticalArcSegment const&>(segment);
  143. draw_elliptical_arc(cursor, segment.point(), arc.center(), arc.radii(), arc.x_axis_rotation(), arc.theta_1(), arc.theta_delta(), color, thickness);
  144. cursor = segment.point();
  145. break;
  146. }
  147. }
  148. }
  149. void Gfx::AntiAliasingPainter::draw_elliptical_arc(FloatPoint const& p1, FloatPoint const& p2, FloatPoint const& center, FloatPoint const& radii, float x_axis_rotation, float theta_1, float theta_delta, Color color, float thickness, Painter::LineStyle style)
  150. {
  151. Gfx::Painter::for_each_line_segment_on_elliptical_arc(p1, p2, center, radii, x_axis_rotation, theta_1, theta_delta, [&](FloatPoint const& fp1, FloatPoint const& fp2) {
  152. draw_line(fp1, fp2, color, thickness, style);
  153. });
  154. }
  155. void Gfx::AntiAliasingPainter::draw_quadratic_bezier_curve(FloatPoint const& control_point, FloatPoint const& p1, FloatPoint const& p2, Color color, float thickness, Painter::LineStyle style)
  156. {
  157. Gfx::Painter::for_each_line_segment_on_bezier_curve(control_point, p1, p2, [&](FloatPoint const& fp1, FloatPoint const& fp2) {
  158. draw_line(fp1, fp2, color, thickness, style);
  159. });
  160. }
  161. void Gfx::AntiAliasingPainter::draw_cubic_bezier_curve(FloatPoint const& control_point_0, FloatPoint const& control_point_1, FloatPoint const& p1, FloatPoint const& p2, Color color, float thickness, Painter::LineStyle style)
  162. {
  163. Gfx::Painter::for_each_line_segment_on_cubic_bezier_curve(control_point_0, control_point_1, p1, p2, [&](FloatPoint const& fp1, FloatPoint const& fp2) {
  164. draw_line(fp1, fp2, color, thickness, style);
  165. });
  166. }
  167. void Gfx::AntiAliasingPainter::draw_circle(IntPoint center, int radius, Color color)
  168. {
  169. /*
  170. Algorithm from: https://cs.uwaterloo.ca/research/tr/1984/CS-84-38.pdf
  171. Inline comments are from the paper.
  172. */
  173. center *= m_underlying_painter.scale();
  174. radius *= m_underlying_painter.scale();
  175. // TODO: Generalize to ellipses (see paper)
  176. // These happen to be the same here, but are treated separately in the paper:
  177. // intensity is the fill alpha
  178. int const intensity = color.alpha();
  179. // 0 to subpixel_resolution is the range of alpha values for the circle edges
  180. int const subpixel_resolution = intensity;
  181. // Note: Variable names below are based off the paper
  182. // Current pixel address
  183. int i = 0;
  184. int q = radius;
  185. // 1st and 2nd order differences of y
  186. int delta_y = 0;
  187. int delta2_y = 0;
  188. // Exact and predicted values of f(i) -- the circle equation scaled by subpixel_resolution
  189. int y = subpixel_resolution * radius;
  190. int y_hat = 0;
  191. // The value of f(i)*f(i)
  192. int f_squared = y * y;
  193. // 1st and 2nd order differences of f(i)*f(i)
  194. int delta_f_squared = subpixel_resolution * subpixel_resolution;
  195. int delta2_f_squared = -delta_f_squared - delta_f_squared;
  196. // edge_intersection_area/subpixel_resolution = percentage of pixel intersected by circle
  197. // (aka the alpha for the pixel)
  198. int edge_intersection_area = 0;
  199. int old_area = edge_intersection_area;
  200. auto predict = [&] {
  201. delta_y += delta2_y;
  202. // y_hat is the predicted value of f(i)
  203. y_hat = y + delta_y;
  204. };
  205. auto minimize = [&] {
  206. // Initialize the minimization
  207. delta_f_squared += delta2_f_squared;
  208. f_squared += delta_f_squared;
  209. int min_squared_error = y_hat * y_hat - f_squared;
  210. int prediction_overshot = 1;
  211. y = y_hat;
  212. // Force error negative
  213. if (min_squared_error > 0) {
  214. min_squared_error = -min_squared_error;
  215. prediction_overshot = -1;
  216. }
  217. // Minimize
  218. int previous_error = min_squared_error;
  219. while (min_squared_error < 0) {
  220. y += prediction_overshot;
  221. previous_error = min_squared_error;
  222. min_squared_error += y + y - prediction_overshot;
  223. }
  224. if (min_squared_error + previous_error > 0)
  225. y -= prediction_overshot;
  226. };
  227. auto correct = [&] {
  228. int error = y - y_hat;
  229. delta2_y += error;
  230. delta_y += error;
  231. };
  232. auto pixel = [&](int x, int y, int alpha) {
  233. if (alpha <= 0 || alpha > 255)
  234. return;
  235. auto pixel_colour = color;
  236. pixel_colour.set_alpha(alpha);
  237. m_underlying_painter.set_pixel(center + IntPoint { x, y }, pixel_colour, true);
  238. };
  239. auto fill = [&](int x, int ymax, int ymin, int alpha) {
  240. while (ymin <= ymax) {
  241. pixel(x, ymin, alpha);
  242. ymin += 1;
  243. }
  244. };
  245. auto eight_pixel = [&](int x, int y, int alpha) {
  246. pixel(x, y, alpha);
  247. pixel(x, -y - 1, alpha);
  248. pixel(-x - 1, -y - 1, alpha);
  249. pixel(-x - 1, y, alpha);
  250. pixel(y, x, alpha);
  251. pixel(y, -x - 1, alpha);
  252. pixel(-y - 1, -x - 1, alpha);
  253. pixel(-y - 1, x, alpha);
  254. };
  255. while (i < q) {
  256. predict();
  257. minimize();
  258. correct();
  259. old_area = edge_intersection_area;
  260. edge_intersection_area += delta_y;
  261. if (edge_intersection_area >= 0) {
  262. // Single pixel on perimeter
  263. eight_pixel(i, q, (edge_intersection_area + old_area) / 2);
  264. fill(i, q - 1, -q, intensity);
  265. fill(-i - 1, q - 1, -q, intensity);
  266. } else {
  267. // Two pixels on perimeter
  268. edge_intersection_area += subpixel_resolution;
  269. eight_pixel(i, q, old_area / 2);
  270. q -= 1;
  271. fill(i, q - 1, -q, intensity);
  272. fill(-i - 1, q - 1, -q, intensity);
  273. if (i < q) {
  274. // Haven't gone below the diagonal
  275. eight_pixel(i, q, (edge_intersection_area + subpixel_resolution) / 2);
  276. fill(q, i - 1, -i, intensity);
  277. fill(-q - 1, i - 1, -i, intensity);
  278. } else {
  279. // Went below the diagonal, fix edge_intersection_area for final pixels
  280. edge_intersection_area += subpixel_resolution;
  281. }
  282. }
  283. i += 1;
  284. }
  285. // Fill in 4 remaning pixels
  286. int alpha = edge_intersection_area / 2;
  287. pixel(q, q, alpha);
  288. pixel(-q - 1, q, alpha);
  289. pixel(-q - 1, -q - 1, alpha);
  290. pixel(q, -q - 1, alpha);
  291. }
  292. void Gfx::AntiAliasingPainter::fill_rect_with_rounded_corners(IntRect const& a_rect, Color color, int radius)
  293. {
  294. fill_rect_with_rounded_corners(a_rect, color, radius, radius, radius, radius);
  295. }
  296. void Gfx::AntiAliasingPainter::fill_rect_with_rounded_corners(IntRect const& a_rect, Color color, int top_left_radius, int top_right_radius, int bottom_right_radius, int bottom_left_radius)
  297. {
  298. if (!top_left_radius && !top_right_radius && !bottom_right_radius && !bottom_left_radius)
  299. return m_underlying_painter.fill_rect(a_rect, color);
  300. if (color.alpha() == 0)
  301. return;
  302. IntPoint top_left_corner {
  303. a_rect.x() + top_left_radius,
  304. a_rect.y() + top_left_radius,
  305. };
  306. IntPoint top_right_corner {
  307. a_rect.x() + a_rect.width() - top_right_radius,
  308. a_rect.y() + top_right_radius,
  309. };
  310. IntPoint bottom_left_corner {
  311. a_rect.x() + bottom_left_radius,
  312. a_rect.y() + a_rect.height() - bottom_right_radius
  313. };
  314. IntPoint bottom_right_corner {
  315. a_rect.x() + a_rect.width() - bottom_left_radius,
  316. a_rect.y() + a_rect.height() - bottom_left_radius
  317. };
  318. IntRect top_rect {
  319. a_rect.x() + top_left_radius,
  320. a_rect.y(),
  321. a_rect.width() - top_left_radius - top_right_radius,
  322. top_left_radius
  323. };
  324. IntRect right_rect {
  325. a_rect.x() + a_rect.width() - top_right_radius,
  326. a_rect.y() + top_right_radius,
  327. top_right_radius,
  328. a_rect.height() - top_right_radius - bottom_right_radius
  329. };
  330. IntRect bottom_rect {
  331. a_rect.x() + bottom_left_radius,
  332. a_rect.y() + a_rect.height() - bottom_right_radius,
  333. a_rect.width() - bottom_left_radius - bottom_right_radius,
  334. bottom_right_radius
  335. };
  336. IntRect left_rect {
  337. a_rect.x(),
  338. a_rect.y() + top_left_radius,
  339. bottom_left_radius,
  340. a_rect.height() - top_left_radius - bottom_left_radius
  341. };
  342. IntRect inner = {
  343. left_rect.x() + left_rect.width(),
  344. left_rect.y(),
  345. a_rect.width() - left_rect.width() - right_rect.width(),
  346. a_rect.height() - top_rect.height() - bottom_rect.height()
  347. };
  348. m_underlying_painter.fill_rect(top_rect, color);
  349. m_underlying_painter.fill_rect(right_rect, color);
  350. m_underlying_painter.fill_rect(bottom_rect, color);
  351. m_underlying_painter.fill_rect(left_rect, color);
  352. m_underlying_painter.fill_rect(inner, color);
  353. // FIXME: Don't draw a whole circle each time
  354. if (top_left_radius)
  355. draw_circle(top_left_corner, top_left_radius, color);
  356. if (top_right_radius)
  357. draw_circle(top_right_corner, top_right_radius, color);
  358. if (bottom_left_radius)
  359. draw_circle(bottom_left_corner, bottom_left_radius, color);
  360. if (bottom_right_radius)
  361. draw_circle(bottom_right_corner, bottom_right_radius, color);
  362. }