UNPKG

3.35 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.QuadTree = void 0;
4const Rectangle_1 = require("./Rectangle");
5const Circle_1 = require("./Circle");
6const CircleWarp_1 = require("./CircleWarp");
7class QuadTree {
8 constructor(rectangle, capacity) {
9 this.rectangle = rectangle;
10 this.capacity = capacity;
11 this.points = [];
12 this.divided = false;
13 }
14 subdivide() {
15 const x = this.rectangle.position.x;
16 const y = this.rectangle.position.y;
17 const w = this.rectangle.size.width;
18 const h = this.rectangle.size.height;
19 const capacity = this.capacity;
20 this.northEast = new QuadTree(new Rectangle_1.Rectangle(x, y, w / 2, h / 2), capacity);
21 this.northWest = new QuadTree(new Rectangle_1.Rectangle(x + w / 2, y, w / 2, h / 2), capacity);
22 this.southEast = new QuadTree(new Rectangle_1.Rectangle(x, y + h / 2, w / 2, h / 2), capacity);
23 this.southWest = new QuadTree(new Rectangle_1.Rectangle(x + w / 2, y + h / 2, w / 2, h / 2), capacity);
24 this.divided = true;
25 }
26 insert(point) {
27 var _a, _b, _c, _d, _e;
28 if (!this.rectangle.contains(point.position)) {
29 return false;
30 }
31 if (this.points.length < this.capacity) {
32 this.points.push(point);
33 return true;
34 }
35 if (!this.divided) {
36 this.subdivide();
37 }
38 return ((_e = (((_a = this.northEast) === null || _a === void 0 ? void 0 : _a.insert(point)) ||
39 ((_b = this.northWest) === null || _b === void 0 ? void 0 : _b.insert(point)) ||
40 ((_c = this.southEast) === null || _c === void 0 ? void 0 : _c.insert(point)) ||
41 ((_d = this.southWest) === null || _d === void 0 ? void 0 : _d.insert(point)))) !== null && _e !== void 0 ? _e : false);
42 }
43 queryCircle(position, radius) {
44 return this.query(new Circle_1.Circle(position.x, position.y, radius));
45 }
46 queryCircleWarp(position, radius, containerOrSize) {
47 const container = containerOrSize;
48 const size = containerOrSize;
49 return this.query(new CircleWarp_1.CircleWarp(position.x, position.y, radius, container.canvas !== undefined ? container.canvas.size : size));
50 }
51 queryRectangle(position, size) {
52 return this.query(new Rectangle_1.Rectangle(position.x, position.y, size.width, size.height));
53 }
54 query(range, found) {
55 var _a, _b, _c, _d;
56 const res = found !== null && found !== void 0 ? found : [];
57 if (!range.intersects(this.rectangle)) {
58 return [];
59 }
60 else {
61 for (const p of this.points) {
62 if (!range.contains(p.position)) {
63 continue;
64 }
65 res.push(p.particle);
66 }
67 if (this.divided) {
68 (_a = this.northEast) === null || _a === void 0 ? void 0 : _a.query(range, res);
69 (_b = this.northWest) === null || _b === void 0 ? void 0 : _b.query(range, res);
70 (_c = this.southEast) === null || _c === void 0 ? void 0 : _c.query(range, res);
71 (_d = this.southWest) === null || _d === void 0 ? void 0 : _d.query(range, res);
72 }
73 }
74 return res;
75 }
76}
77exports.QuadTree = QuadTree;