* Return all objects that could collide with the given object. * * **Re-entrancy contract:** when called with no explicit `result` * argument, this method reuses a single root-level scratch array to * avoid per-frame allocations. The returned reference is therefore * **not safe to retain**
( item: QuadTreeItem, fn?: QuadTreeSortFn, result?: QuadTreeItem[], )
| 434 | * @returns array with all detected objects |
| 435 | */ |
| 436 | retrieve( |
| 437 | item: QuadTreeItem, |
| 438 | fn?: QuadTreeSortFn, |
| 439 | result?: QuadTreeItem[], |
| 440 | ): QuadTreeItem[] { |
| 441 | // Reuse the root's scratch array across calls. Pointer events |
| 442 | // fire on every mouse move and each one used to allocate a |
| 443 | // fresh `[]`; resetting the existing array's length to 0 is |
| 444 | // allocation-free. See the JSDoc above for the re-entrancy |
| 445 | // contract that this optimization implies. |
| 446 | const isRoot = typeof result === "undefined"; |
| 447 | let out: QuadTreeItem[]; |
| 448 | if (isRoot) { |
| 449 | out = this._retrieveScratch!; |
| 450 | out.length = 0; |
| 451 | } else { |
| 452 | out = result; |
| 453 | } |
| 454 | |
| 455 | // add objects at this level |
| 456 | const objects = this.objects; |
| 457 | for (let i = 0, len = objects.length; i < len; i++) { |
| 458 | out.push(objects[i]); |
| 459 | } |
| 460 | |
| 461 | //if we have subnodes ... |
| 462 | if (this.nodes.length > 0) { |
| 463 | const index = this.getIndex(item); |
| 464 | |
| 465 | //if rect fits into a subnode .. |
| 466 | if (index !== -1) { |
| 467 | this.nodes[index].retrieve(item, undefined, out); |
| 468 | } else { |
| 469 | //if rect does not fit into a subnode, check it against all subnodes |
| 470 | for (let i = 0; i < this.nodes.length; i++) { |
| 471 | this.nodes[i].retrieve(item, undefined, out); |
| 472 | } |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | if (isRoot && typeof fn === "function") { |
| 477 | out.sort(fn); |
| 478 | } |
| 479 | |
| 480 | return out; |
| 481 | } |
| 482 | |
| 483 | /** |
| 484 | * Remove the given item from the quadtree. |