EdgeFlagPathRasterizer.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /*
  2. * Copyright (c) 2023-2024, MacDue <macdue@dueutil.tech>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Array.h>
  7. #include <AK/Debug.h>
  8. #include <AK/IntegralMath.h>
  9. #include <AK/Types.h>
  10. #include <LibGfx/AntiAliasingPainter.h>
  11. #include <LibGfx/EdgeFlagPathRasterizer.h>
  12. #include <LibGfx/Painter.h>
  13. #if defined(AK_COMPILER_GCC)
  14. # pragma GCC optimize("O3")
  15. #endif
  16. // This an implementation of edge-flag scanline AA, as described in:
  17. // https://mlab.taik.fi/~kkallio/antialiasing/EdgeFlagAA.pdf
  18. namespace Gfx {
  19. static Vector<Detail::Edge> prepare_edges(ReadonlySpan<FloatLine> lines, unsigned samples_per_pixel, FloatPoint origin,
  20. int top_clip_scanline, int bottom_clip_scanline, int& min_edge_y, int& max_edge_y)
  21. {
  22. Vector<Detail::Edge> edges;
  23. edges.ensure_capacity(lines.size());
  24. // The first visible y value.
  25. auto top_clip = top_clip_scanline * int(samples_per_pixel);
  26. // The last visible y value.
  27. auto bottom_clip = (bottom_clip_scanline + 1) * int(samples_per_pixel);
  28. min_edge_y = bottom_clip;
  29. max_edge_y = top_clip;
  30. for (auto& line : lines) {
  31. auto p0 = line.a() - origin;
  32. auto p1 = line.b() - origin;
  33. p0.scale_by(1, samples_per_pixel);
  34. p1.scale_by(1, samples_per_pixel);
  35. i8 winding = -1;
  36. if (p0.y() > p1.y()) {
  37. swap(p0, p1);
  38. } else {
  39. winding = 1;
  40. }
  41. if (p0.y() == p1.y())
  42. continue;
  43. auto min_y = static_cast<int>(p0.y());
  44. auto max_y = static_cast<int>(p1.y());
  45. // Clip edges that start below the bottom clip...
  46. if (min_y > bottom_clip)
  47. continue;
  48. // ...and edges that end before the top clip.
  49. if (max_y < top_clip)
  50. continue;
  51. auto start_x = p0.x();
  52. auto end_x = p1.x();
  53. auto dx = end_x - start_x;
  54. auto dy = max_y - min_y;
  55. if (dy == 0)
  56. continue;
  57. auto dxdy = dx / dy;
  58. // Trim off the non-visible portions of the edge.
  59. if (min_y < top_clip) {
  60. start_x += dxdy * (top_clip - min_y);
  61. min_y = top_clip;
  62. }
  63. if (max_y > bottom_clip)
  64. max_y = bottom_clip;
  65. min_edge_y = min(min_y, min_edge_y);
  66. max_edge_y = max(max_y, max_edge_y);
  67. edges.unchecked_append(Detail::Edge {
  68. start_x,
  69. min_y,
  70. max_y,
  71. dxdy,
  72. winding,
  73. nullptr });
  74. }
  75. return edges;
  76. }
  77. template<unsigned SamplesPerPixel>
  78. EdgeFlagPathRasterizer<SamplesPerPixel>::EdgeFlagPathRasterizer(IntSize size)
  79. : m_size(size.width() + 1, size.height() + 1)
  80. {
  81. }
  82. template<unsigned SamplesPerPixel>
  83. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill(Painter& painter, Path const& path, Color color, WindingRule winding_rule, FloatPoint offset)
  84. {
  85. fill_internal(painter, path, color, winding_rule, offset);
  86. }
  87. template<unsigned SamplesPerPixel>
  88. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill(Painter& painter, Path const& path, PaintStyle const& style, float opacity, WindingRule winding_rule, FloatPoint offset)
  89. {
  90. style.paint(enclosing_int_rect(path.bounding_box()), [&](PaintStyle::SamplerFunction sampler) {
  91. if (opacity == 0.0f)
  92. return;
  93. if (opacity != 1.0f) {
  94. return fill_internal(
  95. painter, path, [=, sampler = move(sampler)](IntPoint point) {
  96. return sampler(point).with_opacity(opacity);
  97. },
  98. winding_rule, offset);
  99. }
  100. return fill_internal(painter, path, move(sampler), winding_rule, offset);
  101. });
  102. }
  103. template<unsigned SamplesPerPixel>
  104. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill_internal(Painter& painter, Path const& path, auto color_or_function, WindingRule winding_rule, FloatPoint offset)
  105. {
  106. auto bounding_box = enclosing_int_rect(path.bounding_box().translated(offset));
  107. auto dest_rect = bounding_box.translated(painter.translation());
  108. auto origin = bounding_box.top_left().to_type<float>() - offset;
  109. m_blit_origin = dest_rect.top_left();
  110. m_clip = dest_rect.intersected(painter.clip_rect());
  111. // Only allocate enough to plot the parts of the scanline that could be visible.
  112. // Note: This can't clip the LHS.
  113. auto scanline_length = min(m_size.width(), m_clip.right() - m_blit_origin.x());
  114. if (scanline_length <= 0)
  115. return;
  116. m_scanline.resize(scanline_length);
  117. if (m_clip.is_empty())
  118. return;
  119. auto lines = path.split_lines();
  120. if (lines.is_empty())
  121. return;
  122. int min_edge_y = 0;
  123. int max_edge_y = 0;
  124. auto top_clip_scanline = m_clip.top() - m_blit_origin.y();
  125. auto bottom_clip_scanline = m_clip.bottom() - m_blit_origin.y() - 1;
  126. auto edges = prepare_edges(lines, SamplesPerPixel, origin, top_clip_scanline, bottom_clip_scanline, min_edge_y, max_edge_y);
  127. if (edges.is_empty())
  128. return;
  129. int min_scanline = min_edge_y / SamplesPerPixel;
  130. int max_scanline = max_edge_y / SamplesPerPixel;
  131. m_edge_table.set_scanline_range(min_scanline, max_scanline);
  132. for (auto& edge : edges) {
  133. // Create a linked-list of edges starting on this scanline:
  134. int start_scanline = edge.min_y / SamplesPerPixel;
  135. edge.next_edge = m_edge_table[start_scanline];
  136. m_edge_table[start_scanline] = &edge;
  137. }
  138. auto empty_edge_extent = [&] {
  139. return EdgeExtent { m_size.width() - 1, 0 };
  140. };
  141. auto for_each_sample = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y, EdgeExtent& edge_extent, auto callback) {
  142. for (int y = start_subpixel_y; y < end_subpixel_y; y++) {
  143. auto xi = static_cast<int>(edge.x + SubpixelSample::nrooks_subpixel_offsets[y]);
  144. if (xi >= 0 && size_t(xi) < m_scanline.size()) [[likely]] {
  145. SampleType sample = 1 << y;
  146. callback(xi, y, sample);
  147. } else if (xi < 0) {
  148. if (edge.dxdy <= 0)
  149. return;
  150. } else {
  151. xi = m_scanline.size() - 1;
  152. }
  153. edge.x += edge.dxdy;
  154. edge_extent.min_x = min(edge_extent.min_x, xi);
  155. edge_extent.max_x = max(edge_extent.max_x, xi);
  156. }
  157. };
  158. Detail::Edge* active_edges = nullptr;
  159. if (winding_rule == WindingRule::EvenOdd) {
  160. auto plot_edge = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y, EdgeExtent& edge_extent) {
  161. for_each_sample(edge, start_subpixel_y, end_subpixel_y, edge_extent, [&](int xi, int, SampleType sample) {
  162. m_scanline[xi] ^= sample;
  163. });
  164. };
  165. for (int scanline = min_scanline; scanline <= max_scanline; scanline++) {
  166. auto edge_extent = empty_edge_extent();
  167. active_edges = plot_edges_for_scanline(scanline, plot_edge, edge_extent, active_edges);
  168. write_scanline<WindingRule::EvenOdd>(painter, scanline, edge_extent, color_or_function);
  169. }
  170. } else {
  171. VERIFY(winding_rule == WindingRule::Nonzero);
  172. // Only allocate the winding buffer if needed.
  173. // NOTE: non-zero fills are a fair bit less efficient. So if you can do an even-odd fill do that :^)
  174. if (m_windings.is_empty())
  175. m_windings.resize(m_scanline.size());
  176. auto plot_edge = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y, EdgeExtent& edge_extent) {
  177. for_each_sample(edge, start_subpixel_y, end_subpixel_y, edge_extent, [&](int xi, int y, SampleType sample) {
  178. m_scanline[xi] |= sample;
  179. m_windings[xi].counts[y] += edge.winding;
  180. });
  181. };
  182. for (int scanline = min_scanline; scanline <= max_scanline; scanline++) {
  183. auto edge_extent = empty_edge_extent();
  184. active_edges = plot_edges_for_scanline(scanline, plot_edge, edge_extent, active_edges);
  185. write_scanline<WindingRule::Nonzero>(painter, scanline, edge_extent, color_or_function);
  186. }
  187. }
  188. }
  189. ALWAYS_INLINE static auto switch_on_color_or_function(auto& color_or_function, auto color_case, auto function_case)
  190. {
  191. using ColorOrFunction = decltype(color_or_function);
  192. constexpr bool has_constant_color = IsSame<RemoveCVReference<ColorOrFunction>, Color>;
  193. if constexpr (has_constant_color) {
  194. return color_case(color_or_function);
  195. } else {
  196. return function_case(color_or_function);
  197. }
  198. }
  199. template<unsigned SamplesPerPixel>
  200. Color EdgeFlagPathRasterizer<SamplesPerPixel>::scanline_color(int scanline, int offset, u8 alpha, auto& color_or_function)
  201. {
  202. auto color = switch_on_color_or_function(
  203. color_or_function, [](Color color) { return color; },
  204. [&](auto& function) {
  205. return function({ offset, scanline });
  206. });
  207. if (color.alpha() == 255)
  208. return color.with_alpha(alpha, AlphaType::Premultiplied);
  209. return color.with_alpha(color.alpha() * alpha / 255, AlphaType::Premultiplied);
  210. }
  211. template<unsigned SamplesPerPixel>
  212. __attribute__((hot)) Detail::Edge* EdgeFlagPathRasterizer<SamplesPerPixel>::plot_edges_for_scanline(int scanline, auto plot_edge, EdgeExtent& edge_extent, Detail::Edge* active_edges)
  213. {
  214. auto y_subpixel = [](int y) {
  215. return y & (SamplesPerPixel - 1);
  216. };
  217. auto* current_edge = active_edges;
  218. Detail::Edge* prev_edge = nullptr;
  219. // First iterate over the edge in the active edge table, these are edges added on earlier scanlines,
  220. // that have not yet reached their end scanline.
  221. while (current_edge) {
  222. int end_scanline = current_edge->max_y / SamplesPerPixel;
  223. if (scanline == end_scanline) {
  224. // This edge ends this scanline.
  225. plot_edge(*current_edge, 0, y_subpixel(current_edge->max_y), edge_extent);
  226. // Remove this edge from the AET
  227. current_edge = current_edge->next_edge;
  228. if (prev_edge)
  229. prev_edge->next_edge = current_edge;
  230. else
  231. active_edges = current_edge;
  232. } else {
  233. // This edge sticks around for a few more scanlines.
  234. plot_edge(*current_edge, 0, SamplesPerPixel, edge_extent);
  235. prev_edge = current_edge;
  236. current_edge = current_edge->next_edge;
  237. }
  238. }
  239. // Next, iterate over new edges for this line. If active_edges was null this also becomes the new
  240. // AET. Edges new will be appended here.
  241. current_edge = m_edge_table[scanline];
  242. while (current_edge) {
  243. int end_scanline = current_edge->max_y / SamplesPerPixel;
  244. if (scanline == end_scanline) {
  245. // This edge will end this scanlines (no need to add to AET).
  246. plot_edge(*current_edge, y_subpixel(current_edge->min_y), y_subpixel(current_edge->max_y), edge_extent);
  247. } else {
  248. // This edge will live on for a few more scanlines.
  249. plot_edge(*current_edge, y_subpixel(current_edge->min_y), SamplesPerPixel, edge_extent);
  250. // Add this edge to the AET
  251. if (prev_edge)
  252. prev_edge->next_edge = current_edge;
  253. else
  254. active_edges = current_edge;
  255. prev_edge = current_edge;
  256. }
  257. current_edge = current_edge->next_edge;
  258. }
  259. if (prev_edge)
  260. prev_edge->next_edge = nullptr;
  261. m_edge_table[scanline] = nullptr;
  262. return active_edges;
  263. }
  264. template<unsigned SamplesPerPixel>
  265. auto EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_even_odd_scanline(EdgeExtent edge_extent, auto init, auto sample_callback)
  266. {
  267. SampleType sample = init;
  268. VERIFY(edge_extent.min_x >= 0);
  269. VERIFY(edge_extent.max_x < static_cast<int>(m_scanline.size()));
  270. for (int x = edge_extent.min_x; x <= edge_extent.max_x; x++) {
  271. sample ^= m_scanline.data()[x];
  272. sample_callback(x, sample);
  273. m_scanline.data()[x] = 0;
  274. }
  275. return sample;
  276. }
  277. template<unsigned SamplesPerPixel>
  278. auto EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_non_zero_scanline(EdgeExtent edge_extent, auto init, auto sample_callback)
  279. {
  280. NonZeroAcc acc = init;
  281. VERIFY(edge_extent.min_x >= 0);
  282. VERIFY(edge_extent.max_x < static_cast<int>(m_scanline.size()));
  283. for (int x = edge_extent.min_x; x <= edge_extent.max_x; x++) {
  284. if (auto edges = m_scanline.data()[x]) {
  285. // We only need to process the windings when we hit some edges.
  286. for (auto y_sub = 0u; y_sub < SamplesPerPixel; y_sub++) {
  287. auto subpixel_bit = 1 << y_sub;
  288. if (edges & subpixel_bit) {
  289. auto winding = m_windings.data()[x].counts[y_sub];
  290. auto previous_winding_count = acc.winding.counts[y_sub];
  291. acc.winding.counts[y_sub] += winding;
  292. // Toggle fill on change to/from zero.
  293. if (bool(previous_winding_count) ^ bool(acc.winding.counts[y_sub]))
  294. acc.sample ^= subpixel_bit;
  295. }
  296. }
  297. }
  298. sample_callback(x, acc.sample);
  299. m_scanline.data()[x] = 0;
  300. m_windings.data()[x] = {};
  301. }
  302. return acc;
  303. }
  304. template<unsigned SamplesPerPixel>
  305. template<WindingRule WindingRule, typename Callback>
  306. auto EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_scanline(EdgeExtent edge_extent, auto init, Callback callback)
  307. {
  308. if constexpr (WindingRule == WindingRule::EvenOdd)
  309. return accumulate_even_odd_scanline(edge_extent, init, callback);
  310. else
  311. return accumulate_non_zero_scanline(edge_extent, init, callback);
  312. }
  313. template<unsigned SamplesPerPixel>
  314. void EdgeFlagPathRasterizer<SamplesPerPixel>::write_pixel(BitmapFormat format, ARGB32* scanline_ptr, int scanline, int offset, SampleType sample, auto& color_or_function)
  315. {
  316. if (!sample)
  317. return;
  318. auto dest_x = offset + m_blit_origin.x();
  319. auto coverage = SubpixelSample::compute_coverage(sample);
  320. auto paint_color = scanline_color(scanline, offset, coverage_to_alpha(coverage), color_or_function);
  321. scanline_ptr[dest_x] = color_for_format(format, scanline_ptr[dest_x]).blend(paint_color).value();
  322. }
  323. template<unsigned SamplesPerPixel>
  324. void EdgeFlagPathRasterizer<SamplesPerPixel>::fast_fill_solid_color_span(ARGB32* scanline_ptr, int start, int end, Color color)
  325. {
  326. auto start_x = start + m_blit_origin.x();
  327. auto end_x = end + m_blit_origin.x();
  328. fast_u32_fill(scanline_ptr + start_x, color.value(), end_x - start_x + 1);
  329. }
  330. template<unsigned SamplesPerPixel>
  331. template<WindingRule WindingRule>
  332. FLATTEN __attribute__((hot)) void EdgeFlagPathRasterizer<SamplesPerPixel>::write_scanline(Painter& painter, int scanline, EdgeExtent edge_extent, auto& color_or_function)
  333. {
  334. // Handle scanline clipping.
  335. auto left_clip = m_clip.left() - m_blit_origin.x();
  336. EdgeExtent clipped_extent { max(left_clip, edge_extent.min_x), edge_extent.max_x };
  337. if (clipped_extent.min_x > clipped_extent.max_x) {
  338. // Fully clipped. Unfortunately we still need to zero the scanline data.
  339. edge_extent.memset_extent(m_scanline.data(), 0);
  340. if constexpr (WindingRule == WindingRule::Nonzero)
  341. edge_extent.memset_extent(m_windings.data(), 0);
  342. return;
  343. }
  344. // Accumulate non-visible section (without plotting pixels).
  345. auto acc = accumulate_scanline<WindingRule>(EdgeExtent { edge_extent.min_x, left_clip - 1 }, initial_acc<WindingRule>(), [](int, SampleType) {
  346. // Do nothing!
  347. });
  348. // Get pointer to current scanline pixels.
  349. auto dest_format = painter.target().format();
  350. auto dest_ptr = painter.target().scanline(scanline + m_blit_origin.y());
  351. // Simple case: Handle each pixel individually.
  352. // Used for PaintStyle fills and semi-transparent colors.
  353. auto write_scanline_pixelwise = [&](auto& color_or_function) {
  354. accumulate_scanline<WindingRule>(clipped_extent, acc, [&](int x, SampleType sample) {
  355. write_pixel(dest_format, dest_ptr, scanline, x, sample, color_or_function);
  356. });
  357. };
  358. // Fast fill case: Track spans of solid color and set the entire span via a fast_u32_fill().
  359. // Used for opaque colors (i.e. alpha == 255).
  360. auto write_scanline_with_fast_fills = [&](Color color) {
  361. if (color.alpha() != 255)
  362. return write_scanline_pixelwise(color);
  363. constexpr SampleType full_coverage = NumericLimits<SampleType>::max();
  364. int full_coverage_count = 0;
  365. accumulate_scanline<WindingRule>(clipped_extent, acc, [&](int x, SampleType sample) {
  366. if (sample == full_coverage) {
  367. full_coverage_count++;
  368. return;
  369. } else {
  370. write_pixel(dest_format, dest_ptr, scanline, x, sample, color);
  371. }
  372. if (full_coverage_count > 0) {
  373. fast_fill_solid_color_span(dest_ptr, x - full_coverage_count, x - 1, color);
  374. full_coverage_count = 0;
  375. }
  376. });
  377. if (full_coverage_count > 0)
  378. fast_fill_solid_color_span(dest_ptr, clipped_extent.max_x - full_coverage_count + 1, clipped_extent.max_x, color);
  379. };
  380. switch_on_color_or_function(
  381. color_or_function, write_scanline_with_fast_fills, write_scanline_pixelwise);
  382. }
  383. static IntSize path_bounds(Gfx::Path const& path)
  384. {
  385. return enclosing_int_rect(path.bounding_box()).size();
  386. }
  387. // Note: The AntiAliasingPainter and Painter now perform the same antialiasing,
  388. // since it would be harder to turn it off for the standard painter.
  389. // The samples are reduced to 8 for Gfx::Painter though as a "speedy" option.
  390. void Painter::fill_path(Path const& path, Color color, WindingRule winding_rule)
  391. {
  392. EdgeFlagPathRasterizer<8> rasterizer(path_bounds(path));
  393. rasterizer.fill(*this, path, color, winding_rule);
  394. }
  395. void Painter::fill_path(Path const& path, PaintStyle const& paint_style, float opacity, WindingRule winding_rule)
  396. {
  397. EdgeFlagPathRasterizer<8> rasterizer(path_bounds(path));
  398. rasterizer.fill(*this, path, paint_style, opacity, winding_rule);
  399. }
  400. void AntiAliasingPainter::fill_path(Path const& path, Color color, WindingRule winding_rule)
  401. {
  402. EdgeFlagPathRasterizer<32> rasterizer(path_bounds(path));
  403. rasterizer.fill(m_underlying_painter, path, color, winding_rule, m_transform.translation());
  404. }
  405. void AntiAliasingPainter::fill_path(Path const& path, PaintStyle const& paint_style, float opacity, WindingRule winding_rule)
  406. {
  407. EdgeFlagPathRasterizer<32> rasterizer(path_bounds(path));
  408. rasterizer.fill(m_underlying_painter, path, paint_style, opacity, winding_rule, m_transform.translation());
  409. }
  410. template class EdgeFlagPathRasterizer<8>;
  411. template class EdgeFlagPathRasterizer<16>;
  412. template class EdgeFlagPathRasterizer<32>;
  413. }