avocado-old/packages/math/quadtree.js

54 lines
1.1 KiB
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() {
2019-05-02 08:39:52 -05:00
this._visitNodes = [];
this._queryRectangle = [0, 0, 0, 0];
2019-03-20 18:33:59 -05:00
this.quadTree = quadtree();
2019-05-02 08:39:52 -05:00
this.onVisit = this.onVisit.bind(this);
2019-03-20 18:33:59 -05:00
}
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-05-02 08:39:52 -05:00
onVisit(node, x, y, x0, y0) {
const w = x0 - x;
const h = y0 - y;
if (!Rectangle.intersects(this._queryRectangle, [x, y, w, h])) {
return true;
}
if (4 === node.length) {
return;
}
do {
if (Rectangle.isTouching(this._queryRectangle, node.data)) {
this.nodes.push(node);
}
} while (node = node.next);
}
2019-03-20 18:33:59 -05:00
remove(datum) {
this.quadTree.remove(datum);
}
search(queryRectangle) {
2019-05-02 08:39:52 -05:00
this._queryRectangle = queryRectangle;
this.nodes = [];
this.quadTree.visit(this.onVisit);
return this.nodes;
2019-03-20 18:33:59 -05:00
}
}