index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. const ARRAY_TYPES = [
  2. Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
  3. Int32Array, Uint32Array, Float32Array, Float64Array
  4. ];
  5. /** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */
  6. const VERSION = 1; // serialized format version
  7. const HEADER_SIZE = 8;
  8. export default class KDBush {
  9. /**
  10. * Creates an index from raw `ArrayBuffer` data.
  11. * @param {ArrayBuffer} data
  12. */
  13. static from(data) {
  14. if (!(data instanceof ArrayBuffer)) {
  15. throw new Error('Data must be an instance of ArrayBuffer.');
  16. }
  17. const [magic, versionAndType] = new Uint8Array(data, 0, 2);
  18. if (magic !== 0xdb) {
  19. throw new Error('Data does not appear to be in a KDBush format.');
  20. }
  21. const version = versionAndType >> 4;
  22. if (version !== VERSION) {
  23. throw new Error(`Got v${version} data when expected v${VERSION}.`);
  24. }
  25. const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];
  26. if (!ArrayType) {
  27. throw new Error('Unrecognized array type.');
  28. }
  29. const [nodeSize] = new Uint16Array(data, 2, 1);
  30. const [numItems] = new Uint32Array(data, 4, 1);
  31. return new KDBush(numItems, nodeSize, ArrayType, data);
  32. }
  33. /**
  34. * Creates an index that will hold a given number of items.
  35. * @param {number} numItems
  36. * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).
  37. * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
  38. * @param {ArrayBuffer} [data] (For internal use only)
  39. */
  40. constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) {
  41. if (isNaN(numItems) || numItems < 0) throw new Error(`Unpexpected numItems value: ${numItems}.`);
  42. this.numItems = +numItems;
  43. this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
  44. this.ArrayType = ArrayType;
  45. this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;
  46. const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
  47. const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;
  48. const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;
  49. const padCoords = (8 - idsByteSize % 8) % 8;
  50. if (arrayTypeIndex < 0) {
  51. throw new Error(`Unexpected typed array class: ${ArrayType}.`);
  52. }
  53. if (data && (data instanceof ArrayBuffer)) { // reconstruct an index from a buffer
  54. this.data = data;
  55. this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
  56. this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
  57. this._pos = numItems * 2;
  58. this._finished = true;
  59. } else { // initialize a new index
  60. this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);
  61. this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
  62. this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
  63. this._pos = 0;
  64. this._finished = false;
  65. // set header
  66. new Uint8Array(this.data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]);
  67. new Uint16Array(this.data, 2, 1)[0] = nodeSize;
  68. new Uint32Array(this.data, 4, 1)[0] = numItems;
  69. }
  70. }
  71. /**
  72. * Add a point to the index.
  73. * @param {number} x
  74. * @param {number} y
  75. * @returns {number} An incremental index associated with the added item (starting from `0`).
  76. */
  77. add(x, y) {
  78. const index = this._pos >> 1;
  79. this.ids[index] = index;
  80. this.coords[this._pos++] = x;
  81. this.coords[this._pos++] = y;
  82. return index;
  83. }
  84. /**
  85. * Perform indexing of the added points.
  86. */
  87. finish() {
  88. const numAdded = this._pos >> 1;
  89. if (numAdded !== this.numItems) {
  90. throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);
  91. }
  92. // kd-sort both arrays for efficient search
  93. sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);
  94. this._finished = true;
  95. return this;
  96. }
  97. /**
  98. * Search the index for items within a given bounding box.
  99. * @param {number} minX
  100. * @param {number} minY
  101. * @param {number} maxX
  102. * @param {number} maxY
  103. * @returns {number[]} An array of indices correponding to the found items.
  104. */
  105. range(minX, minY, maxX, maxY) {
  106. if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');
  107. const {ids, coords, nodeSize} = this;
  108. const stack = [0, ids.length - 1, 0];
  109. const result = [];
  110. // recursively search for items in range in the kd-sorted arrays
  111. while (stack.length) {
  112. const axis = stack.pop() || 0;
  113. const right = stack.pop() || 0;
  114. const left = stack.pop() || 0;
  115. // if we reached "tree node", search linearly
  116. if (right - left <= nodeSize) {
  117. for (let i = left; i <= right; i++) {
  118. const x = coords[2 * i];
  119. const y = coords[2 * i + 1];
  120. if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);
  121. }
  122. continue;
  123. }
  124. // otherwise find the middle index
  125. const m = (left + right) >> 1;
  126. // include the middle item if it's in range
  127. const x = coords[2 * m];
  128. const y = coords[2 * m + 1];
  129. if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);
  130. // queue search in halves that intersect the query
  131. if (axis === 0 ? minX <= x : minY <= y) {
  132. stack.push(left);
  133. stack.push(m - 1);
  134. stack.push(1 - axis);
  135. }
  136. if (axis === 0 ? maxX >= x : maxY >= y) {
  137. stack.push(m + 1);
  138. stack.push(right);
  139. stack.push(1 - axis);
  140. }
  141. }
  142. return result;
  143. }
  144. /**
  145. * Search the index for items within a given radius.
  146. * @param {number} qx
  147. * @param {number} qy
  148. * @param {number} r Query radius.
  149. * @returns {number[]} An array of indices correponding to the found items.
  150. */
  151. within(qx, qy, r) {
  152. if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');
  153. const {ids, coords, nodeSize} = this;
  154. const stack = [0, ids.length - 1, 0];
  155. const result = [];
  156. const r2 = r * r;
  157. // recursively search for items within radius in the kd-sorted arrays
  158. while (stack.length) {
  159. const axis = stack.pop() || 0;
  160. const right = stack.pop() || 0;
  161. const left = stack.pop() || 0;
  162. // if we reached "tree node", search linearly
  163. if (right - left <= nodeSize) {
  164. for (let i = left; i <= right; i++) {
  165. if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]);
  166. }
  167. continue;
  168. }
  169. // otherwise find the middle index
  170. const m = (left + right) >> 1;
  171. // include the middle item if it's in range
  172. const x = coords[2 * m];
  173. const y = coords[2 * m + 1];
  174. if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);
  175. // queue search in halves that intersect the query
  176. if (axis === 0 ? qx - r <= x : qy - r <= y) {
  177. stack.push(left);
  178. stack.push(m - 1);
  179. stack.push(1 - axis);
  180. }
  181. if (axis === 0 ? qx + r >= x : qy + r >= y) {
  182. stack.push(m + 1);
  183. stack.push(right);
  184. stack.push(1 - axis);
  185. }
  186. }
  187. return result;
  188. }
  189. }
  190. /**
  191. * @param {Uint16Array | Uint32Array} ids
  192. * @param {InstanceType<TypedArrayConstructor>} coords
  193. * @param {number} nodeSize
  194. * @param {number} left
  195. * @param {number} right
  196. * @param {number} axis
  197. */
  198. function sort(ids, coords, nodeSize, left, right, axis) {
  199. if (right - left <= nodeSize) return;
  200. const m = (left + right) >> 1; // middle index
  201. // sort ids and coords around the middle index so that the halves lie
  202. // either left/right or top/bottom correspondingly (taking turns)
  203. select(ids, coords, m, left, right, axis);
  204. // recursively kd-sort first half and second half on the opposite axis
  205. sort(ids, coords, nodeSize, left, m - 1, 1 - axis);
  206. sort(ids, coords, nodeSize, m + 1, right, 1 - axis);
  207. }
  208. /**
  209. * Custom Floyd-Rivest selection algorithm: sort ids and coords so that
  210. * [left..k-1] items are smaller than k-th item (on either x or y axis)
  211. * @param {Uint16Array | Uint32Array} ids
  212. * @param {InstanceType<TypedArrayConstructor>} coords
  213. * @param {number} k
  214. * @param {number} left
  215. * @param {number} right
  216. * @param {number} axis
  217. */
  218. function select(ids, coords, k, left, right, axis) {
  219. while (right > left) {
  220. if (right - left > 600) {
  221. const n = right - left + 1;
  222. const m = k - left + 1;
  223. const z = Math.log(n);
  224. const s = 0.5 * Math.exp(2 * z / 3);
  225. const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
  226. const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
  227. const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
  228. select(ids, coords, k, newLeft, newRight, axis);
  229. }
  230. const t = coords[2 * k + axis];
  231. let i = left;
  232. let j = right;
  233. swapItem(ids, coords, left, k);
  234. if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);
  235. while (i < j) {
  236. swapItem(ids, coords, i, j);
  237. i++;
  238. j--;
  239. while (coords[2 * i + axis] < t) i++;
  240. while (coords[2 * j + axis] > t) j--;
  241. }
  242. if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);
  243. else {
  244. j++;
  245. swapItem(ids, coords, j, right);
  246. }
  247. if (j <= k) left = j + 1;
  248. if (k <= j) right = j - 1;
  249. }
  250. }
  251. /**
  252. * @param {Uint16Array | Uint32Array} ids
  253. * @param {InstanceType<TypedArrayConstructor>} coords
  254. * @param {number} i
  255. * @param {number} j
  256. */
  257. function swapItem(ids, coords, i, j) {
  258. swap(ids, i, j);
  259. swap(coords, 2 * i, 2 * j);
  260. swap(coords, 2 * i + 1, 2 * j + 1);
  261. }
  262. /**
  263. * @param {InstanceType<TypedArrayConstructor>} arr
  264. * @param {number} i
  265. * @param {number} j
  266. */
  267. function swap(arr, i, j) {
  268. const tmp = arr[i];
  269. arr[i] = arr[j];
  270. arr[j] = tmp;
  271. }
  272. /**
  273. * @param {number} ax
  274. * @param {number} ay
  275. * @param {number} bx
  276. * @param {number} by
  277. */
  278. function sqDist(ax, ay, bx, by) {
  279. const dx = ax - bx;
  280. const dy = ay - by;
  281. return dx * dx + dy * dy;
  282. }