Path.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Function.h>
  7. #include <AK/HashTable.h>
  8. #include <AK/QuickSort.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibGfx/Painter.h>
  11. #include <LibGfx/Path.h>
  12. #include <math.h>
  13. namespace Gfx {
  14. void Path::elliptical_arc_to(const FloatPoint& point, const FloatPoint& radii, double x_axis_rotation, bool large_arc, bool sweep)
  15. {
  16. auto next_point = point;
  17. double rx = radii.x();
  18. double ry = radii.y();
  19. double x_axis_rotation_c = cos(x_axis_rotation);
  20. double x_axis_rotation_s = sin(x_axis_rotation);
  21. // Find the last point
  22. FloatPoint last_point { 0, 0 };
  23. if (!m_segments.is_empty())
  24. last_point = m_segments.last().point();
  25. // Step 1 of out-of-range radii correction
  26. if (rx == 0.0 || ry == 0.0) {
  27. append_segment<LineSegment>(next_point);
  28. return;
  29. }
  30. // Step 2 of out-of-range radii correction
  31. if (rx < 0)
  32. rx *= -1.0;
  33. if (ry < 0)
  34. ry *= -1.0;
  35. // POSSIBLY HACK: Handle the case where both points are the same.
  36. auto same_endpoints = next_point == last_point;
  37. if (same_endpoints) {
  38. if (!large_arc) {
  39. // Nothing is going to be drawn anyway.
  40. return;
  41. }
  42. // Move the endpoint by a small amount to avoid division by zero.
  43. next_point.translate_by(0.01f, 0.01f);
  44. }
  45. // Find (cx, cy), theta_1, theta_delta
  46. // Step 1: Compute (x1', y1')
  47. auto x_avg = static_cast<double>(last_point.x() - next_point.x()) / 2.0;
  48. auto y_avg = static_cast<double>(last_point.y() - next_point.y()) / 2.0;
  49. auto x1p = x_axis_rotation_c * x_avg + x_axis_rotation_s * y_avg;
  50. auto y1p = -x_axis_rotation_s * x_avg + x_axis_rotation_c * y_avg;
  51. // Step 2: Compute (cx', cy')
  52. double x1p_sq = pow(x1p, 2.0);
  53. double y1p_sq = pow(y1p, 2.0);
  54. double rx_sq = pow(rx, 2.0);
  55. double ry_sq = pow(ry, 2.0);
  56. // Step 3 of out-of-range radii correction
  57. double lambda = x1p_sq / rx_sq + y1p_sq / ry_sq;
  58. double multiplier;
  59. if (lambda > 1.0) {
  60. auto lambda_sqrt = sqrt(lambda);
  61. rx *= lambda_sqrt;
  62. ry *= lambda_sqrt;
  63. multiplier = 0.0;
  64. } else {
  65. double numerator = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq;
  66. double denominator = rx_sq * y1p_sq + ry_sq * x1p_sq;
  67. multiplier = sqrt(numerator / denominator);
  68. }
  69. if (large_arc == sweep)
  70. multiplier *= -1.0;
  71. double cxp = multiplier * rx * y1p / ry;
  72. double cyp = multiplier * -ry * x1p / rx;
  73. // Step 3: Compute (cx, cy) from (cx', cy')
  74. x_avg = (last_point.x() + next_point.x()) / 2.0f;
  75. y_avg = (last_point.y() + next_point.y()) / 2.0f;
  76. double cx = x_axis_rotation_c * cxp - x_axis_rotation_s * cyp + x_avg;
  77. double cy = x_axis_rotation_s * cxp + x_axis_rotation_c * cyp + y_avg;
  78. double theta_1 = atan2((y1p - cyp) / ry, (x1p - cxp) / rx);
  79. double theta_2 = atan2((-y1p - cyp) / ry, (-x1p - cxp) / rx);
  80. auto theta_delta = theta_2 - theta_1;
  81. if (!sweep && theta_delta > 0.0) {
  82. theta_delta -= 2 * M_PI;
  83. } else if (sweep && theta_delta < 0) {
  84. theta_delta += 2 * M_PI;
  85. }
  86. elliptical_arc_to(
  87. next_point,
  88. { cx, cy },
  89. { rx, ry },
  90. x_axis_rotation,
  91. theta_1,
  92. theta_delta);
  93. }
  94. void Path::close()
  95. {
  96. if (m_segments.size() <= 1)
  97. return;
  98. invalidate_split_lines();
  99. auto& last_point = m_segments.last().point();
  100. for (ssize_t i = m_segments.size() - 1; i >= 0; --i) {
  101. auto& segment = m_segments[i];
  102. if (segment.type() == Segment::Type::MoveTo) {
  103. if (last_point == segment.point())
  104. return;
  105. append_segment<LineSegment>(segment.point());
  106. return;
  107. }
  108. }
  109. }
  110. void Path::close_all_subpaths()
  111. {
  112. if (m_segments.size() <= 1)
  113. return;
  114. invalidate_split_lines();
  115. Optional<FloatPoint> cursor, start_of_subpath;
  116. bool is_first_point_in_subpath { false };
  117. for (auto& segment : m_segments) {
  118. switch (segment.type()) {
  119. case Segment::Type::MoveTo: {
  120. if (cursor.has_value() && !is_first_point_in_subpath) {
  121. // This is a move from a subpath to another
  122. // connect the two ends of this subpath before
  123. // moving on to the next one
  124. VERIFY(start_of_subpath.has_value());
  125. append_segment<MoveSegment>(cursor.value());
  126. append_segment<LineSegment>(start_of_subpath.value());
  127. }
  128. is_first_point_in_subpath = true;
  129. cursor = segment.point();
  130. break;
  131. }
  132. case Segment::Type::LineTo:
  133. case Segment::Type::QuadraticBezierCurveTo:
  134. case Segment::Type::EllipticalArcTo:
  135. if (is_first_point_in_subpath) {
  136. start_of_subpath = cursor;
  137. is_first_point_in_subpath = false;
  138. }
  139. cursor = segment.point();
  140. break;
  141. case Segment::Type::Invalid:
  142. VERIFY_NOT_REACHED();
  143. break;
  144. }
  145. }
  146. }
  147. String Path::to_string() const
  148. {
  149. StringBuilder builder;
  150. builder.append("Path { ");
  151. for (auto& segment : m_segments) {
  152. switch (segment.type()) {
  153. case Segment::Type::MoveTo:
  154. builder.append("MoveTo");
  155. break;
  156. case Segment::Type::LineTo:
  157. builder.append("LineTo");
  158. break;
  159. case Segment::Type::QuadraticBezierCurveTo:
  160. builder.append("QuadraticBezierCurveTo");
  161. break;
  162. case Segment::Type::EllipticalArcTo:
  163. builder.append("EllipticalArcTo");
  164. break;
  165. case Segment::Type::Invalid:
  166. builder.append("Invalid");
  167. break;
  168. }
  169. builder.appendff("({}", segment.point());
  170. switch (segment.type()) {
  171. case Segment::Type::QuadraticBezierCurveTo:
  172. builder.append(", ");
  173. builder.append(static_cast<const QuadraticBezierCurveSegment&>(segment).through().to_string());
  174. break;
  175. case Segment::Type::EllipticalArcTo: {
  176. auto& arc = static_cast<const EllipticalArcSegment&>(segment);
  177. builder.appendff(", {}, {}, {}, {}, {}",
  178. arc.radii().to_string().characters(),
  179. arc.center().to_string().characters(),
  180. arc.x_axis_rotation(),
  181. arc.theta_1(),
  182. arc.theta_delta());
  183. break;
  184. }
  185. default:
  186. break;
  187. }
  188. builder.append(") ");
  189. }
  190. builder.append("}");
  191. return builder.to_string();
  192. }
  193. void Path::segmentize_path()
  194. {
  195. Vector<SplitLineSegment> segments;
  196. float min_x = 0;
  197. float min_y = 0;
  198. float max_x = 0;
  199. float max_y = 0;
  200. auto add_point_to_bbox = [&](const Gfx::FloatPoint& point) {
  201. float x = point.x();
  202. float y = point.y();
  203. min_x = min(min_x, x);
  204. min_y = min(min_y, y);
  205. max_x = max(max_x, x);
  206. max_y = max(max_y, y);
  207. };
  208. auto add_line = [&](const auto& p0, const auto& p1) {
  209. float ymax = p0.y(), ymin = p1.y(), x_of_ymin = p1.x(), x_of_ymax = p0.x();
  210. auto slope = p0.x() == p1.x() ? 0 : ((float)(p0.y() - p1.y())) / ((float)(p0.x() - p1.x()));
  211. if (p0.y() < p1.y()) {
  212. swap(ymin, ymax);
  213. swap(x_of_ymin, x_of_ymax);
  214. }
  215. segments.append({ FloatPoint(p0.x(), p0.y()),
  216. FloatPoint(p1.x(), p1.y()),
  217. slope == 0 ? 0 : 1 / slope,
  218. x_of_ymin,
  219. ymax, ymin, x_of_ymax });
  220. add_point_to_bbox(p1);
  221. };
  222. FloatPoint cursor { 0, 0 };
  223. bool first = true;
  224. for (auto& segment : m_segments) {
  225. switch (segment.type()) {
  226. case Segment::Type::MoveTo:
  227. if (first) {
  228. min_x = segment.point().x();
  229. min_y = segment.point().y();
  230. max_x = segment.point().x();
  231. max_y = segment.point().y();
  232. } else {
  233. add_point_to_bbox(segment.point());
  234. }
  235. cursor = segment.point();
  236. break;
  237. case Segment::Type::LineTo: {
  238. add_line(cursor, segment.point());
  239. cursor = segment.point();
  240. break;
  241. }
  242. case Segment::Type::QuadraticBezierCurveTo: {
  243. auto& control = static_cast<QuadraticBezierCurveSegment&>(segment).through();
  244. Painter::for_each_line_segment_on_bezier_curve(control, cursor, segment.point(), [&](const FloatPoint& p0, const FloatPoint& p1) {
  245. add_line(p0, p1);
  246. });
  247. cursor = segment.point();
  248. break;
  249. }
  250. case Segment::Type::EllipticalArcTo: {
  251. auto& arc = static_cast<EllipticalArcSegment&>(segment);
  252. Painter::for_each_line_segment_on_elliptical_arc(cursor, arc.point(), arc.center(), arc.radii(), arc.x_axis_rotation(), arc.theta_1(), arc.theta_delta(), [&](const FloatPoint& p0, const FloatPoint& p1) {
  253. add_line(p0, p1);
  254. });
  255. cursor = segment.point();
  256. break;
  257. }
  258. case Segment::Type::Invalid:
  259. VERIFY_NOT_REACHED();
  260. }
  261. first = false;
  262. }
  263. // sort segments by ymax
  264. quick_sort(segments, [](const auto& line0, const auto& line1) {
  265. return line1.maximum_y < line0.maximum_y;
  266. });
  267. m_split_lines = move(segments);
  268. m_bounding_box = Gfx::FloatRect { min_x, min_y, max_x - min_x, max_y - min_y };
  269. }
  270. }