AstarMath.cs 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  1. using System.Collections.Generic;
  2. using System;
  3. namespace PF {
  4. /** Contains various spline functions.
  5. * \ingroup utils
  6. */
  7. static class AstarSplines {
  8. public static Vector3 CatmullRom (Vector3 previous, Vector3 start, Vector3 end, Vector3 next, float elapsedTime) {
  9. // References used:
  10. // p.266 GemsV1
  11. //
  12. // tension is often set to 0.5 but you can use any reasonable value:
  13. // http://www.cs.cmu.edu/~462/projects/assn2/assn2/catmullRom.pdf
  14. //
  15. // bias and tension controls:
  16. // http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/interpolation/
  17. float percentComplete = elapsedTime;
  18. float percentCompleteSquared = percentComplete * percentComplete;
  19. float percentCompleteCubed = percentCompleteSquared * percentComplete;
  20. return
  21. previous * (-0.5F*percentCompleteCubed +
  22. percentCompleteSquared -
  23. 0.5F*percentComplete) +
  24. start *
  25. (1.5F*percentCompleteCubed +
  26. -2.5F*percentCompleteSquared + 1.0F) +
  27. end *
  28. (-1.5F*percentCompleteCubed +
  29. 2.0F*percentCompleteSquared +
  30. 0.5F*percentComplete) +
  31. next *
  32. (0.5F*percentCompleteCubed -
  33. 0.5F*percentCompleteSquared);
  34. }
  35. [System.Obsolete("Use CatmullRom")]
  36. public static Vector3 CatmullRomOLD (Vector3 previous, Vector3 start, Vector3 end, Vector3 next, float elapsedTime) {
  37. return CatmullRom(previous, start, end, next, elapsedTime);
  38. }
  39. /** Returns a point on a cubic bezier curve. \a t is clamped between 0 and 1 */
  40. public static Vector3 CubicBezier (Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t) {
  41. t = Mathf.Clamp01(t);
  42. float t2 = 1-t;
  43. return t2*t2*t2 * p0 + 3 * t2*t2 * t * p1 + 3 * t2 * t*t * p2 + t*t*t * p3;
  44. }
  45. /** Returns the derivative for a point on a cubic bezier curve. \a t is clamped between 0 and 1 */
  46. public static Vector3 CubicBezierDerivative (Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t) {
  47. t = Mathf.Clamp01(t);
  48. float t2 = 1-t;
  49. return 3*t2*t2*(p1-p0) + 6*t2*t*(p2 - p1) + 3*t*t*(p3 - p2);
  50. }
  51. /** Returns the second derivative for a point on a cubic bezier curve. \a t is clamped between 0 and 1 */
  52. public static Vector3 CubicBezierSecondDerivative (Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t) {
  53. t = Mathf.Clamp01(t);
  54. float t2 = 1-t;
  55. return 6*t2*(p2 - 2*p1 + p0) + 6*t*(p3 - 2*p2 + p1);
  56. }
  57. }
  58. /** Various vector math utility functions.
  59. * \version A lot of functions in the Polygon class have been moved to this class
  60. * the names have changed slightly and everything now consistently assumes a left handed
  61. * coordinate system now instead of sometimes using a left handed one and sometimes
  62. * using a right handed one. This is why the 'Left' methods in the Polygon class redirect
  63. * to methods named 'Right'. The functionality is exactly the same.
  64. *
  65. * Note the difference between segments and lines. Lines are infinitely
  66. * long but segments have only a finite length.
  67. *
  68. * \ingroup utils
  69. */
  70. public static class VectorMath {
  71. /** Complex number multiplication.
  72. * \returns a * b
  73. *
  74. * Used to rotate vectors in an efficient way.
  75. *
  76. * \see https://en.wikipedia.org/wiki/Complex_number#Multiplication_and_division
  77. */
  78. public static Vector2 ComplexMultiply (Vector2 a, Vector2 b) {
  79. return new Vector2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
  80. }
  81. /** Complex number multiplication.
  82. * \returns a * conjugate(b)
  83. *
  84. * Used to rotate vectors in an efficient way.
  85. *
  86. * \see https://en.wikipedia.org/wiki/Complex_number#Multiplication_and_division
  87. * \see https://en.wikipedia.org/wiki/Complex_conjugate
  88. */
  89. public static Vector2 ComplexMultiplyConjugate (Vector2 a, Vector2 b) {
  90. return new Vector2(a.x * b.x + a.y * b.y, a.y * b.x - a.x * b.y);
  91. }
  92. /** Returns the closest point on the line.
  93. * The line is treated as infinite.
  94. * \see ClosestPointOnSegment
  95. * \see ClosestPointOnLineFactor
  96. */
  97. public static Vector3 ClosestPointOnLine (Vector3 lineStart, Vector3 lineEnd, Vector3 point) {
  98. Vector3 lineDirection = Vector3.Normalize(lineEnd - lineStart);
  99. float dot = Vector3.Dot(point - lineStart, lineDirection);
  100. return lineStart + (dot*lineDirection);
  101. }
  102. /** Factor along the line which is closest to the point.
  103. * Returned value is in the range [0,1] if the point lies on the segment otherwise it just lies on the line.
  104. * The closest point can be calculated using (end-start)*factor + start.
  105. *
  106. * \see ClosestPointOnLine
  107. * \see ClosestPointOnSegment
  108. */
  109. public static float ClosestPointOnLineFactor (Vector3 lineStart, Vector3 lineEnd, Vector3 point) {
  110. var dir = lineEnd - lineStart;
  111. float sqrMagn = dir.sqrMagnitude;
  112. if (sqrMagn <= 0.000001) return 0;
  113. return Vector3.Dot(point - lineStart, dir) / sqrMagn;
  114. }
  115. /** Factor along the line which is closest to the point.
  116. * Returned value is in the range [0,1] if the point lies on the segment otherwise it just lies on the line.
  117. * The closest point can be calculated using (end-start)*factor + start
  118. */
  119. public static float ClosestPointOnLineFactor (Int3 lineStart, Int3 lineEnd, Int3 point) {
  120. var lineDirection = lineEnd - lineStart;
  121. float magn = lineDirection.sqrMagnitude;
  122. float closestPoint = Int3.Dot((point - lineStart), lineDirection);
  123. if (magn != 0) closestPoint /= magn;
  124. return closestPoint;
  125. }
  126. /** Factor of the nearest point on the segment.
  127. * Returned value is in the range [0,1] if the point lies on the segment otherwise it just lies on the line.
  128. * The closest point can be calculated using (end-start)*factor + start;
  129. */
  130. public static float ClosestPointOnLineFactor (Int2 lineStart, Int2 lineEnd, Int2 point) {
  131. var lineDirection = lineEnd - lineStart;
  132. double magn = lineDirection.sqrMagnitudeLong;
  133. double closestPoint = Int2.DotLong(point - lineStart, lineDirection);
  134. if (magn != 0) closestPoint /= magn;
  135. return (float)closestPoint;
  136. }
  137. /** Returns the closest point on the segment.
  138. * The segment is NOT treated as infinite.
  139. * \see ClosestPointOnLine
  140. * \see ClosestPointOnSegmentXZ
  141. */
  142. public static Vector3 ClosestPointOnSegment (Vector3 lineStart, Vector3 lineEnd, Vector3 point) {
  143. var dir = lineEnd - lineStart;
  144. float sqrMagn = dir.sqrMagnitude;
  145. if (sqrMagn <= 0.000001) return lineStart;
  146. float factor = Vector3.Dot(point - lineStart, dir) / sqrMagn;
  147. return lineStart + Mathf.Clamp01(factor)*dir;
  148. }
  149. /** Returns the closest point on the segment in the XZ plane.
  150. * The y coordinate of the result will be the same as the y coordinate of the \a point parameter.
  151. *
  152. * The segment is NOT treated as infinite.
  153. * \see ClosestPointOnSegment
  154. * \see ClosestPointOnLine
  155. */
  156. public static Vector3 ClosestPointOnSegmentXZ (Vector3 lineStart, Vector3 lineEnd, Vector3 point) {
  157. lineStart.y = point.y;
  158. lineEnd.y = point.y;
  159. Vector3 fullDirection = lineEnd-lineStart;
  160. Vector3 fullDirection2 = fullDirection;
  161. fullDirection2.y = 0;
  162. float magn = fullDirection2.magnitude;
  163. Vector3 lineDirection = magn > float.Epsilon ? fullDirection2/magn : Vector3.zero;
  164. float closestPoint = Vector3.Dot((point-lineStart), lineDirection);
  165. return lineStart+(Mathf.Clamp(closestPoint, 0.0f, fullDirection2.magnitude)*lineDirection);
  166. }
  167. /** Returns the approximate shortest squared distance between x,z and the segment p-q.
  168. * The segment is not considered infinite.
  169. * This function is not entirely exact, but it is about twice as fast as DistancePointSegment2.
  170. * \todo Is this actually approximate? It looks exact.
  171. */
  172. public static float SqrDistancePointSegmentApproximate (int x, int z, int px, int pz, int qx, int qz) {
  173. float pqx = (float)(qx - px);
  174. float pqz = (float)(qz - pz);
  175. float dx = (float)(x - px);
  176. float dz = (float)(z - pz);
  177. float d = pqx*pqx + pqz*pqz;
  178. float t = pqx*dx + pqz*dz;
  179. if (d > 0)
  180. t /= d;
  181. if (t < 0)
  182. t = 0;
  183. else if (t > 1)
  184. t = 1;
  185. dx = px + t*pqx - x;
  186. dz = pz + t*pqz - z;
  187. return dx*dx + dz*dz;
  188. }
  189. /** Returns the approximate shortest squared distance between x,z and the segment p-q.
  190. * The segment is not considered infinite.
  191. * This function is not entirely exact, but it is about twice as fast as DistancePointSegment2.
  192. * \todo Is this actually approximate? It looks exact.
  193. */
  194. public static float SqrDistancePointSegmentApproximate (Int3 a, Int3 b, Int3 p) {
  195. float pqx = (float)(b.x - a.x);
  196. float pqz = (float)(b.z - a.z);
  197. float dx = (float)(p.x - a.x);
  198. float dz = (float)(p.z - a.z);
  199. float d = pqx*pqx + pqz*pqz;
  200. float t = pqx*dx + pqz*dz;
  201. if (d > 0)
  202. t /= d;
  203. if (t < 0)
  204. t = 0;
  205. else if (t > 1)
  206. t = 1;
  207. dx = a.x + t*pqx - p.x;
  208. dz = a.z + t*pqz - p.z;
  209. return dx*dx + dz*dz;
  210. }
  211. /** Returns the squared distance between p and the segment a-b.
  212. * The line is not considered infinite.
  213. */
  214. public static float SqrDistancePointSegment (Vector3 a, Vector3 b, Vector3 p) {
  215. var nearest = ClosestPointOnSegment(a, b, p);
  216. return (nearest-p).sqrMagnitude;
  217. }
  218. /** 3D minimum distance between 2 segments.
  219. * Input: two 3D line segments S1 and S2
  220. * \returns the shortest squared distance between S1 and S2
  221. */
  222. public static float SqrDistanceSegmentSegment (Vector3 s1, Vector3 e1, Vector3 s2, Vector3 e2) {
  223. Vector3 u = e1 - s1;
  224. Vector3 v = e2 - s2;
  225. Vector3 w = s1 - s2;
  226. float a = Vector3.Dot(u, u); // always >= 0
  227. float b = Vector3.Dot(u, v);
  228. float c = Vector3.Dot(v, v); // always >= 0
  229. float d = Vector3.Dot(u, w);
  230. float e = Vector3.Dot(v, w);
  231. float D = a*c - b*b; // always >= 0
  232. float sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  233. float tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  234. // compute the line parameters of the two closest points
  235. if (D < 0.000001f) { // the lines are almost parallel
  236. sN = 0.0f; // force using point P0 on segment S1
  237. sD = 1.0f; // to prevent possible division by 0.0 later
  238. tN = e;
  239. tD = c;
  240. } else { // get the closest points on the infinite lines
  241. sN = (b*e - c*d);
  242. tN = (a*e - b*d);
  243. if (sN < 0.0f) { // sc < 0 => the s=0 edge is visible
  244. sN = 0.0f;
  245. tN = e;
  246. tD = c;
  247. } else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  248. sN = sD;
  249. tN = e + b;
  250. tD = c;
  251. }
  252. }
  253. if (tN < 0.0f) { // tc < 0 => the t=0 edge is visible
  254. tN = 0.0f;
  255. // recompute sc for this edge
  256. if (-d < 0.0f)
  257. sN = 0.0f;
  258. else if (-d > a)
  259. sN = sD;
  260. else {
  261. sN = -d;
  262. sD = a;
  263. }
  264. } else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  265. tN = tD;
  266. // recompute sc for this edge
  267. if ((-d + b) < 0.0f)
  268. sN = 0;
  269. else if ((-d + b) > a)
  270. sN = sD;
  271. else {
  272. sN = (-d + b);
  273. sD = a;
  274. }
  275. }
  276. // finally do the division to get sc and tc
  277. sc = (Math.Abs(sN) < 0.000001f ? 0.0f : sN / sD);
  278. tc = (Math.Abs(tN) < 0.000001f ? 0.0f : tN / tD);
  279. // get the difference of the two closest points
  280. Vector3 dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc)
  281. return dP.sqrMagnitude; // return the closest distance
  282. }
  283. /** Squared distance between two points in the XZ plane */
  284. public static float SqrDistanceXZ (Vector3 a, Vector3 b) {
  285. var delta = a-b;
  286. return delta.x*delta.x+delta.z*delta.z;
  287. }
  288. /** Signed area of a triangle in the XZ plane multiplied by 2.
  289. * This will be negative for clockwise triangles and positive for counter-clockwise ones
  290. */
  291. public static long SignedTriangleAreaTimes2XZ (Int3 a, Int3 b, Int3 c) {
  292. return (long)(b.x - a.x) * (long)(c.z - a.z) - (long)(c.x - a.x) * (long)(b.z - a.z);
  293. }
  294. /** Signed area of a triangle in the XZ plane multiplied by 2.
  295. * This will be negative for clockwise triangles and positive for counter-clockwise ones.
  296. */
  297. public static float SignedTriangleAreaTimes2XZ (Vector3 a, Vector3 b, Vector3 c) {
  298. return (b.x - a.x) * (c.z - a.z) - (c.x - a.x) * (b.z - a.z);
  299. }
  300. /** Returns if \a p lies on the right side of the line \a a - \a b.
  301. * Uses XZ space. Does not return true if the points are colinear.
  302. */
  303. public static bool RightXZ (Vector3 a, Vector3 b, Vector3 p) {
  304. return (b.x - a.x) * (p.z - a.z) - (p.x - a.x) * (b.z - a.z) < -float.Epsilon;
  305. }
  306. /** Returns if \a p lies on the right side of the line \a a - \a b.
  307. * Uses XZ space. Does not return true if the points are colinear.
  308. */
  309. public static bool RightXZ (Int3 a, Int3 b, Int3 p) {
  310. return (long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z) < 0;
  311. }
  312. /** Returns which side of the line \a a - \a b that \a p lies on.
  313. * Uses XZ space.
  314. */
  315. public static Side SideXZ (Int3 a, Int3 b, Int3 p) {
  316. var s = (long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z);
  317. return s > 0 ? Side.Left : (s < 0 ? Side.Right : Side.Colinear);
  318. }
  319. /** Returns if \a p lies on the right side of the line \a a - \a b.
  320. * Also returns true if the points are colinear.
  321. */
  322. public static bool RightOrColinear (Vector2 a, Vector2 b, Vector2 p) {
  323. return (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y) <= 0;
  324. }
  325. /** Returns if \a p lies on the right side of the line \a a - \a b.
  326. * Also returns true if the points are colinear.
  327. */
  328. public static bool RightOrColinear (Int2 a, Int2 b, Int2 p) {
  329. return (long)(b.x - a.x) * (long)(p.y - a.y) - (long)(p.x - a.x) * (long)(b.y - a.y) <= 0;
  330. }
  331. /** Returns if \a p lies on the left side of the line \a a - \a b.
  332. * Uses XZ space. Also returns true if the points are colinear.
  333. */
  334. public static bool RightOrColinearXZ (Vector3 a, Vector3 b, Vector3 p) {
  335. return (b.x - a.x) * (p.z - a.z) - (p.x - a.x) * (b.z - a.z) <= 0;
  336. }
  337. /** Returns if \a p lies on the left side of the line \a a - \a b.
  338. * Uses XZ space. Also returns true if the points are colinear.
  339. */
  340. public static bool RightOrColinearXZ (Int3 a, Int3 b, Int3 p) {
  341. return (long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z) <= 0;
  342. }
  343. /** Returns if the points a in a clockwise order.
  344. * Will return true even if the points are colinear or very slightly counter-clockwise
  345. * (if the signed area of the triangle formed by the points has an area less than or equals to float.Epsilon) */
  346. public static bool IsClockwiseMarginXZ (Vector3 a, Vector3 b, Vector3 c) {
  347. return (b.x-a.x)*(c.z-a.z)-(c.x-a.x)*(b.z-a.z) <= float.Epsilon;
  348. }
  349. /** Returns if the points a in a clockwise order */
  350. public static bool IsClockwiseXZ (Vector3 a, Vector3 b, Vector3 c) {
  351. return (b.x-a.x)*(c.z-a.z)-(c.x-a.x)*(b.z-a.z) < 0;
  352. }
  353. /** Returns if the points a in a clockwise order */
  354. public static bool IsClockwiseXZ (Int3 a, Int3 b, Int3 c) {
  355. return RightXZ(a, b, c);
  356. }
  357. /** Returns true if the points a in a clockwise order or if they are colinear */
  358. public static bool IsClockwiseOrColinearXZ (Int3 a, Int3 b, Int3 c) {
  359. return RightOrColinearXZ(a, b, c);
  360. }
  361. /** Returns true if the points a in a clockwise order or if they are colinear */
  362. public static bool IsClockwiseOrColinear (Int2 a, Int2 b, Int2 c) {
  363. return RightOrColinear(a, b, c);
  364. }
  365. /** Returns if the points are colinear (lie on a straight line) */
  366. public static bool IsColinear (Vector3 a, Vector3 b, Vector3 c) {
  367. var lhs = b - a;
  368. var rhs = c - a;
  369. // Take the cross product of lhs and rhs
  370. // The magnitude of the cross product will be zero if the points a,b,c are colinear
  371. float x = lhs.y * rhs.z - lhs.z * rhs.y;
  372. float y = lhs.z * rhs.x - lhs.x * rhs.z;
  373. float z = lhs.x * rhs.y - lhs.y * rhs.x;
  374. float v = x*x + y*y + z*z;
  375. // Epsilon not chosen with much thought, just that float.Epsilon was a bit too small.
  376. return v <= 0.0000001f;
  377. }
  378. /** Returns if the points are colinear (lie on a straight line) */
  379. public static bool IsColinear (Vector2 a, Vector2 b, Vector2 c) {
  380. float v = (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);
  381. // Epsilon not chosen with much thought, just that float.Epsilon was a bit too small.
  382. return v <= 0.0000001f && v >= -0.0000001f;
  383. }
  384. /** Returns if the points are colinear (lie on a straight line) */
  385. public static bool IsColinearXZ (Int3 a, Int3 b, Int3 c) {
  386. return (long)(b.x - a.x) * (long)(c.z - a.z) - (long)(c.x - a.x) * (long)(b.z - a.z) == 0;
  387. }
  388. /** Returns if the points are colinear (lie on a straight line) */
  389. public static bool IsColinearXZ (Vector3 a, Vector3 b, Vector3 c) {
  390. float v = (b.x-a.x)*(c.z-a.z)-(c.x-a.x)*(b.z-a.z);
  391. // Epsilon not chosen with much thought, just that float.Epsilon was a bit too small.
  392. return v <= 0.0000001f && v >= -0.0000001f;
  393. }
  394. /** Returns if the points are colinear (lie on a straight line) */
  395. public static bool IsColinearAlmostXZ (Int3 a, Int3 b, Int3 c) {
  396. long v = (long)(b.x - a.x) * (long)(c.z - a.z) - (long)(c.x - a.x) * (long)(b.z - a.z);
  397. return v > -1 && v < 1;
  398. }
  399. /** Returns if the line segment \a start2 - \a end2 intersects the line segment \a start1 - \a end1.
  400. * If only the endpoints coincide, the result is undefined (may be true or false).
  401. */
  402. public static bool SegmentsIntersect (Int2 start1, Int2 end1, Int2 start2, Int2 end2) {
  403. return RightOrColinear(start1, end1, start2) != RightOrColinear(start1, end1, end2) && RightOrColinear(start2, end2, start1) != RightOrColinear(start2, end2, end1);
  404. }
  405. /** Returns if the line segment \a start2 - \a end2 intersects the line segment \a start1 - \a end1.
  406. * If only the endpoints coincide, the result is undefined (may be true or false).
  407. *
  408. * \note XZ space
  409. */
  410. public static bool SegmentsIntersectXZ (Int3 start1, Int3 end1, Int3 start2, Int3 end2) {
  411. return RightOrColinearXZ(start1, end1, start2) != RightOrColinearXZ(start1, end1, end2) && RightOrColinearXZ(start2, end2, start1) != RightOrColinearXZ(start2, end2, end1);
  412. }
  413. /** Returns if the two line segments intersects. The lines are NOT treated as infinite (just for clarification)
  414. * \see IntersectionPoint
  415. */
  416. public static bool SegmentsIntersectXZ (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2) {
  417. Vector3 dir1 = end1-start1;
  418. Vector3 dir2 = end2-start2;
  419. float den = dir2.z*dir1.x - dir2.x * dir1.z;
  420. if (den == 0) {
  421. return false;
  422. }
  423. float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x);
  424. float nom2 = dir1.x*(start1.z-start2.z) - dir1.z * (start1.x - start2.x);
  425. float u = nom/den;
  426. float u2 = nom2/den;
  427. if (u < 0F || u > 1F || u2 < 0F || u2 > 1F) {
  428. return false;
  429. }
  430. return true;
  431. }
  432. /** Intersection point between two infinite lines.
  433. * Note that start points and directions are taken as parameters instead of start and end points.
  434. * Lines are treated as infinite. If the lines are parallel 'start1' will be returned.
  435. * Intersections are calculated on the XZ plane.
  436. *
  437. * \see LineIntersectionPointXZ
  438. */
  439. public static Vector3 LineDirIntersectionPointXZ (Vector3 start1, Vector3 dir1, Vector3 start2, Vector3 dir2) {
  440. float den = dir2.z*dir1.x - dir2.x * dir1.z;
  441. if (den == 0) {
  442. return start1;
  443. }
  444. float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x);
  445. float u = nom/den;
  446. return start1 + dir1*u;
  447. }
  448. /** Intersection point between two infinite lines.
  449. * Note that start points and directions are taken as parameters instead of start and end points.
  450. * Lines are treated as infinite. If the lines are parallel 'start1' will be returned.
  451. * Intersections are calculated on the XZ plane.
  452. *
  453. * \see LineIntersectionPointXZ
  454. */
  455. public static Vector3 LineDirIntersectionPointXZ (Vector3 start1, Vector3 dir1, Vector3 start2, Vector3 dir2, out bool intersects) {
  456. float den = dir2.z*dir1.x - dir2.x * dir1.z;
  457. if (den == 0) {
  458. intersects = false;
  459. return start1;
  460. }
  461. float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x);
  462. float u = nom/den;
  463. intersects = true;
  464. return start1 + dir1*u;
  465. }
  466. /** Returns if the ray (start1, end1) intersects the segment (start2, end2).
  467. * false is returned if the lines are parallel.
  468. * Only the XZ coordinates are used.
  469. * \todo Double check that this actually works
  470. */
  471. public static bool RaySegmentIntersectXZ (Int3 start1, Int3 end1, Int3 start2, Int3 end2) {
  472. Int3 dir1 = end1-start1;
  473. Int3 dir2 = end2-start2;
  474. long den = dir2.z*dir1.x - dir2.x * dir1.z;
  475. if (den == 0) {
  476. return false;
  477. }
  478. long nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x);
  479. long nom2 = dir1.x*(start1.z-start2.z) - dir1.z * (start1.x - start2.x);
  480. //factor1 < 0
  481. // If both have the same sign, then nom/den < 0 and thus the segment cuts the ray before the ray starts
  482. if (!(nom < 0 ^ den < 0)) {
  483. return false;
  484. }
  485. //factor2 < 0
  486. if (!(nom2 < 0 ^ den < 0)) {
  487. return false;
  488. }
  489. if ((den >= 0 && nom2 > den) || (den < 0 && nom2 <= den)) {
  490. return false;
  491. }
  492. return true;
  493. }
  494. /** Returns the intersection factors for line 1 and line 2. The intersection factors is a distance along the line \a start - \a end where the other line intersects it.\n
  495. * \code intersectionPoint = start1 + factor1 * (end1-start1) \endcode
  496. * \code intersectionPoint2 = start2 + factor2 * (end2-start2) \endcode
  497. * Lines are treated as infinite.\n
  498. * false is returned if the lines are parallel and true if they are not.
  499. * Only the XZ coordinates are used.
  500. */
  501. public static bool LineIntersectionFactorXZ (Int3 start1, Int3 end1, Int3 start2, Int3 end2, out float factor1, out float factor2) {
  502. Int3 dir1 = end1-start1;
  503. Int3 dir2 = end2-start2;
  504. long den = dir2.z*dir1.x - dir2.x * dir1.z;
  505. if (den == 0) {
  506. factor1 = 0;
  507. factor2 = 0;
  508. return false;
  509. }
  510. long nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x);
  511. long nom2 = dir1.x*(start1.z-start2.z) - dir1.z * (start1.x - start2.x);
  512. factor1 = (float)nom/den;
  513. factor2 = (float)nom2/den;
  514. return true;
  515. }
  516. /** Returns the intersection factors for line 1 and line 2. The intersection factors is a distance along the line \a start - \a end where the other line intersects it.\n
  517. * \code intersectionPoint = start1 + factor1 * (end1-start1) \endcode
  518. * \code intersectionPoint2 = start2 + factor2 * (end2-start2) \endcode
  519. * Lines are treated as infinite.\n
  520. * false is returned if the lines are parallel and true if they are not.
  521. * Only the XZ coordinates are used.
  522. */
  523. public static bool LineIntersectionFactorXZ (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2, out float factor1, out float factor2) {
  524. Vector3 dir1 = end1-start1;
  525. Vector3 dir2 = end2-start2;
  526. float den = dir2.z*dir1.x - dir2.x * dir1.z;
  527. if (den <= 0.00001f && den >= -0.00001f) {
  528. factor1 = 0;
  529. factor2 = 0;
  530. return false;
  531. }
  532. float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x);
  533. float nom2 = dir1.x*(start1.z-start2.z) - dir1.z * (start1.x - start2.x);
  534. float u = nom/den;
  535. float u2 = nom2/den;
  536. factor1 = u;
  537. factor2 = u2;
  538. return true;
  539. }
  540. /** Returns the intersection factor for line 1 with ray 2.
  541. * The intersection factors is a factor distance along the line \a start - \a end where the other line intersects it.\n
  542. * \code intersectionPoint = start1 + factor * (end1-start1) \endcode
  543. * Lines are treated as infinite.\n
  544. *
  545. * The second "line" is treated as a ray, meaning only matches on start2 or forwards towards end2 (and beyond) will be returned
  546. * If the point lies on the wrong side of the ray start, Nan will be returned.
  547. *
  548. * NaN is returned if the lines are parallel. */
  549. public static float LineRayIntersectionFactorXZ (Int3 start1, Int3 end1, Int3 start2, Int3 end2) {
  550. Int3 dir1 = end1-start1;
  551. Int3 dir2 = end2-start2;
  552. int den = dir2.z*dir1.x - dir2.x * dir1.z;
  553. if (den == 0) {
  554. return float.NaN;
  555. }
  556. int nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x);
  557. int nom2 = dir1.x*(start1.z-start2.z) - dir1.z * (start1.x - start2.x);
  558. if ((float)nom2/den < 0) {
  559. return float.NaN;
  560. }
  561. return (float)nom/den;
  562. }
  563. /** Returns the intersection factor for line 1 with line 2.
  564. * The intersection factor is a distance along the line \a start1 - \a end1 where the line \a start2 - \a end2 intersects it.\n
  565. * \code intersectionPoint = start1 + intersectionFactor * (end1-start1) \endcode.
  566. * Lines are treated as infinite.\n
  567. * -1 is returned if the lines are parallel (note that this is a valid return value if they are not parallel too) */
  568. public static float LineIntersectionFactorXZ (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2) {
  569. Vector3 dir1 = end1-start1;
  570. Vector3 dir2 = end2-start2;
  571. float den = dir2.z*dir1.x - dir2.x * dir1.z;
  572. if (den == 0) {
  573. return -1;
  574. }
  575. float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x);
  576. float u = nom/den;
  577. return u;
  578. }
  579. /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel */
  580. public static Vector3 LineIntersectionPointXZ (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2) {
  581. bool s;
  582. return LineIntersectionPointXZ(start1, end1, start2, end2, out s);
  583. }
  584. /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel */
  585. public static Vector3 LineIntersectionPointXZ (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2, out bool intersects) {
  586. Vector3 dir1 = end1-start1;
  587. Vector3 dir2 = end2-start2;
  588. float den = dir2.z*dir1.x - dir2.x * dir1.z;
  589. if (den == 0) {
  590. intersects = false;
  591. return start1;
  592. }
  593. float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x);
  594. float u = nom/den;
  595. intersects = true;
  596. return start1 + dir1*u;
  597. }
  598. /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel */
  599. public static Vector2 LineIntersectionPoint (Vector2 start1, Vector2 end1, Vector2 start2, Vector2 end2) {
  600. bool s;
  601. return LineIntersectionPoint(start1, end1, start2, end2, out s);
  602. }
  603. /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel */
  604. public static Vector2 LineIntersectionPoint (Vector2 start1, Vector2 end1, Vector2 start2, Vector2 end2, out bool intersects) {
  605. Vector2 dir1 = end1-start1;
  606. Vector2 dir2 = end2-start2;
  607. float den = dir2.y*dir1.x - dir2.x * dir1.y;
  608. if (den == 0) {
  609. intersects = false;
  610. return start1;
  611. }
  612. float nom = dir2.x*(start1.y-start2.y)- dir2.y*(start1.x-start2.x);
  613. float u = nom/den;
  614. intersects = true;
  615. return start1 + dir1*u;
  616. }
  617. /** Returns the intersection point between the two line segments in XZ space.
  618. * Lines are NOT treated as infinite. \a start1 is returned if the line segments do not intersect
  619. * The point will be returned along the line [start1, end1] (this matters only for the y coordinate).
  620. */
  621. public static Vector3 SegmentIntersectionPointXZ (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2, out bool intersects) {
  622. Vector3 dir1 = end1-start1;
  623. Vector3 dir2 = end2-start2;
  624. float den = dir2.z * dir1.x - dir2.x * dir1.z;
  625. if (den == 0) {
  626. intersects = false;
  627. return start1;
  628. }
  629. float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x);
  630. float nom2 = dir1.x*(start1.z-start2.z) - dir1.z*(start1.x-start2.x);
  631. float u = nom/den;
  632. float u2 = nom2/den;
  633. if (u < 0F || u > 1F || u2 < 0F || u2 > 1F) {
  634. intersects = false;
  635. return start1;
  636. }
  637. intersects = true;
  638. return start1 + dir1*u;
  639. }
  640. /** Intersection of a line and a circle.
  641. * Returns the greatest t such that segmentStart+t*(segmentEnd-segmentStart) lies on the circle.
  642. *
  643. * In case the line does not intersect with the circle, the closest point on the line
  644. * to the circle will be returned.
  645. *
  646. * \note Works for line and sphere in 3D space as well.
  647. *
  648. * \see http://mathworld.wolfram.com/Circle-LineIntersection.html
  649. * \see https://en.wikipedia.org/wiki/Intersection_(Euclidean_geometry)#A_line_and_a_circle
  650. */
  651. public static float LineCircleIntersectionFactor (Vector3 circleCenter, Vector3 linePoint1, Vector3 linePoint2, float radius) {
  652. float segmentLength;
  653. var normalizedDirection = Normalize(linePoint2 - linePoint1, out segmentLength);
  654. var dirToStart = linePoint1 - circleCenter;
  655. var dot = Vector3.Dot(dirToStart, normalizedDirection);
  656. var discriminant = dot * dot - (dirToStart.sqrMagnitude - radius*radius);
  657. if (discriminant < 0) {
  658. // No intersection, pick closest point on segment
  659. discriminant = 0;
  660. }
  661. var t = -dot + Mathf.Sqrt(discriminant);
  662. // Note: the default value of 1 is important for the PathInterpolator.MoveToCircleIntersection2D
  663. // method to work properly. Maybe find some better abstraction where this default value is more obvious.
  664. return segmentLength > 0.00001f ? t / segmentLength : 1f;
  665. }
  666. /** Normalize vector and also return the magnitude.
  667. * This is more efficient than calculating the magnitude and normalizing separately
  668. */
  669. public static Vector3 Normalize (Vector3 v, out float magnitude) {
  670. magnitude = v.magnitude;
  671. // This is the same constant that Unity uses
  672. if (magnitude > 1E-05f) {
  673. return v / magnitude;
  674. } else {
  675. return Vector3.zero;
  676. }
  677. }
  678. /** Normalize vector and also return the magnitude.
  679. * This is more efficient than calculating the magnitude and normalizing separately
  680. */
  681. public static Vector2 Normalize (Vector2 v, out float magnitude) {
  682. magnitude = v.magnitude;
  683. // This is the same constant that Unity uses
  684. if (magnitude > 1E-05f) {
  685. return v / magnitude;
  686. } else {
  687. return Vector2.zero;
  688. }
  689. }
  690. /* Clamp magnitude along the X and Z axes.
  691. * The y component will not be changed.
  692. */
  693. public static Vector3 ClampMagnitudeXZ (Vector3 v, float maxMagnitude) {
  694. float squaredMagnitudeXZ = v.x*v.x + v.z*v.z;
  695. if (squaredMagnitudeXZ > maxMagnitude*maxMagnitude && maxMagnitude > 0) {
  696. var factor = maxMagnitude / Mathf.Sqrt(squaredMagnitudeXZ);
  697. v.x *= factor;
  698. v.z *= factor;
  699. }
  700. return v;
  701. }
  702. /* Magnitude in the XZ plane */
  703. public static float MagnitudeXZ (Vector3 v) {
  704. return Mathf.Sqrt(v.x*v.x + v.z*v.z);
  705. }
  706. }
  707. /** Utility functions for working with numbers and strings.
  708. * \ingroup utils
  709. * \see Polygon
  710. * \see VectorMath
  711. */
  712. public static class AstarMath {
  713. /** Returns the closest point on the line. The line is treated as infinite.
  714. * \see NearestPointStrict
  715. */
  716. [System.Obsolete("Use VectorMath.ClosestPointOnLine instead")]
  717. public static Vector3 NearestPoint (Vector3 lineStart, Vector3 lineEnd, Vector3 point) {
  718. return VectorMath.ClosestPointOnLine(lineStart, lineEnd, point);
  719. }
  720. [System.Obsolete("Use VectorMath.ClosestPointOnLineFactor instead")]
  721. public static float NearestPointFactor (Vector3 lineStart, Vector3 lineEnd, Vector3 point) {
  722. return VectorMath.ClosestPointOnLineFactor(lineStart, lineEnd, point);
  723. }
  724. /** Factor of the nearest point on the segment.
  725. * Returned value is in the range [0,1] if the point lies on the segment otherwise it just lies on the line.
  726. * The closest point can be got by (end-start)*factor + start;
  727. */
  728. [System.Obsolete("Use VectorMath.ClosestPointOnLineFactor instead")]
  729. public static float NearestPointFactor (Int3 lineStart, Int3 lineEnd, Int3 point) {
  730. return VectorMath.ClosestPointOnLineFactor(lineStart, lineEnd, point);
  731. }
  732. /** Factor of the nearest point on the segment.
  733. * Returned value is in the range [0,1] if the point lies on the segment otherwise it just lies on the line.
  734. * The closest point can be got by (end-start)*factor + start;
  735. */
  736. [System.Obsolete("Use VectorMath.ClosestPointOnLineFactor instead")]
  737. public static float NearestPointFactor (Int2 lineStart, Int2 lineEnd, Int2 point) {
  738. return VectorMath.ClosestPointOnLineFactor(lineStart, lineEnd, point);
  739. }
  740. /** Returns the closest point on the line segment. The line is NOT treated as infinite.
  741. * \see NearestPoint
  742. */
  743. [System.Obsolete("Use VectorMath.ClosestPointOnSegment instead")]
  744. public static Vector3 NearestPointStrict (Vector3 lineStart, Vector3 lineEnd, Vector3 point) {
  745. return VectorMath.ClosestPointOnSegment(lineStart, lineEnd, point);
  746. }
  747. /** Returns the closest point on the line segment on the XZ plane. The line is NOT treated as infinite.
  748. * \see NearestPoint
  749. */
  750. [System.Obsolete("Use VectorMath.ClosestPointOnSegmentXZ instead")]
  751. public static Vector3 NearestPointStrictXZ (Vector3 lineStart, Vector3 lineEnd, Vector3 point) {
  752. return VectorMath.ClosestPointOnSegmentXZ(lineStart, lineEnd, point);
  753. }
  754. /** Returns the approximate shortest squared distance between x,z and the line p-q.
  755. * The line is considered infinite.
  756. * This function is not entirely exact, but it is about twice as fast as DistancePointSegment2.
  757. */
  758. [System.Obsolete("Use VectorMath.SqrDistancePointSegmentApproximate instead")]
  759. public static float DistancePointSegment (int x, int z, int px, int pz, int qx, int qz) {
  760. return VectorMath.SqrDistancePointSegmentApproximate(x, z, px, pz, qx, qz);
  761. }
  762. /** Returns the approximate shortest squared distance between x,z and the line p-q.
  763. * The line is considered infinite.
  764. * This function is not entirely exact, but it is about twice as fast as DistancePointSegment2.
  765. */
  766. [System.Obsolete("Use VectorMath.SqrDistancePointSegmentApproximate instead")]
  767. public static float DistancePointSegment (Int3 a, Int3 b, Int3 p) {
  768. return VectorMath.SqrDistancePointSegmentApproximate(a, b, p);
  769. }
  770. /** Returns the squared distance between c and the line a-b. The line is not considered infinite. */
  771. [System.Obsolete("Use VectorMath.SqrDistancePointSegment instead")]
  772. public static float DistancePointSegmentStrict (Vector3 a, Vector3 b, Vector3 p) {
  773. return VectorMath.SqrDistancePointSegment(a, b, p);
  774. }
  775. /** Returns a point on a cubic bezier curve. \a t is clamped between 0 and 1 */
  776. [System.Obsolete("Use AstarSplines.CubicBezier instead")]
  777. public static Vector3 CubicBezier (Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t) {
  778. return AstarSplines.CubicBezier(p0, p1, p2, p3, t);
  779. }
  780. /** Maps a value between startMin and startMax to be between 0 and 1 */
  781. [System.Obsolete("Use Mathf.InverseLerp instead")]
  782. public static float MapTo (float startMin, float startMax, float value) {
  783. return Mathf.InverseLerp(startMin, startMax, value);
  784. }
  785. /** Maps a value between startMin and startMax to be between targetMin and targetMax */
  786. public static float MapTo (float startMin, float startMax, float targetMin, float targetMax, float value) {
  787. return Mathf.Lerp(targetMin, targetMax, Mathf.InverseLerp(startMin, startMax, value));
  788. }
  789. /** Returns a nicely formatted string for the number of bytes (KiB, MiB, GiB etc). Uses decimal names (KB, Mb - 1000) but calculates using binary values (KiB, MiB - 1024) */
  790. public static string FormatBytesBinary (int bytes) {
  791. double sign = bytes >= 0 ? 1D : -1D;
  792. bytes = Mathf.Abs(bytes);
  793. if (bytes < 1024) {
  794. return (bytes*sign)+" bytes";
  795. } else if (bytes < 1024*1024) {
  796. return ((bytes/1024D)*sign).ToString("0.0") + " KiB";
  797. } else if (bytes < 1024*1024*1024) {
  798. return ((bytes/(1024D*1024D))*sign).ToString("0.0") +" MiB";
  799. }
  800. return ((bytes/(1024D*1024D*1024D))*sign).ToString("0.0") +" GiB";
  801. }
  802. }
  803. /** Utility functions for working with polygons, lines, and other vector math.
  804. * All functions which accepts Vector3s but work in 2D space uses the XZ space if nothing else is said.
  805. *
  806. * \version A lot of functions in this class have been moved to the VectorMath class
  807. * the names have changed slightly and everything now consistently assumes a left handed
  808. * coordinate system now instead of sometimes using a left handed one and sometimes
  809. * using a right handed one. This is why the 'Left' methods redirect to methods
  810. * named 'Right'. The functionality is exactly the same.
  811. *
  812. * \ingroup utils
  813. */
  814. public static class Polygon {
  815. /** Returns if the triangle \a ABC contains the point \a p in XZ space.
  816. * The triangle vertices are assumed to be laid out in clockwise order.
  817. */
  818. public static bool ContainsPointXZ (Vector3 a, Vector3 b, Vector3 c, Vector3 p) {
  819. return VectorMath.IsClockwiseMarginXZ(a, b, p) && VectorMath.IsClockwiseMarginXZ(b, c, p) && VectorMath.IsClockwiseMarginXZ(c, a, p);
  820. }
  821. /** Returns if the triangle \a ABC contains the point \a p.
  822. * The triangle vertices are assumed to be laid out in clockwise order.
  823. */
  824. public static bool ContainsPointXZ (Int3 a, Int3 b, Int3 c, Int3 p) {
  825. return VectorMath.IsClockwiseOrColinearXZ(a, b, p) && VectorMath.IsClockwiseOrColinearXZ(b, c, p) && VectorMath.IsClockwiseOrColinearXZ(c, a, p);
  826. }
  827. /** Returns if the triangle \a ABC contains the point \a p.
  828. * The triangle vertices are assumed to be laid out in clockwise order.
  829. */
  830. public static bool ContainsPoint (Int2 a, Int2 b, Int2 c, Int2 p) {
  831. return VectorMath.IsClockwiseOrColinear(a, b, p) && VectorMath.IsClockwiseOrColinear(b, c, p) && VectorMath.IsClockwiseOrColinear(c, a, p);
  832. }
  833. /** Checks if \a p is inside the polygon.
  834. * \author http://unifycommunity.com/wiki/index.php?title=PolyContainsPoint (Eric5h5)
  835. */
  836. public static bool ContainsPoint (Vector2[] polyPoints, Vector2 p) {
  837. int j = polyPoints.Length-1;
  838. bool inside = false;
  839. for (int i = 0; i < polyPoints.Length; j = i++) {
  840. if (((polyPoints[i].y <= p.y && p.y < polyPoints[j].y) || (polyPoints[j].y <= p.y && p.y < polyPoints[i].y)) &&
  841. (p.x < (polyPoints[j].x - polyPoints[i].x) * (p.y - polyPoints[i].y) / (polyPoints[j].y - polyPoints[i].y) + polyPoints[i].x))
  842. inside = !inside;
  843. }
  844. return inside;
  845. }
  846. /** Checks if \a p is inside the polygon (XZ space).
  847. * \author http://unifycommunity.com/wiki/index.php?title=PolyContainsPoint (Eric5h5)
  848. */
  849. public static bool ContainsPointXZ (Vector3[] polyPoints, Vector3 p) {
  850. int j = polyPoints.Length-1;
  851. bool inside = false;
  852. for (int i = 0; i < polyPoints.Length; j = i++) {
  853. if (((polyPoints[i].z <= p.z && p.z < polyPoints[j].z) || (polyPoints[j].z <= p.z && p.z < polyPoints[i].z)) &&
  854. (p.x < (polyPoints[j].x - polyPoints[i].x) * (p.z - polyPoints[i].z) / (polyPoints[j].z - polyPoints[i].z) + polyPoints[i].x))
  855. inside = !inside;
  856. }
  857. return inside;
  858. }
  859. /** Sample Y coordinate of the triangle (p1, p2, p3) at the point p in XZ space.
  860. * The y coordinate of \a p is ignored.
  861. *
  862. * \returns The interpolated y coordinate unless the triangle is degenerate in which case a DivisionByZeroException will be thrown
  863. *
  864. * \see https://en.wikipedia.org/wiki/Barycentric_coordinate_system
  865. */
  866. public static int SampleYCoordinateInTriangle (Int3 p1, Int3 p2, Int3 p3, Int3 p) {
  867. double det = ((double)(p2.z - p3.z)) * (p1.x - p3.x) + ((double)(p3.x - p2.x)) * (p1.z - p3.z);
  868. double lambda1 = ((((double)(p2.z - p3.z)) * (p.x - p3.x) + ((double)(p3.x - p2.x)) * (p.z - p3.z)) / det);
  869. double lambda2 = ((((double)(p3.z - p1.z)) * (p.x - p3.x) + ((double)(p1.x - p3.x)) * (p.z - p3.z)) / det);
  870. return (int)Math.Round(lambda1 * p1.y + lambda2 * p2.y + (1 - lambda1 - lambda2) * p3.y);
  871. }
  872. /** Returns if \a p lies on the left side of the line \a a - \a b. Uses XZ space.
  873. * Does not return true if the points are colinear.
  874. * \deprecated Use VectorMath.RightXZ instead. Note that it now uses a left handed coordinate system (same as Unity)
  875. */
  876. [System.Obsolete("Use VectorMath.RightXZ instead. Note that it now uses a left handed coordinate system (same as Unity)")]
  877. public static bool LeftNotColinear (Vector3 a, Vector3 b, Vector3 p) {
  878. return VectorMath.RightXZ(a, b, p);
  879. }
  880. /** Returns if \a p lies on the left side of the line \a a - \a b. Uses XZ space. Also returns true if the points are colinear
  881. * \deprecated Use VectorMath.RightOrColinearXZ instead. Note that it now uses a left handed coordinate system (same as Unity)
  882. */
  883. [System.Obsolete("Use VectorMath.RightOrColinearXZ instead. Note that it now uses a left handed coordinate system (same as Unity)")]
  884. public static bool Left (Vector3 a, Vector3 b, Vector3 p) {
  885. return VectorMath.RightOrColinearXZ(a, b, p);
  886. }
  887. /** Returns if \a p lies on the left side of the line \a a - \a b. Also returns true if the points are colinear
  888. * \deprecated Use VectorMath.RightOrColinear instead. Note that it now uses a left handed coordinate system (same as Unity)
  889. */
  890. [System.Obsolete("Use VectorMath.RightOrColinear instead. Note that it now uses a left handed coordinate system (same as Unity)")]
  891. public static bool Left (Vector2 a, Vector2 b, Vector2 p) {
  892. return VectorMath.RightOrColinear(a, b, p);
  893. }
  894. /** Returns if \a p lies on the left side of the line \a a - \a b. Uses XZ space. Also returns true if the points are colinear
  895. * \deprecated Use VectorMath.RightOrColinearXZ instead. Note that it now uses a left handed coordinate system (same as Unity)
  896. */
  897. [System.Obsolete("Use VectorMath.RightOrColinearXZ instead. Note that it now uses a left handed coordinate system (same as Unity)")]
  898. public static bool Left (Int3 a, Int3 b, Int3 p) {
  899. return VectorMath.RightOrColinearXZ(a, b, p);
  900. }
  901. /** Returns if \a p lies on the left side of the line \a a - \a b. Uses XZ space.
  902. * \deprecated Use VectorMath.RightXZ instead. Note that it now uses a left handed coordinate system (same as Unity)
  903. */
  904. [System.Obsolete("Use VectorMath.RightXZ instead. Note that it now uses a left handed coordinate system (same as Unity)")]
  905. public static bool LeftNotColinear (Int3 a, Int3 b, Int3 p) {
  906. return VectorMath.RightXZ(a, b, p);
  907. }
  908. /** Returns if \a p lies on the left side of the line \a a - \a b. Also returns true if the points are colinear
  909. * \deprecated Use VectorMath.RightOrColinear instead. Note that it now uses a left handed coordinate system (same as Unity)
  910. */
  911. [System.Obsolete("Use VectorMath.RightOrColinear instead. Note that it now uses a left handed coordinate system (same as Unity)")]
  912. public static bool Left (Int2 a, Int2 b, Int2 p) {
  913. return VectorMath.RightOrColinear(a, b, p);
  914. }
  915. /** Returns if the points a in a clockwise order.
  916. * Will return true even if the points are colinear or very slightly counter-clockwise
  917. * (if the signed area of the triangle formed by the points has an area less than or equals to float.Epsilon)
  918. * \deprecated Use VectorMath.IsClockwiseMarginXZ instead
  919. */
  920. [System.Obsolete("Use VectorMath.IsClockwiseMarginXZ instead")]
  921. public static bool IsClockwiseMargin (Vector3 a, Vector3 b, Vector3 c) {
  922. return VectorMath.IsClockwiseMarginXZ(a, b, c);
  923. }
  924. /** Returns if the points a in a clockwise order
  925. * \deprecated Use VectorMath.IsClockwiseXZ instead
  926. */
  927. [System.Obsolete("Use VectorMath.IsClockwiseXZ instead")]
  928. public static bool IsClockwise (Vector3 a, Vector3 b, Vector3 c) {
  929. return VectorMath.IsClockwiseXZ(a, b, c);
  930. }
  931. /** Returns if the points a in a clockwise order
  932. * \deprecated Use VectorMath.IsClockwiseXZ instead
  933. */
  934. [System.Obsolete("Use VectorMath.IsClockwiseXZ instead")]
  935. public static bool IsClockwise (Int3 a, Int3 b, Int3 c) {
  936. return VectorMath.IsClockwiseXZ(a, b, c);
  937. }
  938. /** Returns true if the points a in a clockwise order or if they are colinear
  939. * \deprecated Use VectorMath.IsClockwiseOrColinearXZ instead
  940. */
  941. [System.Obsolete("Use VectorMath.IsClockwiseOrColinearXZ instead")]
  942. public static bool IsClockwiseMargin (Int3 a, Int3 b, Int3 c) {
  943. return VectorMath.IsClockwiseOrColinearXZ(a, b, c);
  944. }
  945. /** Returns true if the points a in a clockwise order or if they are colinear
  946. * \deprecated Use VectorMath.IsClockwiseOrColinear instead
  947. */
  948. [System.Obsolete("Use VectorMath.IsClockwiseOrColinear instead")]
  949. public static bool IsClockwiseMargin (Int2 a, Int2 b, Int2 c) {
  950. return VectorMath.IsClockwiseOrColinear(a, b, c);
  951. }
  952. /** Returns if the points are colinear (lie on a straight line)
  953. * \deprecated Use VectorMath.IsColinearXZ instead
  954. */
  955. [System.Obsolete("Use VectorMath.IsColinearXZ instead")]
  956. public static bool IsColinear (Int3 a, Int3 b, Int3 c) {
  957. return VectorMath.IsColinearXZ(a, b, c);
  958. }
  959. /** Returns if the points are colinear (lie on a straight line)
  960. * \deprecated Use VectorMath.IsColinearAlmostXZ instead
  961. */
  962. [System.Obsolete("Use VectorMath.IsColinearAlmostXZ instead")]
  963. public static bool IsColinearAlmost (Int3 a, Int3 b, Int3 c) {
  964. return VectorMath.IsColinearAlmostXZ(a, b, c);
  965. }
  966. /** Returns if the points are colinear (lie on a straight line)
  967. * \deprecated Use VectorMath.IsColinearXZ instead
  968. */
  969. [System.Obsolete("Use VectorMath.IsColinearXZ instead")]
  970. public static bool IsColinear (Vector3 a, Vector3 b, Vector3 c) {
  971. return VectorMath.IsColinearXZ(a, b, c);
  972. }
  973. /** Returns if the line segment \a a2 - \a b2 intersects the infinite line \a a - \a b. a-b is infinite, a2-b2 is not infinite */
  974. [System.Obsolete("Marked for removal since it is not used by any part of the A* Pathfinding Project")]
  975. public static bool IntersectsUnclamped (Vector3 a, Vector3 b, Vector3 a2, Vector3 b2) {
  976. return VectorMath.RightOrColinearXZ(a, b, a2) != VectorMath.RightOrColinearXZ(a, b, b2);
  977. }
  978. /** Returns if the line segment \a a2 - \a b2 intersects the line segment \a a - \a b.
  979. * If only the endpoints coincide, the result is undefined (may be true or false).
  980. *
  981. * \deprecated Use VectorMath.SegmentsIntersect instead */
  982. [System.Obsolete("Use VectorMath.SegmentsIntersect instead")]
  983. public static bool Intersects (Int2 start1, Int2 end1, Int2 start2, Int2 end2) {
  984. return VectorMath.SegmentsIntersect(start1, end1, start2, end2);
  985. }
  986. /** Returns if the line segment \a a2 - \a b2 intersects the line segment \a a - \a b.
  987. * If only the endpoints coincide, the result is undefined (may be true or false).
  988. *
  989. * \note XZ space
  990. *
  991. * \deprecated Use VectorMath.SegmentsIntersectXZ instead */
  992. [System.Obsolete("Use VectorMath.SegmentsIntersectXZ instead")]
  993. public static bool Intersects (Int3 start1, Int3 end1, Int3 start2, Int3 end2) {
  994. return VectorMath.SegmentsIntersectXZ(start1, end1, start2, end2);
  995. }
  996. /** Returns if the two line segments intersects. The lines are NOT treated as infinite (just for clarification)
  997. * \see IntersectionPoint
  998. *
  999. * \deprecated Use VectorMath.SegmentsIntersectXZ instead */
  1000. [System.Obsolete("Use VectorMath.SegmentsIntersectXZ instead")]
  1001. public static bool Intersects (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2) {
  1002. return VectorMath.SegmentsIntersectXZ(start1, end1, start2, end2);
  1003. }
  1004. /** Intersection point between two infinite lines.
  1005. * Lines are treated as infinite. If the lines are parallel 'start1' will be returned. Intersections are calculated on the XZ plane.
  1006. *
  1007. * \deprecated Use VectorMath.LineDirIntersectionPointXZ instead */
  1008. [System.Obsolete("Use VectorMath.LineDirIntersectionPointXZ instead")]
  1009. public static Vector3 IntersectionPointOptimized (Vector3 start1, Vector3 dir1, Vector3 start2, Vector3 dir2) {
  1010. return VectorMath.LineDirIntersectionPointXZ(start1, dir1, start2, dir2);
  1011. }
  1012. /** Intersection point between two infinite lines.
  1013. * Lines are treated as infinite. If the lines are parallel 'start1' will be returned. Intersections are calculated on the XZ plane.
  1014. *
  1015. * \deprecated Use VectorMath.LineDirIntersectionPointXZ instead */
  1016. [System.Obsolete("Use VectorMath.LineDirIntersectionPointXZ instead")]
  1017. public static Vector3 IntersectionPointOptimized (Vector3 start1, Vector3 dir1, Vector3 start2, Vector3 dir2, out bool intersects) {
  1018. return VectorMath.LineDirIntersectionPointXZ(start1, dir1, start2, dir2, out intersects);
  1019. }
  1020. /** Returns if the ray (start1, end1) intersects the segment (start2, end2).
  1021. * false is returned if the lines are parallel.
  1022. * Only the XZ coordinates are used.
  1023. * \todo Double check that this actually works
  1024. *
  1025. * \deprecated Use VectorMath.RaySegmentIntersectXZ instead */
  1026. [System.Obsolete("Use VectorMath.RaySegmentIntersectXZ instead")]
  1027. public static bool IntersectionFactorRaySegment (Int3 start1, Int3 end1, Int3 start2, Int3 end2) {
  1028. return VectorMath.RaySegmentIntersectXZ(start1, end1, start2, end2);
  1029. }
  1030. /** Returns the intersection factors for line 1 and line 2. The intersection factors is a distance along the line \a start - \a end where the other line intersects it.\n
  1031. * \code intersectionPoint = start1 + factor1 * (end1-start1) \endcode
  1032. * \code intersectionPoint2 = start2 + factor2 * (end2-start2) \endcode
  1033. * Lines are treated as infinite.\n
  1034. * false is returned if the lines are parallel and true if they are not.
  1035. * Only the XZ coordinates are used.
  1036. *
  1037. * \deprecated Use VectorMath.LineIntersectionFactorXZ instead */
  1038. [System.Obsolete("Use VectorMath.LineIntersectionFactorXZ instead")]
  1039. public static bool IntersectionFactor (Int3 start1, Int3 end1, Int3 start2, Int3 end2, out float factor1, out float factor2) {
  1040. return VectorMath.LineIntersectionFactorXZ(start1, end1, start2, end2, out factor1, out factor2);
  1041. }
  1042. /** Returns the intersection factors for line 1 and line 2. The intersection factors is a distance along the line \a start - \a end where the other line intersects it.\n
  1043. * \code intersectionPoint = start1 + factor1 * (end1-start1) \endcode
  1044. * \code intersectionPoint2 = start2 + factor2 * (end2-start2) \endcode
  1045. * Lines are treated as infinite.\n
  1046. * false is returned if the lines are parallel and true if they are not.
  1047. * Only the XZ coordinates are used.
  1048. *
  1049. * \deprecated Use VectorMath.LineIntersectionFactorXZ instead */
  1050. [System.Obsolete("Use VectorMath.LineIntersectionFactorXZ instead")]
  1051. public static bool IntersectionFactor (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2, out float factor1, out float factor2) {
  1052. return VectorMath.LineIntersectionFactorXZ(start1, end1, start2, end2, out factor1, out factor2);
  1053. }
  1054. /** Returns the intersection factor for line 1 with ray 2.
  1055. * The intersection factors is a factor distance along the line \a start - \a end where the other line intersects it.\n
  1056. * \code intersectionPoint = start1 + factor * (end1-start1) \endcode
  1057. * Lines are treated as infinite.\n
  1058. *
  1059. * The second "line" is treated as a ray, meaning only matches on start2 or forwards towards end2 (and beyond) will be returned
  1060. * If the point lies on the wrong side of the ray start, Nan will be returned.
  1061. *
  1062. * NaN is returned if the lines are parallel. *
  1063. * \deprecated Use VectorMath.LineRayIntersectionFactorXZ instead */
  1064. [System.Obsolete("Use VectorMath.LineRayIntersectionFactorXZ instead")]
  1065. public static float IntersectionFactorRay (Int3 start1, Int3 end1, Int3 start2, Int3 end2) {
  1066. return VectorMath.LineRayIntersectionFactorXZ(start1, end1, start2, end2);
  1067. }
  1068. /** Returns the intersection factor for line 1 with line 2.
  1069. * The intersection factor is a distance along the line \a start1 - \a end1 where the line \a start2 - \a end2 intersects it.\n
  1070. * \code intersectionPoint = start1 + intersectionFactor * (end1-start1) \endcode.
  1071. * Lines are treated as infinite.\n
  1072. * -1 is returned if the lines are parallel (note that this is a valid return value if they are not parallel too) *
  1073. * \deprecated Use VectorMath.LineIntersectionFactorXZ instead */
  1074. [System.Obsolete("Use VectorMath.LineIntersectionFactorXZ instead")]
  1075. public static float IntersectionFactor (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2) {
  1076. return VectorMath.LineIntersectionFactorXZ(start1, end1, start2, end2);
  1077. }
  1078. /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel
  1079. * \deprecated Use VectorMath.LineIntersectionPointXZ instead */
  1080. [System.Obsolete("Use VectorMath.LineIntersectionPointXZ instead")]
  1081. public static Vector3 IntersectionPoint (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2) {
  1082. return VectorMath.LineIntersectionPointXZ(start1, end1, start2, end2);
  1083. }
  1084. /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel
  1085. * \deprecated Use VectorMath.LineIntersectionPointXZ instead */
  1086. [System.Obsolete("Use VectorMath.LineIntersectionPointXZ instead")]
  1087. public static Vector3 IntersectionPoint (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2, out bool intersects) {
  1088. return VectorMath.LineIntersectionPointXZ(start1, end1, start2, end2, out intersects);
  1089. }
  1090. /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel
  1091. * \deprecated Use VectorMath.LineIntersectionPoint instead */
  1092. [System.Obsolete("Use VectorMath.LineIntersectionPoint instead")]
  1093. public static Vector2 IntersectionPoint (Vector2 start1, Vector2 end1, Vector2 start2, Vector2 end2) {
  1094. return VectorMath.LineIntersectionPoint(start1, end1, start2, end2);
  1095. }
  1096. /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel
  1097. * \deprecated Use VectorMath.LineIntersectionPoint instead */
  1098. [System.Obsolete("Use VectorMath.LineIntersectionPoint instead")]
  1099. public static Vector2 IntersectionPoint (Vector2 start1, Vector2 end1, Vector2 start2, Vector2 end2, out bool intersects) {
  1100. return VectorMath.LineIntersectionPoint(start1, end1, start2, end2, out intersects);
  1101. }
  1102. /** Returns the intersection point between the two line segments in XZ space.
  1103. * Lines are NOT treated as infinite. \a start1 is returned if the line segments do not intersect
  1104. * The point will be returned along the line [start1, end1] (this matters only for the y coordinate).
  1105. *
  1106. * \deprecated Use VectorMath.SegmentIntersectionPointXZ instead */
  1107. [System.Obsolete("Use VectorMath.SegmentIntersectionPointXZ instead")]
  1108. public static Vector3 SegmentIntersectionPoint (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2, out bool intersects) {
  1109. return VectorMath.SegmentIntersectionPointXZ(start1, end1, start2, end2, out intersects);
  1110. }
  1111. /** Calculates convex hull in XZ space for the points.
  1112. * Implemented using the very simple Gift Wrapping Algorithm
  1113. * which has a complexity of O(nh) where \a n is the number of points and \a h is the number of points on the hull,
  1114. * so it is in the worst case quadratic.
  1115. *
  1116. * \deprecated Use ConvexHullXZ instead
  1117. */
  1118. [System.Obsolete("Use ConvexHullXZ instead")]
  1119. public static Vector3[] ConvexHull (Vector3[] points) {
  1120. return ConvexHullXZ(points);
  1121. }
  1122. /** Calculates convex hull in XZ space for the points.
  1123. * Implemented using the very simple Gift Wrapping Algorithm
  1124. * which has a complexity of O(nh) where \a n is the number of points and \a h is the number of points on the hull,
  1125. * so it is in the worst case quadratic.
  1126. */
  1127. public static Vector3[] ConvexHullXZ (Vector3[] points) {
  1128. if (points.Length == 0) return new Vector3[0];
  1129. var hull = ListPool<Vector3>.Claim();
  1130. int pointOnHull = 0;
  1131. for (int i = 1; i < points.Length; i++) if (points[i].x < points[pointOnHull].x) pointOnHull = i;
  1132. int startpoint = pointOnHull;
  1133. int counter = 0;
  1134. do {
  1135. hull.Add(points[pointOnHull]);
  1136. int endpoint = 0;
  1137. for (int i = 0; i < points.Length; i++) if (endpoint == pointOnHull || !VectorMath.RightOrColinearXZ(points[pointOnHull], points[endpoint], points[i])) endpoint = i;
  1138. pointOnHull = endpoint;
  1139. counter++;
  1140. if (counter > 10000) {
  1141. #if !SERVER
  1142. UnityEngine.Debug.LogWarning("Infinite Loop in Convex Hull Calculation");
  1143. #endif
  1144. break;
  1145. }
  1146. } while (pointOnHull != startpoint);
  1147. var result = hull.ToArray();
  1148. // Return to pool
  1149. ListPool<Vector3>.Release(hull);
  1150. return result;
  1151. }
  1152. /** Closest point on the triangle \a abc to the point \a p.
  1153. * \see 'Real Time Collision Detection' by Christer Ericson, chapter 5.1, page 141
  1154. */
  1155. public static Vector2 ClosestPointOnTriangle (Vector2 a, Vector2 b, Vector2 c, Vector2 p) {
  1156. // Check if p is in vertex region outside A
  1157. var ab = b - a;
  1158. var ac = c - a;
  1159. var ap = p - a;
  1160. var d1 = Vector2.Dot(ab, ap);
  1161. var d2 = Vector2.Dot(ac, ap);
  1162. // Barycentric coordinates (1,0,0)
  1163. if (d1 <= 0 && d2 <= 0) {
  1164. return a;
  1165. }
  1166. // Check if p is in vertex region outside B
  1167. var bp = p - b;
  1168. var d3 = Vector2.Dot(ab, bp);
  1169. var d4 = Vector2.Dot(ac, bp);
  1170. // Barycentric coordinates (0,1,0)
  1171. if (d3 >= 0 && d4 <= d3) {
  1172. return b;
  1173. }
  1174. // Check if p is in edge region outside AB, if so return a projection of p onto AB
  1175. if (d1 >= 0 && d3 <= 0) {
  1176. var vc = d1 * d4 - d3 * d2;
  1177. if (vc <= 0) {
  1178. // Barycentric coordinates (1-v, v, 0)
  1179. var v = d1 / (d1 - d3);
  1180. return a + ab*v;
  1181. }
  1182. }
  1183. // Check if p is in vertex region outside C
  1184. var cp = p - c;
  1185. var d5 = Vector2.Dot(ab, cp);
  1186. var d6 = Vector2.Dot(ac, cp);
  1187. // Barycentric coordinates (0,0,1)
  1188. if (d6 >= 0 && d5 <= d6) {
  1189. return c;
  1190. }
  1191. // Check if p is in edge region of AC, if so return a projection of p onto AC
  1192. if (d2 >= 0 && d6 <= 0) {
  1193. var vb = d5 * d2 - d1 * d6;
  1194. if (vb <= 0) {
  1195. // Barycentric coordinates (1-v, 0, v)
  1196. var v = d2 / (d2 - d6);
  1197. return a + ac*v;
  1198. }
  1199. }
  1200. // Check if p is in edge region of BC, if so return projection of p onto BC
  1201. if ((d4 - d3) >= 0 && (d5 - d6) >= 0) {
  1202. var va = d3 * d6 - d5 * d4;
  1203. if (va <= 0) {
  1204. var v = (d4 - d3) / ((d4 - d3) + (d5 - d6));
  1205. return b + (c - b) * v;
  1206. }
  1207. }
  1208. return p;
  1209. }
  1210. /** Closest point on the triangle \a abc to the point \a p when seen from above.
  1211. * \see 'Real Time Collision Detection' by Christer Ericson, chapter 5.1, page 141
  1212. */
  1213. public static Vector3 ClosestPointOnTriangleXZ (Vector3 a, Vector3 b, Vector3 c, Vector3 p) {
  1214. // Check if p is in vertex region outside A
  1215. var ab = new Vector2(b.x - a.x, b.z - a.z);
  1216. var ac = new Vector2(c.x - a.x, c.z - a.z);
  1217. var ap = new Vector2(p.x - a.x, p.z - a.z);
  1218. var d1 = Vector2.Dot(ab, ap);
  1219. var d2 = Vector2.Dot(ac, ap);
  1220. // Barycentric coordinates (1,0,0)
  1221. if (d1 <= 0 && d2 <= 0) {
  1222. return a;
  1223. }
  1224. // Check if p is in vertex region outside B
  1225. var bp = new Vector2(p.x - b.x, p.z - b.z);
  1226. var d3 = Vector2.Dot(ab, bp);
  1227. var d4 = Vector2.Dot(ac, bp);
  1228. // Barycentric coordinates (0,1,0)
  1229. if (d3 >= 0 && d4 <= d3) {
  1230. return b;
  1231. }
  1232. // Check if p is in edge region outside AB, if so return a projection of p onto AB
  1233. var vc = d1 * d4 - d3 * d2;
  1234. if (d1 >= 0 && d3 <= 0 && vc <= 0) {
  1235. // Barycentric coordinates (1-v, v, 0)
  1236. var v = d1 / (d1 - d3);
  1237. return (1-v)*a + v*b;
  1238. }
  1239. // Check if p is in vertex region outside C
  1240. var cp = new Vector2(p.x - c.x, p.z - c.z);
  1241. var d5 = Vector2.Dot(ab, cp);
  1242. var d6 = Vector2.Dot(ac, cp);
  1243. // Barycentric coordinates (0,0,1)
  1244. if (d6 >= 0 && d5 <= d6) {
  1245. return c;
  1246. }
  1247. // Check if p is in edge region of AC, if so return a projection of p onto AC
  1248. var vb = d5 * d2 - d1 * d6;
  1249. if (d2 >= 0 && d6 <= 0 && vb <= 0) {
  1250. // Barycentric coordinates (1-v, 0, v)
  1251. var v = d2 / (d2 - d6);
  1252. return (1-v)*a + v*c;
  1253. }
  1254. // Check if p is in edge region of BC, if so return projection of p onto BC
  1255. var va = d3 * d6 - d5 * d4;
  1256. if ((d4 - d3) >= 0 && (d5 - d6) >= 0 && va <= 0) {
  1257. var v = (d4 - d3) / ((d4 - d3) + (d5 - d6));
  1258. return b + (c - b) * v;
  1259. } else {
  1260. // P is inside the face region. Compute the point using its barycentric coordinates (u, v, w)
  1261. // Note that the x and z coordinates will be exactly the same as P's x and z coordinates
  1262. var denom = 1f / (va + vb + vc);
  1263. var v = vb * denom;
  1264. var w = vc * denom;
  1265. return new Vector3(p.x, (1 - v - w)*a.y + v*b.y + w*c.y, p.z);
  1266. }
  1267. }
  1268. /** Closest point on the triangle \a abc to the point \a p.
  1269. * \see 'Real Time Collision Detection' by Christer Ericson, chapter 5.1, page 141
  1270. */
  1271. public static Vector3 ClosestPointOnTriangle (Vector3 a, Vector3 b, Vector3 c, Vector3 p) {
  1272. // Check if p is in vertex region outside A
  1273. var ab = b - a;
  1274. var ac = c - a;
  1275. var ap = p - a;
  1276. var d1 = Vector3.Dot(ab, ap);
  1277. var d2 = Vector3.Dot(ac, ap);
  1278. // Barycentric coordinates (1,0,0)
  1279. if (d1 <= 0 && d2 <= 0)
  1280. return a;
  1281. // Check if p is in vertex region outside B
  1282. var bp = p - b;
  1283. var d3 = Vector3.Dot(ab, bp);
  1284. var d4 = Vector3.Dot(ac, bp);
  1285. // Barycentric coordinates (0,1,0)
  1286. if (d3 >= 0 && d4 <= d3)
  1287. return b;
  1288. // Check if p is in edge region outside AB, if so return a projection of p onto AB
  1289. var vc = d1 * d4 - d3 * d2;
  1290. if (d1 >= 0 && d3 <= 0 && vc <= 0) {
  1291. // Barycentric coordinates (1-v, v, 0)
  1292. var v = d1 / (d1 - d3);
  1293. return a + ab * v;
  1294. }
  1295. // Check if p is in vertex region outside C
  1296. var cp = p - c;
  1297. var d5 = Vector3.Dot(ab, cp);
  1298. var d6 = Vector3.Dot(ac, cp);
  1299. // Barycentric coordinates (0,0,1)
  1300. if (d6 >= 0 && d5 <= d6)
  1301. return c;
  1302. // Check if p is in edge region of AC, if so return a projection of p onto AC
  1303. var vb = d5 * d2 - d1 * d6;
  1304. if (d2 >= 0 && d6 <= 0 && vb <= 0) {
  1305. // Barycentric coordinates (1-v, 0, v)
  1306. var v = d2 / (d2 - d6);
  1307. return a + ac * v;
  1308. }
  1309. // Check if p is in edge region of BC, if so return projection of p onto BC
  1310. var va = d3 * d6 - d5 * d4;
  1311. if ((d4 - d3) >= 0 && (d5 - d6) >= 0 && va <= 0) {
  1312. var v = (d4 - d3) / ((d4 - d3) + (d5 - d6));
  1313. return b + (c - b) * v;
  1314. } else {
  1315. // P is inside the face region. Compute the point using its barycentric coordinates (u, v, w)
  1316. var denom = 1f / (va + vb + vc);
  1317. var v = vb * denom;
  1318. var w = vc * denom;
  1319. // This is equal to: u*a + v*b + w*c, u = va*denom = 1 - v - w;
  1320. return a + ab * v + ac * w;
  1321. }
  1322. }
  1323. /** Get the 3D minimum distance between 2 segments
  1324. * Input: two 3D line segments S1 and S2
  1325. * \returns the shortest squared distance between S1 and S2
  1326. *
  1327. * \deprecated Use VectorMath.SqrDistanceSegmentSegment instead
  1328. */
  1329. [System.Obsolete("Use VectorMath.SqrDistanceSegmentSegment instead")]
  1330. public static float DistanceSegmentSegment3D (Vector3 s1, Vector3 e1, Vector3 s2, Vector3 e2) {
  1331. return VectorMath.SqrDistanceSegmentSegment(s1, e1, s2, e2);
  1332. }
  1333. /** Cached dictionary to avoid excessive allocations */
  1334. static readonly Dictionary<Int3, int> cached_Int3_int_dict = new Dictionary<Int3, int>();
  1335. /** Compress the mesh by removing duplicate vertices.
  1336. *
  1337. * \param vertices Vertices of the input mesh
  1338. * \param triangles Triangles of the input mesh
  1339. * \param outVertices Vertices of the output mesh.
  1340. * \param outTriangles Triangles of the output mesh.
  1341. *
  1342. * Vertices that differ by only 1 along the y coordinate will also be merged together.
  1343. * \warning This function is not threadsafe. It uses some cached structures to reduce allocations.
  1344. */
  1345. public static void CompressMesh (List<Int3> vertices, List<int> triangles, out Int3[] outVertices, out int[] outTriangles) {
  1346. Dictionary<Int3, int> firstVerts = cached_Int3_int_dict;
  1347. firstVerts.Clear();
  1348. // Use cached array to reduce memory allocations
  1349. int[] compressedPointers = ArrayPool<int>.Claim(vertices.Count);
  1350. // Map positions to the first index they were encountered at
  1351. int count = 0;
  1352. for (int i = 0; i < vertices.Count; i++) {
  1353. // Check if the vertex position has already been added
  1354. // Also check one position up and one down because rounding errors can cause vertices
  1355. // that should end up in the same position to be offset 1 unit from each other
  1356. // TODO: Check along X and Z axes as well?
  1357. int ind;
  1358. if (!firstVerts.TryGetValue(vertices[i], out ind) && !firstVerts.TryGetValue(vertices[i] + new Int3(0, 1, 0), out ind) && !firstVerts.TryGetValue(vertices[i] + new Int3(0, -1, 0), out ind)) {
  1359. firstVerts.Add(vertices[i], count);
  1360. compressedPointers[i] = count;
  1361. vertices[count] = vertices[i];
  1362. count++;
  1363. } else {
  1364. compressedPointers[i] = ind;
  1365. }
  1366. }
  1367. // Create the triangle array or reuse the existing buffer
  1368. outTriangles = new int[triangles.Count];
  1369. // Remap the triangles to the new compressed indices
  1370. for (int i = 0; i < outTriangles.Length; i++) {
  1371. outTriangles[i] = compressedPointers[triangles[i]];
  1372. }
  1373. // Create the vertex array or reuse the existing buffer
  1374. outVertices = new Int3[count];
  1375. for (int i = 0; i < count; i++)
  1376. outVertices[i] = vertices[i];
  1377. ArrayPool<int>.Release(ref compressedPointers);
  1378. }
  1379. /** Given a set of edges between vertices, follows those edges and returns them as chains and cycles.
  1380. * \param outline outline[a] = b if there is an edge from \a a to \a b.
  1381. * \param hasInEdge \a hasInEdge should contain \a b if outline[a] = b for any key \a a.
  1382. * \param results Will be called once for each contour with the contour as a parameter as well as a boolean indicating if the contour is a cycle or a chain (see image).
  1383. *
  1384. * \shadowimage{grid_contour_compressed.png}
  1385. */
  1386. public static void TraceContours (Dictionary<int, int> outline, HashSet<int> hasInEdge, System.Action<List<int>, bool> results) {
  1387. // Iterate through chains of the navmesh outline.
  1388. // I.e segments of the outline that are not loops
  1389. // we need to start these at the beginning of the chain.
  1390. // Then iterate over all the loops of the outline.
  1391. // Since they are loops, we can start at any point.
  1392. var obstacleVertices = ListPool<int>.Claim();
  1393. var outlineKeys = ListPool<int>.Claim();
  1394. outlineKeys.AddRange(outline.Keys);
  1395. for (int k = 0; k <= 1; k++) {
  1396. bool cycles = k == 1;
  1397. for (int i = 0; i < outlineKeys.Count; i++) {
  1398. var startIndex = outlineKeys[i];
  1399. // Chains (not cycles) need to start at the start of the chain
  1400. // Cycles can start at any point
  1401. if (!cycles && hasInEdge.Contains(startIndex)) {
  1402. continue;
  1403. }
  1404. var index = startIndex;
  1405. obstacleVertices.Clear();
  1406. obstacleVertices.Add(index);
  1407. while (outline.ContainsKey(index)) {
  1408. var next = outline[index];
  1409. outline.Remove(index);
  1410. obstacleVertices.Add(next);
  1411. // We traversed a full cycle
  1412. if (next == startIndex) break;
  1413. index = next;
  1414. }
  1415. if (obstacleVertices.Count > 1) {
  1416. results(obstacleVertices, cycles);
  1417. }
  1418. }
  1419. }
  1420. ListPool<int>.Release(ref outlineKeys);
  1421. ListPool<int>.Release(ref obstacleVertices);
  1422. }
  1423. /** Divides each segment in the list into \a subSegments segments and fills the result list with the new points */
  1424. public static void Subdivide (List<Vector3> points, List<Vector3> result, int subSegments) {
  1425. for (int i = 0; i < points.Count-1; i++)
  1426. for (int j = 0; j < subSegments; j++)
  1427. result.Add(Vector3.Lerp(points[i], points[i+1], j / (float)subSegments));
  1428. result.Add(points[points.Count-1]);
  1429. }
  1430. }
  1431. }