UNPKG

@mousepox/math

Version:

Math-related objects and utilities

38 lines (37 loc) 1.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SpatialHash = void 0; const core_1 = require("./core"); class SpatialHash { constructor(size) { this.pairs = []; this.buckets = new Map(); this.size = size; } clear() { this.buckets.clear(); } insert(rect) { const ox = Math.floor(rect.x / this.size); const tx = Math.floor((rect.x + rect.width) / this.size); for (let x = ox; x <= tx; ++x) { const oy = Math.floor(rect.y / this.size); const ty = Math.floor((rect.y + rect.height) / this.size); for (let y = oy; y <= ty; ++y) { const key = x + ((core_1.GoldenRatio * y) % 1); let bucket = this.buckets.get(key); if (bucket === undefined) { bucket = []; this.buckets.set(key, bucket); } else { for (const other of bucket) { this.pairs.push([other, rect]); } } bucket.push(rect); } } } } exports.SpatialHash = SpatialHash;