_path.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. /* global a2c */
  2. 'use strict';
  3. var regPathInstructions = /([MmLlHhVvCcSsQqTtAaZz])\s*/,
  4. regPathData = /[-+]?(?:\d*\.\d+|\d+\.?)([eE][-+]?\d+)?/g,
  5. regNumericValues = /[-+]?(\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/,
  6. transform2js = require('./_transforms').transform2js,
  7. transformsMultiply = require('./_transforms').transformsMultiply,
  8. transformArc = require('./_transforms').transformArc,
  9. collections = require('./_collections.js'),
  10. referencesProps = collections.referencesProps,
  11. defaultStrokeWidth = collections.attrsGroupsDefaults.presentation['stroke-width'],
  12. cleanupOutData = require('../lib/svgo/tools').cleanupOutData,
  13. removeLeadingZero = require('../lib/svgo/tools').removeLeadingZero,
  14. prevCtrlPoint;
  15. /**
  16. * Convert path string to JS representation.
  17. *
  18. * @param {String} pathString input string
  19. * @param {Object} params plugin params
  20. * @return {Array} output array
  21. */
  22. exports.path2js = function(path) {
  23. if (path.pathJS) return path.pathJS;
  24. var paramsLength = { // Number of parameters of every path command
  25. H: 1, V: 1, M: 2, L: 2, T: 2, Q: 4, S: 4, C: 6, A: 7,
  26. h: 1, v: 1, m: 2, l: 2, t: 2, q: 4, s: 4, c: 6, a: 7
  27. },
  28. pathData = [], // JS representation of the path data
  29. instruction, // current instruction context
  30. startMoveto = false;
  31. // splitting path string into array like ['M', '10 50', 'L', '20 30']
  32. path.attr('d').value.split(regPathInstructions).forEach(function(data) {
  33. if (!data) return;
  34. if (!startMoveto) {
  35. if (data == 'M' || data == 'm') {
  36. startMoveto = true;
  37. } else return;
  38. }
  39. // instruction item
  40. if (regPathInstructions.test(data)) {
  41. instruction = data;
  42. // z - instruction w/o data
  43. if (instruction == 'Z' || instruction == 'z') {
  44. pathData.push({
  45. instruction: 'z'
  46. });
  47. }
  48. // data item
  49. } else {
  50. data = data.match(regPathData);
  51. if (!data) return;
  52. data = data.map(Number);
  53. // Subsequent moveto pairs of coordinates are threated as implicit lineto commands
  54. // http://www.w3.org/TR/SVG/paths.html#PathDataMovetoCommands
  55. if (instruction == 'M' || instruction == 'm') {
  56. pathData.push({
  57. instruction: pathData.length == 0 ? 'M' : instruction,
  58. data: data.splice(0, 2)
  59. });
  60. instruction = instruction == 'M' ? 'L' : 'l';
  61. }
  62. for (var pair = paramsLength[instruction]; data.length;) {
  63. pathData.push({
  64. instruction: instruction,
  65. data: data.splice(0, pair)
  66. });
  67. }
  68. }
  69. });
  70. // First moveto is actually absolute. Subsequent coordinates were separated above.
  71. if (pathData.length && pathData[0].instruction == 'm') {
  72. pathData[0].instruction = 'M';
  73. }
  74. path.pathJS = pathData;
  75. return pathData;
  76. };
  77. /**
  78. * Convert relative Path data to absolute.
  79. *
  80. * @param {Array} data input data
  81. * @return {Array} output data
  82. */
  83. var relative2absolute = exports.relative2absolute = function(data) {
  84. var currentPoint = [0, 0],
  85. subpathPoint = [0, 0],
  86. i;
  87. data = data.map(function(item) {
  88. var instruction = item.instruction,
  89. itemData = item.data && item.data.slice();
  90. if (instruction == 'M') {
  91. set(currentPoint, itemData);
  92. set(subpathPoint, itemData);
  93. } else if ('mlcsqt'.indexOf(instruction) > -1) {
  94. for (i = 0; i < itemData.length; i++) {
  95. itemData[i] += currentPoint[i % 2];
  96. }
  97. set(currentPoint, itemData);
  98. if (instruction == 'm') {
  99. set(subpathPoint, itemData);
  100. }
  101. } else if (instruction == 'a') {
  102. itemData[5] += currentPoint[0];
  103. itemData[6] += currentPoint[1];
  104. set(currentPoint, itemData);
  105. } else if (instruction == 'h') {
  106. itemData[0] += currentPoint[0];
  107. currentPoint[0] = itemData[0];
  108. } else if (instruction == 'v') {
  109. itemData[0] += currentPoint[1];
  110. currentPoint[1] = itemData[0];
  111. } else if ('MZLCSQTA'.indexOf(instruction) > -1) {
  112. set(currentPoint, itemData);
  113. } else if (instruction == 'H') {
  114. currentPoint[0] = itemData[0];
  115. } else if (instruction == 'V') {
  116. currentPoint[1] = itemData[0];
  117. } else if (instruction == 'z') {
  118. set(currentPoint, subpathPoint);
  119. }
  120. return instruction == 'z' ?
  121. { instruction: 'z' } :
  122. {
  123. instruction: instruction.toUpperCase(),
  124. data: itemData
  125. };
  126. });
  127. return data;
  128. };
  129. /**
  130. * Apply transformation(s) to the Path data.
  131. *
  132. * @param {Object} elem current element
  133. * @param {Array} path input path data
  134. * @param {Object} params whether to apply transforms to stroked lines and transform precision (used for stroke width)
  135. * @return {Array} output path data
  136. */
  137. exports.applyTransforms = function(elem, path, params) {
  138. // if there are no 'stroke' attr and references to other objects such as
  139. // gradiends or clip-path which are also subjects to transform.
  140. if (!elem.hasAttr('transform') || !elem.attr('transform').value ||
  141. elem.someAttr(function(attr) {
  142. return ~referencesProps.indexOf(attr.name) && ~attr.value.indexOf('url(');
  143. }))
  144. return path;
  145. var matrix = transformsMultiply(transform2js(elem.attr('transform').value)),
  146. stroke = elem.computedAttr('stroke'),
  147. id = elem.computedAttr('id'),
  148. transformPrecision = params.transformPrecision,
  149. newPoint, scale;
  150. if (stroke && stroke != 'none') {
  151. if (!params.applyTransformsStroked ||
  152. (matrix.data[0] != matrix.data[3] || matrix.data[1] != -matrix.data[2]) &&
  153. (matrix.data[0] != -matrix.data[3] || matrix.data[1] != matrix.data[2]))
  154. return path;
  155. // "stroke-width" should be inside the part with ID, otherwise it can be overrided in <use>
  156. if (id) {
  157. var idElem = elem,
  158. hasStrokeWidth = false;
  159. do {
  160. if (idElem.hasAttr('stroke-width')) hasStrokeWidth = true;
  161. } while (!idElem.hasAttr('id', id) && !hasStrokeWidth && (idElem = idElem.parentNode));
  162. if (!hasStrokeWidth) return path;
  163. }
  164. scale = +Math.sqrt(matrix.data[0] * matrix.data[0] + matrix.data[1] * matrix.data[1]).toFixed(transformPrecision);
  165. if (scale !== 1) {
  166. var strokeWidth = elem.computedAttr('stroke-width') || defaultStrokeWidth;
  167. if (elem.hasAttr('stroke-width')) {
  168. elem.attrs['stroke-width'].value = elem.attrs['stroke-width'].value.trim()
  169. .replace(regNumericValues, function(num) { return removeLeadingZero(num * scale) });
  170. } else {
  171. elem.addAttr({
  172. name: 'stroke-width',
  173. prefix: '',
  174. local: 'stroke-width',
  175. value: strokeWidth.replace(regNumericValues, function(num) { return removeLeadingZero(num * scale) })
  176. });
  177. }
  178. }
  179. } else if (id) { // Stroke and stroke-width can be redefined with <use>
  180. return path;
  181. }
  182. path.forEach(function(pathItem) {
  183. if (pathItem.data) {
  184. // h -> l
  185. if (pathItem.instruction === 'h') {
  186. pathItem.instruction = 'l';
  187. pathItem.data[1] = 0;
  188. // v -> l
  189. } else if (pathItem.instruction === 'v') {
  190. pathItem.instruction = 'l';
  191. pathItem.data[1] = pathItem.data[0];
  192. pathItem.data[0] = 0;
  193. }
  194. // if there is a translate() transform
  195. if (pathItem.instruction === 'M' &&
  196. (matrix.data[4] !== 0 ||
  197. matrix.data[5] !== 0)
  198. ) {
  199. // then apply it only to the first absoluted M
  200. newPoint = transformPoint(matrix.data, pathItem.data[0], pathItem.data[1]);
  201. set(pathItem.data, newPoint);
  202. set(pathItem.coords, newPoint);
  203. // clear translate() data from transform matrix
  204. matrix.data[4] = 0;
  205. matrix.data[5] = 0;
  206. } else {
  207. if (pathItem.instruction == 'a') {
  208. transformArc(pathItem.data, matrix.data);
  209. // reduce number of digits in rotation angle
  210. if (Math.abs(pathItem.data[2]) > 80) {
  211. var a = pathItem.data[0],
  212. rotation = pathItem.data[2];
  213. pathItem.data[0] = pathItem.data[1];
  214. pathItem.data[1] = a;
  215. pathItem.data[2] = rotation + (rotation > 0 ? -90 : 90);
  216. }
  217. newPoint = transformPoint(matrix.data, pathItem.data[5], pathItem.data[6]);
  218. pathItem.data[5] = newPoint[0];
  219. pathItem.data[6] = newPoint[1];
  220. } else {
  221. for (var i = 0; i < pathItem.data.length; i += 2) {
  222. newPoint = transformPoint(matrix.data, pathItem.data[i], pathItem.data[i + 1]);
  223. pathItem.data[i] = newPoint[0];
  224. pathItem.data[i + 1] = newPoint[1];
  225. }
  226. }
  227. pathItem.coords[0] = pathItem.base[0] + pathItem.data[pathItem.data.length - 2];
  228. pathItem.coords[1] = pathItem.base[1] + pathItem.data[pathItem.data.length - 1];
  229. }
  230. }
  231. });
  232. // remove transform attr
  233. elem.removeAttr('transform');
  234. return path;
  235. };
  236. /**
  237. * Apply transform 3x3 matrix to x-y point.
  238. *
  239. * @param {Array} matrix transform 3x3 matrix
  240. * @param {Array} point x-y point
  241. * @return {Array} point with new coordinates
  242. */
  243. function transformPoint(matrix, x, y) {
  244. return [
  245. matrix[0] * x + matrix[2] * y + matrix[4],
  246. matrix[1] * x + matrix[3] * y + matrix[5]
  247. ];
  248. }
  249. /**
  250. * Compute Cubic Bézie bounding box.
  251. *
  252. * @see http://processingjs.nihongoresources.com/bezierinfo/
  253. *
  254. * @param {Float} xa
  255. * @param {Float} ya
  256. * @param {Float} xb
  257. * @param {Float} yb
  258. * @param {Float} xc
  259. * @param {Float} yc
  260. * @param {Float} xd
  261. * @param {Float} yd
  262. *
  263. * @return {Object}
  264. */
  265. exports.computeCubicBoundingBox = function(xa, ya, xb, yb, xc, yc, xd, yd) {
  266. var minx = Number.POSITIVE_INFINITY,
  267. miny = Number.POSITIVE_INFINITY,
  268. maxx = Number.NEGATIVE_INFINITY,
  269. maxy = Number.NEGATIVE_INFINITY,
  270. ts,
  271. t,
  272. x,
  273. y,
  274. i;
  275. // X
  276. if (xa < minx) { minx = xa; }
  277. if (xa > maxx) { maxx = xa; }
  278. if (xd < minx) { minx= xd; }
  279. if (xd > maxx) { maxx = xd; }
  280. ts = computeCubicFirstDerivativeRoots(xa, xb, xc, xd);
  281. for (i = 0; i < ts.length; i++) {
  282. t = ts[i];
  283. if (t >= 0 && t <= 1) {
  284. x = computeCubicBaseValue(t, xa, xb, xc, xd);
  285. // y = computeCubicBaseValue(t, ya, yb, yc, yd);
  286. if (x < minx) { minx = x; }
  287. if (x > maxx) { maxx = x; }
  288. }
  289. }
  290. // Y
  291. if (ya < miny) { miny = ya; }
  292. if (ya > maxy) { maxy = ya; }
  293. if (yd < miny) { miny = yd; }
  294. if (yd > maxy) { maxy = yd; }
  295. ts = computeCubicFirstDerivativeRoots(ya, yb, yc, yd);
  296. for (i = 0; i < ts.length; i++) {
  297. t = ts[i];
  298. if (t >= 0 && t <= 1) {
  299. // x = computeCubicBaseValue(t, xa, xb, xc, xd);
  300. y = computeCubicBaseValue(t, ya, yb, yc, yd);
  301. if (y < miny) { miny = y; }
  302. if (y > maxy) { maxy = y; }
  303. }
  304. }
  305. return {
  306. minx: minx,
  307. miny: miny,
  308. maxx: maxx,
  309. maxy: maxy
  310. };
  311. };
  312. // compute the value for the cubic bezier function at time=t
  313. function computeCubicBaseValue(t, a, b, c, d) {
  314. var mt = 1 - t;
  315. return mt * mt * mt * a + 3 * mt * mt * t * b + 3 * mt * t * t * c + t * t * t * d;
  316. }
  317. // compute the value for the first derivative of the cubic bezier function at time=t
  318. function computeCubicFirstDerivativeRoots(a, b, c, d) {
  319. var result = [-1, -1],
  320. tl = -a + 2 * b - c,
  321. tr = -Math.sqrt(-a * (c - d) + b * b - b * (c + d) + c * c),
  322. dn = -a + 3 * b - 3 * c + d;
  323. if (dn !== 0) {
  324. result[0] = (tl + tr) / dn;
  325. result[1] = (tl - tr) / dn;
  326. }
  327. return result;
  328. }
  329. /**
  330. * Compute Quadratic Bézier bounding box.
  331. *
  332. * @see http://processingjs.nihongoresources.com/bezierinfo/
  333. *
  334. * @param {Float} xa
  335. * @param {Float} ya
  336. * @param {Float} xb
  337. * @param {Float} yb
  338. * @param {Float} xc
  339. * @param {Float} yc
  340. *
  341. * @return {Object}
  342. */
  343. exports.computeQuadraticBoundingBox = function(xa, ya, xb, yb, xc, yc) {
  344. var minx = Number.POSITIVE_INFINITY,
  345. miny = Number.POSITIVE_INFINITY,
  346. maxx = Number.NEGATIVE_INFINITY,
  347. maxy = Number.NEGATIVE_INFINITY,
  348. t,
  349. x,
  350. y;
  351. // X
  352. if (xa < minx) { minx = xa; }
  353. if (xa > maxx) { maxx = xa; }
  354. if (xc < minx) { minx = xc; }
  355. if (xc > maxx) { maxx = xc; }
  356. t = computeQuadraticFirstDerivativeRoot(xa, xb, xc);
  357. if (t >= 0 && t <= 1) {
  358. x = computeQuadraticBaseValue(t, xa, xb, xc);
  359. // y = computeQuadraticBaseValue(t, ya, yb, yc);
  360. if (x < minx) { minx = x; }
  361. if (x > maxx) { maxx = x; }
  362. }
  363. // Y
  364. if (ya < miny) { miny = ya; }
  365. if (ya > maxy) { maxy = ya; }
  366. if (yc < miny) { miny = yc; }
  367. if (yc > maxy) { maxy = yc; }
  368. t = computeQuadraticFirstDerivativeRoot(ya, yb, yc);
  369. if (t >= 0 && t <=1 ) {
  370. // x = computeQuadraticBaseValue(t, xa, xb, xc);
  371. y = computeQuadraticBaseValue(t, ya, yb, yc);
  372. if (y < miny) { miny = y; }
  373. if (y > maxy) { maxy = y ; }
  374. }
  375. return {
  376. minx: minx,
  377. miny: miny,
  378. maxx: maxx,
  379. maxy: maxy
  380. };
  381. };
  382. // compute the value for the quadratic bezier function at time=t
  383. function computeQuadraticBaseValue(t, a, b, c) {
  384. var mt = 1 - t;
  385. return mt * mt * a + 2 * mt * t * b + t * t * c;
  386. }
  387. // compute the value for the first derivative of the quadratic bezier function at time=t
  388. function computeQuadraticFirstDerivativeRoot(a, b, c) {
  389. var t = -1,
  390. denominator = a - 2 * b + c;
  391. if (denominator !== 0) {
  392. t = (a - b) / denominator;
  393. }
  394. return t;
  395. }
  396. /**
  397. * Convert path array to string.
  398. *
  399. * @param {Array} path input path data
  400. * @param {Object} params plugin params
  401. * @return {String} output path string
  402. */
  403. exports.js2path = function(path, data, params) {
  404. path.pathJS = data;
  405. if (params.collapseRepeated) {
  406. data = collapseRepeated(data);
  407. }
  408. path.attr('d').value = data.reduce(function(pathString, item) {
  409. return pathString += item.instruction + (item.data ? cleanupOutData(item.data, params) : '');
  410. }, '');
  411. };
  412. /**
  413. * Collapse repeated instructions data
  414. *
  415. * @param {Array} path input path data
  416. * @return {Array} output path data
  417. */
  418. function collapseRepeated(data) {
  419. var prev,
  420. prevIndex;
  421. // copy an array and modifieds item to keep original data untouched
  422. data = data.reduce(function(newPath, item) {
  423. if (
  424. prev && item.data &&
  425. item.instruction == prev.instruction
  426. ) {
  427. // concat previous data with current
  428. if (item.instruction != 'M') {
  429. prev = newPath[prevIndex] = {
  430. instruction: prev.instruction,
  431. data: prev.data.concat(item.data),
  432. coords: item.coords,
  433. base: prev.base
  434. };
  435. } else {
  436. prev.data = item.data;
  437. prev.coords = item.coords;
  438. }
  439. } else {
  440. newPath.push(item);
  441. prev = item;
  442. prevIndex = newPath.length - 1;
  443. }
  444. return newPath;
  445. }, []);
  446. return data;
  447. }
  448. function set(dest, source) {
  449. dest[0] = source[source.length - 2];
  450. dest[1] = source[source.length - 1];
  451. return dest;
  452. }
  453. /**
  454. * Checks if two paths have an intersection by checking convex hulls
  455. * collision using Gilbert-Johnson-Keerthi distance algorithm
  456. * http://entropyinteractive.com/2011/04/gjk-algorithm/
  457. *
  458. * @param {Array} path1 JS path representation
  459. * @param {Array} path2 JS path representation
  460. * @return {Boolean}
  461. */
  462. exports.intersects = function(path1, path2) {
  463. if (path1.length < 3 || path2.length < 3) return false; // nothing to fill
  464. // Collect points of every subpath.
  465. var points1 = relative2absolute(path1).reduce(gatherPoints, []),
  466. points2 = relative2absolute(path2).reduce(gatherPoints, []);
  467. // Axis-aligned bounding box check.
  468. if (points1.maxX <= points2.minX || points2.maxX <= points1.minX ||
  469. points1.maxY <= points2.minY || points2.maxY <= points1.minY ||
  470. points1.every(function (set1) {
  471. return points2.every(function (set2) {
  472. return set1[set1.maxX][0] <= set2[set2.minX][0] ||
  473. set2[set2.maxX][0] <= set1[set1.minX][0] ||
  474. set1[set1.maxY][1] <= set2[set2.minY][1] ||
  475. set2[set2.maxY][1] <= set1[set1.minY][1];
  476. });
  477. })
  478. ) return false;
  479. // Get a convex hull from points of each subpath. Has the most complexity O(n·log n).
  480. var hullNest1 = points1.map(convexHull),
  481. hullNest2 = points2.map(convexHull);
  482. // Check intersection of every subpath of the first path with every subpath of the second.
  483. return hullNest1.some(function(hull1) {
  484. if (hull1.length < 3) return false;
  485. return hullNest2.some(function(hull2) {
  486. if (hull2.length < 3) return false;
  487. var simplex = [getSupport(hull1, hull2, [1, 0])], // create the initial simplex
  488. direction = minus(simplex[0]); // set the direction to point towards the origin
  489. var iterations = 1e4; // infinite loop protection, 10 000 iterations is more than enough
  490. while (true) {
  491. if (iterations-- == 0) {
  492. console.error('Error: infinite loop while processing mergePaths plugin.');
  493. return true; // true is the safe value that means “do nothing with paths”
  494. }
  495. // add a new point
  496. simplex.push(getSupport(hull1, hull2, direction));
  497. // see if the new point was on the correct side of the origin
  498. if (dot(direction, simplex[simplex.length - 1]) <= 0) return false;
  499. // process the simplex
  500. if (processSimplex(simplex, direction)) return true;
  501. }
  502. });
  503. });
  504. function getSupport(a, b, direction) {
  505. return sub(supportPoint(a, direction), supportPoint(b, minus(direction)));
  506. }
  507. // Computes farthest polygon point in particular direction.
  508. // Thanks to knowledge of min/max x and y coordinates we can choose a quadrant to search in.
  509. // Since we're working on convex hull, the dot product is increasing until we find the farthest point.
  510. function supportPoint(polygon, direction) {
  511. var index = direction[1] >= 0 ?
  512. direction[0] < 0 ? polygon.maxY : polygon.maxX :
  513. direction[0] < 0 ? polygon.minX : polygon.minY,
  514. max = -Infinity,
  515. value;
  516. while ((value = dot(polygon[index], direction)) > max) {
  517. max = value;
  518. index = ++index % polygon.length;
  519. }
  520. return polygon[(index || polygon.length) - 1];
  521. }
  522. };
  523. function processSimplex(simplex, direction) {
  524. /* jshint -W004 */
  525. // we only need to handle to 1-simplex and 2-simplex
  526. if (simplex.length == 2) { // 1-simplex
  527. var a = simplex[1],
  528. b = simplex[0],
  529. AO = minus(simplex[1]),
  530. AB = sub(b, a);
  531. // AO is in the same direction as AB
  532. if (dot(AO, AB) > 0) {
  533. // get the vector perpendicular to AB facing O
  534. set(direction, orth(AB, a));
  535. } else {
  536. set(direction, AO);
  537. // only A remains in the simplex
  538. simplex.shift();
  539. }
  540. } else { // 2-simplex
  541. var a = simplex[2], // [a, b, c] = simplex
  542. b = simplex[1],
  543. c = simplex[0],
  544. AB = sub(b, a),
  545. AC = sub(c, a),
  546. AO = minus(a),
  547. ACB = orth(AB, AC), // the vector perpendicular to AB facing away from C
  548. ABC = orth(AC, AB); // the vector perpendicular to AC facing away from B
  549. if (dot(ACB, AO) > 0) {
  550. if (dot(AB, AO) > 0) { // region 4
  551. set(direction, ACB);
  552. simplex.shift(); // simplex = [b, a]
  553. } else { // region 5
  554. set(direction, AO);
  555. simplex.splice(0, 2); // simplex = [a]
  556. }
  557. } else if (dot(ABC, AO) > 0) {
  558. if (dot(AC, AO) > 0) { // region 6
  559. set(direction, ABC);
  560. simplex.splice(1, 1); // simplex = [c, a]
  561. } else { // region 5 (again)
  562. set(direction, AO);
  563. simplex.splice(0, 2); // simplex = [a]
  564. }
  565. } else // region 7
  566. return true;
  567. }
  568. return false;
  569. }
  570. function minus(v) {
  571. return [-v[0], -v[1]];
  572. }
  573. function sub(v1, v2) {
  574. return [v1[0] - v2[0], v1[1] - v2[1]];
  575. }
  576. function dot(v1, v2) {
  577. return v1[0] * v2[0] + v1[1] * v2[1];
  578. }
  579. function orth(v, from) {
  580. var o = [-v[1], v[0]];
  581. return dot(o, minus(from)) < 0 ? minus(o) : o;
  582. }
  583. function gatherPoints(points, item, index, path) {
  584. var subPath = points.length && points[points.length - 1],
  585. prev = index && path[index - 1],
  586. basePoint = subPath.length && subPath[subPath.length - 1],
  587. data = item.data,
  588. ctrlPoint = basePoint;
  589. switch (item.instruction) {
  590. case 'M':
  591. points.push(subPath = []);
  592. break;
  593. case 'H':
  594. addPoint(subPath, [data[0], basePoint[1]]);
  595. break;
  596. case 'V':
  597. addPoint(subPath, [basePoint[0], data[0]]);
  598. break;
  599. case 'Q':
  600. addPoint(subPath, data.slice(0, 2));
  601. prevCtrlPoint = [data[2] - data[0], data[3] - data[1]]; // Save control point for shorthand
  602. break;
  603. case 'T':
  604. if (prev.instruction == 'Q' && prev.instruction == 'T') {
  605. ctrlPoint = [basePoint[0] + prevCtrlPoint[0], basePoint[1] + prevCtrlPoint[1]];
  606. addPoint(subPath, ctrlPoint);
  607. prevCtrlPoint = [data[0] - ctrlPoint[0], data[1] - ctrlPoint[1]];
  608. }
  609. break;
  610. case 'C':
  611. // Approximate quibic Bezier curve with middle points between control points
  612. addPoint(subPath, [.5 * (basePoint[0] + data[0]), .5 * (basePoint[1] + data[1])]);
  613. addPoint(subPath, [.5 * (data[0] + data[2]), .5 * (data[1] + data[3])]);
  614. addPoint(subPath, [.5 * (data[2] + data[4]), .5 * (data[3] + data[5])]);
  615. prevCtrlPoint = [data[4] - data[2], data[5] - data[3]]; // Save control point for shorthand
  616. break;
  617. case 'S':
  618. if (prev.instruction == 'C' && prev.instruction == 'S') {
  619. addPoint(subPath, [basePoint[0] + .5 * prevCtrlPoint[0], basePoint[1] + .5 * prevCtrlPoint[1]]);
  620. ctrlPoint = [basePoint[0] + prevCtrlPoint[0], basePoint[1] + prevCtrlPoint[1]];
  621. }
  622. addPoint(subPath, [.5 * (ctrlPoint[0] + data[0]), .5 * (ctrlPoint[1]+ data[1])]);
  623. addPoint(subPath, [.5 * (data[0] + data[2]), .5 * (data[1] + data[3])]);
  624. prevCtrlPoint = [data[2] - data[0], data[3] - data[1]];
  625. break;
  626. case 'A':
  627. // Convert the arc to bezier curves and use the same approximation
  628. var curves = a2c.apply(0, basePoint.concat(data));
  629. for (var cData; (cData = curves.splice(0,6).map(toAbsolute)).length;) {
  630. addPoint(subPath, [.5 * (basePoint[0] + cData[0]), .5 * (basePoint[1] + cData[1])]);
  631. addPoint(subPath, [.5 * (cData[0] + cData[2]), .5 * (cData[1] + cData[3])]);
  632. addPoint(subPath, [.5 * (cData[2] + cData[4]), .5 * (cData[3] + cData[5])]);
  633. if (curves.length) addPoint(subPath, basePoint = cData.slice(-2));
  634. }
  635. break;
  636. }
  637. // Save final command coordinates
  638. if (data && data.length >= 2) addPoint(subPath, data.slice(-2));
  639. return points;
  640. function toAbsolute(n, i) { return n + basePoint[i % 2] }
  641. // Writes data about the extreme points on each axle
  642. function addPoint(path, point) {
  643. if (!path.length || point[1] > path[path.maxY][1]) {
  644. path.maxY = path.length;
  645. points.maxY = points.length ? Math.max(point[1], points.maxY) : point[1];
  646. }
  647. if (!path.length || point[0] > path[path.maxX][0]) {
  648. path.maxX = path.length;
  649. points.maxX = points.length ? Math.max(point[0], points.maxX) : point[0];
  650. }
  651. if (!path.length || point[1] < path[path.minY][1]) {
  652. path.minY = path.length;
  653. points.minY = points.length ? Math.min(point[1], points.minY) : point[1];
  654. }
  655. if (!path.length || point[0] < path[path.minX][0]) {
  656. path.minX = path.length;
  657. points.minX = points.length ? Math.min(point[0], points.minX) : point[0];
  658. }
  659. path.push(point);
  660. }
  661. }
  662. /**
  663. * Forms a convex hull from set of points of every subpath using monotone chain convex hull algorithm.
  664. * http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
  665. *
  666. * @param points An array of [X, Y] coordinates
  667. */
  668. function convexHull(points) {
  669. /* jshint -W004 */
  670. points.sort(function(a, b) {
  671. return a[0] == b[0] ? a[1] - b[1] : a[0] - b[0];
  672. });
  673. var lower = [],
  674. minY = 0,
  675. bottom = 0;
  676. for (var i = 0; i < points.length; i++) {
  677. while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], points[i]) <= 0) {
  678. lower.pop();
  679. }
  680. if (points[i][1] < points[minY][1]) {
  681. minY = i;
  682. bottom = lower.length;
  683. }
  684. lower.push(points[i]);
  685. }
  686. var upper = [],
  687. maxY = points.length - 1,
  688. top = 0;
  689. for (var i = points.length; i--;) {
  690. while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], points[i]) <= 0) {
  691. upper.pop();
  692. }
  693. if (points[i][1] > points[maxY][1]) {
  694. maxY = i;
  695. top = upper.length;
  696. }
  697. upper.push(points[i]);
  698. }
  699. // last points are equal to starting points of the other part
  700. upper.pop();
  701. lower.pop();
  702. var hull = lower.concat(upper);
  703. hull.minX = 0; // by sorting
  704. hull.maxX = lower.length;
  705. hull.minY = bottom;
  706. hull.maxY = (lower.length + top) % hull.length;
  707. return hull;
  708. }
  709. function cross(o, a, b) {
  710. return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
  711. }
  712. /* Based on code from Snap.svg (Apache 2 license). http://snapsvg.io/
  713. * Thanks to Dmitry Baranovskiy for his great work!
  714. */
  715. // jshint ignore: start
  716. function a2c(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
  717. // for more information of where this Math came from visit:
  718. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  719. var _120 = Math.PI * 120 / 180,
  720. rad = Math.PI / 180 * (+angle || 0),
  721. res = [],
  722. rotateX = function(x, y, rad) { return x * Math.cos(rad) - y * Math.sin(rad) },
  723. rotateY = function(x, y, rad) { return x * Math.sin(rad) + y * Math.cos(rad) };
  724. if (!recursive) {
  725. x1 = rotateX(x1, y1, -rad);
  726. y1 = rotateY(x1, y1, -rad);
  727. x2 = rotateX(x2, y2, -rad);
  728. y2 = rotateY(x2, y2, -rad);
  729. var x = (x1 - x2) / 2,
  730. y = (y1 - y2) / 2;
  731. var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
  732. if (h > 1) {
  733. h = Math.sqrt(h);
  734. rx = h * rx;
  735. ry = h * ry;
  736. }
  737. var rx2 = rx * rx,
  738. ry2 = ry * ry,
  739. k = (large_arc_flag == sweep_flag ? -1 : 1) *
  740. Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
  741. cx = k * rx * y / ry + (x1 + x2) / 2,
  742. cy = k * -ry * x / rx + (y1 + y2) / 2,
  743. f1 = Math.asin(((y1 - cy) / ry).toFixed(9)),
  744. f2 = Math.asin(((y2 - cy) / ry).toFixed(9));
  745. f1 = x1 < cx ? Math.PI - f1 : f1;
  746. f2 = x2 < cx ? Math.PI - f2 : f2;
  747. f1 < 0 && (f1 = Math.PI * 2 + f1);
  748. f2 < 0 && (f2 = Math.PI * 2 + f2);
  749. if (sweep_flag && f1 > f2) {
  750. f1 = f1 - Math.PI * 2;
  751. }
  752. if (!sweep_flag && f2 > f1) {
  753. f2 = f2 - Math.PI * 2;
  754. }
  755. } else {
  756. f1 = recursive[0];
  757. f2 = recursive[1];
  758. cx = recursive[2];
  759. cy = recursive[3];
  760. }
  761. var df = f2 - f1;
  762. if (Math.abs(df) > _120) {
  763. var f2old = f2,
  764. x2old = x2,
  765. y2old = y2;
  766. f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
  767. x2 = cx + rx * Math.cos(f2);
  768. y2 = cy + ry * Math.sin(f2);
  769. res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
  770. }
  771. df = f2 - f1;
  772. var c1 = Math.cos(f1),
  773. s1 = Math.sin(f1),
  774. c2 = Math.cos(f2),
  775. s2 = Math.sin(f2),
  776. t = Math.tan(df / 4),
  777. hx = 4 / 3 * rx * t,
  778. hy = 4 / 3 * ry * t,
  779. m = [
  780. - hx * s1, hy * c1,
  781. x2 + hx * s2 - x1, y2 - hy * c2 - y1,
  782. x2 - x1, y2 - y1
  783. ];
  784. if (recursive) {
  785. return m.concat(res);
  786. } else {
  787. res = m.concat(res);
  788. var newres = [];
  789. for (var i = 0, n = res.length; i < n; i++) {
  790. newres[i] = i % 2 ? rotateY(res[i - 1], res[i], rad) : rotateX(res[i], res[i + 1], rad);
  791. }
  792. return newres;
  793. }
  794. }
  795. // jshint ignore: end