Path.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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/Math.h>
  9. #include <AK/QuickSort.h>
  10. #include <AK/StringBuilder.h>
  11. #include <LibGfx/Painter.h>
  12. #include <LibGfx/Path.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 = AK::cos(x_axis_rotation);
  20. double x_axis_rotation_s = AK::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 = x1p * x1p;
  53. double y1p_sq = y1p * y1p;
  54. double rx_sq = rx * rx;
  55. double ry_sq = ry * ry;
  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 = AK::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 = AK::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 = AK::atan2((y1p - cyp) / ry, (x1p - cxp) / rx);
  79. double theta_2 = AK::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. large_arc,
  94. sweep);
  95. }
  96. void Path::close()
  97. {
  98. if (m_segments.size() <= 1)
  99. return;
  100. auto& last_point = m_segments.last().point();
  101. for (ssize_t i = m_segments.size() - 1; i >= 0; --i) {
  102. auto& segment = m_segments[i];
  103. if (segment.type() == Segment::Type::MoveTo) {
  104. if (last_point == segment.point())
  105. return;
  106. append_segment<LineSegment>(segment.point());
  107. invalidate_split_lines();
  108. return;
  109. }
  110. }
  111. }
  112. void Path::close_all_subpaths()
  113. {
  114. if (m_segments.size() <= 1)
  115. return;
  116. invalidate_split_lines();
  117. Optional<FloatPoint> cursor, start_of_subpath;
  118. bool is_first_point_in_subpath { false };
  119. for (auto& segment : m_segments) {
  120. switch (segment.type()) {
  121. case Segment::Type::MoveTo: {
  122. if (cursor.has_value() && !is_first_point_in_subpath) {
  123. // This is a move from a subpath to another
  124. // connect the two ends of this subpath before
  125. // moving on to the next one
  126. VERIFY(start_of_subpath.has_value());
  127. append_segment<MoveSegment>(cursor.value());
  128. append_segment<LineSegment>(start_of_subpath.value());
  129. }
  130. is_first_point_in_subpath = true;
  131. cursor = segment.point();
  132. break;
  133. }
  134. case Segment::Type::LineTo:
  135. case Segment::Type::QuadraticBezierCurveTo:
  136. case Segment::Type::CubicBezierCurveTo:
  137. case Segment::Type::EllipticalArcTo:
  138. if (is_first_point_in_subpath) {
  139. start_of_subpath = cursor;
  140. is_first_point_in_subpath = false;
  141. }
  142. cursor = segment.point();
  143. break;
  144. case Segment::Type::Invalid:
  145. VERIFY_NOT_REACHED();
  146. break;
  147. }
  148. }
  149. }
  150. String Path::to_string() const
  151. {
  152. StringBuilder builder;
  153. builder.append("Path { ");
  154. for (auto& segment : m_segments) {
  155. switch (segment.type()) {
  156. case Segment::Type::MoveTo:
  157. builder.append("MoveTo");
  158. break;
  159. case Segment::Type::LineTo:
  160. builder.append("LineTo");
  161. break;
  162. case Segment::Type::QuadraticBezierCurveTo:
  163. builder.append("QuadraticBezierCurveTo");
  164. break;
  165. case Segment::Type::CubicBezierCurveTo:
  166. builder.append("CubicBezierCurveTo");
  167. break;
  168. case Segment::Type::EllipticalArcTo:
  169. builder.append("EllipticalArcTo");
  170. break;
  171. case Segment::Type::Invalid:
  172. builder.append("Invalid");
  173. break;
  174. }
  175. builder.appendff("({}", segment.point());
  176. switch (segment.type()) {
  177. case Segment::Type::QuadraticBezierCurveTo:
  178. builder.append(", ");
  179. builder.append(static_cast<const QuadraticBezierCurveSegment&>(segment).through().to_string());
  180. break;
  181. case Segment::Type::CubicBezierCurveTo:
  182. builder.append(", ");
  183. builder.append(static_cast<const CubicBezierCurveSegment&>(segment).through_0().to_string());
  184. builder.append(", ");
  185. builder.append(static_cast<const CubicBezierCurveSegment&>(segment).through_1().to_string());
  186. break;
  187. case Segment::Type::EllipticalArcTo: {
  188. auto& arc = static_cast<const EllipticalArcSegment&>(segment);
  189. builder.appendff(", {}, {}, {}, {}, {}",
  190. arc.radii().to_string().characters(),
  191. arc.center().to_string().characters(),
  192. arc.x_axis_rotation(),
  193. arc.theta_1(),
  194. arc.theta_delta());
  195. break;
  196. }
  197. default:
  198. break;
  199. }
  200. builder.append(") ");
  201. }
  202. builder.append("}");
  203. return builder.to_string();
  204. }
  205. void Path::segmentize_path()
  206. {
  207. Vector<SplitLineSegment> segments;
  208. float min_x = 0;
  209. float min_y = 0;
  210. float max_x = 0;
  211. float max_y = 0;
  212. auto add_point_to_bbox = [&](const Gfx::FloatPoint& point) {
  213. float x = point.x();
  214. float y = point.y();
  215. min_x = min(min_x, x);
  216. min_y = min(min_y, y);
  217. max_x = max(max_x, x);
  218. max_y = max(max_y, y);
  219. };
  220. auto add_line = [&](const auto& p0, const auto& p1) {
  221. float ymax = p0.y(), ymin = p1.y(), x_of_ymin = p1.x(), x_of_ymax = p0.x();
  222. auto slope = p0.x() == p1.x() ? 0 : ((float)(p0.y() - p1.y())) / ((float)(p0.x() - p1.x()));
  223. if (p0.y() < p1.y()) {
  224. swap(ymin, ymax);
  225. swap(x_of_ymin, x_of_ymax);
  226. }
  227. segments.append({ FloatPoint(p0.x(), p0.y()),
  228. FloatPoint(p1.x(), p1.y()),
  229. slope == 0 ? 0 : 1 / slope,
  230. x_of_ymin,
  231. ymax, ymin, x_of_ymax });
  232. add_point_to_bbox(p1);
  233. };
  234. FloatPoint cursor { 0, 0 };
  235. bool first = true;
  236. for (auto& segment : m_segments) {
  237. switch (segment.type()) {
  238. case Segment::Type::MoveTo:
  239. if (first) {
  240. min_x = segment.point().x();
  241. min_y = segment.point().y();
  242. max_x = segment.point().x();
  243. max_y = segment.point().y();
  244. } else {
  245. add_point_to_bbox(segment.point());
  246. }
  247. cursor = segment.point();
  248. break;
  249. case Segment::Type::LineTo: {
  250. add_line(cursor, segment.point());
  251. cursor = segment.point();
  252. break;
  253. }
  254. case Segment::Type::QuadraticBezierCurveTo: {
  255. auto& control = static_cast<QuadraticBezierCurveSegment&>(segment).through();
  256. Painter::for_each_line_segment_on_bezier_curve(control, cursor, segment.point(), [&](const FloatPoint& p0, const FloatPoint& p1) {
  257. add_line(p0, p1);
  258. });
  259. cursor = segment.point();
  260. break;
  261. }
  262. case Segment::Type::CubicBezierCurveTo: {
  263. auto& curve = static_cast<CubicBezierCurveSegment const&>(segment);
  264. auto& control_0 = curve.through_0();
  265. auto& control_1 = curve.through_1();
  266. Painter::for_each_line_segment_on_cubic_bezier_curve(control_0, control_1, cursor, segment.point(), [&](const FloatPoint& p0, const FloatPoint& p1) {
  267. add_line(p0, p1);
  268. });
  269. cursor = segment.point();
  270. break;
  271. }
  272. case Segment::Type::EllipticalArcTo: {
  273. auto& arc = static_cast<EllipticalArcSegment&>(segment);
  274. 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) {
  275. add_line(p0, p1);
  276. });
  277. cursor = segment.point();
  278. break;
  279. }
  280. case Segment::Type::Invalid:
  281. VERIFY_NOT_REACHED();
  282. }
  283. first = false;
  284. }
  285. // sort segments by ymax
  286. quick_sort(segments, [](const auto& line0, const auto& line1) {
  287. return line1.maximum_y < line0.maximum_y;
  288. });
  289. m_split_lines = move(segments);
  290. m_bounding_box = Gfx::FloatRect { min_x, min_y, max_x - min_x, max_y - min_y };
  291. }
  292. }