opt: pool

This commit is contained in:
cha0s 2022-05-09 11:01:16 -05:00
parent 3bca7da3bf
commit 18dd5eb75c
2 changed files with 39 additions and 2 deletions

View File

@ -199,6 +199,20 @@ export default (flecks) => {
});
}
static dependencyTree(types) {
const Traits = flecks.get('$avocado/traits.traits');
const tree = new Set(types);
const checking = types;
while (checking.length > 0) {
const Trait = Traits[checking.pop()];
if (Trait) {
checking.push(...Trait.dependencies());
tree.add(Trait.type);
}
}
return tree;
}
async destroy() {
if (this.$$isDestroying) {
return;

View File

@ -24,6 +24,8 @@ export default (flecks) => class Emitter extends decorate(Trait) {
$$particles = {};
$$pool = [];
$$proton = new Proton();
$$streams = [];
@ -59,7 +61,25 @@ export default (flecks) => class Emitter extends decorate(Trait) {
async emitParticleJson(json) {
const {Entity} = flecks.get('$avocado/resource.resources');
return this.entity.emitParticleEntity(await Entity.load(json));
let entity;
if (this.$$pool.length > 0) {
entity = this.$$pool.pop();
const entityTypes = entity.traitTypes();
const jsonTypes = Entity.dependencyTree(Object.keys(json?.traits || {}));
const promises = [];
for (let i = 0; i < entityTypes.length; ++i) {
const entityType = entityTypes[i];
if (!jsonTypes.has(entityType)) {
promises.push(entity.removeTrait(entityType));
}
}
await Promise.all(promises);
await entity.load(json);
}
else {
entity = await Entity.load(json);
}
return this.entity.emitParticleEntity(entity);
}
gatherParticles() {
@ -226,7 +246,10 @@ export default (flecks) => class Emitter extends decorate(Trait) {
onParticleDead(particle) {
particle.body.emit('particleDied');
if (particle.body.isTransientParticle) {
particle.body.destroy();
if (particle.body.list) {
particle.body.list.removeEntity(particle.body);
}
this.$$pool.push(particle.body);
}
}