babylon.earcut.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  2. // Huge respect for a such great lib.
  3. // Earcut license:
  4. // Copyright (c) 2016, Mapbox
  5. //
  6. // Permission to use, copy, modify, and/or distribute this software for any purpose
  7. // with or without fee is hereby granted, provided that the above copyright notice
  8. // and this permission notice appear in all copies.
  9. //
  10. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  11. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  13. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  14. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  16. // THIS SOFTWARE.
  17. module Earcut {
  18. /**
  19. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  20. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  21. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  22. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  23. */
  24. export function earcut(data: number[], holeIndices: number[], dim: number) {
  25. dim = dim || 2;
  26. var hasHoles = holeIndices && holeIndices.length,
  27. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  28. outerNode = linkedList(data, 0, outerLen, dim, true),
  29. triangles = [];
  30. if (!outerNode) return triangles;
  31. var minX, minY, maxX, maxY, x, y, size;
  32. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  33. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  34. if (data.length > 80 * dim) {
  35. minX = maxX = data[0];
  36. minY = maxY = data[1];
  37. for (var i = dim; i < outerLen; i += dim) {
  38. x = data[i];
  39. y = data[i + 1];
  40. if (x < minX) minX = x;
  41. if (y < minY) minY = y;
  42. if (x > maxX) maxX = x;
  43. if (y > maxY) maxY = y;
  44. }
  45. // minX, minY and size are later used to transform coords into integers for z-order calculation
  46. size = Math.max(maxX - minX, maxY - minY);
  47. }
  48. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  49. return triangles;
  50. }
  51. // create a circular doubly linked list from polygon points in the specified winding order
  52. function linkedList(data, start, end, dim, clockwise) {
  53. var i, last;
  54. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  55. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  56. } else {
  57. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  58. }
  59. if (last && equals(last, last.next)) {
  60. removeNode(last);
  61. last = last.next;
  62. }
  63. return last;
  64. }
  65. // eliminate colinear or duplicate points
  66. function filterPoints(start, end) {
  67. if (!start) return start;
  68. if (!end) end = start;
  69. var p = start,
  70. again;
  71. do {
  72. again = false;
  73. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74. removeNode(p);
  75. p = end = p.prev;
  76. if (p === p.next) return null;
  77. again = true;
  78. } else {
  79. p = p.next;
  80. }
  81. } while (again || p !== end);
  82. return end;
  83. }
  84. // main ear slicing loop which triangulates a polygon (given as a linked list)
  85. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  86. if (!ear) return;
  87. // interlink polygon nodes in z-order
  88. if (!pass && size) indexCurve(ear, minX, minY, size);
  89. var stop = ear,
  90. prev,
  91. next;
  92. // iterate through ears, slicing them one by one
  93. while (ear.prev !== ear.next) {
  94. prev = ear.prev;
  95. next = ear.next;
  96. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  97. // cut off the triangle
  98. triangles.push(prev.i / dim);
  99. triangles.push(ear.i / dim);
  100. triangles.push(next.i / dim);
  101. removeNode(ear);
  102. // skipping the next vertice leads to less sliver triangles
  103. ear = next.next;
  104. stop = next.next;
  105. continue;
  106. }
  107. ear = next;
  108. // if we looped through the whole remaining polygon and can't find any more ears
  109. if (ear === stop) {
  110. // try filtering points and slicing again
  111. if (!pass) {
  112. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  113. // if this didn't work, try curing all small self-intersections locally
  114. } else if (pass === 1) {
  115. ear = cureLocalIntersections(ear, triangles, dim);
  116. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  117. // as a last resort, try splitting the remaining polygon into two
  118. } else if (pass === 2) {
  119. splitEarcut(ear, triangles, dim, minX, minY, size);
  120. }
  121. break;
  122. }
  123. }
  124. }
  125. // check whether a polygon node forms a valid ear with adjacent nodes
  126. function isEar(ear) {
  127. var a = ear.prev,
  128. b = ear,
  129. c = ear.next;
  130. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  131. // now make sure we don't have other points inside the potential ear
  132. var p = ear.next.next;
  133. while (p !== ear.prev) {
  134. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  135. area(p.prev, p, p.next) >= 0) return false;
  136. p = p.next;
  137. }
  138. return true;
  139. }
  140. function isEarHashed(ear, minX, minY, size) {
  141. var a = ear.prev,
  142. b = ear,
  143. c = ear.next;
  144. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  145. // triangle bbox; min & max are calculated like this for speed
  146. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
  147. minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
  148. maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
  149. maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  150. // z-order range for the current triangle bbox;
  151. var minZ = zOrder(minTX, minTY, minX, minY, size),
  152. maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  153. // first look for points inside the triangle in increasing z-order
  154. var p = ear.nextZ;
  155. while (p && p.z <= maxZ) {
  156. if (p !== ear.prev &&
  157. p !== ear.next &&
  158. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  159. area(p.prev, p, p.next) >= 0) return false;
  160. p = p.nextZ;
  161. }
  162. // then look for points in decreasing z-order
  163. p = ear.prevZ;
  164. while (p && p.z >= minZ) {
  165. if (p !== ear.prev &&
  166. p !== ear.next &&
  167. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  168. area(p.prev, p, p.next) >= 0) return false;
  169. p = p.prevZ;
  170. }
  171. return true;
  172. }
  173. // go through all polygon nodes and cure small local self-intersections
  174. function cureLocalIntersections(start, triangles, dim) {
  175. var p = start;
  176. do {
  177. var a = p.prev,
  178. b = p.next.next;
  179. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  180. triangles.push(a.i / dim);
  181. triangles.push(p.i / dim);
  182. triangles.push(b.i / dim);
  183. // remove two nodes involved
  184. removeNode(p);
  185. removeNode(p.next);
  186. p = start = b;
  187. }
  188. p = p.next;
  189. } while (p !== start);
  190. return p;
  191. }
  192. // try splitting polygon into two and triangulate them independently
  193. function splitEarcut(start, triangles, dim, minX, minY, size) {
  194. // look for a valid diagonal that divides the polygon into two
  195. var a = start;
  196. do {
  197. var b = a.next.next;
  198. while (b !== a.prev) {
  199. if (a.i !== b.i && isValidDiagonal(a, b)) {
  200. // split the polygon in two by the diagonal
  201. var c = splitPolygon(a, b);
  202. // filter colinear points around the cuts
  203. a = filterPoints(a, a.next);
  204. c = filterPoints(c, c.next);
  205. // run earcut on each half
  206. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  207. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  208. return;
  209. }
  210. b = b.next;
  211. }
  212. a = a.next;
  213. } while (a !== start);
  214. }
  215. // link every hole into the outer loop, producing a single-ring polygon without holes
  216. function eliminateHoles(data, holeIndices, outerNode, dim) {
  217. var queue = [],
  218. i,
  219. len,
  220. start,
  221. end,
  222. list;
  223. for (i = 0, len = holeIndices.length; i < len; i++) {
  224. start = holeIndices[i] * dim;
  225. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  226. list = linkedList(data, start, end, dim, false);
  227. if (list === list.next) list.steiner = true;
  228. queue.push(getLeftmost(list));
  229. }
  230. queue.sort(compareX);
  231. // process holes from left to right
  232. for (i = 0; i < queue.length; i++) {
  233. eliminateHole(queue[i], outerNode);
  234. outerNode = filterPoints(outerNode, outerNode.next);
  235. }
  236. return outerNode;
  237. }
  238. function compareX(a, b) {
  239. return a.x - b.x;
  240. }
  241. // find a bridge between vertices that connects hole with an outer ring and and link it
  242. function eliminateHole(hole, outerNode) {
  243. outerNode = findHoleBridge(hole, outerNode);
  244. if (outerNode) {
  245. var b = splitPolygon(outerNode, hole);
  246. filterPoints(b, b.next);
  247. }
  248. }
  249. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  250. function findHoleBridge(hole, outerNode) {
  251. var p = outerNode,
  252. hx = hole.x,
  253. hy = hole.y,
  254. qx = -Infinity,
  255. m;
  256. // find a segment intersected by a ray from the hole's leftmost point to the left;
  257. // segment's endpoint with lesser x will be potential connection point
  258. do {
  259. if (hy <= p.y && hy >= p.next.y) {
  260. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  261. if (x <= hx && x > qx) {
  262. qx = x;
  263. if (x === hx) {
  264. if (hy === p.y) return p;
  265. if (hy === p.next.y) return p.next;
  266. }
  267. m = p.x < p.next.x ? p : p.next;
  268. }
  269. }
  270. p = p.next;
  271. } while (p !== outerNode);
  272. if (!m) return null;
  273. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  274. // look for points inside the triangle of hole point, segment intersection and endpoint;
  275. // if there are no points found, we have a valid connection;
  276. // otherwise choose the point of the minimum angle with the ray as connection point
  277. var stop = m,
  278. mx = m.x,
  279. my = m.y,
  280. tanMin = Infinity,
  281. tan;
  282. p = m.next;
  283. while (p !== stop) {
  284. if (hx >= p.x &&
  285. p.x >= mx &&
  286. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  287. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  288. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  289. m = p;
  290. tanMin = tan;
  291. }
  292. }
  293. p = p.next;
  294. }
  295. return m;
  296. }
  297. // interlink polygon nodes in z-order
  298. function indexCurve(start, minX, minY, size) {
  299. var p = start;
  300. do {
  301. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
  302. p.prevZ = p.prev;
  303. p.nextZ = p.next;
  304. p = p.next;
  305. } while (p !== start);
  306. p.prevZ.nextZ = null;
  307. p.prevZ = null;
  308. sortLinked(p);
  309. }
  310. // Simon Tatham's linked list merge sort algorithm
  311. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  312. function sortLinked(list) {
  313. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  314. do {
  315. p = list;
  316. list = null;
  317. tail = null;
  318. numMerges = 0;
  319. while (p) {
  320. numMerges++;
  321. q = p;
  322. pSize = 0;
  323. for (i = 0; i < inSize; i++) {
  324. pSize++;
  325. q = q.nextZ;
  326. if (!q) break;
  327. }
  328. qSize = inSize;
  329. while (pSize > 0 || (qSize > 0 && q)) {
  330. if (pSize === 0) {
  331. e = q;
  332. q = q.nextZ;
  333. qSize--;
  334. } else if (qSize === 0 || !q) {
  335. e = p;
  336. p = p.nextZ;
  337. pSize--;
  338. } else if (p.z <= q.z) {
  339. e = p;
  340. p = p.nextZ;
  341. pSize--;
  342. } else {
  343. e = q;
  344. q = q.nextZ;
  345. qSize--;
  346. }
  347. if (tail) tail.nextZ = e;
  348. else list = e;
  349. e.prevZ = tail;
  350. tail = e;
  351. }
  352. p = q;
  353. }
  354. tail.nextZ = null;
  355. inSize *= 2;
  356. } while (numMerges > 1);
  357. return list;
  358. }
  359. // z-order of a point given coords and size of the data bounding box
  360. function zOrder(x, y, minX, minY, size) {
  361. // coords are transformed into non-negative 15-bit integer range
  362. x = 32767 * (x - minX) / size;
  363. y = 32767 * (y - minY) / size;
  364. x = (x | (x << 8)) & 0x00FF00FF;
  365. x = (x | (x << 4)) & 0x0F0F0F0F;
  366. x = (x | (x << 2)) & 0x33333333;
  367. x = (x | (x << 1)) & 0x55555555;
  368. y = (y | (y << 8)) & 0x00FF00FF;
  369. y = (y | (y << 4)) & 0x0F0F0F0F;
  370. y = (y | (y << 2)) & 0x33333333;
  371. y = (y | (y << 1)) & 0x55555555;
  372. return x | (y << 1);
  373. }
  374. // find the leftmost node of a polygon ring
  375. function getLeftmost(start) {
  376. var p = start,
  377. leftmost = start;
  378. do {
  379. if (p.x < leftmost.x) leftmost = p;
  380. p = p.next;
  381. } while (p !== start);
  382. return leftmost;
  383. }
  384. // check if a point lies within a convex triangle
  385. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  386. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  387. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  388. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  389. }
  390. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  391. function isValidDiagonal(a, b) {
  392. return a.next.i !== b.i &&
  393. a.prev.i !== b.i &&
  394. !intersectsPolygon(a, b) &&
  395. locallyInside(a, b) &&
  396. locallyInside(b, a) &&
  397. middleInside(a, b);
  398. }
  399. // signed area of a triangle
  400. function area(p, q, r) {
  401. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  402. }
  403. // check if two points are equal
  404. function equals(p1, p2) {
  405. return p1.x === p2.x && p1.y === p2.y;
  406. }
  407. // check if two segments intersect
  408. function intersects(p1, q1, p2, q2) {
  409. if ((equals(p1, q1) && equals(p2, q2)) ||
  410. (equals(p1, q2) && equals(p2, q1))) return true;
  411. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  412. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  413. }
  414. // check if a polygon diagonal intersects any polygon segments
  415. function intersectsPolygon(a, b) {
  416. var p = a;
  417. do {
  418. if (p.i !== a.i &&
  419. p.next.i !== a.i &&
  420. p.i !== b.i &&
  421. p.next.i !== b.i &&
  422. intersects(p, p.next, a, b)) return true;
  423. p = p.next;
  424. } while (p !== a);
  425. return false;
  426. }
  427. // check if a polygon diagonal is locally inside the polygon
  428. function locallyInside(a, b) {
  429. return area(a.prev, a, a.next) < 0
  430. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  431. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  432. }
  433. // check if the middle point of a polygon diagonal is inside the polygon
  434. function middleInside(a, b) {
  435. var p = a,
  436. inside = false,
  437. px = (a.x + b.x) / 2,
  438. py = (a.y + b.y) / 2;
  439. do {
  440. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  441. inside = !inside;
  442. p = p.next;
  443. } while (p !== a);
  444. return inside;
  445. }
  446. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  447. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  448. function splitPolygon(a, b) {
  449. var a2 = new Node(a.i, a.x, a.y),
  450. b2 = new Node(b.i, b.x, b.y),
  451. an = a.next,
  452. bp = b.prev;
  453. a.next = b;
  454. b.prev = a;
  455. a2.next = an;
  456. an.prev = a2;
  457. b2.next = a2;
  458. a2.prev = b2;
  459. bp.next = b2;
  460. b2.prev = bp;
  461. return b2;
  462. }
  463. // create a node and optionally link it with previous one (in a circular doubly linked list)
  464. function insertNode(i, x, y, last) {
  465. var p = new Node(i, x, y);
  466. if (!last) {
  467. p.prev = p;
  468. p.next = p;
  469. } else {
  470. p.next = last.next;
  471. p.prev = last;
  472. last.next.prev = p;
  473. last.next = p;
  474. }
  475. return p;
  476. }
  477. function removeNode(p) {
  478. p.next.prev = p.prev;
  479. p.prev.next = p.next;
  480. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  481. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  482. }
  483. function Node(i, x, y) {
  484. // vertice index in coordinates array
  485. this.i = i;
  486. // vertex coordinates
  487. this.x = x;
  488. this.y = y;
  489. // previous and next vertice nodes in a polygon ring
  490. this.prev = null;
  491. this.next = null;
  492. // z-order curve value
  493. this.z = null;
  494. // previous and next nodes in z-order
  495. this.prevZ = null;
  496. this.nextZ = null;
  497. // indicates whether this is a steiner point
  498. this.steiner = false;
  499. }
  500. /**
  501. * return a percentage difference between the polygon area and its triangulation area;
  502. * used to verify correctness of triangulation
  503. */
  504. export function deviation(data: number[], holeIndices: number[], dim: number, triangles: number[]) {
  505. var hasHoles = holeIndices && holeIndices.length;
  506. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  507. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  508. if (hasHoles) {
  509. for (var i = 0, len = holeIndices.length; i < len; i++) {
  510. var start = holeIndices[i] * dim;
  511. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  512. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  513. }
  514. }
  515. var trianglesArea = 0;
  516. for (i = 0; i < triangles.length; i += 3) {
  517. var a = triangles[i] * dim;
  518. var b = triangles[i + 1] * dim;
  519. var c = triangles[i + 2] * dim;
  520. trianglesArea += Math.abs(
  521. (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  522. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  523. }
  524. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  525. };
  526. function signedArea(data, start, end, dim) {
  527. var sum = 0;
  528. for (var i = start, j = end - dim; i < end; i += dim) {
  529. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  530. j = i;
  531. }
  532. return sum;
  533. }
  534. /**
  535. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  536. */
  537. export function flatten(data: number[][][]) {
  538. var dim = data[0][0].length,
  539. result = { vertices: [], holes: [], dimensions: dim },
  540. holeIndex = 0;
  541. for (var i = 0; i < data.length; i++) {
  542. for (var j = 0; j < data[i].length; j++) {
  543. for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
  544. }
  545. if (i > 0) {
  546. holeIndex += data[i - 1].length;
  547. result.holes.push(holeIndex);
  548. }
  549. }
  550. return result;
  551. };
  552. }