geometry_2d.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. /*************************************************************************/
  2. /* geometry_2d.h */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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. #ifndef GEOMETRY_2D_H
  31. #define GEOMETRY_2D_H
  32. #include "core/math/delaunay_2d.h"
  33. #include "core/math/rect2.h"
  34. #include "core/math/triangulate.h"
  35. #include "core/object/object.h"
  36. #include "core/templates/vector.h"
  37. class Geometry2D {
  38. Geometry2D();
  39. public:
  40. static real_t get_closest_points_between_segments(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2, Vector2 &c1, Vector2 &c2) {
  41. Vector2 d1 = q1 - p1; // Direction vector of segment S1.
  42. Vector2 d2 = q2 - p2; // Direction vector of segment S2.
  43. Vector2 r = p1 - p2;
  44. real_t a = d1.dot(d1); // Squared length of segment S1, always nonnegative.
  45. real_t e = d2.dot(d2); // Squared length of segment S2, always nonnegative.
  46. real_t f = d2.dot(r);
  47. real_t s, t;
  48. // Check if either or both segments degenerate into points.
  49. if (a <= CMP_EPSILON && e <= CMP_EPSILON) {
  50. // Both segments degenerate into points.
  51. c1 = p1;
  52. c2 = p2;
  53. return Math::sqrt((c1 - c2).dot(c1 - c2));
  54. }
  55. if (a <= CMP_EPSILON) {
  56. // First segment degenerates into a point.
  57. s = 0.0;
  58. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  59. t = CLAMP(t, 0.0, 1.0);
  60. } else {
  61. real_t c = d1.dot(r);
  62. if (e <= CMP_EPSILON) {
  63. // Second segment degenerates into a point.
  64. t = 0.0;
  65. s = CLAMP(-c / a, 0.0, 1.0); // t = 0 => s = (b*t - c) / a = -c / a
  66. } else {
  67. // The general nondegenerate case starts here.
  68. real_t b = d1.dot(d2);
  69. real_t denom = a * e - b * b; // Always nonnegative.
  70. // If segments not parallel, compute closest point on L1 to L2 and
  71. // clamp to segment S1. Else pick arbitrary s (here 0).
  72. if (denom != 0.0) {
  73. s = CLAMP((b * f - c * e) / denom, 0.0, 1.0);
  74. } else {
  75. s = 0.0;
  76. }
  77. // Compute point on L2 closest to S1(s) using
  78. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  79. t = (b * s + f) / e;
  80. //If t in [0,1] done. Else clamp t, recompute s for the new value
  81. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  82. // and clamp s to [0, 1].
  83. if (t < 0.0) {
  84. t = 0.0;
  85. s = CLAMP(-c / a, 0.0, 1.0);
  86. } else if (t > 1.0) {
  87. t = 1.0;
  88. s = CLAMP((b - c) / a, 0.0, 1.0);
  89. }
  90. }
  91. }
  92. c1 = p1 + d1 * s;
  93. c2 = p2 + d2 * t;
  94. return Math::sqrt((c1 - c2).dot(c1 - c2));
  95. }
  96. static Vector2 get_closest_point_to_segment(const Vector2 &p_point, const Vector2 *p_segment) {
  97. Vector2 p = p_point - p_segment[0];
  98. Vector2 n = p_segment[1] - p_segment[0];
  99. real_t l2 = n.length_squared();
  100. if (l2 < 1e-20) {
  101. return p_segment[0]; // Both points are the same, just give any.
  102. }
  103. real_t d = n.dot(p) / l2;
  104. if (d <= 0.0) {
  105. return p_segment[0]; // Before first point.
  106. } else if (d >= 1.0) {
  107. return p_segment[1]; // After first point.
  108. } else {
  109. return p_segment[0] + n * d; // Inside.
  110. }
  111. }
  112. static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
  113. Vector2 an = a - s;
  114. Vector2 bn = b - s;
  115. Vector2 cn = c - s;
  116. bool orientation = an.cross(bn) > 0;
  117. if ((bn.cross(cn) > 0) != orientation) {
  118. return false;
  119. }
  120. return (cn.cross(an) > 0) == orientation;
  121. }
  122. static Vector2 get_closest_point_to_segment_uncapped(const Vector2 &p_point, const Vector2 *p_segment) {
  123. Vector2 p = p_point - p_segment[0];
  124. Vector2 n = p_segment[1] - p_segment[0];
  125. real_t l2 = n.length_squared();
  126. if (l2 < 1e-20) {
  127. return p_segment[0]; // Both points are the same, just give any.
  128. }
  129. real_t d = n.dot(p) / l2;
  130. return p_segment[0] + n * d; // Inside.
  131. }
  132. // Disable False Positives in MSVC compiler; we correctly check for 0 here to prevent a division by 0.
  133. // See: https://github.com/godotengine/godot/pull/44274
  134. #ifdef _MSC_VER
  135. #pragma warning(disable : 4723)
  136. #endif
  137. 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) {
  138. // See http://paulbourke.net/geometry/pointlineplane/
  139. const real_t denom = p_dir_b.y * p_dir_a.x - p_dir_b.x * p_dir_a.y;
  140. if (Math::is_zero_approx(denom)) { // Parallel?
  141. return false;
  142. }
  143. const Vector2 v = p_from_a - p_from_b;
  144. const real_t t = (p_dir_b.x * v.y - p_dir_b.y * v.x) / denom;
  145. r_result = p_from_a + t * p_dir_a;
  146. return true;
  147. }
  148. // Re-enable division by 0 warning
  149. #ifdef _MSC_VER
  150. #pragma warning(default : 4723)
  151. #endif
  152. 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) {
  153. Vector2 B = p_to_a - p_from_a;
  154. Vector2 C = p_from_b - p_from_a;
  155. Vector2 D = p_to_b - p_from_a;
  156. real_t ABlen = B.dot(B);
  157. if (ABlen <= 0) {
  158. return false;
  159. }
  160. Vector2 Bn = B / ABlen;
  161. C = Vector2(C.x * Bn.x + C.y * Bn.y, C.y * Bn.x - C.x * Bn.y);
  162. D = Vector2(D.x * Bn.x + D.y * Bn.y, D.y * Bn.x - D.x * Bn.y);
  163. if ((C.y < 0 && D.y < 0) || (C.y >= 0 && D.y >= 0)) {
  164. return false;
  165. }
  166. real_t ABpos = D.x + (C.x - D.x) * D.y / (D.y - C.y);
  167. // Fail if segment C-D crosses line A-B outside of segment A-B.
  168. if (ABpos < 0 || ABpos > 1.0) {
  169. return false;
  170. }
  171. // (4) Apply the discovered position to line A-B in the original coordinate system.
  172. if (r_result) {
  173. *r_result = p_from_a + B * ABpos;
  174. }
  175. return true;
  176. }
  177. static inline bool is_point_in_circle(const Vector2 &p_point, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  178. return p_point.distance_squared_to(p_circle_pos) <= p_circle_radius * p_circle_radius;
  179. }
  180. static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  181. Vector2 line_vec = p_to - p_from;
  182. Vector2 vec_to_line = p_from - p_circle_pos;
  183. // Create a quadratic formula of the form ax^2 + bx + c = 0
  184. real_t a, b, c;
  185. a = line_vec.dot(line_vec);
  186. b = 2 * vec_to_line.dot(line_vec);
  187. c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius;
  188. // Solve for t.
  189. real_t sqrtterm = b * b - 4 * a * c;
  190. // If the term we intend to square root is less than 0 then the answer won't be real,
  191. // so it definitely won't be t in the range 0 to 1.
  192. if (sqrtterm < 0) {
  193. return -1;
  194. }
  195. // If we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection)
  196. // then the following can be skipped and we can just return the equivalent of res1.
  197. sqrtterm = Math::sqrt(sqrtterm);
  198. real_t res1 = (-b - sqrtterm) / (2 * a);
  199. real_t res2 = (-b + sqrtterm) / (2 * a);
  200. if (res1 >= 0 && res1 <= 1) {
  201. return res1;
  202. }
  203. if (res2 >= 0 && res2 <= 1) {
  204. return res2;
  205. }
  206. return -1;
  207. }
  208. enum PolyBooleanOperation {
  209. OPERATION_UNION,
  210. OPERATION_DIFFERENCE,
  211. OPERATION_INTERSECTION,
  212. OPERATION_XOR
  213. };
  214. enum PolyJoinType {
  215. JOIN_SQUARE,
  216. JOIN_ROUND,
  217. JOIN_MITER
  218. };
  219. enum PolyEndType {
  220. END_POLYGON,
  221. END_JOINED,
  222. END_BUTT,
  223. END_SQUARE,
  224. END_ROUND
  225. };
  226. static Vector<Vector<Point2>> merge_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  227. return _polypaths_do_operation(OPERATION_UNION, p_polygon_a, p_polygon_b);
  228. }
  229. static Vector<Vector<Point2>> clip_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  230. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polygon_a, p_polygon_b);
  231. }
  232. static Vector<Vector<Point2>> intersect_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  233. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polygon_a, p_polygon_b);
  234. }
  235. static Vector<Vector<Point2>> exclude_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  236. return _polypaths_do_operation(OPERATION_XOR, p_polygon_a, p_polygon_b);
  237. }
  238. static Vector<Vector<Point2>> clip_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  239. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polyline, p_polygon, true);
  240. }
  241. static Vector<Vector<Point2>> intersect_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  242. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polyline, p_polygon, true);
  243. }
  244. static Vector<Vector<Point2>> offset_polygon(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type) {
  245. return _polypath_offset(p_polygon, p_delta, p_join_type, END_POLYGON);
  246. }
  247. static Vector<Vector<Point2>> offset_polyline(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  248. 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).");
  249. return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type);
  250. }
  251. static Vector<int> triangulate_delaunay(const Vector<Vector2> &p_points) {
  252. Vector<Delaunay2D::Triangle> tr = Delaunay2D::triangulate(p_points);
  253. Vector<int> triangles;
  254. for (int i = 0; i < tr.size(); i++) {
  255. triangles.push_back(tr[i].points[0]);
  256. triangles.push_back(tr[i].points[1]);
  257. triangles.push_back(tr[i].points[2]);
  258. }
  259. return triangles;
  260. }
  261. static Vector<int> triangulate_polygon(const Vector<Vector2> &p_polygon) {
  262. Vector<int> triangles;
  263. if (!Triangulate::triangulate(p_polygon, triangles)) {
  264. return Vector<int>(); //fail
  265. }
  266. return triangles;
  267. }
  268. static bool is_polygon_clockwise(const Vector<Vector2> &p_polygon) {
  269. int c = p_polygon.size();
  270. if (c < 3) {
  271. return false;
  272. }
  273. const Vector2 *p = p_polygon.ptr();
  274. real_t sum = 0;
  275. for (int i = 0; i < c; i++) {
  276. const Vector2 &v1 = p[i];
  277. const Vector2 &v2 = p[(i + 1) % c];
  278. sum += (v2.x - v1.x) * (v2.y + v1.y);
  279. }
  280. return sum > 0.0f;
  281. }
  282. // Alternate implementation that should be faster.
  283. static bool is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  284. int c = p_polygon.size();
  285. if (c < 3) {
  286. return false;
  287. }
  288. const Vector2 *p = p_polygon.ptr();
  289. Vector2 further_away(-1e20, -1e20);
  290. Vector2 further_away_opposite(1e20, 1e20);
  291. for (int i = 0; i < c; i++) {
  292. further_away.x = MAX(p[i].x, further_away.x);
  293. further_away.y = MAX(p[i].y, further_away.y);
  294. further_away_opposite.x = MIN(p[i].x, further_away_opposite.x);
  295. further_away_opposite.y = MIN(p[i].y, further_away_opposite.y);
  296. }
  297. // Make point outside that won't intersect with points in segment from p_point.
  298. further_away += (further_away - further_away_opposite) * Vector2(1.221313, 1.512312);
  299. int intersections = 0;
  300. for (int i = 0; i < c; i++) {
  301. const Vector2 &v1 = p[i];
  302. const Vector2 &v2 = p[(i + 1) % c];
  303. if (segment_intersects_segment(v1, v2, p_point, further_away, nullptr)) {
  304. intersections++;
  305. }
  306. }
  307. return (intersections & 1);
  308. }
  309. static real_t vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) {
  310. return (real_t)(A.x - O.x) * (B.y - O.y) - (real_t)(A.y - O.y) * (B.x - O.x);
  311. }
  312. // Returns a list of points on the convex hull in counter-clockwise order.
  313. // Note: the last point in the returned list is the same as the first one.
  314. static Vector<Point2> convex_hull(Vector<Point2> P) {
  315. int n = P.size(), k = 0;
  316. Vector<Point2> H;
  317. H.resize(2 * n);
  318. // Sort points lexicographically.
  319. P.sort();
  320. // Build lower hull.
  321. for (int i = 0; i < n; ++i) {
  322. while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) {
  323. k--;
  324. }
  325. H.write[k++] = P[i];
  326. }
  327. // Build upper hull.
  328. for (int i = n - 2, t = k + 1; i >= 0; i--) {
  329. while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) {
  330. k--;
  331. }
  332. H.write[k++] = P[i];
  333. }
  334. H.resize(k);
  335. return H;
  336. }
  337. static Vector<Vector<Vector2>> decompose_polygon_in_convex(Vector<Point2> polygon);
  338. static void make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size);
  339. static Vector<Point2i> pack_rects(const Vector<Size2i> &p_sizes, const Size2i &p_atlas_size);
  340. static Vector<Vector3i> partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size);
  341. private:
  342. 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);
  343. static Vector<Vector<Point2>> _polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type);
  344. };
  345. #endif // GEOMETRY_2D_H