_path.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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. var strData = '';
  433. if (item.data) {
  434. strData = cleanupOutData(item.data, params, item.instruction);
  435. }
  436. return pathString += item.instruction + strData;
  437. }, '');
  438. };
  439. /**
  440. * Collapse repeated instructions data
  441. *
  442. * @param {Array} path input path data
  443. * @return {Array} output path data
  444. */
  445. function collapseRepeated(data) {
  446. var prev,
  447. prevIndex;
  448. // copy an array and modifieds item to keep original data untouched
  449. data = data.reduce(function(newPath, item) {
  450. if (
  451. prev && item.data &&
  452. item.instruction == prev.instruction
  453. ) {
  454. // concat previous data with current
  455. if (item.instruction != 'M') {
  456. prev = newPath[prevIndex] = {
  457. instruction: prev.instruction,
  458. data: prev.data.concat(item.data),
  459. coords: item.coords,
  460. base: prev.base
  461. };
  462. } else {
  463. prev.data = item.data;
  464. prev.coords = item.coords;
  465. }
  466. } else {
  467. newPath.push(item);
  468. prev = item;
  469. prevIndex = newPath.length - 1;
  470. }
  471. return newPath;
  472. }, []);
  473. return data;
  474. }
  475. function set(dest, source) {
  476. dest[0] = source[source.length - 2];
  477. dest[1] = source[source.length - 1];
  478. return dest;
  479. }
  480. /**
  481. * Checks if two paths have an intersection by checking convex hulls
  482. * collision using Gilbert-Johnson-Keerthi distance algorithm
  483. * http://entropyinteractive.com/2011/04/gjk-algorithm/
  484. *
  485. * @param {Array} path1 JS path representation
  486. * @param {Array} path2 JS path representation
  487. * @return {Boolean}
  488. */
  489. exports.intersects = function(path1, path2) {
  490. if (path1.length < 3 || path2.length < 3) return false; // nothing to fill
  491. // Collect points of every subpath.
  492. var points1 = relative2absolute(path1).reduce(gatherPoints, []),
  493. points2 = relative2absolute(path2).reduce(gatherPoints, []);
  494. // Axis-aligned bounding box check.
  495. if (points1.maxX <= points2.minX || points2.maxX <= points1.minX ||
  496. points1.maxY <= points2.minY || points2.maxY <= points1.minY ||
  497. points1.every(function (set1) {
  498. return points2.every(function (set2) {
  499. return set1[set1.maxX][0] <= set2[set2.minX][0] ||
  500. set2[set2.maxX][0] <= set1[set1.minX][0] ||
  501. set1[set1.maxY][1] <= set2[set2.minY][1] ||
  502. set2[set2.maxY][1] <= set1[set1.minY][1];
  503. });
  504. })
  505. ) return false;
  506. // Get a convex hull from points of each subpath. Has the most complexity O(n·log n).
  507. var hullNest1 = points1.map(convexHull),
  508. hullNest2 = points2.map(convexHull);
  509. // Check intersection of every subpath of the first path with every subpath of the second.
  510. return hullNest1.some(function(hull1) {
  511. if (hull1.length < 3) return false;
  512. return hullNest2.some(function(hull2) {
  513. if (hull2.length < 3) return false;
  514. var simplex = [getSupport(hull1, hull2, [1, 0])], // create the initial simplex
  515. direction = minus(simplex[0]); // set the direction to point towards the origin
  516. var iterations = 1e4; // infinite loop protection, 10 000 iterations is more than enough
  517. while (true) {
  518. if (iterations-- == 0) {
  519. console.error('Error: infinite loop while processing mergePaths plugin.');
  520. return true; // true is the safe value that means “do nothing with paths”
  521. }
  522. // add a new point
  523. simplex.push(getSupport(hull1, hull2, direction));
  524. // see if the new point was on the correct side of the origin
  525. if (dot(direction, simplex[simplex.length - 1]) <= 0) return false;
  526. // process the simplex
  527. if (processSimplex(simplex, direction)) return true;
  528. }
  529. });
  530. });
  531. function getSupport(a, b, direction) {
  532. return sub(supportPoint(a, direction), supportPoint(b, minus(direction)));
  533. }
  534. // Computes farthest polygon point in particular direction.
  535. // Thanks to knowledge of min/max x and y coordinates we can choose a quadrant to search in.
  536. // Since we're working on convex hull, the dot product is increasing until we find the farthest point.
  537. function supportPoint(polygon, direction) {
  538. var index = direction[1] >= 0 ?
  539. direction[0] < 0 ? polygon.maxY : polygon.maxX :
  540. direction[0] < 0 ? polygon.minX : polygon.minY,
  541. max = -Infinity,
  542. value;
  543. while ((value = dot(polygon[index], direction)) > max) {
  544. max = value;
  545. index = ++index % polygon.length;
  546. }
  547. return polygon[(index || polygon.length) - 1];
  548. }
  549. };
  550. function processSimplex(simplex, direction) {
  551. /* jshint -W004 */
  552. // we only need to handle to 1-simplex and 2-simplex
  553. if (simplex.length == 2) { // 1-simplex
  554. var a = simplex[1],
  555. b = simplex[0],
  556. AO = minus(simplex[1]),
  557. AB = sub(b, a);
  558. // AO is in the same direction as AB
  559. if (dot(AO, AB) > 0) {
  560. // get the vector perpendicular to AB facing O
  561. set(direction, orth(AB, a));
  562. } else {
  563. set(direction, AO);
  564. // only A remains in the simplex
  565. simplex.shift();
  566. }
  567. } else { // 2-simplex
  568. var a = simplex[2], // [a, b, c] = simplex
  569. b = simplex[1],
  570. c = simplex[0],
  571. AB = sub(b, a),
  572. AC = sub(c, a),
  573. AO = minus(a),
  574. ACB = orth(AB, AC), // the vector perpendicular to AB facing away from C
  575. ABC = orth(AC, AB); // the vector perpendicular to AC facing away from B
  576. if (dot(ACB, AO) > 0) {
  577. if (dot(AB, AO) > 0) { // region 4
  578. set(direction, ACB);
  579. simplex.shift(); // simplex = [b, a]
  580. } else { // region 5
  581. set(direction, AO);
  582. simplex.splice(0, 2); // simplex = [a]
  583. }
  584. } else if (dot(ABC, AO) > 0) {
  585. if (dot(AC, AO) > 0) { // region 6
  586. set(direction, ABC);
  587. simplex.splice(1, 1); // simplex = [c, a]
  588. } else { // region 5 (again)
  589. set(direction, AO);
  590. simplex.splice(0, 2); // simplex = [a]
  591. }
  592. } else // region 7
  593. return true;
  594. }
  595. return false;
  596. }
  597. function minus(v) {
  598. return [-v[0], -v[1]];
  599. }
  600. function sub(v1, v2) {
  601. return [v1[0] - v2[0], v1[1] - v2[1]];
  602. }
  603. function dot(v1, v2) {
  604. return v1[0] * v2[0] + v1[1] * v2[1];
  605. }
  606. function orth(v, from) {
  607. var o = [-v[1], v[0]];
  608. return dot(o, minus(from)) < 0 ? minus(o) : o;
  609. }
  610. function gatherPoints(points, item, index, path) {
  611. var subPath = points.length && points[points.length - 1],
  612. prev = index && path[index - 1],
  613. basePoint = subPath.length && subPath[subPath.length - 1],
  614. data = item.data,
  615. ctrlPoint = basePoint;
  616. switch (item.instruction) {
  617. case 'M':
  618. points.push(subPath = []);
  619. break;
  620. case 'H':
  621. addPoint(subPath, [data[0], basePoint[1]]);
  622. break;
  623. case 'V':
  624. addPoint(subPath, [basePoint[0], data[0]]);
  625. break;
  626. case 'Q':
  627. addPoint(subPath, data.slice(0, 2));
  628. prevCtrlPoint = [data[2] - data[0], data[3] - data[1]]; // Save control point for shorthand
  629. break;
  630. case 'T':
  631. if (prev.instruction == 'Q' || prev.instruction == 'T') {
  632. ctrlPoint = [basePoint[0] + prevCtrlPoint[0], basePoint[1] + prevCtrlPoint[1]];
  633. addPoint(subPath, ctrlPoint);
  634. prevCtrlPoint = [data[0] - ctrlPoint[0], data[1] - ctrlPoint[1]];
  635. }
  636. break;
  637. case 'C':
  638. // Approximate quibic Bezier curve with middle points between control points
  639. addPoint(subPath, [.5 * (basePoint[0] + data[0]), .5 * (basePoint[1] + data[1])]);
  640. addPoint(subPath, [.5 * (data[0] + data[2]), .5 * (data[1] + data[3])]);
  641. addPoint(subPath, [.5 * (data[2] + data[4]), .5 * (data[3] + data[5])]);
  642. prevCtrlPoint = [data[4] - data[2], data[5] - data[3]]; // Save control point for shorthand
  643. break;
  644. case 'S':
  645. if (prev.instruction == 'C' || prev.instruction == 'S') {
  646. addPoint(subPath, [basePoint[0] + .5 * prevCtrlPoint[0], basePoint[1] + .5 * prevCtrlPoint[1]]);
  647. ctrlPoint = [basePoint[0] + prevCtrlPoint[0], basePoint[1] + prevCtrlPoint[1]];
  648. }
  649. addPoint(subPath, [.5 * (ctrlPoint[0] + data[0]), .5 * (ctrlPoint[1]+ data[1])]);
  650. addPoint(subPath, [.5 * (data[0] + data[2]), .5 * (data[1] + data[3])]);
  651. prevCtrlPoint = [data[2] - data[0], data[3] - data[1]];
  652. break;
  653. case 'A':
  654. // Convert the arc to bezier curves and use the same approximation
  655. var curves = a2c.apply(0, basePoint.concat(data));
  656. for (var cData; (cData = curves.splice(0,6).map(toAbsolute)).length;) {
  657. addPoint(subPath, [.5 * (basePoint[0] + cData[0]), .5 * (basePoint[1] + cData[1])]);
  658. addPoint(subPath, [.5 * (cData[0] + cData[2]), .5 * (cData[1] + cData[3])]);
  659. addPoint(subPath, [.5 * (cData[2] + cData[4]), .5 * (cData[3] + cData[5])]);
  660. if (curves.length) addPoint(subPath, basePoint = cData.slice(-2));
  661. }
  662. break;
  663. }
  664. // Save final command coordinates
  665. if (data && data.length >= 2) addPoint(subPath, data.slice(-2));
  666. return points;
  667. function toAbsolute(n, i) { return n + basePoint[i % 2] }
  668. // Writes data about the extreme points on each axle
  669. function addPoint(path, point) {
  670. if (!path.length || point[1] > path[path.maxY][1]) {
  671. path.maxY = path.length;
  672. points.maxY = points.length ? Math.max(point[1], points.maxY) : point[1];
  673. }
  674. if (!path.length || point[0] > path[path.maxX][0]) {
  675. path.maxX = path.length;
  676. points.maxX = points.length ? Math.max(point[0], points.maxX) : point[0];
  677. }
  678. if (!path.length || point[1] < path[path.minY][1]) {
  679. path.minY = path.length;
  680. points.minY = points.length ? Math.min(point[1], points.minY) : point[1];
  681. }
  682. if (!path.length || point[0] < path[path.minX][0]) {
  683. path.minX = path.length;
  684. points.minX = points.length ? Math.min(point[0], points.minX) : point[0];
  685. }
  686. path.push(point);
  687. }
  688. }
  689. /**
  690. * Forms a convex hull from set of points of every subpath using monotone chain convex hull algorithm.
  691. * http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
  692. *
  693. * @param points An array of [X, Y] coordinates
  694. */
  695. function convexHull(points) {
  696. /* jshint -W004 */
  697. points.sort(function(a, b) {
  698. return a[0] == b[0] ? a[1] - b[1] : a[0] - b[0];
  699. });
  700. var lower = [],
  701. minY = 0,
  702. bottom = 0;
  703. for (var i = 0; i < points.length; i++) {
  704. while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], points[i]) <= 0) {
  705. lower.pop();
  706. }
  707. if (points[i][1] < points[minY][1]) {
  708. minY = i;
  709. bottom = lower.length;
  710. }
  711. lower.push(points[i]);
  712. }
  713. var upper = [],
  714. maxY = points.length - 1,
  715. top = 0;
  716. for (var i = points.length; i--;) {
  717. while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], points[i]) <= 0) {
  718. upper.pop();
  719. }
  720. if (points[i][1] > points[maxY][1]) {
  721. maxY = i;
  722. top = upper.length;
  723. }
  724. upper.push(points[i]);
  725. }
  726. // last points are equal to starting points of the other part
  727. upper.pop();
  728. lower.pop();
  729. var hull = lower.concat(upper);
  730. hull.minX = 0; // by sorting
  731. hull.maxX = lower.length;
  732. hull.minY = bottom;
  733. hull.maxY = (lower.length + top) % hull.length;
  734. return hull;
  735. }
  736. function cross(o, a, b) {
  737. return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
  738. }
  739. /* Based on code from Snap.svg (Apache 2 license). http://snapsvg.io/
  740. * Thanks to Dmitry Baranovskiy for his great work!
  741. */
  742. // jshint ignore: start
  743. function a2c(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
  744. // for more information of where this Math came from visit:
  745. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  746. var _120 = Math.PI * 120 / 180,
  747. rad = Math.PI / 180 * (+angle || 0),
  748. res = [],
  749. rotateX = function(x, y, rad) { return x * Math.cos(rad) - y * Math.sin(rad) },
  750. rotateY = function(x, y, rad) { return x * Math.sin(rad) + y * Math.cos(rad) };
  751. if (!recursive) {
  752. x1 = rotateX(x1, y1, -rad);
  753. y1 = rotateY(x1, y1, -rad);
  754. x2 = rotateX(x2, y2, -rad);
  755. y2 = rotateY(x2, y2, -rad);
  756. var x = (x1 - x2) / 2,
  757. y = (y1 - y2) / 2;
  758. var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
  759. if (h > 1) {
  760. h = Math.sqrt(h);
  761. rx = h * rx;
  762. ry = h * ry;
  763. }
  764. var rx2 = rx * rx,
  765. ry2 = ry * ry,
  766. k = (large_arc_flag == sweep_flag ? -1 : 1) *
  767. Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
  768. cx = k * rx * y / ry + (x1 + x2) / 2,
  769. cy = k * -ry * x / rx + (y1 + y2) / 2,
  770. f1 = Math.asin(((y1 - cy) / ry).toFixed(9)),
  771. f2 = Math.asin(((y2 - cy) / ry).toFixed(9));
  772. f1 = x1 < cx ? Math.PI - f1 : f1;
  773. f2 = x2 < cx ? Math.PI - f2 : f2;
  774. f1 < 0 && (f1 = Math.PI * 2 + f1);
  775. f2 < 0 && (f2 = Math.PI * 2 + f2);
  776. if (sweep_flag && f1 > f2) {
  777. f1 = f1 - Math.PI * 2;
  778. }
  779. if (!sweep_flag && f2 > f1) {
  780. f2 = f2 - Math.PI * 2;
  781. }
  782. } else {
  783. f1 = recursive[0];
  784. f2 = recursive[1];
  785. cx = recursive[2];
  786. cy = recursive[3];
  787. }
  788. var df = f2 - f1;
  789. if (Math.abs(df) > _120) {
  790. var f2old = f2,
  791. x2old = x2,
  792. y2old = y2;
  793. f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
  794. x2 = cx + rx * Math.cos(f2);
  795. y2 = cy + ry * Math.sin(f2);
  796. res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
  797. }
  798. df = f2 - f1;
  799. var c1 = Math.cos(f1),
  800. s1 = Math.sin(f1),
  801. c2 = Math.cos(f2),
  802. s2 = Math.sin(f2),
  803. t = Math.tan(df / 4),
  804. hx = 4 / 3 * rx * t,
  805. hy = 4 / 3 * ry * t,
  806. m = [
  807. - hx * s1, hy * c1,
  808. x2 + hx * s2 - x1, y2 - hy * c2 - y1,
  809. x2 - x1, y2 - y1
  810. ];
  811. if (recursive) {
  812. return m.concat(res);
  813. } else {
  814. res = m.concat(res);
  815. var newres = [];
  816. for (var i = 0, n = res.length; i < n; i++) {
  817. newres[i] = i % 2 ? rotateY(res[i - 1], res[i], rad) : rotateX(res[i], res[i + 1], rad);
  818. }
  819. return newres;
  820. }
  821. }
  822. // jshint ignore: end