Path.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Function.h>
  27. #include <AK/HashFunctions.h>
  28. #include <AK/HashTable.h>
  29. #include <AK/QuickSort.h>
  30. #include <AK/StringBuilder.h>
  31. #include <LibGfx/Painter.h>
  32. #include <LibGfx/Path.h>
  33. #include <math.h>
  34. namespace Gfx {
  35. void Path::close()
  36. {
  37. if (m_segments.size() <= 1)
  38. return;
  39. invalidate_split_lines();
  40. auto& last_point = m_segments.last().point;
  41. for (ssize_t i = m_segments.size() - 1; i >= 0; --i) {
  42. auto& segment = m_segments[i];
  43. if (segment.type == Segment::Type::MoveTo) {
  44. if (last_point == segment.point)
  45. return;
  46. m_segments.append({ Segment::Type::LineTo, segment.point });
  47. return;
  48. }
  49. }
  50. }
  51. String Path::to_string() const
  52. {
  53. StringBuilder builder;
  54. builder.append("Path { ");
  55. for (auto& segment : m_segments) {
  56. switch (segment.type) {
  57. case Segment::Type::MoveTo:
  58. builder.append("MoveTo");
  59. break;
  60. case Segment::Type::LineTo:
  61. builder.append("LineTo");
  62. break;
  63. case Segment::Type::QuadraticBezierCurveTo:
  64. builder.append("QuadraticBezierCurveTo");
  65. break;
  66. case Segment::Type::Invalid:
  67. builder.append("Invalid");
  68. break;
  69. }
  70. builder.append('(');
  71. builder.append(segment.point.to_string());
  72. if (segment.through.has_value()) {
  73. builder.append(", ");
  74. builder.append(segment.through.value().to_string());
  75. }
  76. builder.append(')');
  77. builder.append(' ');
  78. }
  79. builder.append("}");
  80. return builder.to_string();
  81. }
  82. void Path::segmentize_path()
  83. {
  84. Vector<LineSegment> segments;
  85. auto add_line = [&](const auto& p0, const auto& p1) {
  86. float ymax = p0.y(), ymin = p1.y(), x_of_ymin = p1.x(), x_of_ymax = p0.x();
  87. auto slope = p0.x() == p1.x() ? 0 : ((float)(p0.y() - p1.y())) / ((float)(p0.x() - p1.x()));
  88. if (p0.y() < p1.y()) {
  89. ymin = ymax;
  90. ymax = p1.y();
  91. x_of_ymax = x_of_ymin;
  92. x_of_ymin = p0.x();
  93. }
  94. segments.append({ Point(p0.x(), p0.y()),
  95. Point(p1.x(), p1.y()),
  96. slope == 0 ? 0 : 1 / slope,
  97. x_of_ymin,
  98. ymax, ymin, x_of_ymax });
  99. };
  100. FloatPoint cursor { 0, 0 };
  101. for (auto& segment : m_segments) {
  102. switch (segment.type) {
  103. case Segment::Type::MoveTo:
  104. cursor = segment.point;
  105. break;
  106. case Segment::Type::LineTo: {
  107. add_line(cursor, segment.point);
  108. cursor = segment.point;
  109. break;
  110. }
  111. case Segment::Type::QuadraticBezierCurveTo: {
  112. auto& control = segment.through.value();
  113. Painter::for_each_line_segment_on_bezier_curve(control, cursor, segment.point, [&](const FloatPoint& p0, const FloatPoint& p1) {
  114. add_line(Point(p0.x(), p0.y()), Point(p1.x(), p1.y()));
  115. });
  116. cursor = segment.point;
  117. break;
  118. }
  119. case Segment::Type::Invalid:
  120. ASSERT_NOT_REACHED();
  121. break;
  122. }
  123. }
  124. // sort segments by ymax
  125. quick_sort(segments, [](const auto& line0, const auto& line1) {
  126. return line1.maximum_y < line0.maximum_y;
  127. });
  128. m_split_lines = move(segments);
  129. }
  130. Vector<Path::LineSegment> Path::split_lines(Path::ShapeKind kind)
  131. {
  132. if (m_split_lines.has_value()) {
  133. const auto& lines = m_split_lines.value();
  134. if (kind == Complex)
  135. return lines;
  136. Vector<LineSegment> segments;
  137. for (auto& line : lines) {
  138. if (is_part_of_closed_polygon(line.from, line.to))
  139. segments.append(line);
  140. }
  141. return move(segments);
  142. }
  143. segmentize_path();
  144. ASSERT(m_split_lines.has_value());
  145. return split_lines(kind);
  146. }
  147. void Path::generate_path_graph()
  148. {
  149. // Generate a (possibly) disconnected cyclic directed graph
  150. // of the line segments in the path.
  151. // This graph will be used to determine whether a line should
  152. // be considered as part of an edge for the shape
  153. // FIXME: This will not chop lines up, so we might still have some
  154. // filling artifacts after this, as a line might pass over an edge
  155. // but be itself a part of _another_ polygon.
  156. HashMap<u32, OwnPtr<PathGraphNode>> graph;
  157. m_graph_node_map = move(graph);
  158. const auto& lines = split_lines();
  159. if (!lines.size())
  160. return;
  161. // now use scanline to find intersecting lines
  162. auto scanline = lines.first().maximum_y;
  163. auto last_line = lines.last().minimum_y;
  164. Vector<LineSegment> active_list;
  165. for (auto& line : lines) {
  166. if (line.maximum_y < scanline)
  167. break;
  168. active_list.append(line);
  169. }
  170. while (scanline >= last_line) {
  171. if (active_list.size() > 1) {
  172. quick_sort(active_list, [](const auto& line0, const auto& line1) {
  173. return line1.x < line0.x;
  174. });
  175. // for every two lines next to each other in the active list
  176. // figure out if they intersect, if they do, store
  177. // the right line as the child of the left line
  178. // in the path graph
  179. for (size_t i = 1; i < active_list.size(); ++i) {
  180. auto& left_line = active_list[i - 1];
  181. auto& right_line = active_list[i];
  182. auto left_hash = hash_line(left_line.from, left_line.to);
  183. auto right_hash = hash_line(right_line.from, right_line.to);
  184. auto maybe_left_entry = m_graph_node_map.value().get(left_hash);
  185. auto maybe_right_entry = m_graph_node_map.value().get(right_hash);
  186. if (!maybe_left_entry.has_value()) {
  187. auto left_entry = make<PathGraphNode>(left_hash, left_line);
  188. m_graph_node_map.value().set(left_hash, move(left_entry));
  189. maybe_left_entry = m_graph_node_map.value().get(left_hash);
  190. }
  191. if (!maybe_right_entry.has_value()) {
  192. auto right_entry = make<PathGraphNode>(right_hash, right_line);
  193. m_graph_node_map.value().set(right_hash, move(right_entry));
  194. maybe_right_entry = m_graph_node_map.value().get(right_hash);
  195. }
  196. // check all four sides for possible intersection
  197. if (((int)fabs(left_line.x - right_line.x)) <= 1
  198. || ((int)fabs(left_line.x - right_line.x + left_line.inverse_slope)) <= 1
  199. || ((int)fabs(left_line.x - right_line.x + right_line.inverse_slope)) <= 1
  200. || ((int)fabs(left_line.x - right_line.x + +right_line.inverse_slope + left_line.inverse_slope)) <= 1) {
  201. const_cast<PathGraphNode*>(maybe_left_entry.value())->children.append(maybe_right_entry.value());
  202. }
  203. left_line.x -= left_line.inverse_slope;
  204. }
  205. active_list.last().x -= active_list.last().inverse_slope;
  206. }
  207. --scanline;
  208. // remove any edge that goes out of bound from the active list
  209. for (size_t i = 0, count = active_list.size(); i < count; ++i) {
  210. if (scanline <= active_list[i].minimum_y) {
  211. active_list.remove(i);
  212. --count;
  213. --i;
  214. }
  215. }
  216. }
  217. }
  218. bool Path::is_part_of_closed_polygon(const Point& p0, const Point& p1)
  219. {
  220. if (!m_graph_node_map.has_value())
  221. generate_path_graph();
  222. ASSERT(m_graph_node_map.has_value());
  223. auto hash = hash_line(p0, p1);
  224. auto maybe_entry = m_graph_node_map.value().get(hash);
  225. if (!maybe_entry.has_value())
  226. return true;
  227. const auto& entry = maybe_entry.value();
  228. // check if the entry is part of a loop
  229. auto is_part_of_loop = false;
  230. HashTable<u32> visited;
  231. Vector<const PathGraphNode*> queue;
  232. queue.append(entry);
  233. for (; queue.size();) {
  234. const auto* node = queue.take_first();
  235. if (visited.contains(node->hash))
  236. continue;
  237. visited.set(node->hash);
  238. if (node == entry) {
  239. is_part_of_loop = true;
  240. break;
  241. }
  242. }
  243. return is_part_of_loop;
  244. }
  245. // FIXME: We need a better hash, and a wider type
  246. unsigned Path::hash_line(const Point& from, const Point& to)
  247. {
  248. u32 p0 = pair_int_hash(from.x(), from.y());
  249. u32 p1 = pair_int_hash(to.x(), to.y());
  250. return pair_int_hash(p0, p1);
  251. }
  252. }