Path.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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 <AK/TypeCasts.h>
  12. #include <LibGfx/Font/ScaledFont.h>
  13. #include <LibGfx/Painter.h>
  14. #include <LibGfx/Path.h>
  15. #include <LibGfx/TextLayout.h>
  16. namespace Gfx {
  17. void Path::approximate_elliptical_arc_with_cubic_beziers(FloatPoint center, FloatSize radii, float x_axis_rotation, float theta, float theta_delta)
  18. {
  19. float sin_x_rotation;
  20. float cos_x_rotation;
  21. AK::sincos(x_axis_rotation, sin_x_rotation, cos_x_rotation);
  22. auto arc_point_and_derivative = [&](float t, FloatPoint& point, FloatPoint& derivative) {
  23. float sin_angle;
  24. float cos_angle;
  25. AK::sincos(t, sin_angle, cos_angle);
  26. point = FloatPoint {
  27. center.x()
  28. + radii.width() * cos_x_rotation * cos_angle
  29. - radii.height() * sin_x_rotation * sin_angle,
  30. center.y()
  31. + radii.width() * sin_x_rotation * cos_angle
  32. + radii.height() * cos_x_rotation * sin_angle,
  33. };
  34. derivative = FloatPoint {
  35. -radii.width() * cos_x_rotation * sin_angle
  36. - radii.height() * sin_x_rotation * cos_angle,
  37. -radii.width() * sin_x_rotation * sin_angle
  38. + radii.height() * cos_x_rotation * cos_angle,
  39. };
  40. };
  41. auto approximate_arc_between = [&](float start_angle, float end_angle) {
  42. auto t = AK::tan((end_angle - start_angle) / 2);
  43. auto alpha = AK::sin(end_angle - start_angle) * ((AK::sqrt(4 + 3 * t * t) - 1) / 3);
  44. FloatPoint p1, d1;
  45. FloatPoint p2, d2;
  46. arc_point_and_derivative(start_angle, p1, d1);
  47. arc_point_and_derivative(end_angle, p2, d2);
  48. auto q1 = p1 + d1.scaled(alpha, alpha);
  49. auto q2 = p2 - d2.scaled(alpha, alpha);
  50. cubic_bezier_curve_to(q1, q2, p2);
  51. };
  52. // FIXME: Come up with a more mathematically sound step size (using some error calculation).
  53. auto step = theta_delta;
  54. int step_count = 1;
  55. while (fabs(step) > AK::Pi<float> / 4) {
  56. step /= 2;
  57. step_count *= 2;
  58. }
  59. float prev = theta;
  60. float t = prev + step;
  61. for (int i = 0; i < step_count; i++, prev = t, t += step)
  62. approximate_arc_between(prev, t);
  63. }
  64. void Path::elliptical_arc_to(FloatPoint point, FloatSize radii, float x_axis_rotation, bool large_arc, bool sweep)
  65. {
  66. auto next_point = point;
  67. double rx = radii.width();
  68. double ry = radii.height();
  69. double x_axis_rotation_s;
  70. double x_axis_rotation_c;
  71. AK::sincos(static_cast<double>(x_axis_rotation), x_axis_rotation_s, x_axis_rotation_c);
  72. FloatPoint last_point = this->last_point();
  73. // Step 1 of out-of-range radii correction
  74. if (rx == 0.0 || ry == 0.0) {
  75. append_segment<LineSegment>(next_point);
  76. return;
  77. }
  78. // Step 2 of out-of-range radii correction
  79. if (rx < 0)
  80. rx *= -1.0;
  81. if (ry < 0)
  82. ry *= -1.0;
  83. // POSSIBLY HACK: Handle the case where both points are the same.
  84. auto same_endpoints = next_point == last_point;
  85. if (same_endpoints) {
  86. if (!large_arc) {
  87. // Nothing is going to be drawn anyway.
  88. return;
  89. }
  90. // Move the endpoint by a small amount to avoid division by zero.
  91. next_point.translate_by(0.01f, 0.01f);
  92. }
  93. // Find (cx, cy), theta_1, theta_delta
  94. // Step 1: Compute (x1', y1')
  95. auto x_avg = static_cast<double>(last_point.x() - next_point.x()) / 2.0;
  96. auto y_avg = static_cast<double>(last_point.y() - next_point.y()) / 2.0;
  97. auto x1p = x_axis_rotation_c * x_avg + x_axis_rotation_s * y_avg;
  98. auto y1p = -x_axis_rotation_s * x_avg + x_axis_rotation_c * y_avg;
  99. // Step 2: Compute (cx', cy')
  100. double x1p_sq = x1p * x1p;
  101. double y1p_sq = y1p * y1p;
  102. double rx_sq = rx * rx;
  103. double ry_sq = ry * ry;
  104. // Step 3 of out-of-range radii correction
  105. double lambda = x1p_sq / rx_sq + y1p_sq / ry_sq;
  106. double multiplier;
  107. if (lambda > 1.0) {
  108. auto lambda_sqrt = AK::sqrt(lambda);
  109. rx *= lambda_sqrt;
  110. ry *= lambda_sqrt;
  111. multiplier = 0.0;
  112. } else {
  113. double numerator = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq;
  114. double denominator = rx_sq * y1p_sq + ry_sq * x1p_sq;
  115. multiplier = AK::sqrt(numerator / denominator);
  116. }
  117. if (large_arc == sweep)
  118. multiplier *= -1.0;
  119. double cxp = multiplier * rx * y1p / ry;
  120. double cyp = multiplier * -ry * x1p / rx;
  121. // Step 3: Compute (cx, cy) from (cx', cy')
  122. x_avg = (last_point.x() + next_point.x()) / 2.0f;
  123. y_avg = (last_point.y() + next_point.y()) / 2.0f;
  124. double cx = x_axis_rotation_c * cxp - x_axis_rotation_s * cyp + x_avg;
  125. double cy = x_axis_rotation_s * cxp + x_axis_rotation_c * cyp + y_avg;
  126. double theta_1 = AK::atan2((y1p - cyp) / ry, (x1p - cxp) / rx);
  127. double theta_2 = AK::atan2((-y1p - cyp) / ry, (-x1p - cxp) / rx);
  128. auto theta_delta = theta_2 - theta_1;
  129. if (!sweep && theta_delta > 0.0) {
  130. theta_delta -= 2 * AK::Pi<double>;
  131. } else if (sweep && theta_delta < 0) {
  132. theta_delta += 2 * AK::Pi<double>;
  133. }
  134. approximate_elliptical_arc_with_cubic_beziers(
  135. { cx, cy },
  136. { rx, ry },
  137. x_axis_rotation,
  138. theta_1,
  139. theta_delta);
  140. }
  141. void Path::text(Utf8View text, Font const& font)
  142. {
  143. if (!is<ScaledFont>(font)) {
  144. // FIXME: This API only accepts Gfx::Font for ease of use.
  145. dbgln("Cannot path-ify bitmap fonts!");
  146. return;
  147. }
  148. auto& scaled_font = static_cast<ScaledFont const&>(font);
  149. for_each_glyph_position(
  150. last_point(), text, font, [&](GlyphPosition glyph_position) {
  151. move_to(glyph_position.position);
  152. // FIXME: This does not correctly handle multi-codepoint glyphs (i.e. emojis).
  153. auto glyph_id = scaled_font.glyph_id_for_code_point(*glyph_position.it);
  154. scaled_font.append_glyph_path_to(*this, glyph_id);
  155. },
  156. IncludeLeftBearing::Yes);
  157. }
  158. FloatPoint Path::last_point()
  159. {
  160. FloatPoint last_point { 0, 0 };
  161. if (!m_segments.is_empty())
  162. last_point = m_segments.last()->point();
  163. return last_point;
  164. }
  165. void Path::close()
  166. {
  167. if (m_segments.size() <= 1)
  168. return;
  169. auto last_point = m_segments.last()->point();
  170. for (ssize_t i = m_segments.size() - 1; i >= 0; --i) {
  171. auto& segment = m_segments[i];
  172. if (segment->type() == Segment::Type::MoveTo) {
  173. if (last_point == segment->point())
  174. return;
  175. append_segment<LineSegment>(segment->point());
  176. invalidate_split_lines();
  177. return;
  178. }
  179. }
  180. }
  181. void Path::close_all_subpaths()
  182. {
  183. if (m_segments.size() <= 1)
  184. return;
  185. invalidate_split_lines();
  186. Optional<FloatPoint> cursor, start_of_subpath;
  187. bool is_first_point_in_subpath { false };
  188. auto close_previous_subpath = [&] {
  189. if (cursor.has_value() && !is_first_point_in_subpath) {
  190. // This is a move from a subpath to another
  191. // connect the two ends of this subpath before
  192. // moving on to the next one
  193. VERIFY(start_of_subpath.has_value());
  194. append_segment<MoveSegment>(cursor.value());
  195. append_segment<LineSegment>(start_of_subpath.value());
  196. }
  197. };
  198. auto segment_count = m_segments.size();
  199. for (size_t i = 0; i < segment_count; i++) {
  200. // Note: We need to use m_segments[i] as append_segment() may invalidate any references.
  201. switch (m_segments[i]->type()) {
  202. case Segment::Type::MoveTo: {
  203. close_previous_subpath();
  204. is_first_point_in_subpath = true;
  205. cursor = m_segments[i]->point();
  206. break;
  207. }
  208. case Segment::Type::LineTo:
  209. case Segment::Type::QuadraticBezierCurveTo:
  210. case Segment::Type::CubicBezierCurveTo:
  211. if (is_first_point_in_subpath) {
  212. start_of_subpath = cursor;
  213. is_first_point_in_subpath = false;
  214. }
  215. cursor = m_segments[i]->point();
  216. break;
  217. case Segment::Type::Invalid:
  218. VERIFY_NOT_REACHED();
  219. break;
  220. }
  221. }
  222. if (m_segments.last()->type() != Segment::Type::MoveTo)
  223. close_previous_subpath();
  224. }
  225. DeprecatedString Path::to_deprecated_string() const
  226. {
  227. StringBuilder builder;
  228. builder.append("Path { "sv);
  229. for (auto& segment : m_segments) {
  230. switch (segment->type()) {
  231. case Segment::Type::MoveTo:
  232. builder.append("MoveTo"sv);
  233. break;
  234. case Segment::Type::LineTo:
  235. builder.append("LineTo"sv);
  236. break;
  237. case Segment::Type::QuadraticBezierCurveTo:
  238. builder.append("QuadraticBezierCurveTo"sv);
  239. break;
  240. case Segment::Type::CubicBezierCurveTo:
  241. builder.append("CubicBezierCurveTo"sv);
  242. break;
  243. case Segment::Type::Invalid:
  244. builder.append("Invalid"sv);
  245. break;
  246. }
  247. builder.appendff("({}", segment->point());
  248. switch (segment->type()) {
  249. case Segment::Type::QuadraticBezierCurveTo:
  250. builder.append(", "sv);
  251. builder.append(static_cast<QuadraticBezierCurveSegment const&>(*segment).through().to_deprecated_string());
  252. break;
  253. case Segment::Type::CubicBezierCurveTo:
  254. builder.append(", "sv);
  255. builder.append(static_cast<CubicBezierCurveSegment const&>(*segment).through_0().to_deprecated_string());
  256. builder.append(", "sv);
  257. builder.append(static_cast<CubicBezierCurveSegment const&>(*segment).through_1().to_deprecated_string());
  258. break;
  259. default:
  260. break;
  261. }
  262. builder.append(") "sv);
  263. }
  264. builder.append('}');
  265. return builder.to_deprecated_string();
  266. }
  267. void Path::segmentize_path()
  268. {
  269. Vector<FloatLine> segments;
  270. float min_x = 0;
  271. float min_y = 0;
  272. float max_x = 0;
  273. float max_y = 0;
  274. bool first = true;
  275. auto add_point_to_bbox = [&](Gfx::FloatPoint point) {
  276. float x = point.x();
  277. float y = point.y();
  278. if (first) {
  279. min_x = max_x = x;
  280. min_y = max_y = y;
  281. first = false;
  282. } else {
  283. min_x = min(min_x, x);
  284. min_y = min(min_y, y);
  285. max_x = max(max_x, x);
  286. max_y = max(max_y, y);
  287. }
  288. };
  289. auto add_line = [&](auto const& p0, auto const& p1) {
  290. segments.append({ p0, p1 });
  291. add_point_to_bbox(p1);
  292. };
  293. FloatPoint cursor { 0, 0 };
  294. for (auto& segment : m_segments) {
  295. switch (segment->type()) {
  296. case Segment::Type::MoveTo:
  297. add_point_to_bbox(segment->point());
  298. cursor = segment->point();
  299. break;
  300. case Segment::Type::LineTo: {
  301. add_line(cursor, segment->point());
  302. cursor = segment->point();
  303. break;
  304. }
  305. case Segment::Type::QuadraticBezierCurveTo: {
  306. auto control = static_cast<QuadraticBezierCurveSegment const&>(*segment).through();
  307. Painter::for_each_line_segment_on_bezier_curve(control, cursor, segment->point(), [&](FloatPoint p0, FloatPoint p1) {
  308. add_line(p0, p1);
  309. });
  310. cursor = segment->point();
  311. break;
  312. }
  313. case Segment::Type::CubicBezierCurveTo: {
  314. auto& curve = static_cast<CubicBezierCurveSegment const&>(*segment);
  315. auto control_0 = curve.through_0();
  316. auto control_1 = curve.through_1();
  317. Painter::for_each_line_segment_on_cubic_bezier_curve(control_0, control_1, cursor, segment->point(), [&](FloatPoint p0, FloatPoint p1) {
  318. add_line(p0, p1);
  319. });
  320. cursor = segment->point();
  321. break;
  322. }
  323. case Segment::Type::Invalid:
  324. VERIFY_NOT_REACHED();
  325. }
  326. first = false;
  327. }
  328. m_split_lines = move(segments);
  329. m_bounding_box = Gfx::FloatRect { min_x, min_y, max_x - min_x, max_y - min_y };
  330. }
  331. Path Path::copy_transformed(Gfx::AffineTransform const& transform) const
  332. {
  333. Path result;
  334. for (auto const& segment : m_segments) {
  335. switch (segment->type()) {
  336. case Segment::Type::MoveTo:
  337. result.move_to(transform.map(segment->point()));
  338. break;
  339. case Segment::Type::LineTo: {
  340. result.line_to(transform.map(segment->point()));
  341. break;
  342. }
  343. case Segment::Type::QuadraticBezierCurveTo: {
  344. auto const& quadratic_segment = static_cast<QuadraticBezierCurveSegment const&>(*segment);
  345. result.quadratic_bezier_curve_to(transform.map(quadratic_segment.through()), transform.map(segment->point()));
  346. break;
  347. }
  348. case Segment::Type::CubicBezierCurveTo: {
  349. auto const& cubic_segment = static_cast<CubicBezierCurveSegment const&>(*segment);
  350. result.cubic_bezier_curve_to(transform.map(cubic_segment.through_0()), transform.map(cubic_segment.through_1()), transform.map(segment->point()));
  351. break;
  352. }
  353. case Segment::Type::Invalid:
  354. VERIFY_NOT_REACHED();
  355. }
  356. }
  357. return result;
  358. }
  359. void Path::add_path(Path const& other)
  360. {
  361. m_segments.extend(other.m_segments);
  362. invalidate_split_lines();
  363. }
  364. void Path::ensure_subpath(FloatPoint point)
  365. {
  366. if (m_need_new_subpath && m_segments.is_empty()) {
  367. move_to(point);
  368. m_need_new_subpath = false;
  369. }
  370. }
  371. template<typename T>
  372. struct RoundTrip {
  373. RoundTrip(ReadonlySpan<T> span)
  374. : m_span(span)
  375. {
  376. }
  377. size_t size() const
  378. {
  379. return m_span.size() * 2 - 1;
  380. }
  381. T const& operator[](size_t index) const
  382. {
  383. // Follow the path:
  384. if (index < m_span.size())
  385. return m_span[index];
  386. // Then in reverse:
  387. if (index < size())
  388. return m_span[size() - index - 1];
  389. // Then wrap around again:
  390. return m_span[index - size() + 1];
  391. }
  392. private:
  393. ReadonlySpan<T> m_span;
  394. };
  395. Path Path::stroke_to_fill(float thickness) const
  396. {
  397. // Note: This convolves a polygon with the path using the algorithm described
  398. // in https://keithp.com/~keithp/talks/cairo2003.pdf (3.1 Stroking Splines via Convolution)
  399. VERIFY(thickness > 0);
  400. auto& lines = split_lines();
  401. if (lines.is_empty())
  402. return Path {};
  403. // Paths can be disconnected, which a pain to deal with, so split it up.
  404. Vector<Vector<FloatPoint>> segments;
  405. segments.append({ lines.first().a() });
  406. for (auto& line : lines) {
  407. if (line.a() == segments.last().last()) {
  408. segments.last().append(line.b());
  409. } else {
  410. segments.append({ line.a(), line.b() });
  411. }
  412. }
  413. // Note: This is the same as the tolerance from bezier curve splitting.
  414. constexpr auto flatness = 0.015f;
  415. auto pen_vertex_count = max(
  416. static_cast<int>(ceilf(AK::Pi<float> / acosf(1 - (2 * flatness) / thickness))), 4);
  417. if (pen_vertex_count % 2 == 1)
  418. pen_vertex_count += 1;
  419. Vector<FloatPoint, 128> pen_vertices;
  420. pen_vertices.ensure_capacity(pen_vertex_count);
  421. // Generate vertices for the pen (going counterclockwise). The pen does not necessarily need
  422. // to be a circle (or an approximation of one), but other shapes are untested.
  423. float theta = 0;
  424. float theta_delta = (AK::Pi<float> * 2) / pen_vertex_count;
  425. for (int i = 0; i < pen_vertex_count; i++) {
  426. float sin_theta;
  427. float cos_theta;
  428. AK::sincos(theta, sin_theta, cos_theta);
  429. pen_vertices.unchecked_append({ cos_theta * thickness / 2, sin_theta * thickness / 2 });
  430. theta -= theta_delta;
  431. }
  432. auto wrapping_index = [](auto& vertices, auto index) {
  433. return vertices[(index + vertices.size()) % vertices.size()];
  434. };
  435. auto angle_between = [](auto p1, auto p2) {
  436. auto delta = p2 - p1;
  437. return atan2f(delta.y(), delta.x());
  438. };
  439. struct ActiveRange {
  440. float start;
  441. float end;
  442. bool in_range(float angle) const
  443. {
  444. // Note: Since active ranges go counterclockwise start > end unless we wrap around at 180 degrees
  445. return ((angle <= start && angle >= end)
  446. || (start < end && angle <= start)
  447. || (start < end && angle >= end));
  448. }
  449. };
  450. Vector<ActiveRange, 128> active_ranges;
  451. active_ranges.ensure_capacity(pen_vertices.size());
  452. for (auto i = 0; i < pen_vertex_count; i++) {
  453. active_ranges.unchecked_append({ angle_between(wrapping_index(pen_vertices, i - 1), pen_vertices[i]),
  454. angle_between(pen_vertices[i], wrapping_index(pen_vertices, i + 1)) });
  455. }
  456. auto clockwise = [](float current_angle, float target_angle) {
  457. if (target_angle < 0)
  458. target_angle += AK::Pi<float> * 2;
  459. if (current_angle < 0)
  460. current_angle += AK::Pi<float> * 2;
  461. if (target_angle < current_angle)
  462. target_angle += AK::Pi<float> * 2;
  463. return (target_angle - current_angle) <= AK::Pi<float>;
  464. };
  465. Path convolution;
  466. for (auto& segment : segments) {
  467. RoundTrip<FloatPoint> shape { segment };
  468. bool first = true;
  469. auto add_vertex = [&](auto v) {
  470. if (first) {
  471. convolution.move_to(v);
  472. first = false;
  473. } else {
  474. convolution.line_to(v);
  475. }
  476. };
  477. auto shape_idx = 0u;
  478. auto slope = [&] {
  479. return angle_between(shape[shape_idx], shape[shape_idx + 1]);
  480. };
  481. auto start_slope = slope();
  482. // Note: At least one range must be active.
  483. auto active = *active_ranges.find_first_index_if([&](auto& range) {
  484. return range.in_range(start_slope);
  485. });
  486. while (shape_idx < shape.size()) {
  487. add_vertex(shape[shape_idx] + pen_vertices[active]);
  488. auto slope_now = slope();
  489. auto range = active_ranges[active];
  490. if (range.in_range(slope_now)) {
  491. shape_idx++;
  492. } else {
  493. if (clockwise(slope_now, range.end)) {
  494. if (active == static_cast<size_t>(pen_vertex_count - 1))
  495. active = 0;
  496. else
  497. active++;
  498. } else {
  499. if (active == 0)
  500. active = pen_vertex_count - 1;
  501. else
  502. active--;
  503. }
  504. }
  505. }
  506. }
  507. return convolution;
  508. }
  509. }