Skip to content

Commit

Permalink
add bake group transforms test
Browse files Browse the repository at this point in the history
  • Loading branch information
alexjlockwood committed Nov 27, 2017
1 parent cdf269a commit 7b375aa
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/plugins/bakeGroupTransforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { JsApi } from '../lib/jsapi';
import { Plugin } from './_types';

export const defaultParams = {
floatPrecision: 3,
transformPrecision: 5,
applyTransformsStroked: true,
};
Expand All @@ -35,6 +36,48 @@ function fn(item: JsApi, params: Params) {
) {
return item;
}

const { floatPrecision } = params;
const error = +Math.pow(0.1, floatPrecision).toFixed(floatPrecision);

/**
* Decrease accuracy of floating-point numbers
* in path data keeping a specified number of decimals.
* Smart rounds values like 2.3491 to 2.35 instead of 2.349.
* Doesn't apply "smartness" if the number precision fits already.
*
* @param {Array} data input data array
* @return {Array} output data array
*/
function strongRound(data: number[]) {
for (let i = data.length; i-- > 0; ) {
if (+data[i].toFixed(floatPrecision) !== data[i]) {
const rounded = +data[i].toFixed(floatPrecision - 1);
data[i] =
+Math.abs(rounded - data[i]).toFixed(floatPrecision + 1) >= error
? +data[i].toFixed(floatPrecision)
: rounded;
}
}
return data;
}

/**
* Simple rounding function if precision is 0.
*
* @param {Array} data input data array
* @return {Array} output data array
*/
function round(data: number[]) {
for (let i = data.length; i-- > 0; ) {
data[i] = Math.round(data[i]);
}
return data;
}

const roundData =
floatPrecision > 0 && floatPrecision < 20 ? strongRound : round;

const g1Attrs = getGroupAttrs(item);
item.content.forEach(i => {
if (i.isElem('group')) {
Expand Down Expand Up @@ -64,6 +107,7 @@ function fn(item: JsApi, params: Params) {
}
convertToRelative(data);
data = applyTransforms(item, i, data, params);
data.forEach(d => roundData(d.data));
js2path(i, data, {
collapseRepeated: false,
negativeExtraSpace: false,
Expand Down
13 changes: 13 additions & 0 deletions test/plugins/bakeGroupTransforms.01.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android">
<group android:pivotX="500" android:pivotY="500" android:rotation="180">
<path android:pathData="M 0 0 L 500 500 L 1000 1000"/>
</group>
</vector>

@@@

<vector xmlns:android="http://schemas.android.com/apk/res/android">
<group>
<path android:pathData="M1000 1000l-500 -500l-500 -500"/>
</group>
</vector>

0 comments on commit 7b375aa

Please sign in to comment.