feat: system frequency

This commit is contained in:
cha0s 2024-06-30 15:54:23 -05:00
parent 2ab82d1d3e
commit b9a86312de
5 changed files with 27 additions and 28 deletions

View File

@ -2,6 +2,8 @@ import {System} from '@/ecs/index.js';
export default class PlantGrowth extends System {
frequency = 1;
static queries() {
return {
default: ['Plant'],

View File

@ -2,6 +2,8 @@ import {System} from '@/ecs/index.js';
export default class Water extends System {
frequency = 1;
tick(elapsed) {
const {Water} = this.ecs.get(1);
for (const tile in Water.water) {

View File

@ -344,32 +344,31 @@ export default class Ecs {
}
tick(elapsed) {
for (const systemName in this.Systems) {
if (this.Systems[systemName].active) {
this.Systems[systemName].tick(elapsed);
}
}
for (const systemName in this.Systems) {
if (this.Systems[systemName].active) {
this.Systems[systemName].finalize(elapsed);
}
}
this.tickDestruction();
}
tickDestruction() {
const unique = new Set();
const destroying = new Set();
for (const systemName in this.Systems) {
const System = this.Systems[systemName];
if (System.active) {
for (let j = 0; j < System.destroying.length; j++) {
unique.add(System.destroying[j]);
if (System.frequency) {
System.elapsed += elapsed;
if (System.elapsed < System.frequency) {
continue;
}
}
while (!System.frequency || System.elapsed >= System.frequency) {
System.tick(System.frequency ? System.elapsed : elapsed);
for (let j = 0; j < System.destroying.length; j++) {
destroying.add(System.destroying[j]);
}
System.tickDestruction();
if (!System.frequency) {
break;
}
System.elapsed -= System.frequency;
}
System.tickDestruction();
}
}
if (unique.size > 0) {
this.destroyMany(unique.values());
if (destroying.size > 0) {
this.destroyMany(destroying.values());
}
}

View File

@ -209,13 +209,9 @@ test('creates entities when ticking systems', () => {
});
test('schedules entities to be deleted when ticking systems', () => {
let entity;
const ecs = new Ecs({
Systems: {
Despawn: class extends System {
finalize() {
entity = ecs.get(1);
}
tick() {
this.destroyEntity(1);
}
@ -225,8 +221,6 @@ test('schedules entities to be deleted when ticking systems', () => {
ecs.system('Despawn').active = true;
ecs.create();
ecs.tick(1);
expect(entity)
.to.not.be.undefined;
expect(ecs.get(1))
.to.be.undefined;
});

View File

@ -10,6 +10,10 @@ export default class System {
ecs;
elapsed = 0;
frequency;
queries = {};
constructor(ecs) {
@ -45,8 +49,6 @@ export default class System {
}
}
finalize() {}
async insertComponents(entityId, components) {
return this.ecs.insert(entityId, components);
}