geometry.h 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. /*************************************************************************/
  2. /* geometry.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_H
  31. #define GEOMETRY_H
  32. #include "core/math/delaunay.h"
  33. #include "core/math/face3.h"
  34. #include "core/math/rect2.h"
  35. #include "core/math/triangulate.h"
  36. #include "core/math/vector3.h"
  37. #include "core/object.h"
  38. #include "core/pool_vector.h"
  39. #include "core/print_string.h"
  40. #include "core/vector.h"
  41. class Geometry {
  42. Geometry();
  43. public:
  44. static real_t get_closest_points_between_segments(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2, Vector2 &c1, Vector2 &c2) {
  45. Vector2 d1 = q1 - p1; // Direction vector of segment S1.
  46. Vector2 d2 = q2 - p2; // Direction vector of segment S2.
  47. Vector2 r = p1 - p2;
  48. real_t a = d1.dot(d1); // Squared length of segment S1, always nonnegative.
  49. real_t e = d2.dot(d2); // Squared length of segment S2, always nonnegative.
  50. real_t f = d2.dot(r);
  51. real_t s, t;
  52. // Check if either or both segments degenerate into points.
  53. if (a <= CMP_EPSILON && e <= CMP_EPSILON) {
  54. // Both segments degenerate into points.
  55. c1 = p1;
  56. c2 = p2;
  57. return Math::sqrt((c1 - c2).dot(c1 - c2));
  58. }
  59. if (a <= CMP_EPSILON) {
  60. // First segment degenerates into a point.
  61. s = 0.0;
  62. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  63. t = CLAMP(t, 0.0, 1.0);
  64. } else {
  65. real_t c = d1.dot(r);
  66. if (e <= CMP_EPSILON) {
  67. // Second segment degenerates into a point.
  68. t = 0.0;
  69. s = CLAMP(-c / a, 0.0, 1.0); // t = 0 => s = (b*t - c) / a = -c / a
  70. } else {
  71. // The general nondegenerate case starts here.
  72. real_t b = d1.dot(d2);
  73. real_t denom = a * e - b * b; // Always nonnegative.
  74. // If segments not parallel, compute closest point on L1 to L2 and
  75. // clamp to segment S1. Else pick arbitrary s (here 0).
  76. if (denom != 0.0) {
  77. s = CLAMP((b * f - c * e) / denom, 0.0, 1.0);
  78. } else
  79. s = 0.0;
  80. // Compute point on L2 closest to S1(s) using
  81. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  82. t = (b * s + f) / e;
  83. //If t in [0,1] done. Else clamp t, recompute s for the new value
  84. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  85. // and clamp s to [0, 1].
  86. if (t < 0.0) {
  87. t = 0.0;
  88. s = CLAMP(-c / a, 0.0, 1.0);
  89. } else if (t > 1.0) {
  90. t = 1.0;
  91. s = CLAMP((b - c) / a, 0.0, 1.0);
  92. }
  93. }
  94. }
  95. c1 = p1 + d1 * s;
  96. c2 = p2 + d2 * t;
  97. return Math::sqrt((c1 - c2).dot(c1 - c2));
  98. }
  99. static void get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2, Vector3 &c1, Vector3 &c2) {
  100. // Do the function 'd' as defined by pb. I think is is dot product of some sort.
  101. #define d_of(m, n, o, p) ((m.x - n.x) * (o.x - p.x) + (m.y - n.y) * (o.y - p.y) + (m.z - n.z) * (o.z - p.z))
  102. // Calculate the parametric position on the 2 curves, mua and mub.
  103. real_t mua = (d_of(p1, q1, q2, q1) * d_of(q2, q1, p2, p1) - d_of(p1, q1, p2, p1) * d_of(q2, q1, q2, q1)) / (d_of(p2, p1, p2, p1) * d_of(q2, q1, q2, q1) - d_of(q2, q1, p2, p1) * d_of(q2, q1, p2, p1));
  104. real_t mub = (d_of(p1, q1, q2, q1) + mua * d_of(q2, q1, p2, p1)) / d_of(q2, q1, q2, q1);
  105. // Clip the value between [0..1] constraining the solution to lie on the original curves.
  106. if (mua < 0) mua = 0;
  107. if (mub < 0) mub = 0;
  108. if (mua > 1) mua = 1;
  109. if (mub > 1) mub = 1;
  110. c1 = p1.linear_interpolate(p2, mua);
  111. c2 = q1.linear_interpolate(q2, mub);
  112. }
  113. static real_t get_closest_distance_between_segments(const Vector3 &p_from_a, const Vector3 &p_to_a, const Vector3 &p_from_b, const Vector3 &p_to_b) {
  114. Vector3 u = p_to_a - p_from_a;
  115. Vector3 v = p_to_b - p_from_b;
  116. Vector3 w = p_from_a - p_to_a;
  117. real_t a = u.dot(u); // Always >= 0
  118. real_t b = u.dot(v);
  119. real_t c = v.dot(v); // Always >= 0
  120. real_t d = u.dot(w);
  121. real_t e = v.dot(w);
  122. real_t D = a * c - b * b; // Always >= 0
  123. real_t sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  124. real_t tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  125. // Compute the line parameters of the two closest points.
  126. if (D < CMP_EPSILON) { // The lines are almost parallel.
  127. sN = 0.0; // Force using point P0 on segment S1
  128. sD = 1.0; // to prevent possible division by 0.0 later.
  129. tN = e;
  130. tD = c;
  131. } else { // Get the closest points on the infinite lines
  132. sN = (b * e - c * d);
  133. tN = (a * e - b * d);
  134. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible.
  135. sN = 0.0;
  136. tN = e;
  137. tD = c;
  138. } else if (sN > sD) { // sc > 1 => the s=1 edge is visible.
  139. sN = sD;
  140. tN = e + b;
  141. tD = c;
  142. }
  143. }
  144. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible.
  145. tN = 0.0;
  146. // Recompute sc for this edge.
  147. if (-d < 0.0)
  148. sN = 0.0;
  149. else if (-d > a)
  150. sN = sD;
  151. else {
  152. sN = -d;
  153. sD = a;
  154. }
  155. } else if (tN > tD) { // tc > 1 => the t=1 edge is visible.
  156. tN = tD;
  157. // Recompute sc for this edge.
  158. if ((-d + b) < 0.0)
  159. sN = 0;
  160. else if ((-d + b) > a)
  161. sN = sD;
  162. else {
  163. sN = (-d + b);
  164. sD = a;
  165. }
  166. }
  167. // Finally do the division to get sc and tc.
  168. sc = (Math::is_zero_approx(sN) ? 0.0 : sN / sD);
  169. tc = (Math::is_zero_approx(tN) ? 0.0 : tN / tD);
  170. // Get the difference of the two closest points.
  171. Vector3 dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc)
  172. return dP.length(); // Return the closest distance.
  173. }
  174. static inline bool ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2, Vector3 *r_res = 0) {
  175. Vector3 e1 = p_v1 - p_v0;
  176. Vector3 e2 = p_v2 - p_v0;
  177. Vector3 h = p_dir.cross(e2);
  178. real_t a = e1.dot(h);
  179. if (Math::is_zero_approx(a)) // Parallel test.
  180. return false;
  181. real_t f = 1.0 / a;
  182. Vector3 s = p_from - p_v0;
  183. real_t u = f * s.dot(h);
  184. if (u < 0.0 || u > 1.0)
  185. return false;
  186. Vector3 q = s.cross(e1);
  187. real_t v = f * p_dir.dot(q);
  188. if (v < 0.0 || u + v > 1.0)
  189. return false;
  190. // At this stage we can compute t to find out where
  191. // the intersection point is on the line.
  192. real_t t = f * e2.dot(q);
  193. if (t > 0.00001) { // ray intersection
  194. if (r_res)
  195. *r_res = p_from + p_dir * t;
  196. return true;
  197. } else // This means that there is a line intersection but not a ray intersection.
  198. return false;
  199. }
  200. static inline bool segment_intersects_triangle(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2, Vector3 *r_res = 0) {
  201. Vector3 rel = p_to - p_from;
  202. Vector3 e1 = p_v1 - p_v0;
  203. Vector3 e2 = p_v2 - p_v0;
  204. Vector3 h = rel.cross(e2);
  205. real_t a = e1.dot(h);
  206. if (Math::is_zero_approx(a)) // Parallel test.
  207. return false;
  208. real_t f = 1.0 / a;
  209. Vector3 s = p_from - p_v0;
  210. real_t u = f * s.dot(h);
  211. if (u < 0.0 || u > 1.0)
  212. return false;
  213. Vector3 q = s.cross(e1);
  214. real_t v = f * rel.dot(q);
  215. if (v < 0.0 || u + v > 1.0)
  216. return false;
  217. // At this stage we can compute t to find out where
  218. // the intersection point is on the line.
  219. real_t t = f * e2.dot(q);
  220. if (t > CMP_EPSILON && t <= 1.0) { // Ray intersection.
  221. if (r_res)
  222. *r_res = p_from + rel * t;
  223. return true;
  224. } else // This means that there is a line intersection but not a ray intersection.
  225. return false;
  226. }
  227. static inline bool segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius, Vector3 *r_res = 0, Vector3 *r_norm = 0) {
  228. Vector3 sphere_pos = p_sphere_pos - p_from;
  229. Vector3 rel = (p_to - p_from);
  230. real_t rel_l = rel.length();
  231. if (rel_l < CMP_EPSILON)
  232. return false; // Both points are the same.
  233. Vector3 normal = rel / rel_l;
  234. real_t sphere_d = normal.dot(sphere_pos);
  235. real_t ray_distance = sphere_pos.distance_to(normal * sphere_d);
  236. if (ray_distance >= p_sphere_radius)
  237. return false;
  238. real_t inters_d2 = p_sphere_radius * p_sphere_radius - ray_distance * ray_distance;
  239. real_t inters_d = sphere_d;
  240. if (inters_d2 >= CMP_EPSILON)
  241. inters_d -= Math::sqrt(inters_d2);
  242. // Check in segment.
  243. if (inters_d < 0 || inters_d > rel_l)
  244. return false;
  245. Vector3 result = p_from + normal * inters_d;
  246. if (r_res)
  247. *r_res = result;
  248. if (r_norm)
  249. *r_norm = (result - p_sphere_pos).normalized();
  250. return true;
  251. }
  252. static inline bool segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, real_t p_height, real_t p_radius, Vector3 *r_res = 0, Vector3 *r_norm = 0, int p_cylinder_axis = 2) {
  253. Vector3 rel = (p_to - p_from);
  254. real_t rel_l = rel.length();
  255. if (rel_l < CMP_EPSILON)
  256. return false; // Both points are the same.
  257. ERR_FAIL_COND_V(p_cylinder_axis < 0, false);
  258. ERR_FAIL_COND_V(p_cylinder_axis > 2, false);
  259. Vector3 cylinder_axis;
  260. cylinder_axis[p_cylinder_axis] = 1.0;
  261. // First check if they are parallel.
  262. Vector3 normal = (rel / rel_l);
  263. Vector3 crs = normal.cross(cylinder_axis);
  264. real_t crs_l = crs.length();
  265. Vector3 axis_dir;
  266. if (crs_l < CMP_EPSILON) {
  267. Vector3 side_axis;
  268. side_axis[(p_cylinder_axis + 1) % 3] = 1.0; // Any side axis OK.
  269. axis_dir = side_axis;
  270. } else {
  271. axis_dir = crs / crs_l;
  272. }
  273. real_t dist = axis_dir.dot(p_from);
  274. if (dist >= p_radius)
  275. return false; // Too far away.
  276. // Convert to 2D.
  277. real_t w2 = p_radius * p_radius - dist * dist;
  278. if (w2 < CMP_EPSILON)
  279. return false; // Avoid numerical error.
  280. Size2 size(Math::sqrt(w2), p_height * 0.5);
  281. Vector3 side_dir = axis_dir.cross(cylinder_axis).normalized();
  282. Vector2 from2D(side_dir.dot(p_from), p_from[p_cylinder_axis]);
  283. Vector2 to2D(side_dir.dot(p_to), p_to[p_cylinder_axis]);
  284. real_t min = 0, max = 1;
  285. int axis = -1;
  286. for (int i = 0; i < 2; i++) {
  287. real_t seg_from = from2D[i];
  288. real_t seg_to = to2D[i];
  289. real_t box_begin = -size[i];
  290. real_t box_end = size[i];
  291. real_t cmin, cmax;
  292. if (seg_from < seg_to) {
  293. if (seg_from > box_end || seg_to < box_begin)
  294. return false;
  295. real_t length = seg_to - seg_from;
  296. cmin = (seg_from < box_begin) ? ((box_begin - seg_from) / length) : 0;
  297. cmax = (seg_to > box_end) ? ((box_end - seg_from) / length) : 1;
  298. } else {
  299. if (seg_to > box_end || seg_from < box_begin)
  300. return false;
  301. real_t length = seg_to - seg_from;
  302. cmin = (seg_from > box_end) ? (box_end - seg_from) / length : 0;
  303. cmax = (seg_to < box_begin) ? (box_begin - seg_from) / length : 1;
  304. }
  305. if (cmin > min) {
  306. min = cmin;
  307. axis = i;
  308. }
  309. if (cmax < max)
  310. max = cmax;
  311. if (max < min)
  312. return false;
  313. }
  314. // Convert to 3D again.
  315. Vector3 result = p_from + (rel * min);
  316. Vector3 res_normal = result;
  317. if (axis == 0) {
  318. res_normal[p_cylinder_axis] = 0;
  319. } else {
  320. int axis_side = (p_cylinder_axis + 1) % 3;
  321. res_normal[axis_side] = 0;
  322. axis_side = (axis_side + 1) % 3;
  323. res_normal[axis_side] = 0;
  324. }
  325. res_normal.normalize();
  326. if (r_res)
  327. *r_res = result;
  328. if (r_norm)
  329. *r_norm = res_normal;
  330. return true;
  331. }
  332. static bool segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Plane *p_planes, int p_plane_count, Vector3 *p_res, Vector3 *p_norm) {
  333. real_t min = -1e20, max = 1e20;
  334. Vector3 rel = p_to - p_from;
  335. real_t rel_l = rel.length();
  336. if (rel_l < CMP_EPSILON)
  337. return false;
  338. Vector3 dir = rel / rel_l;
  339. int min_index = -1;
  340. for (int i = 0; i < p_plane_count; i++) {
  341. const Plane &p = p_planes[i];
  342. real_t den = p.normal.dot(dir);
  343. if (Math::abs(den) <= CMP_EPSILON)
  344. continue; // Ignore parallel plane.
  345. real_t dist = -p.distance_to(p_from) / den;
  346. if (den > 0) {
  347. // Backwards facing plane.
  348. if (dist < max)
  349. max = dist;
  350. } else {
  351. // Front facing plane.
  352. if (dist > min) {
  353. min = dist;
  354. min_index = i;
  355. }
  356. }
  357. }
  358. if (max <= min || min < 0 || min > rel_l || min_index == -1) // Exit conditions.
  359. return false; // No intersection.
  360. if (p_res)
  361. *p_res = p_from + dir * min;
  362. if (p_norm)
  363. *p_norm = p_planes[min_index].normal;
  364. return true;
  365. }
  366. static Vector3 get_closest_point_to_segment(const Vector3 &p_point, const Vector3 *p_segment) {
  367. Vector3 p = p_point - p_segment[0];
  368. Vector3 n = p_segment[1] - p_segment[0];
  369. real_t l2 = n.length_squared();
  370. if (l2 < 1e-20)
  371. return p_segment[0]; // Both points are the same, just give any.
  372. real_t d = n.dot(p) / l2;
  373. if (d <= 0.0)
  374. return p_segment[0]; // Before first point.
  375. else if (d >= 1.0)
  376. return p_segment[1]; // After first point.
  377. else
  378. return p_segment[0] + n * d; // Inside.
  379. }
  380. static Vector3 get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 *p_segment) {
  381. Vector3 p = p_point - p_segment[0];
  382. Vector3 n = p_segment[1] - p_segment[0];
  383. real_t l2 = n.length_squared();
  384. if (l2 < 1e-20)
  385. return p_segment[0]; // Both points are the same, just give any.
  386. real_t d = n.dot(p) / l2;
  387. return p_segment[0] + n * d; // Inside.
  388. }
  389. static Vector2 get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 *p_segment) {
  390. Vector2 p = p_point - p_segment[0];
  391. Vector2 n = p_segment[1] - p_segment[0];
  392. real_t l2 = n.length_squared();
  393. if (l2 < 1e-20)
  394. return p_segment[0]; // Both points are the same, just give any.
  395. real_t d = n.dot(p) / l2;
  396. if (d <= 0.0)
  397. return p_segment[0]; // Before first point.
  398. else if (d >= 1.0)
  399. return p_segment[1]; // After first point.
  400. else
  401. return p_segment[0] + n * d; // Inside.
  402. }
  403. static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
  404. Vector2 an = a - s;
  405. Vector2 bn = b - s;
  406. Vector2 cn = c - s;
  407. bool orientation = an.cross(bn) > 0;
  408. if ((bn.cross(cn) > 0) != orientation) return false;
  409. return (cn.cross(an) > 0) == orientation;
  410. }
  411. static Vector3 barycentric_coordinates_2d(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
  412. // http://www.blackpawn.com/texts/pointinpoly/
  413. Vector2 v0 = c - a;
  414. Vector2 v1 = b - a;
  415. Vector2 v2 = s - a;
  416. // Compute dot products
  417. double dot00 = v0.dot(v0);
  418. double dot01 = v0.dot(v1);
  419. double dot02 = v0.dot(v2);
  420. double dot11 = v1.dot(v1);
  421. double dot12 = v1.dot(v2);
  422. // Compute barycentric coordinates
  423. double invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01);
  424. double b2 = (dot11 * dot02 - dot01 * dot12) * invDenom;
  425. double b1 = (dot00 * dot12 - dot01 * dot02) * invDenom;
  426. double b0 = 1.0f - b2 - b1;
  427. return Vector3(b0, b1, b2);
  428. }
  429. static Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 *p_segment) {
  430. Vector2 p = p_point - p_segment[0];
  431. Vector2 n = p_segment[1] - p_segment[0];
  432. real_t l2 = n.length_squared();
  433. if (l2 < 1e-20)
  434. return p_segment[0]; // Both points are the same, just give any.
  435. real_t d = n.dot(p) / l2;
  436. return p_segment[0] + n * d; // Inside.
  437. }
  438. static bool line_intersects_line_2d(const Vector2 &p_from_a, const Vector2 &p_dir_a, const Vector2 &p_from_b, const Vector2 &p_dir_b, Vector2 &r_result) {
  439. // See http://paulbourke.net/geometry/pointlineplane/
  440. const real_t denom = p_dir_b.y * p_dir_a.x - p_dir_b.x * p_dir_a.y;
  441. if (Math::is_zero_approx(denom)) { // Parallel?
  442. return false;
  443. }
  444. const Vector2 v = p_from_a - p_from_b;
  445. const real_t t = (p_dir_b.x * v.y - p_dir_b.y * v.x) / denom;
  446. r_result = p_from_a + t * p_dir_a;
  447. return true;
  448. }
  449. static bool segment_intersects_segment_2d(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b, Vector2 *r_result) {
  450. Vector2 B = p_to_a - p_from_a;
  451. Vector2 C = p_from_b - p_from_a;
  452. Vector2 D = p_to_b - p_from_a;
  453. real_t ABlen = B.dot(B);
  454. if (ABlen <= 0)
  455. return false;
  456. Vector2 Bn = B / ABlen;
  457. C = Vector2(C.x * Bn.x + C.y * Bn.y, C.y * Bn.x - C.x * Bn.y);
  458. D = Vector2(D.x * Bn.x + D.y * Bn.y, D.y * Bn.x - D.x * Bn.y);
  459. if ((C.y < 0 && D.y < 0) || (C.y >= 0 && D.y >= 0))
  460. return false;
  461. real_t ABpos = D.x + (C.x - D.x) * D.y / (D.y - C.y);
  462. // Fail if segment C-D crosses line A-B outside of segment A-B.
  463. if (ABpos < 0 || ABpos > 1.0)
  464. return false;
  465. // (4) Apply the discovered position to line A-B in the original coordinate system.
  466. if (r_result)
  467. *r_result = p_from_a + B * ABpos;
  468. return true;
  469. }
  470. static inline bool point_in_projected_triangle(const Vector3 &p_point, const Vector3 &p_v1, const Vector3 &p_v2, const Vector3 &p_v3) {
  471. Vector3 face_n = (p_v1 - p_v3).cross(p_v1 - p_v2);
  472. Vector3 n1 = (p_point - p_v3).cross(p_point - p_v2);
  473. if (face_n.dot(n1) < 0)
  474. return false;
  475. Vector3 n2 = (p_v1 - p_v3).cross(p_v1 - p_point);
  476. if (face_n.dot(n2) < 0)
  477. return false;
  478. Vector3 n3 = (p_v1 - p_point).cross(p_v1 - p_v2);
  479. if (face_n.dot(n3) < 0)
  480. return false;
  481. return true;
  482. }
  483. static inline bool triangle_sphere_intersection_test(const Vector3 *p_triangle, const Vector3 &p_normal, const Vector3 &p_sphere_pos, real_t p_sphere_radius, Vector3 &r_triangle_contact, Vector3 &r_sphere_contact) {
  484. real_t d = p_normal.dot(p_sphere_pos) - p_normal.dot(p_triangle[0]);
  485. if (d > p_sphere_radius || d < -p_sphere_radius) // Not touching the plane of the face, return.
  486. return false;
  487. Vector3 contact = p_sphere_pos - (p_normal * d);
  488. /** 2nd) TEST INSIDE TRIANGLE **/
  489. if (Geometry::point_in_projected_triangle(contact, p_triangle[0], p_triangle[1], p_triangle[2])) {
  490. r_triangle_contact = contact;
  491. r_sphere_contact = p_sphere_pos - p_normal * p_sphere_radius;
  492. //printf("solved inside triangle\n");
  493. return true;
  494. }
  495. /** 3rd TEST INSIDE EDGE CYLINDERS **/
  496. const Vector3 verts[4] = { p_triangle[0], p_triangle[1], p_triangle[2], p_triangle[0] }; // for() friendly
  497. for (int i = 0; i < 3; i++) {
  498. // Check edge cylinder.
  499. Vector3 n1 = verts[i] - verts[i + 1];
  500. Vector3 n2 = p_sphere_pos - verts[i + 1];
  501. ///@TODO Maybe discard by range here to make the algorithm quicker.
  502. // Check point within cylinder radius.
  503. Vector3 axis = n1.cross(n2).cross(n1);
  504. axis.normalize();
  505. real_t ad = axis.dot(n2);
  506. if (ABS(ad) > p_sphere_radius) {
  507. // No chance with this edge, too far away.
  508. continue;
  509. }
  510. // Check point within edge capsule cylinder.
  511. /** 4th TEST INSIDE EDGE POINTS **/
  512. real_t sphere_at = n1.dot(n2);
  513. if (sphere_at >= 0 && sphere_at < n1.dot(n1)) {
  514. r_triangle_contact = p_sphere_pos - axis * (axis.dot(n2));
  515. r_sphere_contact = p_sphere_pos - axis * p_sphere_radius;
  516. // Point inside here.
  517. return true;
  518. }
  519. real_t r2 = p_sphere_radius * p_sphere_radius;
  520. if (n2.length_squared() < r2) {
  521. Vector3 n = (p_sphere_pos - verts[i + 1]).normalized();
  522. r_triangle_contact = verts[i + 1];
  523. r_sphere_contact = p_sphere_pos - n * p_sphere_radius;
  524. return true;
  525. }
  526. if (n2.distance_squared_to(n1) < r2) {
  527. Vector3 n = (p_sphere_pos - verts[i]).normalized();
  528. r_triangle_contact = verts[i];
  529. r_sphere_contact = p_sphere_pos - n * p_sphere_radius;
  530. return true;
  531. }
  532. break; // It's pointless to continue at this point, so save some CPU cycles.
  533. }
  534. return false;
  535. }
  536. static inline bool is_point_in_circle(const Vector2 &p_point, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  537. return p_point.distance_squared_to(p_circle_pos) <= p_circle_radius * p_circle_radius;
  538. }
  539. static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  540. Vector2 line_vec = p_to - p_from;
  541. Vector2 vec_to_line = p_from - p_circle_pos;
  542. // Create a quadratic formula of the form ax^2 + bx + c = 0
  543. real_t a, b, c;
  544. a = line_vec.dot(line_vec);
  545. b = 2 * vec_to_line.dot(line_vec);
  546. c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius;
  547. // Solve for t.
  548. real_t sqrtterm = b * b - 4 * a * c;
  549. // If the term we intend to square root is less than 0 then the answer won't be real,
  550. // so it definitely won't be t in the range 0 to 1.
  551. if (sqrtterm < 0) return -1;
  552. // If we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection)
  553. // then the following can be skipped and we can just return the equivalent of res1.
  554. sqrtterm = Math::sqrt(sqrtterm);
  555. real_t res1 = (-b - sqrtterm) / (2 * a);
  556. real_t res2 = (-b + sqrtterm) / (2 * a);
  557. if (res1 >= 0 && res1 <= 1) return res1;
  558. if (res2 >= 0 && res2 <= 1) return res2;
  559. return -1;
  560. }
  561. static inline Vector<Vector3> clip_polygon(const Vector<Vector3> &polygon, const Plane &p_plane) {
  562. enum LocationCache {
  563. LOC_INSIDE = 1,
  564. LOC_BOUNDARY = 0,
  565. LOC_OUTSIDE = -1
  566. };
  567. if (polygon.size() == 0)
  568. return polygon;
  569. int *location_cache = (int *)alloca(sizeof(int) * polygon.size());
  570. int inside_count = 0;
  571. int outside_count = 0;
  572. for (int a = 0; a < polygon.size(); a++) {
  573. real_t dist = p_plane.distance_to(polygon[a]);
  574. if (dist < -CMP_POINT_IN_PLANE_EPSILON) {
  575. location_cache[a] = LOC_INSIDE;
  576. inside_count++;
  577. } else {
  578. if (dist > CMP_POINT_IN_PLANE_EPSILON) {
  579. location_cache[a] = LOC_OUTSIDE;
  580. outside_count++;
  581. } else {
  582. location_cache[a] = LOC_BOUNDARY;
  583. }
  584. }
  585. }
  586. if (outside_count == 0) {
  587. return polygon; // No changes.
  588. } else if (inside_count == 0) {
  589. return Vector<Vector3>(); // Empty.
  590. }
  591. long previous = polygon.size() - 1;
  592. Vector<Vector3> clipped;
  593. for (int index = 0; index < polygon.size(); index++) {
  594. int loc = location_cache[index];
  595. if (loc == LOC_OUTSIDE) {
  596. if (location_cache[previous] == LOC_INSIDE) {
  597. const Vector3 &v1 = polygon[previous];
  598. const Vector3 &v2 = polygon[index];
  599. Vector3 segment = v1 - v2;
  600. real_t den = p_plane.normal.dot(segment);
  601. real_t dist = p_plane.distance_to(v1) / den;
  602. dist = -dist;
  603. clipped.push_back(v1 + segment * dist);
  604. }
  605. } else {
  606. const Vector3 &v1 = polygon[index];
  607. if ((loc == LOC_INSIDE) && (location_cache[previous] == LOC_OUTSIDE)) {
  608. const Vector3 &v2 = polygon[previous];
  609. Vector3 segment = v1 - v2;
  610. real_t den = p_plane.normal.dot(segment);
  611. real_t dist = p_plane.distance_to(v1) / den;
  612. dist = -dist;
  613. clipped.push_back(v1 + segment * dist);
  614. }
  615. clipped.push_back(v1);
  616. }
  617. previous = index;
  618. }
  619. return clipped;
  620. }
  621. enum PolyBooleanOperation {
  622. OPERATION_UNION,
  623. OPERATION_DIFFERENCE,
  624. OPERATION_INTERSECTION,
  625. OPERATION_XOR
  626. };
  627. enum PolyJoinType {
  628. JOIN_SQUARE,
  629. JOIN_ROUND,
  630. JOIN_MITER
  631. };
  632. enum PolyEndType {
  633. END_POLYGON,
  634. END_JOINED,
  635. END_BUTT,
  636. END_SQUARE,
  637. END_ROUND
  638. };
  639. static Vector<Vector<Point2> > merge_polygons_2d(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  640. return _polypaths_do_operation(OPERATION_UNION, p_polygon_a, p_polygon_b);
  641. }
  642. static Vector<Vector<Point2> > clip_polygons_2d(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  643. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polygon_a, p_polygon_b);
  644. }
  645. static Vector<Vector<Point2> > intersect_polygons_2d(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  646. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polygon_a, p_polygon_b);
  647. }
  648. static Vector<Vector<Point2> > exclude_polygons_2d(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  649. return _polypaths_do_operation(OPERATION_XOR, p_polygon_a, p_polygon_b);
  650. }
  651. static Vector<Vector<Point2> > clip_polyline_with_polygon_2d(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  652. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polyline, p_polygon, true);
  653. }
  654. static Vector<Vector<Point2> > intersect_polyline_with_polygon_2d(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  655. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polyline, p_polygon, true);
  656. }
  657. static Vector<Vector<Point2> > offset_polygon_2d(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type) {
  658. return _polypath_offset(p_polygon, p_delta, p_join_type, END_POLYGON);
  659. }
  660. static Vector<Vector<Point2> > offset_polyline_2d(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  661. ERR_FAIL_COND_V_MSG(p_end_type == END_POLYGON, Vector<Vector<Point2> >(), "Attempt to offset a polyline like a polygon (use offset_polygon_2d instead).");
  662. return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type);
  663. }
  664. static Vector<int> triangulate_delaunay_2d(const Vector<Vector2> &p_points) {
  665. Vector<Delaunay2D::Triangle> tr = Delaunay2D::triangulate(p_points);
  666. Vector<int> triangles;
  667. for (int i = 0; i < tr.size(); i++) {
  668. triangles.push_back(tr[i].points[0]);
  669. triangles.push_back(tr[i].points[1]);
  670. triangles.push_back(tr[i].points[2]);
  671. }
  672. return triangles;
  673. }
  674. static Vector<int> triangulate_polygon(const Vector<Vector2> &p_polygon) {
  675. Vector<int> triangles;
  676. if (!Triangulate::triangulate(p_polygon, triangles))
  677. return Vector<int>(); //fail
  678. return triangles;
  679. }
  680. static bool is_polygon_clockwise(const Vector<Vector2> &p_polygon) {
  681. int c = p_polygon.size();
  682. if (c < 3)
  683. return false;
  684. const Vector2 *p = p_polygon.ptr();
  685. real_t sum = 0;
  686. for (int i = 0; i < c; i++) {
  687. const Vector2 &v1 = p[i];
  688. const Vector2 &v2 = p[(i + 1) % c];
  689. sum += (v2.x - v1.x) * (v2.y + v1.y);
  690. }
  691. return sum > 0.0f;
  692. }
  693. // Alternate implementation that should be faster.
  694. static bool is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  695. int c = p_polygon.size();
  696. if (c < 3)
  697. return false;
  698. const Vector2 *p = p_polygon.ptr();
  699. Vector2 further_away(-1e20, -1e20);
  700. Vector2 further_away_opposite(1e20, 1e20);
  701. for (int i = 0; i < c; i++) {
  702. further_away.x = MAX(p[i].x, further_away.x);
  703. further_away.y = MAX(p[i].y, further_away.y);
  704. further_away_opposite.x = MIN(p[i].x, further_away_opposite.x);
  705. further_away_opposite.y = MIN(p[i].y, further_away_opposite.y);
  706. }
  707. // Make point outside that won't intersect with points in segment from p_point.
  708. further_away += (further_away - further_away_opposite) * Vector2(1.221313, 1.512312);
  709. int intersections = 0;
  710. for (int i = 0; i < c; i++) {
  711. const Vector2 &v1 = p[i];
  712. const Vector2 &v2 = p[(i + 1) % c];
  713. if (segment_intersects_segment_2d(v1, v2, p_point, further_away, NULL)) {
  714. intersections++;
  715. }
  716. }
  717. return (intersections & 1);
  718. }
  719. static PoolVector<PoolVector<Face3> > separate_objects(PoolVector<Face3> p_array);
  720. // Create a "wrap" that encloses the given geometry.
  721. static PoolVector<Face3> wrap_geometry(PoolVector<Face3> p_array, real_t *p_error = NULL);
  722. struct MeshData {
  723. struct Face {
  724. Plane plane;
  725. Vector<int> indices;
  726. };
  727. Vector<Face> faces;
  728. struct Edge {
  729. int a, b;
  730. };
  731. Vector<Edge> edges;
  732. Vector<Vector3> vertices;
  733. void optimize_vertices();
  734. };
  735. _FORCE_INLINE_ static int get_uv84_normal_bit(const Vector3 &p_vector) {
  736. int lat = Math::fast_ftoi(Math::floor(Math::acos(p_vector.dot(Vector3(0, 1, 0))) * 4.0 / Math_PI + 0.5));
  737. if (lat == 0) {
  738. return 24;
  739. } else if (lat == 4) {
  740. return 25;
  741. }
  742. int lon = Math::fast_ftoi(Math::floor((Math_PI + Math::atan2(p_vector.x, p_vector.z)) * 8.0 / (Math_PI * 2.0) + 0.5)) % 8;
  743. return lon + (lat - 1) * 8;
  744. }
  745. _FORCE_INLINE_ static int get_uv84_normal_bit_neighbors(int p_idx) {
  746. if (p_idx == 24) {
  747. return 1 | 2 | 4 | 8;
  748. } else if (p_idx == 25) {
  749. return (1 << 23) | (1 << 22) | (1 << 21) | (1 << 20);
  750. } else {
  751. int ret = 0;
  752. if ((p_idx % 8) == 0)
  753. ret |= (1 << (p_idx + 7));
  754. else
  755. ret |= (1 << (p_idx - 1));
  756. if ((p_idx % 8) == 7)
  757. ret |= (1 << (p_idx - 7));
  758. else
  759. ret |= (1 << (p_idx + 1));
  760. int mask = ret | (1 << p_idx);
  761. if (p_idx < 8)
  762. ret |= 24;
  763. else
  764. ret |= mask >> 8;
  765. if (p_idx >= 16)
  766. ret |= 25;
  767. else
  768. ret |= mask << 8;
  769. return ret;
  770. }
  771. }
  772. static real_t vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) {
  773. return (real_t)(A.x - O.x) * (B.y - O.y) - (real_t)(A.y - O.y) * (B.x - O.x);
  774. }
  775. // Returns a list of points on the convex hull in counter-clockwise order.
  776. // Note: the last point in the returned list is the same as the first one.
  777. static Vector<Point2> convex_hull_2d(Vector<Point2> P) {
  778. int n = P.size(), k = 0;
  779. Vector<Point2> H;
  780. H.resize(2 * n);
  781. // Sort points lexicographically.
  782. P.sort();
  783. // Build lower hull.
  784. for (int i = 0; i < n; ++i) {
  785. while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0)
  786. k--;
  787. H.write[k++] = P[i];
  788. }
  789. // Build upper hull.
  790. for (int i = n - 2, t = k + 1; i >= 0; i--) {
  791. while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0)
  792. k--;
  793. H.write[k++] = P[i];
  794. }
  795. H.resize(k);
  796. return H;
  797. }
  798. static Vector<Vector<Vector2> > decompose_polygon_in_convex(Vector<Point2> polygon);
  799. static MeshData build_convex_mesh(const PoolVector<Plane> &p_planes);
  800. static PoolVector<Plane> build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis = Vector3::AXIS_Z);
  801. static PoolVector<Plane> build_box_planes(const Vector3 &p_extents);
  802. static PoolVector<Plane> build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z);
  803. static PoolVector<Plane> build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis = Vector3::AXIS_Z);
  804. static void make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size);
  805. struct PackRectsResult {
  806. int x;
  807. int y;
  808. bool packed;
  809. };
  810. static Vector<PackRectsResult> partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size);
  811. static Vector<Vector3> compute_convex_mesh_points(const Plane *p_planes, int p_plane_count);
  812. private:
  813. 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);
  814. static Vector<Vector<Point2> > _polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type);
  815. };
  816. #endif