@spearwolf/twopoint5d
Version:
Create 2.5D realtime graphics and pixelart with WebGL and three.js
77 lines • 3.12 kB
JavaScript
import { Map2DTileCoordsUtil } from './Map2DTileCoordsUtil.js';
export class Map2DSpatialHashGrid {
static getKey(x, y) {
return `${x};${y}`;
}
#tiles;
#tileCoordsUtil;
constructor(tileWidth = 0, tileHeight = 0, xOffset = 0, yOffset = 0) {
this.#tiles = new Map();
this.#tileCoordsUtil = new Map2DTileCoordsUtil(tileWidth, tileHeight, xOffset, yOffset);
}
add(...renderables) {
for (const renderable of renderables) {
const { left, top, width, height } = renderable.aabb;
const [tileLeft, tileTop, tileColumns, tileRows] = this.#tileCoordsUtil.getTileCoords(left, top, width, height);
for (let y = 0; y < tileRows; y++) {
for (let x = 0; x < tileColumns; x++) {
const tileKey = Map2DSpatialHashGrid.getKey(tileLeft + x, tileTop + y);
let tileSet = this.#tiles.get(tileKey);
if (tileSet) {
tileSet.add(renderable);
}
else {
tileSet = new Set();
this.#tiles.set(tileKey, tileSet);
}
tileSet.add(renderable);
}
}
}
return this;
}
remove(...renderables) {
for (const renderable of renderables) {
const { left, top, width, height } = renderable.aabb;
const [tileLeft, tileTop, tileColumns, tileRows] = this.#tileCoordsUtil.getTileCoords(left, top, width, height);
for (let y = 0; y < tileRows; y++) {
for (let x = 0; x < tileColumns; x++) {
const tileKey = Map2DSpatialHashGrid.getKey(tileLeft + x, tileTop + y);
const tileSet = this.#tiles.get(tileKey);
if (tileSet) {
tileSet.delete(renderable);
if (tileSet.size === 0) {
this.#tiles.delete(tileKey);
}
}
}
}
}
return this;
}
findWithin(aabb) {
const { left, top, width, height } = aabb;
const [tileLeft, tileTop, tileColumns, tileRows] = this.#tileCoordsUtil.getTileCoords(left, top, width, height);
return this.getTiles(tileLeft, tileTop, tileColumns, tileRows);
}
getTiles(tileX, tileY, width = 1, height = 1) {
let renderables;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const tileSet = this.getTile(tileX + x, tileY + y);
if (tileSet) {
renderables ??= new Set();
for (const renderable of tileSet) {
renderables.add(renderable);
}
}
}
}
return renderables;
}
getTile(tileX, tileY) {
const tileKey = Map2DSpatialHashGrid.getKey(tileX, tileY);
return this.#tiles.get(tileKey);
}
}
//# sourceMappingURL=Map2DSpatialHashGrid.js.map