avocado-old/packages/math/quadtree.js

48 lines
913 B
JavaScript
Raw Normal View History

2019-03-20 18:33:59 -05:00
import {quadtree} from 'd3-quadtree';
import * as Rectangle from './rectangle';
export class QuadTree {
constructor() {
this.quadTree = quadtree();
}
add(datum) {
this.quadTree.add(datum);
}
2019-04-30 17:11:41 -05:00
clear() {
const data = this.quadTree.data();
for (let i = 0; i < data.length; i++) {
const datum = data[i];
this.quadTree.remove(datum);
}
}
2019-03-20 18:33:59 -05:00
remove(datum) {
this.quadTree.remove(datum);
}
search(queryRectangle) {
const nodes = [];
2019-04-16 23:59:08 -05:00
this.quadTree.visit((node, x, y, x0, y0) => {
const w = x0 - x;
const h = y0 - y;
if (!Rectangle.intersects(queryRectangle, [x, y, w, h])) {
2019-03-20 18:33:59 -05:00
return true;
}
2019-04-16 23:59:08 -05:00
if (4 === node.length) {
return;
2019-03-20 18:33:59 -05:00
}
2019-04-20 01:02:47 -05:00
do {
if (Rectangle.intersects(queryRectangle, node.data)) {
nodes.push(node);
}
} while (node = node.next);
2019-03-20 18:33:59 -05:00
});
2019-04-16 23:59:08 -05:00
return nodes;
2019-03-20 18:33:59 -05:00
}
}