_path.js 31 KB

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