index.js 16 KB

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