polygon-clipping.esm.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820
  1. import SplayTree from 'splaytree';
  2. function _classCallCheck(instance, Constructor) {
  3. if (!(instance instanceof Constructor)) {
  4. throw new TypeError("Cannot call a class as a function");
  5. }
  6. }
  7. function _defineProperties(target, props) {
  8. for (var i = 0; i < props.length; i++) {
  9. var descriptor = props[i];
  10. descriptor.enumerable = descriptor.enumerable || false;
  11. descriptor.configurable = true;
  12. if ("value" in descriptor) descriptor.writable = true;
  13. Object.defineProperty(target, descriptor.key, descriptor);
  14. }
  15. }
  16. function _createClass(Constructor, protoProps, staticProps) {
  17. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  18. if (staticProps) _defineProperties(Constructor, staticProps);
  19. return Constructor;
  20. }
  21. /**
  22. * A bounding box has the format:
  23. *
  24. * { ll: { x: xmin, y: ymin }, ur: { x: xmax, y: ymax } }
  25. *
  26. */
  27. var isInBbox = function isInBbox(bbox, point) {
  28. return bbox.ll.x <= point.x && point.x <= bbox.ur.x && bbox.ll.y <= point.y && point.y <= bbox.ur.y;
  29. };
  30. /* Returns either null, or a bbox (aka an ordered pair of points)
  31. * If there is only one point of overlap, a bbox with identical points
  32. * will be returned */
  33. var getBboxOverlap = function getBboxOverlap(b1, b2) {
  34. // check if the bboxes overlap at all
  35. if (b2.ur.x < b1.ll.x || b1.ur.x < b2.ll.x || b2.ur.y < b1.ll.y || b1.ur.y < b2.ll.y) return null; // find the middle two X values
  36. var lowerX = b1.ll.x < b2.ll.x ? b2.ll.x : b1.ll.x;
  37. var upperX = b1.ur.x < b2.ur.x ? b1.ur.x : b2.ur.x; // find the middle two Y values
  38. var lowerY = b1.ll.y < b2.ll.y ? b2.ll.y : b1.ll.y;
  39. var upperY = b1.ur.y < b2.ur.y ? b1.ur.y : b2.ur.y; // put those middle values together to get the overlap
  40. return {
  41. ll: {
  42. x: lowerX,
  43. y: lowerY
  44. },
  45. ur: {
  46. x: upperX,
  47. y: upperY
  48. }
  49. };
  50. };
  51. /* Javascript doesn't do integer math. Everything is
  52. * floating point with percision Number.EPSILON.
  53. *
  54. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON
  55. */
  56. var epsilon = Number.EPSILON; // IE Polyfill
  57. if (epsilon === undefined) epsilon = Math.pow(2, -52);
  58. var EPSILON_SQ = epsilon * epsilon;
  59. /* FLP comparator */
  60. var cmp = function cmp(a, b) {
  61. // check if they're both 0
  62. if (-epsilon < a && a < epsilon) {
  63. if (-epsilon < b && b < epsilon) {
  64. return 0;
  65. }
  66. } // check if they're flp equal
  67. var ab = a - b;
  68. if (ab * ab < EPSILON_SQ * a * b) {
  69. return 0;
  70. } // normal comparison
  71. return a < b ? -1 : 1;
  72. };
  73. /**
  74. * This class rounds incoming values sufficiently so that
  75. * floating points problems are, for the most part, avoided.
  76. *
  77. * Incoming points are have their x & y values tested against
  78. * all previously seen x & y values. If either is 'too close'
  79. * to a previously seen value, it's value is 'snapped' to the
  80. * previously seen value.
  81. *
  82. * All points should be rounded by this class before being
  83. * stored in any data structures in the rest of this algorithm.
  84. */
  85. var PtRounder = /*#__PURE__*/function () {
  86. function PtRounder() {
  87. _classCallCheck(this, PtRounder);
  88. this.reset();
  89. }
  90. _createClass(PtRounder, [{
  91. key: "reset",
  92. value: function reset() {
  93. this.xRounder = new CoordRounder();
  94. this.yRounder = new CoordRounder();
  95. }
  96. }, {
  97. key: "round",
  98. value: function round(x, y) {
  99. return {
  100. x: this.xRounder.round(x),
  101. y: this.yRounder.round(y)
  102. };
  103. }
  104. }]);
  105. return PtRounder;
  106. }();
  107. var CoordRounder = /*#__PURE__*/function () {
  108. function CoordRounder() {
  109. _classCallCheck(this, CoordRounder);
  110. this.tree = new SplayTree(); // preseed with 0 so we don't end up with values < Number.EPSILON
  111. this.round(0);
  112. } // Note: this can rounds input values backwards or forwards.
  113. // You might ask, why not restrict this to just rounding
  114. // forwards? Wouldn't that allow left endpoints to always
  115. // remain left endpoints during splitting (never change to
  116. // right). No - it wouldn't, because we snap intersections
  117. // to endpoints (to establish independence from the segment
  118. // angle for t-intersections).
  119. _createClass(CoordRounder, [{
  120. key: "round",
  121. value: function round(coord) {
  122. var node = this.tree.add(coord);
  123. var prevNode = this.tree.prev(node);
  124. if (prevNode !== null && cmp(node.key, prevNode.key) === 0) {
  125. this.tree.remove(coord);
  126. return prevNode.key;
  127. }
  128. var nextNode = this.tree.next(node);
  129. if (nextNode !== null && cmp(node.key, nextNode.key) === 0) {
  130. this.tree.remove(coord);
  131. return nextNode.key;
  132. }
  133. return coord;
  134. }
  135. }]);
  136. return CoordRounder;
  137. }(); // singleton available by import
  138. var rounder = new PtRounder();
  139. /* Cross Product of two vectors with first point at origin */
  140. var crossProduct = function crossProduct(a, b) {
  141. return a.x * b.y - a.y * b.x;
  142. };
  143. /* Dot Product of two vectors with first point at origin */
  144. var dotProduct = function dotProduct(a, b) {
  145. return a.x * b.x + a.y * b.y;
  146. };
  147. /* Comparator for two vectors with same starting point */
  148. var compareVectorAngles = function compareVectorAngles(basePt, endPt1, endPt2) {
  149. var v1 = {
  150. x: endPt1.x - basePt.x,
  151. y: endPt1.y - basePt.y
  152. };
  153. var v2 = {
  154. x: endPt2.x - basePt.x,
  155. y: endPt2.y - basePt.y
  156. };
  157. var kross = crossProduct(v1, v2);
  158. return cmp(kross, 0);
  159. };
  160. var length = function length(v) {
  161. return Math.sqrt(dotProduct(v, v));
  162. };
  163. /* Get the sine of the angle from pShared -> pAngle to pShaed -> pBase */
  164. var sineOfAngle = function sineOfAngle(pShared, pBase, pAngle) {
  165. var vBase = {
  166. x: pBase.x - pShared.x,
  167. y: pBase.y - pShared.y
  168. };
  169. var vAngle = {
  170. x: pAngle.x - pShared.x,
  171. y: pAngle.y - pShared.y
  172. };
  173. return crossProduct(vAngle, vBase) / length(vAngle) / length(vBase);
  174. };
  175. /* Get the cosine of the angle from pShared -> pAngle to pShaed -> pBase */
  176. var cosineOfAngle = function cosineOfAngle(pShared, pBase, pAngle) {
  177. var vBase = {
  178. x: pBase.x - pShared.x,
  179. y: pBase.y - pShared.y
  180. };
  181. var vAngle = {
  182. x: pAngle.x - pShared.x,
  183. y: pAngle.y - pShared.y
  184. };
  185. return dotProduct(vAngle, vBase) / length(vAngle) / length(vBase);
  186. };
  187. /* Get the x coordinate where the given line (defined by a point and vector)
  188. * crosses the horizontal line with the given y coordiante.
  189. * In the case of parrallel lines (including overlapping ones) returns null. */
  190. var horizontalIntersection = function horizontalIntersection(pt, v, y) {
  191. if (v.y === 0) return null;
  192. return {
  193. x: pt.x + v.x / v.y * (y - pt.y),
  194. y: y
  195. };
  196. };
  197. /* Get the y coordinate where the given line (defined by a point and vector)
  198. * crosses the vertical line with the given x coordiante.
  199. * In the case of parrallel lines (including overlapping ones) returns null. */
  200. var verticalIntersection = function verticalIntersection(pt, v, x) {
  201. if (v.x === 0) return null;
  202. return {
  203. x: x,
  204. y: pt.y + v.y / v.x * (x - pt.x)
  205. };
  206. };
  207. /* Get the intersection of two lines, each defined by a base point and a vector.
  208. * In the case of parrallel lines (including overlapping ones) returns null. */
  209. var intersection = function intersection(pt1, v1, pt2, v2) {
  210. // take some shortcuts for vertical and horizontal lines
  211. // this also ensures we don't calculate an intersection and then discover
  212. // it's actually outside the bounding box of the line
  213. if (v1.x === 0) return verticalIntersection(pt2, v2, pt1.x);
  214. if (v2.x === 0) return verticalIntersection(pt1, v1, pt2.x);
  215. if (v1.y === 0) return horizontalIntersection(pt2, v2, pt1.y);
  216. if (v2.y === 0) return horizontalIntersection(pt1, v1, pt2.y); // General case for non-overlapping segments.
  217. // This algorithm is based on Schneider and Eberly.
  218. // http://www.cimec.org.ar/~ncalvo/Schneider_Eberly.pdf - pg 244
  219. var kross = crossProduct(v1, v2);
  220. if (kross == 0) return null;
  221. var ve = {
  222. x: pt2.x - pt1.x,
  223. y: pt2.y - pt1.y
  224. };
  225. var d1 = crossProduct(ve, v1) / kross;
  226. var d2 = crossProduct(ve, v2) / kross; // take the average of the two calculations to minimize rounding error
  227. var x1 = pt1.x + d2 * v1.x,
  228. x2 = pt2.x + d1 * v2.x;
  229. var y1 = pt1.y + d2 * v1.y,
  230. y2 = pt2.y + d1 * v2.y;
  231. var x = (x1 + x2) / 2;
  232. var y = (y1 + y2) / 2;
  233. return {
  234. x: x,
  235. y: y
  236. };
  237. };
  238. var SweepEvent = /*#__PURE__*/function () {
  239. _createClass(SweepEvent, null, [{
  240. key: "compare",
  241. // for ordering sweep events in the sweep event queue
  242. value: function compare(a, b) {
  243. // favor event with a point that the sweep line hits first
  244. var ptCmp = SweepEvent.comparePoints(a.point, b.point);
  245. if (ptCmp !== 0) return ptCmp; // the points are the same, so link them if needed
  246. if (a.point !== b.point) a.link(b); // favor right events over left
  247. if (a.isLeft !== b.isLeft) return a.isLeft ? 1 : -1; // we have two matching left or right endpoints
  248. // ordering of this case is the same as for their segments
  249. return Segment.compare(a.segment, b.segment);
  250. } // for ordering points in sweep line order
  251. }, {
  252. key: "comparePoints",
  253. value: function comparePoints(aPt, bPt) {
  254. if (aPt.x < bPt.x) return -1;
  255. if (aPt.x > bPt.x) return 1;
  256. if (aPt.y < bPt.y) return -1;
  257. if (aPt.y > bPt.y) return 1;
  258. return 0;
  259. } // Warning: 'point' input will be modified and re-used (for performance)
  260. }]);
  261. function SweepEvent(point, isLeft) {
  262. _classCallCheck(this, SweepEvent);
  263. if (point.events === undefined) point.events = [this];else point.events.push(this);
  264. this.point = point;
  265. this.isLeft = isLeft; // this.segment, this.otherSE set by factory
  266. }
  267. _createClass(SweepEvent, [{
  268. key: "link",
  269. value: function link(other) {
  270. if (other.point === this.point) {
  271. throw new Error('Tried to link already linked events');
  272. }
  273. var otherEvents = other.point.events;
  274. for (var i = 0, iMax = otherEvents.length; i < iMax; i++) {
  275. var evt = otherEvents[i];
  276. this.point.events.push(evt);
  277. evt.point = this.point;
  278. }
  279. this.checkForConsuming();
  280. }
  281. /* Do a pass over our linked events and check to see if any pair
  282. * of segments match, and should be consumed. */
  283. }, {
  284. key: "checkForConsuming",
  285. value: function checkForConsuming() {
  286. // FIXME: The loops in this method run O(n^2) => no good.
  287. // Maintain little ordered sweep event trees?
  288. // Can we maintaining an ordering that avoids the need
  289. // for the re-sorting with getLeftmostComparator in geom-out?
  290. // Compare each pair of events to see if other events also match
  291. var numEvents = this.point.events.length;
  292. for (var i = 0; i < numEvents; i++) {
  293. var evt1 = this.point.events[i];
  294. if (evt1.segment.consumedBy !== undefined) continue;
  295. for (var j = i + 1; j < numEvents; j++) {
  296. var evt2 = this.point.events[j];
  297. if (evt2.consumedBy !== undefined) continue;
  298. if (evt1.otherSE.point.events !== evt2.otherSE.point.events) continue;
  299. evt1.segment.consume(evt2.segment);
  300. }
  301. }
  302. }
  303. }, {
  304. key: "getAvailableLinkedEvents",
  305. value: function getAvailableLinkedEvents() {
  306. // point.events is always of length 2 or greater
  307. var events = [];
  308. for (var i = 0, iMax = this.point.events.length; i < iMax; i++) {
  309. var evt = this.point.events[i];
  310. if (evt !== this && !evt.segment.ringOut && evt.segment.isInResult()) {
  311. events.push(evt);
  312. }
  313. }
  314. return events;
  315. }
  316. /**
  317. * Returns a comparator function for sorting linked events that will
  318. * favor the event that will give us the smallest left-side angle.
  319. * All ring construction starts as low as possible heading to the right,
  320. * so by always turning left as sharp as possible we'll get polygons
  321. * without uncessary loops & holes.
  322. *
  323. * The comparator function has a compute cache such that it avoids
  324. * re-computing already-computed values.
  325. */
  326. }, {
  327. key: "getLeftmostComparator",
  328. value: function getLeftmostComparator(baseEvent) {
  329. var _this = this;
  330. var cache = new Map();
  331. var fillCache = function fillCache(linkedEvent) {
  332. var nextEvent = linkedEvent.otherSE;
  333. cache.set(linkedEvent, {
  334. sine: sineOfAngle(_this.point, baseEvent.point, nextEvent.point),
  335. cosine: cosineOfAngle(_this.point, baseEvent.point, nextEvent.point)
  336. });
  337. };
  338. return function (a, b) {
  339. if (!cache.has(a)) fillCache(a);
  340. if (!cache.has(b)) fillCache(b);
  341. var _cache$get = cache.get(a),
  342. asine = _cache$get.sine,
  343. acosine = _cache$get.cosine;
  344. var _cache$get2 = cache.get(b),
  345. bsine = _cache$get2.sine,
  346. bcosine = _cache$get2.cosine; // both on or above x-axis
  347. if (asine >= 0 && bsine >= 0) {
  348. if (acosine < bcosine) return 1;
  349. if (acosine > bcosine) return -1;
  350. return 0;
  351. } // both below x-axis
  352. if (asine < 0 && bsine < 0) {
  353. if (acosine < bcosine) return -1;
  354. if (acosine > bcosine) return 1;
  355. return 0;
  356. } // one above x-axis, one below
  357. if (bsine < asine) return -1;
  358. if (bsine > asine) return 1;
  359. return 0;
  360. };
  361. }
  362. }]);
  363. return SweepEvent;
  364. }();
  365. // segments and sweep events when all else is identical
  366. var segmentId = 0;
  367. var Segment = /*#__PURE__*/function () {
  368. _createClass(Segment, null, [{
  369. key: "compare",
  370. /* This compare() function is for ordering segments in the sweep
  371. * line tree, and does so according to the following criteria:
  372. *
  373. * Consider the vertical line that lies an infinestimal step to the
  374. * right of the right-more of the two left endpoints of the input
  375. * segments. Imagine slowly moving a point up from negative infinity
  376. * in the increasing y direction. Which of the two segments will that
  377. * point intersect first? That segment comes 'before' the other one.
  378. *
  379. * If neither segment would be intersected by such a line, (if one
  380. * or more of the segments are vertical) then the line to be considered
  381. * is directly on the right-more of the two left inputs.
  382. */
  383. value: function compare(a, b) {
  384. var alx = a.leftSE.point.x;
  385. var blx = b.leftSE.point.x;
  386. var arx = a.rightSE.point.x;
  387. var brx = b.rightSE.point.x; // check if they're even in the same vertical plane
  388. if (brx < alx) return 1;
  389. if (arx < blx) return -1;
  390. var aly = a.leftSE.point.y;
  391. var bly = b.leftSE.point.y;
  392. var ary = a.rightSE.point.y;
  393. var bry = b.rightSE.point.y; // is left endpoint of segment B the right-more?
  394. if (alx < blx) {
  395. // are the two segments in the same horizontal plane?
  396. if (bly < aly && bly < ary) return 1;
  397. if (bly > aly && bly > ary) return -1; // is the B left endpoint colinear to segment A?
  398. var aCmpBLeft = a.comparePoint(b.leftSE.point);
  399. if (aCmpBLeft < 0) return 1;
  400. if (aCmpBLeft > 0) return -1; // is the A right endpoint colinear to segment B ?
  401. var bCmpARight = b.comparePoint(a.rightSE.point);
  402. if (bCmpARight !== 0) return bCmpARight; // colinear segments, consider the one with left-more
  403. // left endpoint to be first (arbitrary?)
  404. return -1;
  405. } // is left endpoint of segment A the right-more?
  406. if (alx > blx) {
  407. if (aly < bly && aly < bry) return -1;
  408. if (aly > bly && aly > bry) return 1; // is the A left endpoint colinear to segment B?
  409. var bCmpALeft = b.comparePoint(a.leftSE.point);
  410. if (bCmpALeft !== 0) return bCmpALeft; // is the B right endpoint colinear to segment A?
  411. var aCmpBRight = a.comparePoint(b.rightSE.point);
  412. if (aCmpBRight < 0) return 1;
  413. if (aCmpBRight > 0) return -1; // colinear segments, consider the one with left-more
  414. // left endpoint to be first (arbitrary?)
  415. return 1;
  416. } // if we get here, the two left endpoints are in the same
  417. // vertical plane, ie alx === blx
  418. // consider the lower left-endpoint to come first
  419. if (aly < bly) return -1;
  420. if (aly > bly) return 1; // left endpoints are identical
  421. // check for colinearity by using the left-more right endpoint
  422. // is the A right endpoint more left-more?
  423. if (arx < brx) {
  424. var _bCmpARight = b.comparePoint(a.rightSE.point);
  425. if (_bCmpARight !== 0) return _bCmpARight;
  426. } // is the B right endpoint more left-more?
  427. if (arx > brx) {
  428. var _aCmpBRight = a.comparePoint(b.rightSE.point);
  429. if (_aCmpBRight < 0) return 1;
  430. if (_aCmpBRight > 0) return -1;
  431. }
  432. if (arx !== brx) {
  433. // are these two [almost] vertical segments with opposite orientation?
  434. // if so, the one with the lower right endpoint comes first
  435. var ay = ary - aly;
  436. var ax = arx - alx;
  437. var by = bry - bly;
  438. var bx = brx - blx;
  439. if (ay > ax && by < bx) return 1;
  440. if (ay < ax && by > bx) return -1;
  441. } // we have colinear segments with matching orientation
  442. // consider the one with more left-more right endpoint to be first
  443. if (arx > brx) return 1;
  444. if (arx < brx) return -1; // if we get here, two two right endpoints are in the same
  445. // vertical plane, ie arx === brx
  446. // consider the lower right-endpoint to come first
  447. if (ary < bry) return -1;
  448. if (ary > bry) return 1; // right endpoints identical as well, so the segments are idential
  449. // fall back on creation order as consistent tie-breaker
  450. if (a.id < b.id) return -1;
  451. if (a.id > b.id) return 1; // identical segment, ie a === b
  452. return 0;
  453. }
  454. /* Warning: a reference to ringWindings input will be stored,
  455. * and possibly will be later modified */
  456. }]);
  457. function Segment(leftSE, rightSE, rings, windings) {
  458. _classCallCheck(this, Segment);
  459. this.id = ++segmentId;
  460. this.leftSE = leftSE;
  461. leftSE.segment = this;
  462. leftSE.otherSE = rightSE;
  463. this.rightSE = rightSE;
  464. rightSE.segment = this;
  465. rightSE.otherSE = leftSE;
  466. this.rings = rings;
  467. this.windings = windings; // left unset for performance, set later in algorithm
  468. // this.ringOut, this.consumedBy, this.prev
  469. }
  470. _createClass(Segment, [{
  471. key: "replaceRightSE",
  472. /* When a segment is split, the rightSE is replaced with a new sweep event */
  473. value: function replaceRightSE(newRightSE) {
  474. this.rightSE = newRightSE;
  475. this.rightSE.segment = this;
  476. this.rightSE.otherSE = this.leftSE;
  477. this.leftSE.otherSE = this.rightSE;
  478. }
  479. }, {
  480. key: "bbox",
  481. value: function bbox() {
  482. var y1 = this.leftSE.point.y;
  483. var y2 = this.rightSE.point.y;
  484. return {
  485. ll: {
  486. x: this.leftSE.point.x,
  487. y: y1 < y2 ? y1 : y2
  488. },
  489. ur: {
  490. x: this.rightSE.point.x,
  491. y: y1 > y2 ? y1 : y2
  492. }
  493. };
  494. }
  495. /* A vector from the left point to the right */
  496. }, {
  497. key: "vector",
  498. value: function vector() {
  499. return {
  500. x: this.rightSE.point.x - this.leftSE.point.x,
  501. y: this.rightSE.point.y - this.leftSE.point.y
  502. };
  503. }
  504. }, {
  505. key: "isAnEndpoint",
  506. value: function isAnEndpoint(pt) {
  507. return pt.x === this.leftSE.point.x && pt.y === this.leftSE.point.y || pt.x === this.rightSE.point.x && pt.y === this.rightSE.point.y;
  508. }
  509. /* Compare this segment with a point.
  510. *
  511. * A point P is considered to be colinear to a segment if there
  512. * exists a distance D such that if we travel along the segment
  513. * from one * endpoint towards the other a distance D, we find
  514. * ourselves at point P.
  515. *
  516. * Return value indicates:
  517. *
  518. * 1: point lies above the segment (to the left of vertical)
  519. * 0: point is colinear to segment
  520. * -1: point lies below the segment (to the right of vertical)
  521. */
  522. }, {
  523. key: "comparePoint",
  524. value: function comparePoint(point) {
  525. if (this.isAnEndpoint(point)) return 0;
  526. var lPt = this.leftSE.point;
  527. var rPt = this.rightSE.point;
  528. var v = this.vector(); // Exactly vertical segments.
  529. if (lPt.x === rPt.x) {
  530. if (point.x === lPt.x) return 0;
  531. return point.x < lPt.x ? 1 : -1;
  532. } // Nearly vertical segments with an intersection.
  533. // Check to see where a point on the line with matching Y coordinate is.
  534. var yDist = (point.y - lPt.y) / v.y;
  535. var xFromYDist = lPt.x + yDist * v.x;
  536. if (point.x === xFromYDist) return 0; // General case.
  537. // Check to see where a point on the line with matching X coordinate is.
  538. var xDist = (point.x - lPt.x) / v.x;
  539. var yFromXDist = lPt.y + xDist * v.y;
  540. if (point.y === yFromXDist) return 0;
  541. return point.y < yFromXDist ? -1 : 1;
  542. }
  543. /**
  544. * Given another segment, returns the first non-trivial intersection
  545. * between the two segments (in terms of sweep line ordering), if it exists.
  546. *
  547. * A 'non-trivial' intersection is one that will cause one or both of the
  548. * segments to be split(). As such, 'trivial' vs. 'non-trivial' intersection:
  549. *
  550. * * endpoint of segA with endpoint of segB --> trivial
  551. * * endpoint of segA with point along segB --> non-trivial
  552. * * endpoint of segB with point along segA --> non-trivial
  553. * * point along segA with point along segB --> non-trivial
  554. *
  555. * If no non-trivial intersection exists, return null
  556. * Else, return null.
  557. */
  558. }, {
  559. key: "getIntersection",
  560. value: function getIntersection(other) {
  561. // If bboxes don't overlap, there can't be any intersections
  562. var tBbox = this.bbox();
  563. var oBbox = other.bbox();
  564. var bboxOverlap = getBboxOverlap(tBbox, oBbox);
  565. if (bboxOverlap === null) return null; // We first check to see if the endpoints can be considered intersections.
  566. // This will 'snap' intersections to endpoints if possible, and will
  567. // handle cases of colinearity.
  568. var tlp = this.leftSE.point;
  569. var trp = this.rightSE.point;
  570. var olp = other.leftSE.point;
  571. var orp = other.rightSE.point; // does each endpoint touch the other segment?
  572. // note that we restrict the 'touching' definition to only allow segments
  573. // to touch endpoints that lie forward from where we are in the sweep line pass
  574. var touchesOtherLSE = isInBbox(tBbox, olp) && this.comparePoint(olp) === 0;
  575. var touchesThisLSE = isInBbox(oBbox, tlp) && other.comparePoint(tlp) === 0;
  576. var touchesOtherRSE = isInBbox(tBbox, orp) && this.comparePoint(orp) === 0;
  577. var touchesThisRSE = isInBbox(oBbox, trp) && other.comparePoint(trp) === 0; // do left endpoints match?
  578. if (touchesThisLSE && touchesOtherLSE) {
  579. // these two cases are for colinear segments with matching left
  580. // endpoints, and one segment being longer than the other
  581. if (touchesThisRSE && !touchesOtherRSE) return trp;
  582. if (!touchesThisRSE && touchesOtherRSE) return orp; // either the two segments match exactly (two trival intersections)
  583. // or just on their left endpoint (one trivial intersection
  584. return null;
  585. } // does this left endpoint matches (other doesn't)
  586. if (touchesThisLSE) {
  587. // check for segments that just intersect on opposing endpoints
  588. if (touchesOtherRSE) {
  589. if (tlp.x === orp.x && tlp.y === orp.y) return null;
  590. } // t-intersection on left endpoint
  591. return tlp;
  592. } // does other left endpoint matches (this doesn't)
  593. if (touchesOtherLSE) {
  594. // check for segments that just intersect on opposing endpoints
  595. if (touchesThisRSE) {
  596. if (trp.x === olp.x && trp.y === olp.y) return null;
  597. } // t-intersection on left endpoint
  598. return olp;
  599. } // trivial intersection on right endpoints
  600. if (touchesThisRSE && touchesOtherRSE) return null; // t-intersections on just one right endpoint
  601. if (touchesThisRSE) return trp;
  602. if (touchesOtherRSE) return orp; // None of our endpoints intersect. Look for a general intersection between
  603. // infinite lines laid over the segments
  604. var pt = intersection(tlp, this.vector(), olp, other.vector()); // are the segments parrallel? Note that if they were colinear with overlap,
  605. // they would have an endpoint intersection and that case was already handled above
  606. if (pt === null) return null; // is the intersection found between the lines not on the segments?
  607. if (!isInBbox(bboxOverlap, pt)) return null; // round the the computed point if needed
  608. return rounder.round(pt.x, pt.y);
  609. }
  610. /**
  611. * Split the given segment into multiple segments on the given points.
  612. * * Each existing segment will retain its leftSE and a new rightSE will be
  613. * generated for it.
  614. * * A new segment will be generated which will adopt the original segment's
  615. * rightSE, and a new leftSE will be generated for it.
  616. * * If there are more than two points given to split on, new segments
  617. * in the middle will be generated with new leftSE and rightSE's.
  618. * * An array of the newly generated SweepEvents will be returned.
  619. *
  620. * Warning: input array of points is modified
  621. */
  622. }, {
  623. key: "split",
  624. value: function split(point) {
  625. var newEvents = [];
  626. var alreadyLinked = point.events !== undefined;
  627. var newLeftSE = new SweepEvent(point, true);
  628. var newRightSE = new SweepEvent(point, false);
  629. var oldRightSE = this.rightSE;
  630. this.replaceRightSE(newRightSE);
  631. newEvents.push(newRightSE);
  632. newEvents.push(newLeftSE);
  633. var newSeg = new Segment(newLeftSE, oldRightSE, this.rings.slice(), this.windings.slice()); // when splitting a nearly vertical downward-facing segment,
  634. // sometimes one of the resulting new segments is vertical, in which
  635. // case its left and right events may need to be swapped
  636. if (SweepEvent.comparePoints(newSeg.leftSE.point, newSeg.rightSE.point) > 0) {
  637. newSeg.swapEvents();
  638. }
  639. if (SweepEvent.comparePoints(this.leftSE.point, this.rightSE.point) > 0) {
  640. this.swapEvents();
  641. } // in the point we just used to create new sweep events with was already
  642. // linked to other events, we need to check if either of the affected
  643. // segments should be consumed
  644. if (alreadyLinked) {
  645. newLeftSE.checkForConsuming();
  646. newRightSE.checkForConsuming();
  647. }
  648. return newEvents;
  649. }
  650. /* Swap which event is left and right */
  651. }, {
  652. key: "swapEvents",
  653. value: function swapEvents() {
  654. var tmpEvt = this.rightSE;
  655. this.rightSE = this.leftSE;
  656. this.leftSE = tmpEvt;
  657. this.leftSE.isLeft = true;
  658. this.rightSE.isLeft = false;
  659. for (var i = 0, iMax = this.windings.length; i < iMax; i++) {
  660. this.windings[i] *= -1;
  661. }
  662. }
  663. /* Consume another segment. We take their rings under our wing
  664. * and mark them as consumed. Use for perfectly overlapping segments */
  665. }, {
  666. key: "consume",
  667. value: function consume(other) {
  668. var consumer = this;
  669. var consumee = other;
  670. while (consumer.consumedBy) {
  671. consumer = consumer.consumedBy;
  672. }
  673. while (consumee.consumedBy) {
  674. consumee = consumee.consumedBy;
  675. }
  676. var cmp = Segment.compare(consumer, consumee);
  677. if (cmp === 0) return; // already consumed
  678. // the winner of the consumption is the earlier segment
  679. // according to sweep line ordering
  680. if (cmp > 0) {
  681. var tmp = consumer;
  682. consumer = consumee;
  683. consumee = tmp;
  684. } // make sure a segment doesn't consume it's prev
  685. if (consumer.prev === consumee) {
  686. var _tmp = consumer;
  687. consumer = consumee;
  688. consumee = _tmp;
  689. }
  690. for (var i = 0, iMax = consumee.rings.length; i < iMax; i++) {
  691. var ring = consumee.rings[i];
  692. var winding = consumee.windings[i];
  693. var index = consumer.rings.indexOf(ring);
  694. if (index === -1) {
  695. consumer.rings.push(ring);
  696. consumer.windings.push(winding);
  697. } else consumer.windings[index] += winding;
  698. }
  699. consumee.rings = null;
  700. consumee.windings = null;
  701. consumee.consumedBy = consumer; // mark sweep events consumed as to maintain ordering in sweep event queue
  702. consumee.leftSE.consumedBy = consumer.leftSE;
  703. consumee.rightSE.consumedBy = consumer.rightSE;
  704. }
  705. /* The first segment previous segment chain that is in the result */
  706. }, {
  707. key: "prevInResult",
  708. value: function prevInResult() {
  709. if (this._prevInResult !== undefined) return this._prevInResult;
  710. if (!this.prev) this._prevInResult = null;else if (this.prev.isInResult()) this._prevInResult = this.prev;else this._prevInResult = this.prev.prevInResult();
  711. return this._prevInResult;
  712. }
  713. }, {
  714. key: "beforeState",
  715. value: function beforeState() {
  716. if (this._beforeState !== undefined) return this._beforeState;
  717. if (!this.prev) this._beforeState = {
  718. rings: [],
  719. windings: [],
  720. multiPolys: []
  721. };else {
  722. var seg = this.prev.consumedBy || this.prev;
  723. this._beforeState = seg.afterState();
  724. }
  725. return this._beforeState;
  726. }
  727. }, {
  728. key: "afterState",
  729. value: function afterState() {
  730. if (this._afterState !== undefined) return this._afterState;
  731. var beforeState = this.beforeState();
  732. this._afterState = {
  733. rings: beforeState.rings.slice(0),
  734. windings: beforeState.windings.slice(0),
  735. multiPolys: []
  736. };
  737. var ringsAfter = this._afterState.rings;
  738. var windingsAfter = this._afterState.windings;
  739. var mpsAfter = this._afterState.multiPolys; // calculate ringsAfter, windingsAfter
  740. for (var i = 0, iMax = this.rings.length; i < iMax; i++) {
  741. var ring = this.rings[i];
  742. var winding = this.windings[i];
  743. var index = ringsAfter.indexOf(ring);
  744. if (index === -1) {
  745. ringsAfter.push(ring);
  746. windingsAfter.push(winding);
  747. } else windingsAfter[index] += winding;
  748. } // calcualte polysAfter
  749. var polysAfter = [];
  750. var polysExclude = [];
  751. for (var _i = 0, _iMax = ringsAfter.length; _i < _iMax; _i++) {
  752. if (windingsAfter[_i] === 0) continue; // non-zero rule
  753. var _ring = ringsAfter[_i];
  754. var poly = _ring.poly;
  755. if (polysExclude.indexOf(poly) !== -1) continue;
  756. if (_ring.isExterior) polysAfter.push(poly);else {
  757. if (polysExclude.indexOf(poly) === -1) polysExclude.push(poly);
  758. var _index = polysAfter.indexOf(_ring.poly);
  759. if (_index !== -1) polysAfter.splice(_index, 1);
  760. }
  761. } // calculate multiPolysAfter
  762. for (var _i2 = 0, _iMax2 = polysAfter.length; _i2 < _iMax2; _i2++) {
  763. var mp = polysAfter[_i2].multiPoly;
  764. if (mpsAfter.indexOf(mp) === -1) mpsAfter.push(mp);
  765. }
  766. return this._afterState;
  767. }
  768. /* Is this segment part of the final result? */
  769. }, {
  770. key: "isInResult",
  771. value: function isInResult() {
  772. // if we've been consumed, we're not in the result
  773. if (this.consumedBy) return false;
  774. if (this._isInResult !== undefined) return this._isInResult;
  775. var mpsBefore = this.beforeState().multiPolys;
  776. var mpsAfter = this.afterState().multiPolys;
  777. switch (operation.type) {
  778. case 'union':
  779. {
  780. // UNION - included iff:
  781. // * On one side of us there is 0 poly interiors AND
  782. // * On the other side there is 1 or more.
  783. var noBefores = mpsBefore.length === 0;
  784. var noAfters = mpsAfter.length === 0;
  785. this._isInResult = noBefores !== noAfters;
  786. break;
  787. }
  788. case 'intersection':
  789. {
  790. // INTERSECTION - included iff:
  791. // * on one side of us all multipolys are rep. with poly interiors AND
  792. // * on the other side of us, not all multipolys are repsented
  793. // with poly interiors
  794. var least;
  795. var most;
  796. if (mpsBefore.length < mpsAfter.length) {
  797. least = mpsBefore.length;
  798. most = mpsAfter.length;
  799. } else {
  800. least = mpsAfter.length;
  801. most = mpsBefore.length;
  802. }
  803. this._isInResult = most === operation.numMultiPolys && least < most;
  804. break;
  805. }
  806. case 'xor':
  807. {
  808. // XOR - included iff:
  809. // * the difference between the number of multipolys represented
  810. // with poly interiors on our two sides is an odd number
  811. var diff = Math.abs(mpsBefore.length - mpsAfter.length);
  812. this._isInResult = diff % 2 === 1;
  813. break;
  814. }
  815. case 'difference':
  816. {
  817. // DIFFERENCE included iff:
  818. // * on exactly one side, we have just the subject
  819. var isJustSubject = function isJustSubject(mps) {
  820. return mps.length === 1 && mps[0].isSubject;
  821. };
  822. this._isInResult = isJustSubject(mpsBefore) !== isJustSubject(mpsAfter);
  823. break;
  824. }
  825. default:
  826. throw new Error("Unrecognized operation type found ".concat(operation.type));
  827. }
  828. return this._isInResult;
  829. }
  830. }], [{
  831. key: "fromRing",
  832. value: function fromRing(pt1, pt2, ring) {
  833. var leftPt, rightPt, winding; // ordering the two points according to sweep line ordering
  834. var cmpPts = SweepEvent.comparePoints(pt1, pt2);
  835. if (cmpPts < 0) {
  836. leftPt = pt1;
  837. rightPt = pt2;
  838. winding = 1;
  839. } else if (cmpPts > 0) {
  840. leftPt = pt2;
  841. rightPt = pt1;
  842. winding = -1;
  843. } else throw new Error("Tried to create degenerate segment at [".concat(pt1.x, ", ").concat(pt1.y, "]"));
  844. var leftSE = new SweepEvent(leftPt, true);
  845. var rightSE = new SweepEvent(rightPt, false);
  846. return new Segment(leftSE, rightSE, [ring], [winding]);
  847. }
  848. }]);
  849. return Segment;
  850. }();
  851. var RingIn = /*#__PURE__*/function () {
  852. function RingIn(geomRing, poly, isExterior) {
  853. _classCallCheck(this, RingIn);
  854. if (!Array.isArray(geomRing) || geomRing.length === 0) {
  855. throw new Error('Input geometry is not a valid Polygon or MultiPolygon');
  856. }
  857. this.poly = poly;
  858. this.isExterior = isExterior;
  859. this.segments = [];
  860. if (typeof geomRing[0][0] !== 'number' || typeof geomRing[0][1] !== 'number') {
  861. throw new Error('Input geometry is not a valid Polygon or MultiPolygon');
  862. }
  863. var firstPoint = rounder.round(geomRing[0][0], geomRing[0][1]);
  864. this.bbox = {
  865. ll: {
  866. x: firstPoint.x,
  867. y: firstPoint.y
  868. },
  869. ur: {
  870. x: firstPoint.x,
  871. y: firstPoint.y
  872. }
  873. };
  874. var prevPoint = firstPoint;
  875. for (var i = 1, iMax = geomRing.length; i < iMax; i++) {
  876. if (typeof geomRing[i][0] !== 'number' || typeof geomRing[i][1] !== 'number') {
  877. throw new Error('Input geometry is not a valid Polygon or MultiPolygon');
  878. }
  879. var point = rounder.round(geomRing[i][0], geomRing[i][1]); // skip repeated points
  880. if (point.x === prevPoint.x && point.y === prevPoint.y) continue;
  881. this.segments.push(Segment.fromRing(prevPoint, point, this));
  882. if (point.x < this.bbox.ll.x) this.bbox.ll.x = point.x;
  883. if (point.y < this.bbox.ll.y) this.bbox.ll.y = point.y;
  884. if (point.x > this.bbox.ur.x) this.bbox.ur.x = point.x;
  885. if (point.y > this.bbox.ur.y) this.bbox.ur.y = point.y;
  886. prevPoint = point;
  887. } // add segment from last to first if last is not the same as first
  888. if (firstPoint.x !== prevPoint.x || firstPoint.y !== prevPoint.y) {
  889. this.segments.push(Segment.fromRing(prevPoint, firstPoint, this));
  890. }
  891. }
  892. _createClass(RingIn, [{
  893. key: "getSweepEvents",
  894. value: function getSweepEvents() {
  895. var sweepEvents = [];
  896. for (var i = 0, iMax = this.segments.length; i < iMax; i++) {
  897. var segment = this.segments[i];
  898. sweepEvents.push(segment.leftSE);
  899. sweepEvents.push(segment.rightSE);
  900. }
  901. return sweepEvents;
  902. }
  903. }]);
  904. return RingIn;
  905. }();
  906. var PolyIn = /*#__PURE__*/function () {
  907. function PolyIn(geomPoly, multiPoly) {
  908. _classCallCheck(this, PolyIn);
  909. if (!Array.isArray(geomPoly)) {
  910. throw new Error('Input geometry is not a valid Polygon or MultiPolygon');
  911. }
  912. this.exteriorRing = new RingIn(geomPoly[0], this, true); // copy by value
  913. this.bbox = {
  914. ll: {
  915. x: this.exteriorRing.bbox.ll.x,
  916. y: this.exteriorRing.bbox.ll.y
  917. },
  918. ur: {
  919. x: this.exteriorRing.bbox.ur.x,
  920. y: this.exteriorRing.bbox.ur.y
  921. }
  922. };
  923. this.interiorRings = [];
  924. for (var i = 1, iMax = geomPoly.length; i < iMax; i++) {
  925. var ring = new RingIn(geomPoly[i], this, false);
  926. if (ring.bbox.ll.x < this.bbox.ll.x) this.bbox.ll.x = ring.bbox.ll.x;
  927. if (ring.bbox.ll.y < this.bbox.ll.y) this.bbox.ll.y = ring.bbox.ll.y;
  928. if (ring.bbox.ur.x > this.bbox.ur.x) this.bbox.ur.x = ring.bbox.ur.x;
  929. if (ring.bbox.ur.y > this.bbox.ur.y) this.bbox.ur.y = ring.bbox.ur.y;
  930. this.interiorRings.push(ring);
  931. }
  932. this.multiPoly = multiPoly;
  933. }
  934. _createClass(PolyIn, [{
  935. key: "getSweepEvents",
  936. value: function getSweepEvents() {
  937. var sweepEvents = this.exteriorRing.getSweepEvents();
  938. for (var i = 0, iMax = this.interiorRings.length; i < iMax; i++) {
  939. var ringSweepEvents = this.interiorRings[i].getSweepEvents();
  940. for (var j = 0, jMax = ringSweepEvents.length; j < jMax; j++) {
  941. sweepEvents.push(ringSweepEvents[j]);
  942. }
  943. }
  944. return sweepEvents;
  945. }
  946. }]);
  947. return PolyIn;
  948. }();
  949. var MultiPolyIn = /*#__PURE__*/function () {
  950. function MultiPolyIn(geom, isSubject) {
  951. _classCallCheck(this, MultiPolyIn);
  952. if (!Array.isArray(geom)) {
  953. throw new Error('Input geometry is not a valid Polygon or MultiPolygon');
  954. }
  955. try {
  956. // if the input looks like a polygon, convert it to a multipolygon
  957. if (typeof geom[0][0][0] === 'number') geom = [geom];
  958. } catch (ex) {// The input is either malformed or has empty arrays.
  959. // In either case, it will be handled later on.
  960. }
  961. this.polys = [];
  962. this.bbox = {
  963. ll: {
  964. x: Number.POSITIVE_INFINITY,
  965. y: Number.POSITIVE_INFINITY
  966. },
  967. ur: {
  968. x: Number.NEGATIVE_INFINITY,
  969. y: Number.NEGATIVE_INFINITY
  970. }
  971. };
  972. for (var i = 0, iMax = geom.length; i < iMax; i++) {
  973. var poly = new PolyIn(geom[i], this);
  974. if (poly.bbox.ll.x < this.bbox.ll.x) this.bbox.ll.x = poly.bbox.ll.x;
  975. if (poly.bbox.ll.y < this.bbox.ll.y) this.bbox.ll.y = poly.bbox.ll.y;
  976. if (poly.bbox.ur.x > this.bbox.ur.x) this.bbox.ur.x = poly.bbox.ur.x;
  977. if (poly.bbox.ur.y > this.bbox.ur.y) this.bbox.ur.y = poly.bbox.ur.y;
  978. this.polys.push(poly);
  979. }
  980. this.isSubject = isSubject;
  981. }
  982. _createClass(MultiPolyIn, [{
  983. key: "getSweepEvents",
  984. value: function getSweepEvents() {
  985. var sweepEvents = [];
  986. for (var i = 0, iMax = this.polys.length; i < iMax; i++) {
  987. var polySweepEvents = this.polys[i].getSweepEvents();
  988. for (var j = 0, jMax = polySweepEvents.length; j < jMax; j++) {
  989. sweepEvents.push(polySweepEvents[j]);
  990. }
  991. }
  992. return sweepEvents;
  993. }
  994. }]);
  995. return MultiPolyIn;
  996. }();
  997. var RingOut = /*#__PURE__*/function () {
  998. _createClass(RingOut, null, [{
  999. key: "factory",
  1000. /* Given the segments from the sweep line pass, compute & return a series
  1001. * of closed rings from all the segments marked to be part of the result */
  1002. value: function factory(allSegments) {
  1003. var ringsOut = [];
  1004. for (var i = 0, iMax = allSegments.length; i < iMax; i++) {
  1005. var segment = allSegments[i];
  1006. if (!segment.isInResult() || segment.ringOut) continue;
  1007. var prevEvent = null;
  1008. var event = segment.leftSE;
  1009. var nextEvent = segment.rightSE;
  1010. var events = [event];
  1011. var startingPoint = event.point;
  1012. var intersectionLEs = [];
  1013. /* Walk the chain of linked events to form a closed ring */
  1014. while (true) {
  1015. prevEvent = event;
  1016. event = nextEvent;
  1017. events.push(event);
  1018. /* Is the ring complete? */
  1019. if (event.point === startingPoint) break;
  1020. while (true) {
  1021. var availableLEs = event.getAvailableLinkedEvents();
  1022. /* Did we hit a dead end? This shouldn't happen. Indicates some earlier
  1023. * part of the algorithm malfunctioned... please file a bug report. */
  1024. if (availableLEs.length === 0) {
  1025. var firstPt = events[0].point;
  1026. var lastPt = events[events.length - 1].point;
  1027. throw new Error("Unable to complete output ring starting at [".concat(firstPt.x, ",") + " ".concat(firstPt.y, "]. Last matching segment found ends at") + " [".concat(lastPt.x, ", ").concat(lastPt.y, "]."));
  1028. }
  1029. /* Only one way to go, so cotinue on the path */
  1030. if (availableLEs.length === 1) {
  1031. nextEvent = availableLEs[0].otherSE;
  1032. break;
  1033. }
  1034. /* We must have an intersection. Check for a completed loop */
  1035. var indexLE = null;
  1036. for (var j = 0, jMax = intersectionLEs.length; j < jMax; j++) {
  1037. if (intersectionLEs[j].point === event.point) {
  1038. indexLE = j;
  1039. break;
  1040. }
  1041. }
  1042. /* Found a completed loop. Cut that off and make a ring */
  1043. if (indexLE !== null) {
  1044. var intersectionLE = intersectionLEs.splice(indexLE)[0];
  1045. var ringEvents = events.splice(intersectionLE.index);
  1046. ringEvents.unshift(ringEvents[0].otherSE);
  1047. ringsOut.push(new RingOut(ringEvents.reverse()));
  1048. continue;
  1049. }
  1050. /* register the intersection */
  1051. intersectionLEs.push({
  1052. index: events.length,
  1053. point: event.point
  1054. });
  1055. /* Choose the left-most option to continue the walk */
  1056. var comparator = event.getLeftmostComparator(prevEvent);
  1057. nextEvent = availableLEs.sort(comparator)[0].otherSE;
  1058. break;
  1059. }
  1060. }
  1061. ringsOut.push(new RingOut(events));
  1062. }
  1063. return ringsOut;
  1064. }
  1065. }]);
  1066. function RingOut(events) {
  1067. _classCallCheck(this, RingOut);
  1068. this.events = events;
  1069. for (var i = 0, iMax = events.length; i < iMax; i++) {
  1070. events[i].segment.ringOut = this;
  1071. }
  1072. this.poly = null;
  1073. }
  1074. _createClass(RingOut, [{
  1075. key: "getGeom",
  1076. value: function getGeom() {
  1077. // Remove superfluous points (ie extra points along a straight line),
  1078. var prevPt = this.events[0].point;
  1079. var points = [prevPt];
  1080. for (var i = 1, iMax = this.events.length - 1; i < iMax; i++) {
  1081. var _pt = this.events[i].point;
  1082. var _nextPt = this.events[i + 1].point;
  1083. if (compareVectorAngles(_pt, prevPt, _nextPt) === 0) continue;
  1084. points.push(_pt);
  1085. prevPt = _pt;
  1086. } // ring was all (within rounding error of angle calc) colinear points
  1087. if (points.length === 1) return null; // check if the starting point is necessary
  1088. var pt = points[0];
  1089. var nextPt = points[1];
  1090. if (compareVectorAngles(pt, prevPt, nextPt) === 0) points.shift();
  1091. points.push(points[0]);
  1092. var step = this.isExteriorRing() ? 1 : -1;
  1093. var iStart = this.isExteriorRing() ? 0 : points.length - 1;
  1094. var iEnd = this.isExteriorRing() ? points.length : -1;
  1095. var orderedPoints = [];
  1096. for (var _i = iStart; _i != iEnd; _i += step) {
  1097. orderedPoints.push([points[_i].x, points[_i].y]);
  1098. }
  1099. return orderedPoints;
  1100. }
  1101. }, {
  1102. key: "isExteriorRing",
  1103. value: function isExteriorRing() {
  1104. if (this._isExteriorRing === undefined) {
  1105. var enclosing = this.enclosingRing();
  1106. this._isExteriorRing = enclosing ? !enclosing.isExteriorRing() : true;
  1107. }
  1108. return this._isExteriorRing;
  1109. }
  1110. }, {
  1111. key: "enclosingRing",
  1112. value: function enclosingRing() {
  1113. if (this._enclosingRing === undefined) {
  1114. this._enclosingRing = this._calcEnclosingRing();
  1115. }
  1116. return this._enclosingRing;
  1117. }
  1118. /* Returns the ring that encloses this one, if any */
  1119. }, {
  1120. key: "_calcEnclosingRing",
  1121. value: function _calcEnclosingRing() {
  1122. // start with the ealier sweep line event so that the prevSeg
  1123. // chain doesn't lead us inside of a loop of ours
  1124. var leftMostEvt = this.events[0];
  1125. for (var i = 1, iMax = this.events.length; i < iMax; i++) {
  1126. var evt = this.events[i];
  1127. if (SweepEvent.compare(leftMostEvt, evt) > 0) leftMostEvt = evt;
  1128. }
  1129. var prevSeg = leftMostEvt.segment.prevInResult();
  1130. var prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null;
  1131. while (true) {
  1132. // no segment found, thus no ring can enclose us
  1133. if (!prevSeg) return null; // no segments below prev segment found, thus the ring of the prev
  1134. // segment must loop back around and enclose us
  1135. if (!prevPrevSeg) return prevSeg.ringOut; // if the two segments are of different rings, the ring of the prev
  1136. // segment must either loop around us or the ring of the prev prev
  1137. // seg, which would make us and the ring of the prev peers
  1138. if (prevPrevSeg.ringOut !== prevSeg.ringOut) {
  1139. if (prevPrevSeg.ringOut.enclosingRing() !== prevSeg.ringOut) {
  1140. return prevSeg.ringOut;
  1141. } else return prevSeg.ringOut.enclosingRing();
  1142. } // two segments are from the same ring, so this was a penisula
  1143. // of that ring. iterate downward, keep searching
  1144. prevSeg = prevPrevSeg.prevInResult();
  1145. prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null;
  1146. }
  1147. }
  1148. }]);
  1149. return RingOut;
  1150. }();
  1151. var PolyOut = /*#__PURE__*/function () {
  1152. function PolyOut(exteriorRing) {
  1153. _classCallCheck(this, PolyOut);
  1154. this.exteriorRing = exteriorRing;
  1155. exteriorRing.poly = this;
  1156. this.interiorRings = [];
  1157. }
  1158. _createClass(PolyOut, [{
  1159. key: "addInterior",
  1160. value: function addInterior(ring) {
  1161. this.interiorRings.push(ring);
  1162. ring.poly = this;
  1163. }
  1164. }, {
  1165. key: "getGeom",
  1166. value: function getGeom() {
  1167. var geom = [this.exteriorRing.getGeom()]; // exterior ring was all (within rounding error of angle calc) colinear points
  1168. if (geom[0] === null) return null;
  1169. for (var i = 0, iMax = this.interiorRings.length; i < iMax; i++) {
  1170. var ringGeom = this.interiorRings[i].getGeom(); // interior ring was all (within rounding error of angle calc) colinear points
  1171. if (ringGeom === null) continue;
  1172. geom.push(ringGeom);
  1173. }
  1174. return geom;
  1175. }
  1176. }]);
  1177. return PolyOut;
  1178. }();
  1179. var MultiPolyOut = /*#__PURE__*/function () {
  1180. function MultiPolyOut(rings) {
  1181. _classCallCheck(this, MultiPolyOut);
  1182. this.rings = rings;
  1183. this.polys = this._composePolys(rings);
  1184. }
  1185. _createClass(MultiPolyOut, [{
  1186. key: "getGeom",
  1187. value: function getGeom() {
  1188. var geom = [];
  1189. for (var i = 0, iMax = this.polys.length; i < iMax; i++) {
  1190. var polyGeom = this.polys[i].getGeom(); // exterior ring was all (within rounding error of angle calc) colinear points
  1191. if (polyGeom === null) continue;
  1192. geom.push(polyGeom);
  1193. }
  1194. return geom;
  1195. }
  1196. }, {
  1197. key: "_composePolys",
  1198. value: function _composePolys(rings) {
  1199. var polys = [];
  1200. for (var i = 0, iMax = rings.length; i < iMax; i++) {
  1201. var ring = rings[i];
  1202. if (ring.poly) continue;
  1203. if (ring.isExteriorRing()) polys.push(new PolyOut(ring));else {
  1204. var enclosingRing = ring.enclosingRing();
  1205. if (!enclosingRing.poly) polys.push(new PolyOut(enclosingRing));
  1206. enclosingRing.poly.addInterior(ring);
  1207. }
  1208. }
  1209. return polys;
  1210. }
  1211. }]);
  1212. return MultiPolyOut;
  1213. }();
  1214. /**
  1215. * NOTE: We must be careful not to change any segments while
  1216. * they are in the SplayTree. AFAIK, there's no way to tell
  1217. * the tree to rebalance itself - thus before splitting
  1218. * a segment that's in the tree, we remove it from the tree,
  1219. * do the split, then re-insert it. (Even though splitting a
  1220. * segment *shouldn't* change its correct position in the
  1221. * sweep line tree, the reality is because of rounding errors,
  1222. * it sometimes does.)
  1223. */
  1224. var SweepLine = /*#__PURE__*/function () {
  1225. function SweepLine(queue) {
  1226. var comparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Segment.compare;
  1227. _classCallCheck(this, SweepLine);
  1228. this.queue = queue;
  1229. this.tree = new SplayTree(comparator);
  1230. this.segments = [];
  1231. }
  1232. _createClass(SweepLine, [{
  1233. key: "process",
  1234. value: function process(event) {
  1235. var segment = event.segment;
  1236. var newEvents = []; // if we've already been consumed by another segment,
  1237. // clean up our body parts and get out
  1238. if (event.consumedBy) {
  1239. if (event.isLeft) this.queue.remove(event.otherSE);else this.tree.remove(segment);
  1240. return newEvents;
  1241. }
  1242. var node = event.isLeft ? this.tree.insert(segment) : this.tree.find(segment);
  1243. if (!node) throw new Error("Unable to find segment #".concat(segment.id, " ") + "[".concat(segment.leftSE.point.x, ", ").concat(segment.leftSE.point.y, "] -> ") + "[".concat(segment.rightSE.point.x, ", ").concat(segment.rightSE.point.y, "] ") + 'in SweepLine tree. Please submit a bug report.');
  1244. var prevNode = node;
  1245. var nextNode = node;
  1246. var prevSeg = undefined;
  1247. var nextSeg = undefined; // skip consumed segments still in tree
  1248. while (prevSeg === undefined) {
  1249. prevNode = this.tree.prev(prevNode);
  1250. if (prevNode === null) prevSeg = null;else if (prevNode.key.consumedBy === undefined) prevSeg = prevNode.key;
  1251. } // skip consumed segments still in tree
  1252. while (nextSeg === undefined) {
  1253. nextNode = this.tree.next(nextNode);
  1254. if (nextNode === null) nextSeg = null;else if (nextNode.key.consumedBy === undefined) nextSeg = nextNode.key;
  1255. }
  1256. if (event.isLeft) {
  1257. // Check for intersections against the previous segment in the sweep line
  1258. var prevMySplitter = null;
  1259. if (prevSeg) {
  1260. var prevInter = prevSeg.getIntersection(segment);
  1261. if (prevInter !== null) {
  1262. if (!segment.isAnEndpoint(prevInter)) prevMySplitter = prevInter;
  1263. if (!prevSeg.isAnEndpoint(prevInter)) {
  1264. var newEventsFromSplit = this._splitSafely(prevSeg, prevInter);
  1265. for (var i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {
  1266. newEvents.push(newEventsFromSplit[i]);
  1267. }
  1268. }
  1269. }
  1270. } // Check for intersections against the next segment in the sweep line
  1271. var nextMySplitter = null;
  1272. if (nextSeg) {
  1273. var nextInter = nextSeg.getIntersection(segment);
  1274. if (nextInter !== null) {
  1275. if (!segment.isAnEndpoint(nextInter)) nextMySplitter = nextInter;
  1276. if (!nextSeg.isAnEndpoint(nextInter)) {
  1277. var _newEventsFromSplit = this._splitSafely(nextSeg, nextInter);
  1278. for (var _i = 0, _iMax = _newEventsFromSplit.length; _i < _iMax; _i++) {
  1279. newEvents.push(_newEventsFromSplit[_i]);
  1280. }
  1281. }
  1282. }
  1283. } // For simplicity, even if we find more than one intersection we only
  1284. // spilt on the 'earliest' (sweep-line style) of the intersections.
  1285. // The other intersection will be handled in a future process().
  1286. if (prevMySplitter !== null || nextMySplitter !== null) {
  1287. var mySplitter = null;
  1288. if (prevMySplitter === null) mySplitter = nextMySplitter;else if (nextMySplitter === null) mySplitter = prevMySplitter;else {
  1289. var cmpSplitters = SweepEvent.comparePoints(prevMySplitter, nextMySplitter);
  1290. mySplitter = cmpSplitters <= 0 ? prevMySplitter : nextMySplitter;
  1291. } // Rounding errors can cause changes in ordering,
  1292. // so remove afected segments and right sweep events before splitting
  1293. this.queue.remove(segment.rightSE);
  1294. newEvents.push(segment.rightSE);
  1295. var _newEventsFromSplit2 = segment.split(mySplitter);
  1296. for (var _i2 = 0, _iMax2 = _newEventsFromSplit2.length; _i2 < _iMax2; _i2++) {
  1297. newEvents.push(_newEventsFromSplit2[_i2]);
  1298. }
  1299. }
  1300. if (newEvents.length > 0) {
  1301. // We found some intersections, so re-do the current event to
  1302. // make sure sweep line ordering is totally consistent for later
  1303. // use with the segment 'prev' pointers
  1304. this.tree.remove(segment);
  1305. newEvents.push(event);
  1306. } else {
  1307. // done with left event
  1308. this.segments.push(segment);
  1309. segment.prev = prevSeg;
  1310. }
  1311. } else {
  1312. // event.isRight
  1313. // since we're about to be removed from the sweep line, check for
  1314. // intersections between our previous and next segments
  1315. if (prevSeg && nextSeg) {
  1316. var inter = prevSeg.getIntersection(nextSeg);
  1317. if (inter !== null) {
  1318. if (!prevSeg.isAnEndpoint(inter)) {
  1319. var _newEventsFromSplit3 = this._splitSafely(prevSeg, inter);
  1320. for (var _i3 = 0, _iMax3 = _newEventsFromSplit3.length; _i3 < _iMax3; _i3++) {
  1321. newEvents.push(_newEventsFromSplit3[_i3]);
  1322. }
  1323. }
  1324. if (!nextSeg.isAnEndpoint(inter)) {
  1325. var _newEventsFromSplit4 = this._splitSafely(nextSeg, inter);
  1326. for (var _i4 = 0, _iMax4 = _newEventsFromSplit4.length; _i4 < _iMax4; _i4++) {
  1327. newEvents.push(_newEventsFromSplit4[_i4]);
  1328. }
  1329. }
  1330. }
  1331. }
  1332. this.tree.remove(segment);
  1333. }
  1334. return newEvents;
  1335. }
  1336. /* Safely split a segment that is currently in the datastructures
  1337. * IE - a segment other than the one that is currently being processed. */
  1338. }, {
  1339. key: "_splitSafely",
  1340. value: function _splitSafely(seg, pt) {
  1341. // Rounding errors can cause changes in ordering,
  1342. // so remove afected segments and right sweep events before splitting
  1343. // removeNode() doesn't work, so have re-find the seg
  1344. // https://github.com/w8r/splay-tree/pull/5
  1345. this.tree.remove(seg);
  1346. var rightSE = seg.rightSE;
  1347. this.queue.remove(rightSE);
  1348. var newEvents = seg.split(pt);
  1349. newEvents.push(rightSE); // splitting can trigger consumption
  1350. if (seg.consumedBy === undefined) this.tree.insert(seg);
  1351. return newEvents;
  1352. }
  1353. }]);
  1354. return SweepLine;
  1355. }();
  1356. var POLYGON_CLIPPING_MAX_QUEUE_SIZE = typeof process !== 'undefined' && process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE || 1000000;
  1357. var POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS = typeof process !== 'undefined' && process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS || 1000000;
  1358. var Operation = /*#__PURE__*/function () {
  1359. function Operation() {
  1360. _classCallCheck(this, Operation);
  1361. }
  1362. _createClass(Operation, [{
  1363. key: "run",
  1364. value: function run(type, geom, moreGeoms) {
  1365. operation.type = type;
  1366. rounder.reset();
  1367. /* Convert inputs to MultiPoly objects */
  1368. var multipolys = [new MultiPolyIn(geom, true)];
  1369. for (var i = 0, iMax = moreGeoms.length; i < iMax; i++) {
  1370. multipolys.push(new MultiPolyIn(moreGeoms[i], false));
  1371. }
  1372. operation.numMultiPolys = multipolys.length;
  1373. /* BBox optimization for difference operation
  1374. * If the bbox of a multipolygon that's part of the clipping doesn't
  1375. * intersect the bbox of the subject at all, we can just drop that
  1376. * multiploygon. */
  1377. if (operation.type === 'difference') {
  1378. // in place removal
  1379. var subject = multipolys[0];
  1380. var _i = 1;
  1381. while (_i < multipolys.length) {
  1382. if (getBboxOverlap(multipolys[_i].bbox, subject.bbox) !== null) _i++;else multipolys.splice(_i, 1);
  1383. }
  1384. }
  1385. /* BBox optimization for intersection operation
  1386. * If we can find any pair of multipolygons whose bbox does not overlap,
  1387. * then the result will be empty. */
  1388. if (operation.type === 'intersection') {
  1389. // TODO: this is O(n^2) in number of polygons. By sorting the bboxes,
  1390. // it could be optimized to O(n * ln(n))
  1391. for (var _i2 = 0, _iMax = multipolys.length; _i2 < _iMax; _i2++) {
  1392. var mpA = multipolys[_i2];
  1393. for (var j = _i2 + 1, jMax = multipolys.length; j < jMax; j++) {
  1394. if (getBboxOverlap(mpA.bbox, multipolys[j].bbox) === null) return [];
  1395. }
  1396. }
  1397. }
  1398. /* Put segment endpoints in a priority queue */
  1399. var queue = new SplayTree(SweepEvent.compare);
  1400. for (var _i3 = 0, _iMax2 = multipolys.length; _i3 < _iMax2; _i3++) {
  1401. var sweepEvents = multipolys[_i3].getSweepEvents();
  1402. for (var _j = 0, _jMax = sweepEvents.length; _j < _jMax; _j++) {
  1403. queue.insert(sweepEvents[_j]);
  1404. if (queue.size > POLYGON_CLIPPING_MAX_QUEUE_SIZE) {
  1405. // prevents an infinite loop, an otherwise common manifestation of bugs
  1406. throw new Error('Infinite loop when putting segment endpoints in a priority queue ' + '(queue size too big). Please file a bug report.');
  1407. }
  1408. }
  1409. }
  1410. /* Pass the sweep line over those endpoints */
  1411. var sweepLine = new SweepLine(queue);
  1412. var prevQueueSize = queue.size;
  1413. var node = queue.pop();
  1414. while (node) {
  1415. var evt = node.key;
  1416. if (queue.size === prevQueueSize) {
  1417. // prevents an infinite loop, an otherwise common manifestation of bugs
  1418. var seg = evt.segment;
  1419. throw new Error("Unable to pop() ".concat(evt.isLeft ? 'left' : 'right', " SweepEvent ") + "[".concat(evt.point.x, ", ").concat(evt.point.y, "] from segment #").concat(seg.id, " ") + "[".concat(seg.leftSE.point.x, ", ").concat(seg.leftSE.point.y, "] -> ") + "[".concat(seg.rightSE.point.x, ", ").concat(seg.rightSE.point.y, "] from queue. ") + 'Please file a bug report.');
  1420. }
  1421. if (queue.size > POLYGON_CLIPPING_MAX_QUEUE_SIZE) {
  1422. // prevents an infinite loop, an otherwise common manifestation of bugs
  1423. throw new Error('Infinite loop when passing sweep line over endpoints ' + '(queue size too big). Please file a bug report.');
  1424. }
  1425. if (sweepLine.segments.length > POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS) {
  1426. // prevents an infinite loop, an otherwise common manifestation of bugs
  1427. throw new Error('Infinite loop when passing sweep line over endpoints ' + '(too many sweep line segments). Please file a bug report.');
  1428. }
  1429. var newEvents = sweepLine.process(evt);
  1430. for (var _i4 = 0, _iMax3 = newEvents.length; _i4 < _iMax3; _i4++) {
  1431. var _evt = newEvents[_i4];
  1432. if (_evt.consumedBy === undefined) queue.insert(_evt);
  1433. }
  1434. prevQueueSize = queue.size;
  1435. node = queue.pop();
  1436. } // free some memory we don't need anymore
  1437. rounder.reset();
  1438. /* Collect and compile segments we're keeping into a multipolygon */
  1439. var ringsOut = RingOut.factory(sweepLine.segments);
  1440. var result = new MultiPolyOut(ringsOut);
  1441. return result.getGeom();
  1442. }
  1443. }]);
  1444. return Operation;
  1445. }(); // singleton available by import
  1446. var operation = new Operation();
  1447. var union = function union(geom) {
  1448. for (var _len = arguments.length, moreGeoms = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  1449. moreGeoms[_key - 1] = arguments[_key];
  1450. }
  1451. return operation.run('union', geom, moreGeoms);
  1452. };
  1453. var intersection$1 = function intersection(geom) {
  1454. for (var _len2 = arguments.length, moreGeoms = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  1455. moreGeoms[_key2 - 1] = arguments[_key2];
  1456. }
  1457. return operation.run('intersection', geom, moreGeoms);
  1458. };
  1459. var xor = function xor(geom) {
  1460. for (var _len3 = arguments.length, moreGeoms = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
  1461. moreGeoms[_key3 - 1] = arguments[_key3];
  1462. }
  1463. return operation.run('xor', geom, moreGeoms);
  1464. };
  1465. var difference = function difference(subjectGeom) {
  1466. for (var _len4 = arguments.length, clippingGeoms = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
  1467. clippingGeoms[_key4 - 1] = arguments[_key4];
  1468. }
  1469. return operation.run('difference', subjectGeom, clippingGeoms);
  1470. };
  1471. var index = {
  1472. union: union,
  1473. intersection: intersection$1,
  1474. xor: xor,
  1475. difference: difference
  1476. };
  1477. export default index;