polygon-clipping.cjs.js 60 KB

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