geometry_2d.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. /**************************************************************************/
  2. /* geometry_2d.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #pragma once
  31. #include "core/math/delaunay_2d.h"
  32. #include "core/math/math_funcs.h"
  33. #include "core/math/triangulate.h"
  34. #include "core/math/vector2.h"
  35. #include "core/math/vector2i.h"
  36. #include "core/math/vector3.h"
  37. #include "core/math/vector3i.h"
  38. #include "core/templates/vector.h"
  39. class Geometry2D {
  40. public:
  41. static real_t get_closest_points_between_segments(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2, Vector2 &c1, Vector2 &c2) {
  42. Vector2 d1 = q1 - p1; // Direction vector of segment S1.
  43. Vector2 d2 = q2 - p2; // Direction vector of segment S2.
  44. Vector2 r = p1 - p2;
  45. real_t a = d1.dot(d1); // Squared length of segment S1, always nonnegative.
  46. real_t e = d2.dot(d2); // Squared length of segment S2, always nonnegative.
  47. real_t f = d2.dot(r);
  48. real_t s, t;
  49. // Check if either or both segments degenerate into points.
  50. if (a <= (real_t)CMP_EPSILON && e <= (real_t)CMP_EPSILON) {
  51. // Both segments degenerate into points.
  52. c1 = p1;
  53. c2 = p2;
  54. return Math::sqrt((c1 - c2).dot(c1 - c2));
  55. }
  56. if (a <= (real_t)CMP_EPSILON) {
  57. // First segment degenerates into a point.
  58. s = 0.0;
  59. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  60. t = CLAMP(t, 0.0f, 1.0f);
  61. } else {
  62. real_t c = d1.dot(r);
  63. if (e <= (real_t)CMP_EPSILON) {
  64. // Second segment degenerates into a point.
  65. t = 0.0;
  66. s = CLAMP(-c / a, 0.0f, 1.0f); // t = 0 => s = (b*t - c) / a = -c / a
  67. } else {
  68. // The general nondegenerate case starts here.
  69. real_t b = d1.dot(d2);
  70. real_t denom = a * e - b * b; // Always nonnegative.
  71. // If segments not parallel, compute closest point on L1 to L2 and
  72. // clamp to segment S1. Else pick arbitrary s (here 0).
  73. if (denom != 0.0f) {
  74. s = CLAMP((b * f - c * e) / denom, 0.0f, 1.0f);
  75. } else {
  76. s = 0.0;
  77. }
  78. // Compute point on L2 closest to S1(s) using
  79. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  80. t = (b * s + f) / e;
  81. //If t in [0,1] done. Else clamp t, recompute s for the new value
  82. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  83. // and clamp s to [0, 1].
  84. if (t < 0.0f) {
  85. t = 0.0;
  86. s = CLAMP(-c / a, 0.0f, 1.0f);
  87. } else if (t > 1.0f) {
  88. t = 1.0;
  89. s = CLAMP((b - c) / a, 0.0f, 1.0f);
  90. }
  91. }
  92. }
  93. c1 = p1 + d1 * s;
  94. c2 = p2 + d2 * t;
  95. return Math::sqrt((c1 - c2).dot(c1 - c2));
  96. }
  97. #ifndef DISABLE_DEPRECATED
  98. static Vector2 get_closest_point_to_segment(const Vector2 &p_point, const Vector2 *p_segment) {
  99. return get_closest_point_to_segment(p_point, p_segment[0], p_segment[1]);
  100. }
  101. #endif // DISABLE_DEPRECATED
  102. static Vector2 get_closest_point_to_segment(const Vector2 &p_point, const Vector2 &p_segment_a, const Vector2 &p_segment_b) {
  103. Vector2 p = p_point - p_segment_a;
  104. Vector2 n = p_segment_b - p_segment_a;
  105. real_t l2 = n.length_squared();
  106. if (l2 < 1e-20f) {
  107. return p_segment_a; // Both points are the same, just give any.
  108. }
  109. real_t d = n.dot(p) / l2;
  110. if (d <= 0.0f) {
  111. return p_segment_a; // Before first point.
  112. } else if (d >= 1.0f) {
  113. return p_segment_b; // After first point.
  114. } else {
  115. return p_segment_a + n * d; // Inside.
  116. }
  117. }
  118. #ifndef DISABLE_DEPRECATED
  119. static real_t get_distance_to_segment(const Vector2 &p_point, const Vector2 *p_segment) {
  120. return get_distance_to_segment(p_point, p_segment[0], p_segment[1]);
  121. }
  122. #endif // DISABLE_DEPRECATED
  123. static real_t get_distance_to_segment(const Vector2 &p_point, const Vector2 &p_segment_a, const Vector2 &p_segment_b) {
  124. return p_point.distance_to(get_closest_point_to_segment(p_point, p_segment_a, p_segment_b));
  125. }
  126. static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
  127. Vector2 an = a - s;
  128. Vector2 bn = b - s;
  129. Vector2 cn = c - s;
  130. bool orientation = an.cross(bn) > 0;
  131. if ((bn.cross(cn) > 0) != orientation) {
  132. return false;
  133. }
  134. return (cn.cross(an) > 0) == orientation;
  135. }
  136. #ifndef DISABLE_DEPRECATED
  137. static Vector2 get_closest_point_to_segment_uncapped(const Vector2 &p_point, const Vector2 *p_segment) {
  138. return get_closest_point_to_segment_uncapped(p_point, p_segment[0], p_segment[1]);
  139. }
  140. #endif // DISABLE_DEPRECATED
  141. static Vector2 get_closest_point_to_segment_uncapped(const Vector2 &p_point, const Vector2 &p_segment_a, const Vector2 &p_segment_b) {
  142. Vector2 p = p_point - p_segment_a;
  143. Vector2 n = p_segment_b - p_segment_a;
  144. real_t l2 = n.length_squared();
  145. if (l2 < 1e-20f) {
  146. return p_segment_a; // Both points are the same, just give any.
  147. }
  148. real_t d = n.dot(p) / l2;
  149. return p_segment_a + n * d; // Inside.
  150. }
  151. GODOT_MSVC_WARNING_PUSH_AND_IGNORE(4723) // Potential divide by 0. False positive (see: GH-44274).
  152. static bool line_intersects_line(const Vector2 &p_from_a, const Vector2 &p_dir_a, const Vector2 &p_from_b, const Vector2 &p_dir_b, Vector2 &r_result) {
  153. // See http://paulbourke.net/geometry/pointlineplane/
  154. const real_t denom = p_dir_b.y * p_dir_a.x - p_dir_b.x * p_dir_a.y;
  155. if (Math::is_zero_approx(denom)) { // Parallel?
  156. return false;
  157. }
  158. const Vector2 v = p_from_a - p_from_b;
  159. const real_t t = (p_dir_b.x * v.y - p_dir_b.y * v.x) / denom;
  160. r_result = p_from_a + t * p_dir_a;
  161. return true;
  162. }
  163. GODOT_MSVC_WARNING_POP
  164. static bool segment_intersects_segment(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b, Vector2 *r_result) {
  165. Vector2 B = p_to_a - p_from_a;
  166. Vector2 C = p_from_b - p_from_a;
  167. Vector2 D = p_to_b - p_from_a;
  168. real_t ABlen = B.dot(B);
  169. if (ABlen <= 0) {
  170. return false;
  171. }
  172. Vector2 Bn = B / ABlen;
  173. C = Vector2(C.x * Bn.x + C.y * Bn.y, C.y * Bn.x - C.x * Bn.y);
  174. D = Vector2(D.x * Bn.x + D.y * Bn.y, D.y * Bn.x - D.x * Bn.y);
  175. // Fail if C x B and D x B have the same sign (segments don't intersect).
  176. if ((C.y < (real_t)-CMP_EPSILON && D.y < (real_t)-CMP_EPSILON) || (C.y > (real_t)CMP_EPSILON && D.y > (real_t)CMP_EPSILON)) {
  177. return false;
  178. }
  179. // Fail if segments are parallel or colinear.
  180. // (when A x B == zero, i.e (C - D) x B == zero, i.e C x B == D x B)
  181. if (Math::is_equal_approx(C.y, D.y)) {
  182. return false;
  183. }
  184. real_t ABpos = D.x + (C.x - D.x) * D.y / (D.y - C.y);
  185. // Fail if segment C-D crosses line A-B outside of segment A-B.
  186. if ((ABpos < 0) || (ABpos > 1)) {
  187. return false;
  188. }
  189. // Apply the discovered position to line A-B in the original coordinate system.
  190. if (r_result) {
  191. *r_result = p_from_a + B * ABpos;
  192. }
  193. return true;
  194. }
  195. static inline bool is_point_in_circle(const Vector2 &p_point, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  196. return p_point.distance_squared_to(p_circle_pos) <= p_circle_radius * p_circle_radius;
  197. }
  198. static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  199. Vector2 line_vec = p_to - p_from;
  200. Vector2 vec_to_line = p_from - p_circle_pos;
  201. // Create a quadratic formula of the form ax^2 + bx + c = 0
  202. real_t a, b, c;
  203. a = line_vec.dot(line_vec);
  204. b = 2 * vec_to_line.dot(line_vec);
  205. c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius;
  206. // Solve for t.
  207. real_t sqrtterm = b * b - 4 * a * c;
  208. // If the term we intend to square root is less than 0 then the answer won't be real,
  209. // so it definitely won't be t in the range 0 to 1.
  210. if (sqrtterm < 0) {
  211. return -1;
  212. }
  213. // If we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection)
  214. // then the following can be skipped and we can just return the equivalent of res1.
  215. sqrtterm = Math::sqrt(sqrtterm);
  216. real_t res1 = (-b - sqrtterm) / (2 * a);
  217. real_t res2 = (-b + sqrtterm) / (2 * a);
  218. if (res1 >= 0 && res1 <= 1) {
  219. return res1;
  220. }
  221. if (res2 >= 0 && res2 <= 1) {
  222. return res2;
  223. }
  224. return -1;
  225. }
  226. static bool segment_intersects_rect(const Vector2 &p_from, const Vector2 &p_to, const Rect2 &p_rect) {
  227. if (p_rect.has_point(p_from) || p_rect.has_point(p_to)) {
  228. return true;
  229. }
  230. const Vector2 rect_points[4] = {
  231. p_rect.position,
  232. p_rect.position + Vector2(p_rect.size.x, 0),
  233. p_rect.position + p_rect.size,
  234. p_rect.position + Vector2(0, p_rect.size.y)
  235. };
  236. // Check if any of the rect's edges intersect the segment.
  237. for (int i = 0; i < 4; i++) {
  238. if (segment_intersects_segment(p_from, p_to, rect_points[i], rect_points[(i + 1) % 4], nullptr)) {
  239. return true;
  240. }
  241. }
  242. return false;
  243. }
  244. enum PolyBooleanOperation {
  245. OPERATION_UNION,
  246. OPERATION_DIFFERENCE,
  247. OPERATION_INTERSECTION,
  248. OPERATION_XOR
  249. };
  250. enum PolyJoinType {
  251. JOIN_SQUARE,
  252. JOIN_ROUND,
  253. JOIN_MITER
  254. };
  255. enum PolyEndType {
  256. END_POLYGON,
  257. END_JOINED,
  258. END_BUTT,
  259. END_SQUARE,
  260. END_ROUND
  261. };
  262. static Vector<Vector<Point2>> merge_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  263. return _polypaths_do_operation(OPERATION_UNION, p_polygon_a, p_polygon_b);
  264. }
  265. static Vector<Vector<Point2>> clip_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  266. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polygon_a, p_polygon_b);
  267. }
  268. static Vector<Vector<Point2>> intersect_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  269. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polygon_a, p_polygon_b);
  270. }
  271. static Vector<Vector<Point2>> exclude_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  272. return _polypaths_do_operation(OPERATION_XOR, p_polygon_a, p_polygon_b);
  273. }
  274. static Vector<Vector<Point2>> clip_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  275. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polyline, p_polygon, true);
  276. }
  277. static Vector<Vector<Point2>> intersect_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  278. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polyline, p_polygon, true);
  279. }
  280. static Vector<Vector<Point2>> offset_polygon(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type) {
  281. return _polypath_offset(p_polygon, p_delta, p_join_type, END_POLYGON);
  282. }
  283. static Vector<Vector<Point2>> offset_polyline(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  284. ERR_FAIL_COND_V_MSG(p_end_type == END_POLYGON, Vector<Vector<Point2>>(), "Attempt to offset a polyline like a polygon (use offset_polygon instead).");
  285. return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type);
  286. }
  287. static Vector<int> triangulate_delaunay(const Vector<Vector2> &p_points) {
  288. Vector<Delaunay2D::Triangle> tr = Delaunay2D::triangulate(p_points);
  289. Vector<int> triangles;
  290. triangles.resize(3 * tr.size());
  291. int *ptr = triangles.ptrw();
  292. for (int i = 0; i < tr.size(); i++) {
  293. *ptr++ = tr[i].points[0];
  294. *ptr++ = tr[i].points[1];
  295. *ptr++ = tr[i].points[2];
  296. }
  297. return triangles;
  298. }
  299. static Vector<int> triangulate_polygon(const Vector<Vector2> &p_polygon) {
  300. Vector<int> triangles;
  301. if (!Triangulate::triangulate(p_polygon, triangles)) {
  302. return Vector<int>(); //fail
  303. }
  304. return triangles;
  305. }
  306. // Assumes cartesian coordinate system with +x to the right, +y up.
  307. // If using screen coordinates (+x to the right, +y down) the result will need to be flipped.
  308. static bool is_polygon_clockwise(const Vector<Vector2> &p_polygon) {
  309. int c = p_polygon.size();
  310. if (c < 3) {
  311. return false;
  312. }
  313. const Vector2 *p = p_polygon.ptr();
  314. real_t sum = 0;
  315. for (int i = 0; i < c; i++) {
  316. const Vector2 &v1 = p[i];
  317. const Vector2 &v2 = p[(i + 1) % c];
  318. sum += (v2.x - v1.x) * (v2.y + v1.y);
  319. }
  320. return sum > 0.0f;
  321. }
  322. // Alternate implementation that should be faster.
  323. static bool is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  324. int c = p_polygon.size();
  325. if (c < 3) {
  326. return false;
  327. }
  328. const Vector2 *p = p_polygon.ptr();
  329. Vector2 further_away(-1e20, -1e20);
  330. Vector2 further_away_opposite(1e20, 1e20);
  331. for (int i = 0; i < c; i++) {
  332. further_away = further_away.max(p[i]);
  333. further_away_opposite = further_away_opposite.min(p[i]);
  334. }
  335. // Make point outside that won't intersect with points in segment from p_point.
  336. further_away += (further_away - further_away_opposite) * Vector2(1.221313, 1.512312);
  337. int intersections = 0;
  338. for (int i = 0; i < c; i++) {
  339. const Vector2 &v1 = p[i];
  340. const Vector2 &v2 = p[(i + 1) % c];
  341. Vector2 res;
  342. if (segment_intersects_segment(v1, v2, p_point, further_away, &res)) {
  343. intersections++;
  344. if (res.is_equal_approx(p_point)) {
  345. // Point is in one of the polygon edges.
  346. return true;
  347. }
  348. }
  349. }
  350. return (intersections & 1);
  351. }
  352. static bool is_segment_intersecting_polygon(const Vector2 &p_from, const Vector2 &p_to, const Vector<Vector2> &p_polygon) {
  353. int c = p_polygon.size();
  354. const Vector2 *p = p_polygon.ptr();
  355. for (int i = 0; i < c; i++) {
  356. const Vector2 &v1 = p[i];
  357. const Vector2 &v2 = p[(i + 1) % c];
  358. if (segment_intersects_segment(p_from, p_to, v1, v2, nullptr)) {
  359. return true;
  360. }
  361. }
  362. return false;
  363. }
  364. static real_t vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) {
  365. return (real_t)(A.x - O.x) * (B.y - O.y) - (real_t)(A.y - O.y) * (B.x - O.x);
  366. }
  367. // Returns a list of points on the convex hull in counter-clockwise order.
  368. // Note: the last point in the returned list is the same as the first one.
  369. static Vector<Point2> convex_hull(Vector<Point2> P) {
  370. int n = P.size(), k = 0;
  371. Vector<Point2> H;
  372. H.resize(2 * n);
  373. // Sort points lexicographically.
  374. P.sort();
  375. // Build lower hull.
  376. for (int i = 0; i < n; ++i) {
  377. while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) {
  378. k--;
  379. }
  380. H.write[k++] = P[i];
  381. }
  382. // Build upper hull.
  383. for (int i = n - 2, t = k + 1; i >= 0; i--) {
  384. while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) {
  385. k--;
  386. }
  387. H.write[k++] = P[i];
  388. }
  389. H.resize(k);
  390. return H;
  391. }
  392. static Vector<Point2i> bresenham_line(const Point2i &p_from, const Point2i &p_to) {
  393. Vector<Point2i> points;
  394. Vector2i delta = (p_to - p_from).abs() * 2;
  395. Vector2i step = (p_to - p_from).sign();
  396. Vector2i current = p_from;
  397. if (delta.x > delta.y) {
  398. int err = delta.x / 2;
  399. for (; current.x != p_to.x; current.x += step.x) {
  400. points.push_back(current);
  401. err -= delta.y;
  402. if (err < 0) {
  403. current.y += step.y;
  404. err += delta.x;
  405. }
  406. }
  407. } else {
  408. int err = delta.y / 2;
  409. for (; current.y != p_to.y; current.y += step.y) {
  410. points.push_back(current);
  411. err -= delta.x;
  412. if (err < 0) {
  413. current.x += step.x;
  414. err += delta.y;
  415. }
  416. }
  417. }
  418. points.push_back(current);
  419. return points;
  420. }
  421. static void merge_many_polygons(const Vector<Vector<Point2>> &p_polygons, Vector<Vector<Vector2>> &r_out_polygons, Vector<Vector<Vector2>> &r_out_holes);
  422. static Vector<Vector<Vector2>> decompose_many_polygons_in_convex(const Vector<Vector<Point2>> &p_polygons, const Vector<Vector<Point2>> &p_holes);
  423. static Vector<Vector<Vector2>> decompose_polygon_in_convex(const Vector<Point2> &p_polygon);
  424. static void make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size);
  425. static Vector<Vector3i> partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size);
  426. private:
  427. static Vector<Vector<Point2>> _polypaths_do_operation(PolyBooleanOperation p_op, const Vector<Point2> &p_polypath_a, const Vector<Point2> &p_polypath_b, bool is_a_open = false);
  428. static Vector<Vector<Point2>> _polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type);
  429. };