typescript 八叉树的简单实现
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
interface QuadTreeNode<T> {
bounds: {
x: number,
y: number,
width: number,
height: number
};
nodes: QuadTreeNode<T>[];
items: T[];
split(): void;
insert(item: T, x: number, y: number): void;
retrieve(x: number, y: number): T[];
}
class QuadTree<T> implements QuadTreeNode<T> {
bounds: { x: number, y: number, width: number, height: number };
nodes: QuadTreeNode<T>[];
items: T[];
maxItems: number;
maxDepth: number;
constructor(x: number, y: number, width: number, height: number, maxItems: number, maxDepth: number) {
this.bounds = { x, y, width, height };
this.items = [];
this.nodes = [];
this.maxItems = maxItems;
this.maxDepth = maxDepth;
}
split(): void {
if (this.nodes.length > 0) {
return; // already split
}
const { x, y, width, height } = this.bounds;
const nextWidth = width / 2;
const nextHeight = height / 2;
this.nodes = [
new QuadTree(x, y, nextWidth, nextHeight, this.maxItems, this.maxDepth - 1),
new QuadTree(x + nextWidth, y, nextWidth, nextHeight, this.maxItems, this.maxDepth - 1),
new QuadTree(x, y + nextHeight, nextWidth, nextHeight, this.maxItems, this.maxDepth - 1),
new QuadTree(x + nextWidth, y + nextHeight, nextWidth, nextHeight, this.maxItems, this.maxDepth - 1)
];
}
insert(item: T, x: number, y: number): void {
if (this.nodes.length > 0 && this.bounds.width / 2 > 0 && this.bounds.height / 2 > 0) {
const index = this.getIndex(x, y);
if (index !== -1) {
this.nodes[index].insert(item, x, y);
return;
}
}
this.items.push(item);
if (this.items.length > this.maxItems && this.bounds.width / 2 > 0 && this.bounds.height / 2 > 0 && this.maxDepth > 0) {
if (this.nodes.length === 0) {
this.split();
}
while (this.items.length > 0) {
const item = this.items.pop();
const index = this.getIndex(x, y);
评论已关闭