feat: apply

This commit is contained in:
cha0s 2024-12-01 22:49:00 -06:00
parent 1abbf9db3f
commit a98049fe07
2 changed files with 55 additions and 2 deletions

View File

@ -9,6 +9,7 @@ class Ecs {
Components = {};
entities = new Map();
Systems = {};
tracking = true;
constructor({Components, Systems}) {
for (const componentName in Components) {
@ -31,6 +32,38 @@ class Ecs {
};
}
apply(diff) {
const {tracking} = this;
this.tracking = false;
for (const [entityId, change] of diff) {
const entity = this.entities.get(entityId);
if (false === change) {
this.destroyImmediately(entity);
continue;
}
if (!entity) {
this.createSpecific(entityId, change);
continue;
}
for (const componentName in change) {
const values = change[componentName];
const Component = this.Components[componentName];
if (false === values) {
entity.removeComponent(Component);
continue;
}
if (!entity.has(componentName)) {
entity.addComponent(Component, values);
continue;
}
for (const key in values) {
entity[componentName][key] = values[key];
}
}
}
this.tracking = tracking;
}
create(components = {}) {
return this.createSpecific(this.nextId(), components);
}
@ -117,8 +150,10 @@ class Ecs {
}
markChange(entityId, componentName, change) {
this.$$diff = undefined;
this.changes.push({entityId, componentName, change});
if (this.tracking) {
this.$$diff = undefined;
this.changes.push({entityId, componentName, change});
}
}
static merge(l, r) {

View File

@ -106,3 +106,21 @@ test('serialization', async () => {
schema.encode(ecs.diff(), view);
expect(schema.decode(view)).to.deep.equal(ecs.diff());
});
test('apply', () => {
const ecs = new Ecs({Components: {A}, Systems: {}});
ecs.apply(new Map([[32, {}]]))
const entity = ecs.entities.get(32);
expect(entity).not.to.be.undefined;
expect(entity.has('A')).to.be.false;
ecs.apply(new Map([[32, {A: {}}]]))
expect(entity.has('A')).to.be.true;
expect(entity.A.a).to.equal(64);
ecs.apply(new Map([[32, {A: {a: 128}}]]))
expect(entity.A.a).to.equal(128);
ecs.apply(new Map([[32, {A: false}]]))
expect(entity.has('A')).to.be.false;
ecs.apply(new Map([[32, false]]))
expect(ecs.entities.get(32)).to.be.undefined;
expect(ecs.diff()).to.deep.equal(new Map());
});