silphius/app/ecs/base.js

101 lines
2.0 KiB
JavaScript
Raw Normal View History

2024-06-10 22:42:30 -05:00
export default class Base {
2024-06-14 15:18:55 -05:00
ecs;
2024-06-10 22:42:30 -05:00
map = [];
pool = [];
static schema;
2024-06-14 15:18:55 -05:00
constructor(ecs) {
this.ecs = ecs;
}
2024-06-10 22:42:30 -05:00
allocateMany(count) {
const results = [];
while (count-- > 0 && this.pool.length > 0) {
results.push(this.pool.pop());
}
return results;
}
2024-06-11 19:10:57 -05:00
create(entityId, values) {
this.createMany([[entityId, values]]);
2024-06-10 22:42:30 -05:00
}
2024-06-11 19:10:57 -05:00
destroy(entityId) {
this.destroyMany([entityId]);
2024-06-10 22:42:30 -05:00
}
destroyMany(entities) {
this.freeMany(
entities
2024-06-11 19:10:57 -05:00
.map((entityId) => {
if ('undefined' !== typeof this.map[entityId]) {
return this.map[entityId];
2024-06-10 22:42:30 -05:00
}
2024-06-11 19:10:57 -05:00
throw new Error(`can't free for non-existent id ${entityId}`);
2024-06-10 22:42:30 -05:00
}),
);
for (let i = 0; i < entities.length; i++) {
this.map[entities[i]] = undefined;
}
}
static filterDefaults(instance) {
const json = {};
2024-06-12 01:38:05 -05:00
for (const key in this.properties) {
const {defaultValue} = this.properties[key];
if (key in instance && instance[key] !== defaultValue) {
json[key] = instance[key];
2024-06-10 22:42:30 -05:00
}
}
return json;
}
freeMany(indices) {
for (let i = 0; i < indices.length; ++i) {
this.pool.push(indices[i]);
}
}
2024-06-14 15:18:55 -05:00
static gathered(id, key) {
this.name = key;
}
2024-06-10 22:42:30 -05:00
insertMany(entities) {
const creating = [];
for (let i = 0; i < entities.length; i++) {
2024-06-11 19:10:57 -05:00
const [entityId, values] = entities[i];
if (!this.get(entityId)) {
creating.push([entityId, values]);
2024-06-10 22:42:30 -05:00
}
else {
2024-06-11 19:10:57 -05:00
const instance = this.get(entityId);
2024-06-10 22:42:30 -05:00
for (const i in values) {
instance[i] = values[i];
}
}
}
this.createMany(creating);
}
2024-06-14 15:18:55 -05:00
markChange(entityId, key, value) {
this.ecs.markChange(entityId, {[this.constructor.name]: {[key]: value}})
}
2024-06-10 22:42:30 -05:00
mergeDiff(original, update) {
return {...original, ...update};
}
2024-06-12 01:38:05 -05:00
static get properties() {
return this.schema.specification.properties;
}
2024-06-11 19:10:57 -05:00
sizeOf(entityId) {
return this.constructor.schema.sizeOf(this.get(entityId));
2024-06-10 22:42:30 -05:00
}
}