refactor: particle emission stream

This commit is contained in:
cha0s 2019-12-12 19:55:30 -06:00
parent 12307024fc
commit d94bafd2f5

View File

@ -1,3 +1,5 @@
import K from 'kefir';
import {compose, merge} from '@avocado/core'; import {compose, merge} from '@avocado/core';
import {Entity, StateProperty, Trait} from '@avocado/entity'; import {Entity, StateProperty, Trait} from '@avocado/entity';
import {Vector} from '@avocado/math'; import {Vector} from '@avocado/math';
@ -83,9 +85,10 @@ export class Emitter extends decorate(Trait) {
return hooks; return hooks;
} }
emitParticleJson(json) { emitParticleJson(json, emitter) {
return Entity.loadOrInstance(json).then((particle) => { Entity.loadOrInstance(json).then((particle) => {
this.entity.emitParticleEntity(particle); this.entity.emitParticleEntity(particle);
emitter.emit(particle);
}); });
} }
@ -154,21 +157,23 @@ export class Emitter extends decorate(Trait) {
} }
// Prime. // Prime.
this.onParticleUpdate(protonParticle); this.onParticleUpdate(protonParticle);
return entity;
}, },
emitParticleJson: (json) => { emitParticleJson: (json) => {
return K.stream((emitter) => {
let { let {
count = 1, count = 1,
rate = 0, rate = 0,
} = json; } = json;
if (0 === rate) { if (0 === rate) {
for (let i = 0; i < count; ++i) { for (let i = 0; i < count; ++i) {
this.emitParticleJson(json); this.emitParticleJson(json, emitter);
} }
} }
else { else {
const ticker = new Ticker(rate); const ticker = new Ticker(rate);
this.emitParticleJson(json); this.emitParticleJson(json, emitter);
count -= 1; count -= 1;
if (count > 0) { if (count > 0) {
const removeEmission = () => { const removeEmission = () => {
@ -176,17 +181,21 @@ export class Emitter extends decorate(Trait) {
if (-1 !== index) { if (-1 !== index) {
this.emissions.splice(index, 1); this.emissions.splice(index, 1);
} }
emitter.end();
}; };
this.entity.on('destroy', removeEmission); this.entity.on('destroy', removeEmission);
ticker.on('tick', () => { ticker.on('tick', () => {
this.emitParticleJson(json); this.emitParticleJson(json, emitter);
if (0 >= --count) { if (0 >= --count) {
removeEmission(); removeEmission();
} }
}); });
this.emissions.push(ticker); this.emissions.push(ticker);
return;
} }
} }
emitter.end();
});
}, },
emitParticle: (key, json = {}) => { emitParticle: (key, json = {}) => {
@ -195,7 +204,7 @@ export class Emitter extends decorate(Trait) {
return; return;
} }
const mergedJson = merge({}, particleJson, json); const mergedJson = merge({}, particleJson, json);
this.entity.emitParticleJson(mergedJson); return this.entity.emitParticleJson(mergedJson);
}, },
}; };