silphius/app/ecs/systems/maintain-collider-hash.js

64 lines
1.2 KiB
JavaScript
Raw Normal View History

2024-07-28 18:40:58 -05:00
import {System} from '@/ecs/index.js';
import SpatialHash from '@/util/spatial-hash.js';
export default class MaintainColliderHash extends System {
hash;
deindex(entities) {
super.deindex(entities);
for (const id of entities) {
this.hash.remove(id);
}
}
static get priority() {
return {
after: 'IntegratePhysics',
};
}
reindex(entities) {
for (const id of entities) {
if (1 === id) {
2024-07-30 09:56:53 -05:00
const {AreaSize} = this.ecs.get(1);
if (AreaSize) {
this.hash = new SpatialHash(AreaSize);
}
2024-07-28 18:40:58 -05:00
}
}
super.reindex(entities);
for (const id of entities) {
this.updateHash(this.ecs.get(id));
}
}
updateHash(entity) {
2024-07-30 09:56:53 -05:00
if (!entity.Collider || !this.hash) {
2024-07-28 18:40:58 -05:00
return;
}
this.hash.update(entity.Collider.aabb, entity.id);
}
tick() {
for (const entity of this.ecs.changed(['Direction'])) {
if (!entity.Collider) {
continue;
}
entity.Collider.updateAabbs();
}
for (const entity of this.ecs.changed(['Position'])) {
this.updateHash(entity);
}
}
within(query) {
const within = new Set();
for (const id of this.hash.within(query)) {
within.add(this.ecs.get(id));
}
return within;
}
}