index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. import quickselect from 'quickselect';
  2. export default class RBush {
  3. constructor(maxEntries = 9) {
  4. // max entries in a node is 9 by default; min node fill is 40% for best performance
  5. this._maxEntries = Math.max(4, maxEntries);
  6. this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
  7. this.clear();
  8. }
  9. all() {
  10. return this._all(this.data, []);
  11. }
  12. search(bbox) {
  13. let node = this.data;
  14. const result = [];
  15. if (!intersects(bbox, node)) return result;
  16. const toBBox = this.toBBox;
  17. const nodesToSearch = [];
  18. while (node) {
  19. for (let i = 0; i < node.children.length; i++) {
  20. const child = node.children[i];
  21. const childBBox = node.leaf ? toBBox(child) : child;
  22. if (intersects(bbox, childBBox)) {
  23. if (node.leaf) result.push(child);
  24. else if (contains(bbox, childBBox)) this._all(child, result);
  25. else nodesToSearch.push(child);
  26. }
  27. }
  28. node = nodesToSearch.pop();
  29. }
  30. return result;
  31. }
  32. collides(bbox) {
  33. let node = this.data;
  34. if (!intersects(bbox, node)) return false;
  35. const nodesToSearch = [];
  36. while (node) {
  37. for (let i = 0; i < node.children.length; i++) {
  38. const child = node.children[i];
  39. const childBBox = node.leaf ? this.toBBox(child) : child;
  40. if (intersects(bbox, childBBox)) {
  41. if (node.leaf || contains(bbox, childBBox)) return true;
  42. nodesToSearch.push(child);
  43. }
  44. }
  45. node = nodesToSearch.pop();
  46. }
  47. return false;
  48. }
  49. load(data) {
  50. if (!(data && data.length)) return this;
  51. if (data.length < this._minEntries) {
  52. for (let i = 0; i < data.length; i++) {
  53. this.insert(data[i]);
  54. }
  55. return this;
  56. }
  57. // recursively build the tree with the given data from scratch using OMT algorithm
  58. let node = this._build(data.slice(), 0, data.length - 1, 0);
  59. if (!this.data.children.length) {
  60. // save as is if tree is empty
  61. this.data = node;
  62. } else if (this.data.height === node.height) {
  63. // split root if trees have the same height
  64. this._splitRoot(this.data, node);
  65. } else {
  66. if (this.data.height < node.height) {
  67. // swap trees if inserted one is bigger
  68. const tmpNode = this.data;
  69. this.data = node;
  70. node = tmpNode;
  71. }
  72. // insert the small tree into the large tree at appropriate level
  73. this._insert(node, this.data.height - node.height - 1, true);
  74. }
  75. return this;
  76. }
  77. insert(item) {
  78. if (item) this._insert(item, this.data.height - 1);
  79. return this;
  80. }
  81. clear() {
  82. this.data = createNode([]);
  83. return this;
  84. }
  85. remove(item, equalsFn) {
  86. if (!item) return this;
  87. let node = this.data;
  88. const bbox = this.toBBox(item);
  89. const path = [];
  90. const indexes = [];
  91. let i, parent, goingUp;
  92. // depth-first iterative tree traversal
  93. while (node || path.length) {
  94. if (!node) { // go up
  95. node = path.pop();
  96. parent = path[path.length - 1];
  97. i = indexes.pop();
  98. goingUp = true;
  99. }
  100. if (node.leaf) { // check current node
  101. const index = findItem(item, node.children, equalsFn);
  102. if (index !== -1) {
  103. // item found, remove the item and condense tree upwards
  104. node.children.splice(index, 1);
  105. path.push(node);
  106. this._condense(path);
  107. return this;
  108. }
  109. }
  110. if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
  111. path.push(node);
  112. indexes.push(i);
  113. i = 0;
  114. parent = node;
  115. node = node.children[0];
  116. } else if (parent) { // go right
  117. i++;
  118. node = parent.children[i];
  119. goingUp = false;
  120. } else node = null; // nothing found
  121. }
  122. return this;
  123. }
  124. toBBox(item) { return item; }
  125. compareMinX(a, b) { return a.minX - b.minX; }
  126. compareMinY(a, b) { return a.minY - b.minY; }
  127. toJSON() { return this.data; }
  128. fromJSON(data) {
  129. this.data = data;
  130. return this;
  131. }
  132. _all(node, result) {
  133. const nodesToSearch = [];
  134. while (node) {
  135. if (node.leaf) result.push(...node.children);
  136. else nodesToSearch.push(...node.children);
  137. node = nodesToSearch.pop();
  138. }
  139. return result;
  140. }
  141. _build(items, left, right, height) {
  142. const N = right - left + 1;
  143. let M = this._maxEntries;
  144. let node;
  145. if (N <= M) {
  146. // reached leaf level; return leaf
  147. node = createNode(items.slice(left, right + 1));
  148. calcBBox(node, this.toBBox);
  149. return node;
  150. }
  151. if (!height) {
  152. // target height of the bulk-loaded tree
  153. height = Math.ceil(Math.log(N) / Math.log(M));
  154. // target number of root entries to maximize storage utilization
  155. M = Math.ceil(N / Math.pow(M, height - 1));
  156. }
  157. node = createNode([]);
  158. node.leaf = false;
  159. node.height = height;
  160. // split the items into M mostly square tiles
  161. const N2 = Math.ceil(N / M);
  162. const N1 = N2 * Math.ceil(Math.sqrt(M));
  163. multiSelect(items, left, right, N1, this.compareMinX);
  164. for (let i = left; i <= right; i += N1) {
  165. const right2 = Math.min(i + N1 - 1, right);
  166. multiSelect(items, i, right2, N2, this.compareMinY);
  167. for (let j = i; j <= right2; j += N2) {
  168. const right3 = Math.min(j + N2 - 1, right2);
  169. // pack each entry recursively
  170. node.children.push(this._build(items, j, right3, height - 1));
  171. }
  172. }
  173. calcBBox(node, this.toBBox);
  174. return node;
  175. }
  176. _chooseSubtree(bbox, node, level, path) {
  177. while (true) {
  178. path.push(node);
  179. if (node.leaf || path.length - 1 === level) break;
  180. let minArea = Infinity;
  181. let minEnlargement = Infinity;
  182. let targetNode;
  183. for (let i = 0; i < node.children.length; i++) {
  184. const child = node.children[i];
  185. const area = bboxArea(child);
  186. const enlargement = enlargedArea(bbox, child) - area;
  187. // choose entry with the least area enlargement
  188. if (enlargement < minEnlargement) {
  189. minEnlargement = enlargement;
  190. minArea = area < minArea ? area : minArea;
  191. targetNode = child;
  192. } else if (enlargement === minEnlargement) {
  193. // otherwise choose one with the smallest area
  194. if (area < minArea) {
  195. minArea = area;
  196. targetNode = child;
  197. }
  198. }
  199. }
  200. node = targetNode || node.children[0];
  201. }
  202. return node;
  203. }
  204. _insert(item, level, isNode) {
  205. const bbox = isNode ? item : this.toBBox(item);
  206. const insertPath = [];
  207. // find the best node for accommodating the item, saving all nodes along the path too
  208. const node = this._chooseSubtree(bbox, this.data, level, insertPath);
  209. // put the item into the node
  210. node.children.push(item);
  211. extend(node, bbox);
  212. // split on node overflow; propagate upwards if necessary
  213. while (level >= 0) {
  214. if (insertPath[level].children.length > this._maxEntries) {
  215. this._split(insertPath, level);
  216. level--;
  217. } else break;
  218. }
  219. // adjust bboxes along the insertion path
  220. this._adjustParentBBoxes(bbox, insertPath, level);
  221. }
  222. // split overflowed node into two
  223. _split(insertPath, level) {
  224. const node = insertPath[level];
  225. const M = node.children.length;
  226. const m = this._minEntries;
  227. this._chooseSplitAxis(node, m, M);
  228. const splitIndex = this._chooseSplitIndex(node, m, M);
  229. const newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
  230. newNode.height = node.height;
  231. newNode.leaf = node.leaf;
  232. calcBBox(node, this.toBBox);
  233. calcBBox(newNode, this.toBBox);
  234. if (level) insertPath[level - 1].children.push(newNode);
  235. else this._splitRoot(node, newNode);
  236. }
  237. _splitRoot(node, newNode) {
  238. // split root node
  239. this.data = createNode([node, newNode]);
  240. this.data.height = node.height + 1;
  241. this.data.leaf = false;
  242. calcBBox(this.data, this.toBBox);
  243. }
  244. _chooseSplitIndex(node, m, M) {
  245. let index;
  246. let minOverlap = Infinity;
  247. let minArea = Infinity;
  248. for (let i = m; i <= M - m; i++) {
  249. const bbox1 = distBBox(node, 0, i, this.toBBox);
  250. const bbox2 = distBBox(node, i, M, this.toBBox);
  251. const overlap = intersectionArea(bbox1, bbox2);
  252. const area = bboxArea(bbox1) + bboxArea(bbox2);
  253. // choose distribution with minimum overlap
  254. if (overlap < minOverlap) {
  255. minOverlap = overlap;
  256. index = i;
  257. minArea = area < minArea ? area : minArea;
  258. } else if (overlap === minOverlap) {
  259. // otherwise choose distribution with minimum area
  260. if (area < minArea) {
  261. minArea = area;
  262. index = i;
  263. }
  264. }
  265. }
  266. return index || M - m;
  267. }
  268. // sorts node children by the best axis for split
  269. _chooseSplitAxis(node, m, M) {
  270. const compareMinX = node.leaf ? this.compareMinX : compareNodeMinX;
  271. const compareMinY = node.leaf ? this.compareMinY : compareNodeMinY;
  272. const xMargin = this._allDistMargin(node, m, M, compareMinX);
  273. const yMargin = this._allDistMargin(node, m, M, compareMinY);
  274. // if total distributions margin value is minimal for x, sort by minX,
  275. // otherwise it's already sorted by minY
  276. if (xMargin < yMargin) node.children.sort(compareMinX);
  277. }
  278. // total margin of all possible split distributions where each node is at least m full
  279. _allDistMargin(node, m, M, compare) {
  280. node.children.sort(compare);
  281. const toBBox = this.toBBox;
  282. const leftBBox = distBBox(node, 0, m, toBBox);
  283. const rightBBox = distBBox(node, M - m, M, toBBox);
  284. let margin = bboxMargin(leftBBox) + bboxMargin(rightBBox);
  285. for (let i = m; i < M - m; i++) {
  286. const child = node.children[i];
  287. extend(leftBBox, node.leaf ? toBBox(child) : child);
  288. margin += bboxMargin(leftBBox);
  289. }
  290. for (let i = M - m - 1; i >= m; i--) {
  291. const child = node.children[i];
  292. extend(rightBBox, node.leaf ? toBBox(child) : child);
  293. margin += bboxMargin(rightBBox);
  294. }
  295. return margin;
  296. }
  297. _adjustParentBBoxes(bbox, path, level) {
  298. // adjust bboxes along the given tree path
  299. for (let i = level; i >= 0; i--) {
  300. extend(path[i], bbox);
  301. }
  302. }
  303. _condense(path) {
  304. // go through the path, removing empty nodes and updating bboxes
  305. for (let i = path.length - 1, siblings; i >= 0; i--) {
  306. if (path[i].children.length === 0) {
  307. if (i > 0) {
  308. siblings = path[i - 1].children;
  309. siblings.splice(siblings.indexOf(path[i]), 1);
  310. } else this.clear();
  311. } else calcBBox(path[i], this.toBBox);
  312. }
  313. }
  314. }
  315. function findItem(item, items, equalsFn) {
  316. if (!equalsFn) return items.indexOf(item);
  317. for (let i = 0; i < items.length; i++) {
  318. if (equalsFn(item, items[i])) return i;
  319. }
  320. return -1;
  321. }
  322. // calculate node's bbox from bboxes of its children
  323. function calcBBox(node, toBBox) {
  324. distBBox(node, 0, node.children.length, toBBox, node);
  325. }
  326. // min bounding rectangle of node children from k to p-1
  327. function distBBox(node, k, p, toBBox, destNode) {
  328. if (!destNode) destNode = createNode(null);
  329. destNode.minX = Infinity;
  330. destNode.minY = Infinity;
  331. destNode.maxX = -Infinity;
  332. destNode.maxY = -Infinity;
  333. for (let i = k; i < p; i++) {
  334. const child = node.children[i];
  335. extend(destNode, node.leaf ? toBBox(child) : child);
  336. }
  337. return destNode;
  338. }
  339. function extend(a, b) {
  340. a.minX = Math.min(a.minX, b.minX);
  341. a.minY = Math.min(a.minY, b.minY);
  342. a.maxX = Math.max(a.maxX, b.maxX);
  343. a.maxY = Math.max(a.maxY, b.maxY);
  344. return a;
  345. }
  346. function compareNodeMinX(a, b) { return a.minX - b.minX; }
  347. function compareNodeMinY(a, b) { return a.minY - b.minY; }
  348. function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
  349. function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
  350. function enlargedArea(a, b) {
  351. return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
  352. (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
  353. }
  354. function intersectionArea(a, b) {
  355. const minX = Math.max(a.minX, b.minX);
  356. const minY = Math.max(a.minY, b.minY);
  357. const maxX = Math.min(a.maxX, b.maxX);
  358. const maxY = Math.min(a.maxY, b.maxY);
  359. return Math.max(0, maxX - minX) *
  360. Math.max(0, maxY - minY);
  361. }
  362. function contains(a, b) {
  363. return a.minX <= b.minX &&
  364. a.minY <= b.minY &&
  365. b.maxX <= a.maxX &&
  366. b.maxY <= a.maxY;
  367. }
  368. function intersects(a, b) {
  369. return b.minX <= a.maxX &&
  370. b.minY <= a.maxY &&
  371. b.maxX >= a.minX &&
  372. b.maxY >= a.minY;
  373. }
  374. function createNode(children) {
  375. return {
  376. children,
  377. height: 1,
  378. leaf: true,
  379. minX: Infinity,
  380. minY: Infinity,
  381. maxX: -Infinity,
  382. maxY: -Infinity
  383. };
  384. }
  385. // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
  386. // combines selection algorithm with binary divide & conquer approach
  387. function multiSelect(arr, left, right, n, compare) {
  388. const stack = [left, right];
  389. while (stack.length) {
  390. right = stack.pop();
  391. left = stack.pop();
  392. if (right - left <= n) continue;
  393. const mid = left + Math.ceil((right - left) / n / 2) * n;
  394. quickselect(arr, mid, left, right, compare);
  395. stack.push(left, mid, mid, right);
  396. }
  397. }