intersect.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. 'use strict';
  2. /**
  3. * This file contains portions that got extraced from Snap.svg (licensed Apache-2.0).
  4. *
  5. * @see https://github.com/adobe-webplatform/Snap.svg/blob/master/src/path.js
  6. */
  7. /* eslint no-fallthrough: "off" */
  8. var has = 'hasOwnProperty',
  9. p2s = /,?([a-z]),?/gi,
  10. toFloat = parseFloat,
  11. math = Math,
  12. PI = math.PI,
  13. mmin = math.min,
  14. mmax = math.max,
  15. pow = math.pow,
  16. abs = math.abs,
  17. pathCommand = /([a-z])[\s,]*((-?\d*\.?\d*(?:e[-+]?\d+)?[\s]*,?[\s]*)+)/ig,
  18. pathValues = /(-?\d*\.?\d*(?:e[-+]?\\d+)?)[\s]*,?[\s]*/ig;
  19. function is(o, type) {
  20. type = String.prototype.toLowerCase.call(type);
  21. if (type == 'finite') {
  22. return isFinite(o);
  23. }
  24. if (type == 'array' && (o instanceof Array || Array.isArray && Array.isArray(o))) {
  25. return true;
  26. }
  27. return (type == 'null' && o === null) ||
  28. (type == typeof o && o !== null) ||
  29. (type == 'object' && o === Object(o)) ||
  30. Object.prototype.toString.call(o).slice(8, -1).toLowerCase() == type;
  31. }
  32. function clone(obj) {
  33. if (typeof obj == 'function' || Object(obj) !== obj) {
  34. return obj;
  35. }
  36. var res = new obj.constructor;
  37. for (var key in obj) if (obj[has](key)) {
  38. res[key] = clone(obj[key]);
  39. }
  40. return res;
  41. }
  42. function repush(array, item) {
  43. for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
  44. return array.push(array.splice(i, 1)[0]);
  45. }
  46. }
  47. function cacher(f, scope, postprocessor) {
  48. function newf() {
  49. var arg = Array.prototype.slice.call(arguments, 0),
  50. args = arg.join('\u2400'),
  51. cache = newf.cache = newf.cache || {},
  52. count = newf.count = newf.count || [];
  53. if (cache[has](args)) {
  54. repush(count, args);
  55. return postprocessor ? postprocessor(cache[args]) : cache[args];
  56. }
  57. count.length >= 1e3 && delete cache[count.shift()];
  58. count.push(args);
  59. cache[args] = f.apply(scope, arg);
  60. return postprocessor ? postprocessor(cache[args]) : cache[args];
  61. }
  62. return newf;
  63. }
  64. function parsePathString(pathString) {
  65. if (!pathString) {
  66. return null;
  67. }
  68. var pth = paths(pathString);
  69. if (pth.arr) {
  70. return clone(pth.arr);
  71. }
  72. var paramCounts = { a: 7, c: 6, o: 2, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, u: 3, z: 0 },
  73. data = [];
  74. if (is(pathString, 'array') && is(pathString[0], 'array')) { // rough assumption
  75. data = clone(pathString);
  76. }
  77. if (!data.length) {
  78. String(pathString).replace(pathCommand, function(a, b, c) {
  79. var params = [],
  80. name = b.toLowerCase();
  81. c.replace(pathValues, function(a, b) {
  82. b && params.push(+b);
  83. });
  84. if (name == 'm' && params.length > 2) {
  85. data.push([b].concat(params.splice(0, 2)));
  86. name = 'l';
  87. b = b == 'm' ? 'l' : 'L';
  88. }
  89. if (name == 'o' && params.length == 1) {
  90. data.push([b, params[0]]);
  91. }
  92. if (name == 'r') {
  93. data.push([b].concat(params));
  94. } else while (params.length >= paramCounts[name]) {
  95. data.push([b].concat(params.splice(0, paramCounts[name])));
  96. if (!paramCounts[name]) {
  97. break;
  98. }
  99. }
  100. });
  101. }
  102. data.toString = paths.toString;
  103. pth.arr = clone(data);
  104. return data;
  105. }
  106. function paths(ps) {
  107. var p = paths.ps = paths.ps || {};
  108. if (p[ps]) {
  109. p[ps].sleep = 100;
  110. } else {
  111. p[ps] = {
  112. sleep: 100
  113. };
  114. }
  115. setTimeout(function() {
  116. for (var key in p) if (p[has](key) && key != ps) {
  117. p[key].sleep--;
  118. !p[key].sleep && delete p[key];
  119. }
  120. });
  121. return p[ps];
  122. }
  123. function box(x, y, width, height) {
  124. if (x == null) {
  125. x = y = width = height = 0;
  126. }
  127. if (y == null) {
  128. y = x.y;
  129. width = x.width;
  130. height = x.height;
  131. x = x.x;
  132. }
  133. return {
  134. x: x,
  135. y: y,
  136. width: width,
  137. w: width,
  138. height: height,
  139. h: height,
  140. x2: x + width,
  141. y2: y + height,
  142. cx: x + width / 2,
  143. cy: y + height / 2,
  144. r1: math.min(width, height) / 2,
  145. r2: math.max(width, height) / 2,
  146. r0: math.sqrt(width * width + height * height) / 2,
  147. path: rectPath(x, y, width, height),
  148. vb: [x, y, width, height].join(' ')
  149. };
  150. }
  151. function pathToString() {
  152. return this.join(',').replace(p2s, '$1');
  153. }
  154. function pathClone(pathArray) {
  155. var res = clone(pathArray);
  156. res.toString = pathToString;
  157. return res;
  158. }
  159. function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
  160. var t1 = 1 - t,
  161. t13 = pow(t1, 3),
  162. t12 = pow(t1, 2),
  163. t2 = t * t,
  164. t3 = t2 * t,
  165. x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x,
  166. y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y,
  167. mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x),
  168. my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y),
  169. nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x),
  170. ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y),
  171. ax = t1 * p1x + t * c1x,
  172. ay = t1 * p1y + t * c1y,
  173. cx = t1 * c2x + t * p2x,
  174. cy = t1 * c2y + t * p2y,
  175. alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
  176. return {
  177. x: x,
  178. y: y,
  179. m: { x: mx, y: my },
  180. n: { x: nx, y: ny },
  181. start: { x: ax, y: ay },
  182. end: { x: cx, y: cy },
  183. alpha: alpha
  184. };
  185. }
  186. function bezierBBox(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
  187. if (!is(p1x, 'array')) {
  188. p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y];
  189. }
  190. var bbox = curveBBox.apply(null, p1x);
  191. return box(
  192. bbox.min.x,
  193. bbox.min.y,
  194. bbox.max.x - bbox.min.x,
  195. bbox.max.y - bbox.min.y
  196. );
  197. }
  198. function isPointInsideBBox(bbox, x, y) {
  199. return x >= bbox.x &&
  200. x <= bbox.x + bbox.width &&
  201. y >= bbox.y &&
  202. y <= bbox.y + bbox.height;
  203. }
  204. function isBBoxIntersect(bbox1, bbox2) {
  205. bbox1 = box(bbox1);
  206. bbox2 = box(bbox2);
  207. return isPointInsideBBox(bbox2, bbox1.x, bbox1.y)
  208. || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y)
  209. || isPointInsideBBox(bbox2, bbox1.x, bbox1.y2)
  210. || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y2)
  211. || isPointInsideBBox(bbox1, bbox2.x, bbox2.y)
  212. || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y)
  213. || isPointInsideBBox(bbox1, bbox2.x, bbox2.y2)
  214. || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y2)
  215. || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x
  216. || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x)
  217. && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y
  218. || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y);
  219. }
  220. function base3(t, p1, p2, p3, p4) {
  221. var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4,
  222. t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3;
  223. return t * t2 - 3 * p1 + 3 * p2;
  224. }
  225. function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) {
  226. if (z == null) {
  227. z = 1;
  228. }
  229. z = z > 1 ? 1 : z < 0 ? 0 : z;
  230. var z2 = z / 2,
  231. n = 12,
  232. Tvalues = [-.1252,.1252,-.3678,.3678,-.5873,.5873,-.7699,.7699,-.9041,.9041,-.9816,.9816],
  233. Cvalues = [0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472],
  234. sum = 0;
  235. for (var i = 0; i < n; i++) {
  236. var ct = z2 * Tvalues[i] + z2,
  237. xbase = base3(ct, x1, x2, x3, x4),
  238. ybase = base3(ct, y1, y2, y3, y4),
  239. comb = xbase * xbase + ybase * ybase;
  240. sum += Cvalues[i] * math.sqrt(comb);
  241. }
  242. return z2 * sum;
  243. }
  244. function intersectLines(x1, y1, x2, y2, x3, y3, x4, y4) {
  245. if (
  246. mmax(x1, x2) < mmin(x3, x4) ||
  247. mmin(x1, x2) > mmax(x3, x4) ||
  248. mmax(y1, y2) < mmin(y3, y4) ||
  249. mmin(y1, y2) > mmax(y3, y4)
  250. ) {
  251. return;
  252. }
  253. var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4),
  254. ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4),
  255. denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  256. if (!denominator) {
  257. return;
  258. }
  259. var px = nx / denominator,
  260. py = ny / denominator,
  261. px2 = +px.toFixed(2),
  262. py2 = +py.toFixed(2);
  263. if (
  264. px2 < +mmin(x1, x2).toFixed(2) ||
  265. px2 > +mmax(x1, x2).toFixed(2) ||
  266. px2 < +mmin(x3, x4).toFixed(2) ||
  267. px2 > +mmax(x3, x4).toFixed(2) ||
  268. py2 < +mmin(y1, y2).toFixed(2) ||
  269. py2 > +mmax(y1, y2).toFixed(2) ||
  270. py2 < +mmin(y3, y4).toFixed(2) ||
  271. py2 > +mmax(y3, y4).toFixed(2)
  272. ) {
  273. return;
  274. }
  275. return { x: px, y: py };
  276. }
  277. function findBezierIntersections(bez1, bez2, justCount) {
  278. var bbox1 = bezierBBox(bez1),
  279. bbox2 = bezierBBox(bez2);
  280. if (!isBBoxIntersect(bbox1, bbox2)) {
  281. return justCount ? 0 : [];
  282. }
  283. var l1 = bezlen.apply(0, bez1),
  284. l2 = bezlen.apply(0, bez2),
  285. n1 = ~~(l1 / 5),
  286. n2 = ~~(l2 / 5),
  287. dots1 = [],
  288. dots2 = [],
  289. xy = {},
  290. res = justCount ? 0 : [];
  291. for (var i = 0; i < n1 + 1; i++) {
  292. var p = findDotsAtSegment.apply(0, bez1.concat(i / n1));
  293. dots1.push({ x: p.x, y: p.y, t: i / n1 });
  294. }
  295. for (i = 0; i < n2 + 1; i++) {
  296. p = findDotsAtSegment.apply(0, bez2.concat(i / n2));
  297. dots2.push({ x: p.x, y: p.y, t: i / n2 });
  298. }
  299. for (i = 0; i < n1; i++) {
  300. for (var j = 0; j < n2; j++) {
  301. var di = dots1[i],
  302. di1 = dots1[i + 1],
  303. dj = dots2[j],
  304. dj1 = dots2[j + 1],
  305. ci = abs(di1.x - di.x) < .01 ? 'y' : 'x',
  306. cj = abs(dj1.x - dj.x) < .01 ? 'y' : 'x',
  307. is = intersectLines(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y);
  308. if (is) {
  309. if (xy[is.x.toFixed(0)] == is.y.toFixed(0)) {
  310. continue;
  311. }
  312. xy[is.x.toFixed(0)] = is.y.toFixed(0);
  313. var t1 = di.t + abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t),
  314. t2 = dj.t + abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t);
  315. if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) {
  316. if (justCount) {
  317. res++;
  318. } else {
  319. res.push({
  320. x: is.x,
  321. y: is.y,
  322. t1: t1,
  323. t2: t2
  324. });
  325. }
  326. }
  327. }
  328. }
  329. }
  330. return res;
  331. }
  332. /**
  333. * Find or counts the intersections between two SVG paths.
  334. *
  335. * Returns a number in counting mode and a list of intersections otherwise.
  336. *
  337. * A single intersection entry contains the intersection coordinates (x, y)
  338. * as well as additional information regarding the intersecting segments
  339. * on each path (segment1, segment2) and the relative location of the
  340. * intersection on these segments (t1, t2).
  341. *
  342. * The path may be an SVG path string or a list of path components
  343. * such as `[ [ 'M', 0, 10 ], [ 'L', 20, 0 ] ]`.
  344. *
  345. * @example
  346. *
  347. * var intersections = findPathIntersections(
  348. * 'M0,0L100,100',
  349. * [ [ 'M', 0, 100 ], [ 'L', 100, 0 ] ]
  350. * );
  351. *
  352. * // intersections = [
  353. * // { x: 50, y: 50, segment1: 1, segment2: 1, t1: 0.5, t2: 0.5 }
  354. * //
  355. *
  356. * @param {String|Array<PathDef>} path1
  357. * @param {String|Array<PathDef>} path2
  358. * @param {Boolean} [justCount=false]
  359. *
  360. * @return {Array<Intersection>|Number}
  361. */
  362. function findPathIntersections(path1, path2, justCount) {
  363. path1 = pathToCurve(path1);
  364. path2 = pathToCurve(path2);
  365. var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2,
  366. res = justCount ? 0 : [];
  367. for (var i = 0, ii = path1.length; i < ii; i++) {
  368. var pi = path1[i];
  369. if (pi[0] == 'M') {
  370. x1 = x1m = pi[1];
  371. y1 = y1m = pi[2];
  372. } else {
  373. if (pi[0] == 'C') {
  374. bez1 = [x1, y1].concat(pi.slice(1));
  375. x1 = bez1[6];
  376. y1 = bez1[7];
  377. } else {
  378. bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m];
  379. x1 = x1m;
  380. y1 = y1m;
  381. }
  382. for (var j = 0, jj = path2.length; j < jj; j++) {
  383. var pj = path2[j];
  384. if (pj[0] == 'M') {
  385. x2 = x2m = pj[1];
  386. y2 = y2m = pj[2];
  387. } else {
  388. if (pj[0] == 'C') {
  389. bez2 = [x2, y2].concat(pj.slice(1));
  390. x2 = bez2[6];
  391. y2 = bez2[7];
  392. } else {
  393. bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m];
  394. x2 = x2m;
  395. y2 = y2m;
  396. }
  397. var intr = findBezierIntersections(bez1, bez2, justCount);
  398. if (justCount) {
  399. res += intr;
  400. } else {
  401. for (var k = 0, kk = intr.length; k < kk; k++) {
  402. intr[k].segment1 = i;
  403. intr[k].segment2 = j;
  404. intr[k].bez1 = bez1;
  405. intr[k].bez2 = bez2;
  406. }
  407. res = res.concat(intr);
  408. }
  409. }
  410. }
  411. }
  412. }
  413. return res;
  414. }
  415. function rectPath(x, y, w, h, r) {
  416. if (r) {
  417. return [
  418. ['M', +x + (+r), y],
  419. ['l', w - r * 2, 0],
  420. ['a', r, r, 0, 0, 1, r, r],
  421. ['l', 0, h - r * 2],
  422. ['a', r, r, 0, 0, 1, -r, r],
  423. ['l', r * 2 - w, 0],
  424. ['a', r, r, 0, 0, 1, -r, -r],
  425. ['l', 0, r * 2 - h],
  426. ['a', r, r, 0, 0, 1, r, -r],
  427. ['z']
  428. ];
  429. }
  430. var res = [['M', x, y], ['l', w, 0], ['l', 0, h], ['l', -w, 0], ['z']];
  431. res.toString = pathToString;
  432. return res;
  433. }
  434. function ellipsePath(x, y, rx, ry, a) {
  435. if (a == null && ry == null) {
  436. ry = rx;
  437. }
  438. x = +x;
  439. y = +y;
  440. rx = +rx;
  441. ry = +ry;
  442. if (a != null) {
  443. var rad = Math.PI / 180,
  444. x1 = x + rx * Math.cos(-ry * rad),
  445. x2 = x + rx * Math.cos(-a * rad),
  446. y1 = y + rx * Math.sin(-ry * rad),
  447. y2 = y + rx * Math.sin(-a * rad),
  448. res = [['M', x1, y1], ['A', rx, rx, 0, +(a - ry > 180), 0, x2, y2]];
  449. } else {
  450. res = [
  451. ['M', x, y],
  452. ['m', 0, -ry],
  453. ['a', rx, ry, 0, 1, 1, 0, 2 * ry],
  454. ['a', rx, ry, 0, 1, 1, 0, -2 * ry],
  455. ['z']
  456. ];
  457. }
  458. res.toString = pathToString;
  459. return res;
  460. }
  461. function pathToAbsolute(pathArray) {
  462. var pth = paths(pathArray);
  463. if (pth.abs) {
  464. return pathClone(pth.abs);
  465. }
  466. if (!is(pathArray, 'array') || !is(pathArray && pathArray[0], 'array')) { // rough assumption
  467. pathArray = parsePathString(pathArray);
  468. }
  469. if (!pathArray || !pathArray.length) {
  470. return [['M', 0, 0]];
  471. }
  472. var res = [],
  473. x = 0,
  474. y = 0,
  475. mx = 0,
  476. my = 0,
  477. start = 0,
  478. pa0;
  479. if (pathArray[0][0] == 'M') {
  480. x = +pathArray[0][1];
  481. y = +pathArray[0][2];
  482. mx = x;
  483. my = y;
  484. start++;
  485. res[0] = ['M', x, y];
  486. }
  487. var crz = pathArray.length == 3 &&
  488. pathArray[0][0] == 'M' &&
  489. pathArray[1][0].toUpperCase() == 'R' &&
  490. pathArray[2][0].toUpperCase() == 'Z';
  491. for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
  492. res.push(r = []);
  493. pa = pathArray[i];
  494. pa0 = pa[0];
  495. if (pa0 != pa0.toUpperCase()) {
  496. r[0] = pa0.toUpperCase();
  497. switch (r[0]) {
  498. case 'A':
  499. r[1] = pa[1];
  500. r[2] = pa[2];
  501. r[3] = pa[3];
  502. r[4] = pa[4];
  503. r[5] = pa[5];
  504. r[6] = +pa[6] + x;
  505. r[7] = +pa[7] + y;
  506. break;
  507. case 'V':
  508. r[1] = +pa[1] + y;
  509. break;
  510. case 'H':
  511. r[1] = +pa[1] + x;
  512. break;
  513. case 'R':
  514. var dots = [x, y].concat(pa.slice(1));
  515. for (var j = 2, jj = dots.length; j < jj; j++) {
  516. dots[j] = +dots[j] + x;
  517. dots[++j] = +dots[j] + y;
  518. }
  519. res.pop();
  520. res = res.concat(catmulRomToBezier(dots, crz));
  521. break;
  522. case 'O':
  523. res.pop();
  524. dots = ellipsePath(x, y, pa[1], pa[2]);
  525. dots.push(dots[0]);
  526. res = res.concat(dots);
  527. break;
  528. case 'U':
  529. res.pop();
  530. res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3]));
  531. r = ['U'].concat(res[res.length - 1].slice(-2));
  532. break;
  533. case 'M':
  534. mx = +pa[1] + x;
  535. my = +pa[2] + y;
  536. default:
  537. for (j = 1, jj = pa.length; j < jj; j++) {
  538. r[j] = +pa[j] + ((j % 2) ? x : y);
  539. }
  540. }
  541. } else if (pa0 == 'R') {
  542. dots = [x, y].concat(pa.slice(1));
  543. res.pop();
  544. res = res.concat(catmulRomToBezier(dots, crz));
  545. r = ['R'].concat(pa.slice(-2));
  546. } else if (pa0 == 'O') {
  547. res.pop();
  548. dots = ellipsePath(x, y, pa[1], pa[2]);
  549. dots.push(dots[0]);
  550. res = res.concat(dots);
  551. } else if (pa0 == 'U') {
  552. res.pop();
  553. res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3]));
  554. r = ['U'].concat(res[res.length - 1].slice(-2));
  555. } else {
  556. for (var k = 0, kk = pa.length; k < kk; k++) {
  557. r[k] = pa[k];
  558. }
  559. }
  560. pa0 = pa0.toUpperCase();
  561. if (pa0 != 'O') {
  562. switch (r[0]) {
  563. case 'Z':
  564. x = +mx;
  565. y = +my;
  566. break;
  567. case 'H':
  568. x = r[1];
  569. break;
  570. case 'V':
  571. y = r[1];
  572. break;
  573. case 'M':
  574. mx = r[r.length - 2];
  575. my = r[r.length - 1];
  576. default:
  577. x = r[r.length - 2];
  578. y = r[r.length - 1];
  579. }
  580. }
  581. }
  582. res.toString = pathToString;
  583. pth.abs = pathClone(res);
  584. return res;
  585. }
  586. function lineToCurve(x1, y1, x2, y2) {
  587. return [
  588. x1, y1, x2,
  589. y2, x2, y2
  590. ];
  591. }
  592. function qubicToCurve(x1, y1, ax, ay, x2, y2) {
  593. var _13 = 1 / 3,
  594. _23 = 2 / 3;
  595. return [
  596. _13 * x1 + _23 * ax,
  597. _13 * y1 + _23 * ay,
  598. _13 * x2 + _23 * ax,
  599. _13 * y2 + _23 * ay,
  600. x2,
  601. y2
  602. ];
  603. }
  604. function arcToCurve(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
  605. // for more information of where this math came from visit:
  606. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  607. var _120 = PI * 120 / 180,
  608. rad = PI / 180 * (+angle || 0),
  609. res = [],
  610. xy,
  611. rotate = cacher(function(x, y, rad) {
  612. var X = x * math.cos(rad) - y * math.sin(rad),
  613. Y = x * math.sin(rad) + y * math.cos(rad);
  614. return { x: X, y: Y };
  615. });
  616. if (!recursive) {
  617. xy = rotate(x1, y1, -rad);
  618. x1 = xy.x;
  619. y1 = xy.y;
  620. xy = rotate(x2, y2, -rad);
  621. x2 = xy.x;
  622. y2 = xy.y;
  623. var x = (x1 - x2) / 2,
  624. y = (y1 - y2) / 2;
  625. var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
  626. if (h > 1) {
  627. h = math.sqrt(h);
  628. rx = h * rx;
  629. ry = h * ry;
  630. }
  631. var rx2 = rx * rx,
  632. ry2 = ry * ry,
  633. k = (large_arc_flag == sweep_flag ? -1 : 1) *
  634. math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
  635. cx = k * rx * y / ry + (x1 + x2) / 2,
  636. cy = k * -ry * x / rx + (y1 + y2) / 2,
  637. f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
  638. f2 = math.asin(((y2 - cy) / ry).toFixed(9));
  639. f1 = x1 < cx ? PI - f1 : f1;
  640. f2 = x2 < cx ? PI - f2 : f2;
  641. f1 < 0 && (f1 = PI * 2 + f1);
  642. f2 < 0 && (f2 = PI * 2 + f2);
  643. if (sweep_flag && f1 > f2) {
  644. f1 = f1 - PI * 2;
  645. }
  646. if (!sweep_flag && f2 > f1) {
  647. f2 = f2 - PI * 2;
  648. }
  649. } else {
  650. f1 = recursive[0];
  651. f2 = recursive[1];
  652. cx = recursive[2];
  653. cy = recursive[3];
  654. }
  655. var df = f2 - f1;
  656. if (abs(df) > _120) {
  657. var f2old = f2,
  658. x2old = x2,
  659. y2old = y2;
  660. f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
  661. x2 = cx + rx * math.cos(f2);
  662. y2 = cy + ry * math.sin(f2);
  663. res = arcToCurve(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
  664. }
  665. df = f2 - f1;
  666. var c1 = math.cos(f1),
  667. s1 = math.sin(f1),
  668. c2 = math.cos(f2),
  669. s2 = math.sin(f2),
  670. t = math.tan(df / 4),
  671. hx = 4 / 3 * rx * t,
  672. hy = 4 / 3 * ry * t,
  673. m1 = [x1, y1],
  674. m2 = [x1 + hx * s1, y1 - hy * c1],
  675. m3 = [x2 + hx * s2, y2 - hy * c2],
  676. m4 = [x2, y2];
  677. m2[0] = 2 * m1[0] - m2[0];
  678. m2[1] = 2 * m1[1] - m2[1];
  679. if (recursive) {
  680. return [m2, m3, m4].concat(res);
  681. } else {
  682. res = [m2, m3, m4].concat(res).join().split(',');
  683. var newres = [];
  684. for (var i = 0, ii = res.length; i < ii; i++) {
  685. newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
  686. }
  687. return newres;
  688. }
  689. }
  690. // http://schepers.cc/getting-to-the-point
  691. function catmulRomToBezier(crp, z) {
  692. var d = [];
  693. for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
  694. var p = [
  695. { x: +crp[i - 2], y: +crp[i - 1] },
  696. { x: +crp[i], y: +crp[i + 1] },
  697. { x: +crp[i + 2], y: +crp[i + 3] },
  698. { x: +crp[i + 4], y: +crp[i + 5] }
  699. ];
  700. if (z) {
  701. if (!i) {
  702. p[0] = { x: +crp[iLen - 2], y: +crp[iLen - 1] };
  703. } else if (iLen - 4 == i) {
  704. p[3] = { x: +crp[0], y: +crp[1] };
  705. } else if (iLen - 2 == i) {
  706. p[2] = { x: +crp[0], y: +crp[1] };
  707. p[3] = { x: +crp[2], y: +crp[3] };
  708. }
  709. } else {
  710. if (iLen - 4 == i) {
  711. p[3] = p[2];
  712. } else if (!i) {
  713. p[0] = { x: +crp[i], y: +crp[i + 1] };
  714. }
  715. }
  716. d.push(['C',
  717. (-p[0].x + 6 * p[1].x + p[2].x) / 6,
  718. (-p[0].y + 6 * p[1].y + p[2].y) / 6,
  719. (p[1].x + 6 * p[2].x - p[3].x) / 6,
  720. (p[1].y + 6*p[2].y - p[3].y) / 6,
  721. p[2].x,
  722. p[2].y
  723. ]);
  724. }
  725. return d;
  726. }
  727. // Returns bounding box of cubic bezier curve.
  728. // Source: http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
  729. // Original version: NISHIO Hirokazu
  730. // Modifications: https://github.com/timo22345
  731. function curveBBox(x0, y0, x1, y1, x2, y2, x3, y3) {
  732. var tvalues = [],
  733. bounds = [[], []],
  734. a, b, c, t, t1, t2, b2ac, sqrtb2ac;
  735. for (var i = 0; i < 2; ++i) {
  736. if (i == 0) {
  737. b = 6 * x0 - 12 * x1 + 6 * x2;
  738. a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
  739. c = 3 * x1 - 3 * x0;
  740. } else {
  741. b = 6 * y0 - 12 * y1 + 6 * y2;
  742. a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
  743. c = 3 * y1 - 3 * y0;
  744. }
  745. if (abs(a) < 1e-12) {
  746. if (abs(b) < 1e-12) {
  747. continue;
  748. }
  749. t = -c / b;
  750. if (0 < t && t < 1) {
  751. tvalues.push(t);
  752. }
  753. continue;
  754. }
  755. b2ac = b * b - 4 * c * a;
  756. sqrtb2ac = math.sqrt(b2ac);
  757. if (b2ac < 0) {
  758. continue;
  759. }
  760. t1 = (-b + sqrtb2ac) / (2 * a);
  761. if (0 < t1 && t1 < 1) {
  762. tvalues.push(t1);
  763. }
  764. t2 = (-b - sqrtb2ac) / (2 * a);
  765. if (0 < t2 && t2 < 1) {
  766. tvalues.push(t2);
  767. }
  768. }
  769. var j = tvalues.length,
  770. jlen = j,
  771. mt;
  772. while (j--) {
  773. t = tvalues[j];
  774. mt = 1 - t;
  775. bounds[0][j] = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
  776. bounds[1][j] = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
  777. }
  778. bounds[0][jlen] = x0;
  779. bounds[1][jlen] = y0;
  780. bounds[0][jlen + 1] = x3;
  781. bounds[1][jlen + 1] = y3;
  782. bounds[0].length = bounds[1].length = jlen + 2;
  783. return {
  784. min: { x: mmin.apply(0, bounds[0]), y: mmin.apply(0, bounds[1]) },
  785. max: { x: mmax.apply(0, bounds[0]), y: mmax.apply(0, bounds[1]) }
  786. };
  787. }
  788. function pathToCurve(path, path2) {
  789. var pth = !path2 && paths(path);
  790. if (!path2 && pth.curve) {
  791. return pathClone(pth.curve);
  792. }
  793. var p = pathToAbsolute(path),
  794. p2 = path2 && pathToAbsolute(path2),
  795. attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null },
  796. attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null },
  797. processPath = function(path, d, pcom) {
  798. var nx, ny;
  799. if (!path) {
  800. return ['C', d.x, d.y, d.x, d.y, d.x, d.y];
  801. }
  802. !(path[0] in { T: 1, Q: 1 }) && (d.qx = d.qy = null);
  803. switch (path[0]) {
  804. case 'M':
  805. d.X = path[1];
  806. d.Y = path[2];
  807. break;
  808. case 'A':
  809. path = ['C'].concat(arcToCurve.apply(0, [d.x, d.y].concat(path.slice(1))));
  810. break;
  811. case 'S':
  812. if (pcom == 'C' || pcom == 'S') {
  813. // In 'S' case we have to take into account, if the previous command is C/S.
  814. nx = d.x * 2 - d.bx;
  815. // And reflect the previous
  816. ny = d.y * 2 - d.by;
  817. // command's control point relative to the current point.
  818. }
  819. else {
  820. // or some else or nothing
  821. nx = d.x;
  822. ny = d.y;
  823. }
  824. path = ['C', nx, ny].concat(path.slice(1));
  825. break;
  826. case 'T':
  827. if (pcom == 'Q' || pcom == 'T') {
  828. // In 'T' case we have to take into account, if the previous command is Q/T.
  829. d.qx = d.x * 2 - d.qx;
  830. // And make a reflection similar
  831. d.qy = d.y * 2 - d.qy;
  832. // to case 'S'.
  833. }
  834. else {
  835. // or something else or nothing
  836. d.qx = d.x;
  837. d.qy = d.y;
  838. }
  839. path = ['C'].concat(qubicToCurve(d.x, d.y, d.qx, d.qy, path[1], path[2]));
  840. break;
  841. case 'Q':
  842. d.qx = path[1];
  843. d.qy = path[2];
  844. path = ['C'].concat(qubicToCurve(d.x, d.y, path[1], path[2], path[3], path[4]));
  845. break;
  846. case 'L':
  847. path = ['C'].concat(lineToCurve(d.x, d.y, path[1], path[2]));
  848. break;
  849. case 'H':
  850. path = ['C'].concat(lineToCurve(d.x, d.y, path[1], d.y));
  851. break;
  852. case 'V':
  853. path = ['C'].concat(lineToCurve(d.x, d.y, d.x, path[1]));
  854. break;
  855. case 'Z':
  856. path = ['C'].concat(lineToCurve(d.x, d.y, d.X, d.Y));
  857. break;
  858. }
  859. return path;
  860. },
  861. fixArc = function(pp, i) {
  862. if (pp[i].length > 7) {
  863. pp[i].shift();
  864. var pi = pp[i];
  865. while (pi.length) {
  866. pcoms1[i] = 'A'; // if created multiple C:s, their original seg is saved
  867. p2 && (pcoms2[i] = 'A'); // the same as above
  868. pp.splice(i++, 0, ['C'].concat(pi.splice(0, 6)));
  869. }
  870. pp.splice(i, 1);
  871. ii = mmax(p.length, p2 && p2.length || 0);
  872. }
  873. },
  874. fixM = function(path1, path2, a1, a2, i) {
  875. if (path1 && path2 && path1[i][0] == 'M' && path2[i][0] != 'M') {
  876. path2.splice(i, 0, ['M', a2.x, a2.y]);
  877. a1.bx = 0;
  878. a1.by = 0;
  879. a1.x = path1[i][1];
  880. a1.y = path1[i][2];
  881. ii = mmax(p.length, p2 && p2.length || 0);
  882. }
  883. },
  884. pcoms1 = [], // path commands of original path p
  885. pcoms2 = [], // path commands of original path p2
  886. pfirst = '', // temporary holder for original path command
  887. pcom = ''; // holder for previous path command of original path
  888. for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
  889. p[i] && (pfirst = p[i][0]); // save current path command
  890. if (pfirst != 'C') // C is not saved yet, because it may be result of conversion
  891. {
  892. pcoms1[i] = pfirst; // Save current path command
  893. i && (pcom = pcoms1[i - 1]); // Get previous path command pcom
  894. }
  895. p[i] = processPath(p[i], attrs, pcom); // Previous path command is inputted to processPath
  896. if (pcoms1[i] != 'A' && pfirst == 'C') pcoms1[i] = 'C'; // A is the only command
  897. // which may produce multiple C:s
  898. // so we have to make sure that C is also C in original path
  899. fixArc(p, i); // fixArc adds also the right amount of A:s to pcoms1
  900. if (p2) { // the same procedures is done to p2
  901. p2[i] && (pfirst = p2[i][0]);
  902. if (pfirst != 'C') {
  903. pcoms2[i] = pfirst;
  904. i && (pcom = pcoms2[i - 1]);
  905. }
  906. p2[i] = processPath(p2[i], attrs2, pcom);
  907. if (pcoms2[i] != 'A' && pfirst == 'C') {
  908. pcoms2[i] = 'C';
  909. }
  910. fixArc(p2, i);
  911. }
  912. fixM(p, p2, attrs, attrs2, i);
  913. fixM(p2, p, attrs2, attrs, i);
  914. var seg = p[i],
  915. seg2 = p2 && p2[i],
  916. seglen = seg.length,
  917. seg2len = p2 && seg2.length;
  918. attrs.x = seg[seglen - 2];
  919. attrs.y = seg[seglen - 1];
  920. attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
  921. attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
  922. attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
  923. attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
  924. attrs2.x = p2 && seg2[seg2len - 2];
  925. attrs2.y = p2 && seg2[seg2len - 1];
  926. }
  927. if (!p2) {
  928. pth.curve = pathClone(p);
  929. }
  930. return p2 ? [p, p2] : p;
  931. }
  932. module.exports = findPathIntersections;