@thi.ng/geom-axidraw
Version:
Conversion and preparation of thi.ng/geom shapes & shape groups to/from AxiDraw pen plotter draw commands
48 lines (47 loc) • 1.28 kB
JavaScript
import { sortByCachedKey } from "@thi.ng/arrays/sort-cached";
import { compareNumAsc } from "@thi.ng/compare/numeric";
import { KdTreeSet } from "@thi.ng/geom-accel/kd-tree-set";
import { centroid } from "@thi.ng/geom/centroid";
import { ZERO2 } from "@thi.ng/vectors/api";
import { distSq2 } from "@thi.ng/vectors/distsq";
const pointsByNearestNeighbor = (accel = new KdTreeSet(2), ref = ZERO2) => function* (pts) {
accel.into(pts);
while (accel.size) {
ref = accel.queryKeys(ref, 1e4, 1)[0];
accel.remove(ref);
yield ref;
}
};
const pointsByProximity = (ref = ZERO2) => (pts) => {
return sortByCachedKey(
pts.slice(),
(p) => distSq2(p, ref),
compareNumAsc
);
};
const shapesByProximity = (ref = ZERO2) => (shapes) => {
return sortByCachedKey(
shapes.slice(),
(s) => distSq2(centroid(s) || ZERO2, ref),
compareNumAsc
);
};
const shapesByNearestNeighbor = (accel, ref = ZERO2) => function* (shapes) {
accel.into(
shapes.map(
(s) => [centroid(s) || [0, 0], s]
)
);
while (accel.size) {
const pair = accel.query(ref, 1e4, 1)[0];
ref = pair[0];
accel.remove(ref);
yield pair[1];
}
};
export {
pointsByNearestNeighbor,
pointsByProximity,
shapesByNearestNeighbor,
shapesByProximity
};