silphius/app/ecs/query.js
2024-08-04 20:54:56 -05:00

69 lines
1.6 KiB
JavaScript

export default class Query {
$$criteria = {with: [], without: []};
$$ecs;
$$map = new Map();
constructor(parameters, ecs) {
this.$$ecs = ecs;
for (let i = 0; i < parameters.length; ++i) {
const parameter = parameters[i];
switch (parameter.charCodeAt(0)) {
case '!'.charCodeAt(0):
this.$$criteria.without.push(ecs.Components[parameter.slice(1)]);
break;
default:
this.$$criteria.with.push(ecs.Components[parameter]);
break;
}
}
}
get count() {
return this.$$map.size;
}
deindex(entityIds) {
for (const entityId of entityIds) {
this.$$map.delete(entityId);
}
}
reindex(entityIds) {
if (0 === this.$$criteria.with.length && 0 === this.$$criteria.without.length) {
for (const entityId of entityIds) {
this.$$map.set(entityId, this.$$ecs.get(entityId));
}
return;
}
for (const entityId of entityIds) {
let should = true;
for (let j = 0; j < this.$$criteria.with.length; ++j) {
if ('undefined' === typeof this.$$criteria.with[j].get(entityId)) {
should = false;
break;
}
}
if (should) {
for (let j = 0; j < this.$$criteria.without.length; ++j) {
if ('undefined' !== typeof this.$$criteria.without[j].get(entityId)) {
should = false;
break;
}
}
}
if (should) {
this.$$map.set(entityId, this.$$ecs.get(entityId));
}
else if (!should) {
this.$$map.delete(entityId);
}
}
}
select() {
return this.$$map.values();
}
}