From 18dd5eb75c5292652c61d3110437cf7404b5812d Mon Sep 17 00:00:00 2001 From: cha0s Date: Mon, 9 May 2022 11:01:16 -0500 Subject: [PATCH] opt: pool --- packages/entity/src/resources/entity.js | 14 +++++++++++++ packages/physics/src/traits/emitter.js | 27 +++++++++++++++++++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/packages/entity/src/resources/entity.js b/packages/entity/src/resources/entity.js index 53c42ed..cd3b699 100644 --- a/packages/entity/src/resources/entity.js +++ b/packages/entity/src/resources/entity.js @@ -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; diff --git a/packages/physics/src/traits/emitter.js b/packages/physics/src/traits/emitter.js index 454b079..0f004db 100644 --- a/packages/physics/src/traits/emitter.js +++ b/packages/physics/src/traits/emitter.js @@ -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); } }