earcut.js 19 KB

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