UNPKG

20.8 kBJavaScriptView Raw
1'use strict';
2
3module.exports = earcut;
4module.exports.default = earcut;
5
6function earcut(data, holeIndices, dim) {
7
8 dim = dim || 2;
9
10 var hasHoles = holeIndices && holeIndices.length,
11 outerLen = hasHoles ? holeIndices[0] * dim : data.length,
12 outerNode = linkedList(data, 0, outerLen, dim, true),
13 triangles = [];
14
15 if (!outerNode || outerNode.next === outerNode.prev) return triangles;
16
17 var minX, minY, maxX, maxY, x, y, invSize;
18
19 if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
20
21 // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
22 if (data.length > 80 * dim) {
23 minX = maxX = data[0];
24 minY = maxY = data[1];
25
26 for (var i = dim; i < outerLen; i += dim) {
27 x = data[i];
28 y = data[i + 1];
29 if (x < minX) minX = x;
30 if (y < minY) minY = y;
31 if (x > maxX) maxX = x;
32 if (y > maxY) maxY = y;
33 }
34
35 // minX, minY and invSize are later used to transform coords into integers for z-order calculation
36 invSize = Math.max(maxX - minX, maxY - minY);
37 invSize = invSize !== 0 ? 32767 / invSize : 0;
38 }
39
40 earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
41
42 return triangles;
43}
44
45// create a circular doubly linked list from polygon points in the specified winding order
46function linkedList(data, start, end, dim, clockwise) {
47 var i, last;
48
49 if (clockwise === (signedArea(data, start, end, dim) > 0)) {
50 for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
51 } else {
52 for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
53 }
54
55 if (last && equals(last, last.next)) {
56 removeNode(last);
57 last = last.next;
58 }
59
60 return last;
61}
62
63// eliminate colinear or duplicate points
64function filterPoints(start, end) {
65 if (!start) return start;
66 if (!end) end = start;
67
68 var p = start,
69 again;
70 do {
71 again = false;
72
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) break;
77 again = true;
78
79 } else {
80 p = p.next;
81 }
82 } while (again || p !== end);
83
84 return end;
85}
86
87// main ear slicing loop which triangulates a polygon (given as a linked list)
88function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
89 if (!ear) return;
90
91 // interlink polygon nodes in z-order
92 if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
93
94 var stop = ear,
95 prev, next;
96
97 // iterate through ears, slicing them one by one
98 while (ear.prev !== ear.next) {
99 prev = ear.prev;
100 next = ear.next;
101
102 if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
103 // cut off the triangle
104 triangles.push(prev.i / dim | 0);
105 triangles.push(ear.i / dim | 0);
106 triangles.push(next.i / dim | 0);
107
108 removeNode(ear);
109
110 // skipping the next vertex leads to less sliver triangles
111 ear = next.next;
112 stop = next.next;
113
114 continue;
115 }
116
117 ear = next;
118
119 // if we looped through the whole remaining polygon and can't find any more ears
120 if (ear === stop) {
121 // try filtering points and slicing again
122 if (!pass) {
123 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
124
125 // if this didn't work, try curing all small self-intersections locally
126 } else if (pass === 1) {
127 ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
128 earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
129
130 // as a last resort, try splitting the remaining polygon into two
131 } else if (pass === 2) {
132 splitEarcut(ear, triangles, dim, minX, minY, invSize);
133 }
134
135 break;
136 }
137 }
138}
139
140// check whether a polygon node forms a valid ear with adjacent nodes
141function isEar(ear) {
142 var a = ear.prev,
143 b = ear,
144 c = ear.next;
145
146 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
147
148 // now make sure we don't have other points inside the potential ear
149 var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
150
151 // triangle bbox; min & max are calculated like this for speed
152 var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx),
153 y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy),
154 x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx),
155 y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy);
156
157 var p = c.next;
158 while (p !== a) {
159 if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
160 pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) &&
161 area(p.prev, p, p.next) >= 0) return false;
162 p = p.next;
163 }
164
165 return true;
166}
167
168function isEarHashed(ear, minX, minY, invSize) {
169 var a = ear.prev,
170 b = ear,
171 c = ear.next;
172
173 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
174
175 var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
176
177 // triangle bbox; min & max are calculated like this for speed
178 var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx),
179 y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy),
180 x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx),
181 y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy);
182
183 // z-order range for the current triangle bbox;
184 var minZ = zOrder(x0, y0, minX, minY, invSize),
185 maxZ = zOrder(x1, y1, minX, minY, invSize);
186
187 var p = ear.prevZ,
188 n = ear.nextZ;
189
190 // look for points inside the triangle in both directions
191 while (p && p.z >= minZ && n && n.z <= maxZ) {
192 if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
193 pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
194 p = p.prevZ;
195
196 if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
197 pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
198 n = n.nextZ;
199 }
200
201 // look for remaining points in decreasing z-order
202 while (p && p.z >= minZ) {
203 if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
204 pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
205 p = p.prevZ;
206 }
207
208 // look for remaining points in increasing z-order
209 while (n && n.z <= maxZ) {
210 if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
211 pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
212 n = n.nextZ;
213 }
214
215 return true;
216}
217
218// go through all polygon nodes and cure small local self-intersections
219function cureLocalIntersections(start, triangles, dim) {
220 var p = start;
221 do {
222 var a = p.prev,
223 b = p.next.next;
224
225 if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
226
227 triangles.push(a.i / dim | 0);
228 triangles.push(p.i / dim | 0);
229 triangles.push(b.i / dim | 0);
230
231 // remove two nodes involved
232 removeNode(p);
233 removeNode(p.next);
234
235 p = start = b;
236 }
237 p = p.next;
238 } while (p !== start);
239
240 return filterPoints(p);
241}
242
243// try splitting polygon into two and triangulate them independently
244function splitEarcut(start, triangles, dim, minX, minY, invSize) {
245 // look for a valid diagonal that divides the polygon into two
246 var a = start;
247 do {
248 var b = a.next.next;
249 while (b !== a.prev) {
250 if (a.i !== b.i && isValidDiagonal(a, b)) {
251 // split the polygon in two by the diagonal
252 var c = splitPolygon(a, b);
253
254 // filter colinear points around the cuts
255 a = filterPoints(a, a.next);
256 c = filterPoints(c, c.next);
257
258 // run earcut on each half
259 earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
260 earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
261 return;
262 }
263 b = b.next;
264 }
265 a = a.next;
266 } while (a !== start);
267}
268
269// link every hole into the outer loop, producing a single-ring polygon without holes
270function eliminateHoles(data, holeIndices, outerNode, dim) {
271 var queue = [],
272 i, len, start, end, list;
273
274 for (i = 0, len = holeIndices.length; i < len; i++) {
275 start = holeIndices[i] * dim;
276 end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
277 list = linkedList(data, start, end, dim, false);
278 if (list === list.next) list.steiner = true;
279 queue.push(getLeftmost(list));
280 }
281
282 queue.sort(compareX);
283
284 // process holes from left to right
285 for (i = 0; i < queue.length; i++) {
286 outerNode = eliminateHole(queue[i], outerNode);
287 }
288
289 return outerNode;
290}
291
292function compareX(a, b) {
293 return a.x - b.x;
294}
295
296// find a bridge between vertices that connects hole with an outer ring and and link it
297function eliminateHole(hole, outerNode) {
298 var bridge = findHoleBridge(hole, outerNode);
299 if (!bridge) {
300 return outerNode;
301 }
302
303 var bridgeReverse = splitPolygon(bridge, hole);
304
305 // filter collinear points around the cuts
306 filterPoints(bridgeReverse, bridgeReverse.next);
307 return filterPoints(bridge, bridge.next);
308}
309
310// David Eberly's algorithm for finding a bridge between hole and outer polygon
311function findHoleBridge(hole, outerNode) {
312 var p = outerNode,
313 hx = hole.x,
314 hy = hole.y,
315 qx = -Infinity,
316 m;
317
318 // find a segment intersected by a ray from the hole's leftmost point to the left;
319 // segment's endpoint with lesser x will be potential connection point
320 do {
321 if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
322 var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
323 if (x <= hx && x > qx) {
324 qx = x;
325 m = p.x < p.next.x ? p : p.next;
326 if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
327 }
328 }
329 p = p.next;
330 } while (p !== outerNode);
331
332 if (!m) return null;
333
334 // look for points inside the triangle of hole point, segment intersection and endpoint;
335 // if there are no points found, we have a valid connection;
336 // otherwise choose the point of the minimum angle with the ray as connection point
337
338 var stop = m,
339 mx = m.x,
340 my = m.y,
341 tanMin = Infinity,
342 tan;
343
344 p = m;
345
346 do {
347 if (hx >= p.x && p.x >= mx && hx !== p.x &&
348 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
349
350 tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
351
352 if (locallyInside(p, hole) &&
353 (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
354 m = p;
355 tanMin = tan;
356 }
357 }
358
359 p = p.next;
360 } while (p !== stop);
361
362 return m;
363}
364
365// whether sector in vertex m contains sector in vertex p in the same coordinates
366function sectorContainsSector(m, p) {
367 return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
368}
369
370// interlink polygon nodes in z-order
371function indexCurve(start, minX, minY, invSize) {
372 var p = start;
373 do {
374 if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
375 p.prevZ = p.prev;
376 p.nextZ = p.next;
377 p = p.next;
378 } while (p !== start);
379
380 p.prevZ.nextZ = null;
381 p.prevZ = null;
382
383 sortLinked(p);
384}
385
386// Simon Tatham's linked list merge sort algorithm
387// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
388function sortLinked(list) {
389 var i, p, q, e, tail, numMerges, pSize, qSize,
390 inSize = 1;
391
392 do {
393 p = list;
394 list = null;
395 tail = null;
396 numMerges = 0;
397
398 while (p) {
399 numMerges++;
400 q = p;
401 pSize = 0;
402 for (i = 0; i < inSize; i++) {
403 pSize++;
404 q = q.nextZ;
405 if (!q) break;
406 }
407 qSize = inSize;
408
409 while (pSize > 0 || (qSize > 0 && q)) {
410
411 if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
412 e = p;
413 p = p.nextZ;
414 pSize--;
415 } else {
416 e = q;
417 q = q.nextZ;
418 qSize--;
419 }
420
421 if (tail) tail.nextZ = e;
422 else list = e;
423
424 e.prevZ = tail;
425 tail = e;
426 }
427
428 p = q;
429 }
430
431 tail.nextZ = null;
432 inSize *= 2;
433
434 } while (numMerges > 1);
435
436 return list;
437}
438
439// z-order of a point given coords and inverse of the longer side of data bbox
440function zOrder(x, y, minX, minY, invSize) {
441 // coords are transformed into non-negative 15-bit integer range
442 x = (x - minX) * invSize | 0;
443 y = (y - minY) * invSize | 0;
444
445 x = (x | (x << 8)) & 0x00FF00FF;
446 x = (x | (x << 4)) & 0x0F0F0F0F;
447 x = (x | (x << 2)) & 0x33333333;
448 x = (x | (x << 1)) & 0x55555555;
449
450 y = (y | (y << 8)) & 0x00FF00FF;
451 y = (y | (y << 4)) & 0x0F0F0F0F;
452 y = (y | (y << 2)) & 0x33333333;
453 y = (y | (y << 1)) & 0x55555555;
454
455 return x | (y << 1);
456}
457
458// find the leftmost node of a polygon ring
459function getLeftmost(start) {
460 var p = start,
461 leftmost = start;
462 do {
463 if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
464 p = p.next;
465 } while (p !== start);
466
467 return leftmost;
468}
469
470// check if a point lies within a convex triangle
471function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
472 return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
473 (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
474 (bx - px) * (cy - py) >= (cx - px) * (by - py);
475}
476
477// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
478function isValidDiagonal(a, b) {
479 return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
480 (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
481 (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
482 equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
483}
484
485// signed area of a triangle
486function area(p, q, r) {
487 return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
488}
489
490// check if two points are equal
491function equals(p1, p2) {
492 return p1.x === p2.x && p1.y === p2.y;
493}
494
495// check if two segments intersect
496function intersects(p1, q1, p2, q2) {
497 var o1 = sign(area(p1, q1, p2));
498 var o2 = sign(area(p1, q1, q2));
499 var o3 = sign(area(p2, q2, p1));
500 var o4 = sign(area(p2, q2, q1));
501
502 if (o1 !== o2 && o3 !== o4) return true; // general case
503
504 if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
505 if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
506 if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
507 if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
508
509 return false;
510}
511
512// for collinear points p, q, r, check if point q lies on segment pr
513function onSegment(p, q, r) {
514 return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
515}
516
517function sign(num) {
518 return num > 0 ? 1 : num < 0 ? -1 : 0;
519}
520
521// check if a polygon diagonal intersects any polygon segments
522function intersectsPolygon(a, b) {
523 var p = a;
524 do {
525 if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
526 intersects(p, p.next, a, b)) return true;
527 p = p.next;
528 } while (p !== a);
529
530 return false;
531}
532
533// check if a polygon diagonal is locally inside the polygon
534function locallyInside(a, b) {
535 return area(a.prev, a, a.next) < 0 ?
536 area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
537 area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
538}
539
540// check if the middle point of a polygon diagonal is inside the polygon
541function middleInside(a, b) {
542 var p = a,
543 inside = false,
544 px = (a.x + b.x) / 2,
545 py = (a.y + b.y) / 2;
546 do {
547 if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
548 (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
549 inside = !inside;
550 p = p.next;
551 } while (p !== a);
552
553 return inside;
554}
555
556// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
557// if one belongs to the outer ring and another to a hole, it merges it into a single ring
558function splitPolygon(a, b) {
559 var a2 = new Node(a.i, a.x, a.y),
560 b2 = new Node(b.i, b.x, b.y),
561 an = a.next,
562 bp = b.prev;
563
564 a.next = b;
565 b.prev = a;
566
567 a2.next = an;
568 an.prev = a2;
569
570 b2.next = a2;
571 a2.prev = b2;
572
573 bp.next = b2;
574 b2.prev = bp;
575
576 return b2;
577}
578
579// create a node and optionally link it with previous one (in a circular doubly linked list)
580function insertNode(i, x, y, last) {
581 var p = new Node(i, x, y);
582
583 if (!last) {
584 p.prev = p;
585 p.next = p;
586
587 } else {
588 p.next = last.next;
589 p.prev = last;
590 last.next.prev = p;
591 last.next = p;
592 }
593 return p;
594}
595
596function removeNode(p) {
597 p.next.prev = p.prev;
598 p.prev.next = p.next;
599
600 if (p.prevZ) p.prevZ.nextZ = p.nextZ;
601 if (p.nextZ) p.nextZ.prevZ = p.prevZ;
602}
603
604function Node(i, x, y) {
605 // vertex index in coordinates array
606 this.i = i;
607
608 // vertex coordinates
609 this.x = x;
610 this.y = y;
611
612 // previous and next vertex nodes in a polygon ring
613 this.prev = null;
614 this.next = null;
615
616 // z-order curve value
617 this.z = 0;
618
619 // previous and next nodes in z-order
620 this.prevZ = null;
621 this.nextZ = null;
622
623 // indicates whether this is a steiner point
624 this.steiner = false;
625}
626
627// return a percentage difference between the polygon area and its triangulation area;
628// used to verify correctness of triangulation
629earcut.deviation = function (data, holeIndices, dim, triangles) {
630 var hasHoles = holeIndices && holeIndices.length;
631 var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
632
633 var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
634 if (hasHoles) {
635 for (var i = 0, len = holeIndices.length; i < len; i++) {
636 var start = holeIndices[i] * dim;
637 var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
638 polygonArea -= Math.abs(signedArea(data, start, end, dim));
639 }
640 }
641
642 var trianglesArea = 0;
643 for (i = 0; i < triangles.length; i += 3) {
644 var a = triangles[i] * dim;
645 var b = triangles[i + 1] * dim;
646 var c = triangles[i + 2] * dim;
647 trianglesArea += Math.abs(
648 (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
649 (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
650 }
651
652 return polygonArea === 0 && trianglesArea === 0 ? 0 :
653 Math.abs((trianglesArea - polygonArea) / polygonArea);
654};
655
656function signedArea(data, start, end, dim) {
657 var sum = 0;
658 for (var i = start, j = end - dim; i < end; i += dim) {
659 sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
660 j = i;
661 }
662 return sum;
663}
664
665// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
666earcut.flatten = function (data) {
667 var dim = data[0][0].length,
668 result = {vertices: [], holes: [], dimensions: dim},
669 holeIndex = 0;
670
671 for (var i = 0; i < data.length; i++) {
672 for (var j = 0; j < data[i].length; j++) {
673 for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
674 }
675 if (i > 0) {
676 holeIndex += data[i - 1].length;
677 result.holes.push(holeIndex);
678 }
679 }
680 return result;
681};