polygon-clipping.esm.js 54 KB

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