rbush.js 16 KB

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