CPU based ParticleSystem implementation (#2730)

* Add RenderComponent markForCustomIARender

* CPU based ParticleSystem implementation

* Remove GPU based ParticleMaterial
This commit is contained in:
pandamicro
2018-05-24 16:05:15 +08:00
committed by GitHub
parent 8aea3b8be6
commit acb08dcab5
7 changed files with 571 additions and 759 deletions
+10 -1
View File
@@ -91,8 +91,17 @@ var RenderComponent = cc.Class({
}
},
markForCustomIARender (enable) {
if (enable && this.enabledInHierarchy) {
this.node._renderFlag |= RenderFlow.FLAG_CUSTOM_IA_RENDER;
}
else if (!enable) {
this.node._renderFlag &= ~RenderFlow.FLAG_CUSTOM_IA_RENDER;
}
},
disableRender () {
this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA);
this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | cc.RenderFlow.FLAG_CUSTOM_IA_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA);
},
requestRenderData () {
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+141 -311
View File
@@ -33,6 +33,7 @@ const tiffReader = require('./CCTIFFReader');
const textureUtil = require('../core/utils/texture-util');
const renderEngine = require('../core/renderer/render-engine');
const RenderFlow = require('../core/renderer/render-flow');
const ParticleSimulator = require('./particle-simulator');
const gfx = renderEngine.gfx;
const ParticleMaterial = renderEngine.ParticleMaterial;
const Particles = renderEngine.Particles;
@@ -267,17 +268,15 @@ var properties = {
},
/**
* !#en Current quantity of particles that are being simulated,
* this function can be very slow currently, please don't use it frequently.
* !#en Current quantity of particles that are being simulated.
* !#zh 当前播放的粒子数量。
* 当前版本该函数性能不够好,请不要频繁调用(比如每帧检查)。
* @property {Number} particleCount
* @readonly
*/
particleCount: {
visible: false,
get: function () {
return this._vfx.particleCount;
get () {
return this._simulator.particles.length;
},
readonly: true
},
@@ -322,6 +321,20 @@ var properties = {
tooltip: CC_DEV && 'i18n:COMPONENT.particle_system.dstBlendFactor'
},
/**
* !#en Indicate whether the system simulation have stopped.
* !#zh 指示粒子播放是否完毕。
* @property {Boolean} autoRemoveOnFinish
*/
_stopped: true,
stopped: {
get () {
return this._stopped;
},
animatable: false,
visible: false
},
/**
* !#en If set to true, the particle system will automatically start playing on onLoad.
* !#zh 如果设置为 true 运行时会自动发射粒子。
@@ -336,16 +349,8 @@ var properties = {
* !#zh 粒子播放完毕后自动销毁所在的节点。
* @property {Boolean} autoRemoveOnFinish
*/
_autoRemoveOnFinish: false,
autoRemoveOnFinish: {
get: function () {
return this._autoRemoveOnFinish;
},
set: function (value) {
if (this._autoRemoveOnFinish !== value) {
this._autoRemoveOnFinish = value;
}
},
default: false,
animatable: false,
tooltip: CC_DEV && 'i18n:COMPONENT.particle_system.autoRemoveOnFinish'
},
@@ -358,8 +363,7 @@ var properties = {
*/
active: {
get: function () {
// TODO: check wether it's activated (not stopped)
return this.enabledInHierarchy;
return this._simulator.active;
},
visible: false
},
@@ -370,16 +374,7 @@ var properties = {
* @property {Number} totalParticles
* @default 150
*/
_totalParticles: 150,
totalParticles: {
get () {
return this._totalParticles;
},
set (val) {
this._totalParticles = val;
this._maxParticleDirty = true;
}
},
totalParticles: 150,
/**
* !#en How many seconds the emitter wil run. -1 means 'forever'.
* !#zh 发射器生存时间,单位秒,-1表示持续发射。
@@ -393,111 +388,92 @@ var properties = {
* @property {Number} emissionRate
* @default 10
*/
_emissionRate: 10,
emissionRate: {
get () {
return this._emissionRate;
},
set (val) {
this._emissionRate = val;
this._maxParticleDirty = true;
}
},
emissionRate: 10,
/**
* !#en Life of each particle setter.
* !#zh 粒子的运行时间。
* @property {Number} life
* @default 1
*/
_life: 1,
life: {
get () {
return this._life;
},
set (val) {
this._life = val;
this._maxParticleDirty = true;
}
},
life: 1,
/**
* !#en Variation of life.
* !#zh 粒子的运行时间变化范围。
* @property {Number} lifeVar
* @default 0
*/
_lifeVar: 0,
lifeVar: {
get () {
return this._lifeVar;
},
set (val) {
this._lifeVar = val;
this._maxParticleDirty = true;
}
},
lifeVar: 0,
/**
* !#en Start color of each particle.
* !#zh 粒子初始颜色。
* @property {Color} startColor
* @default cc.Color.WHITE
* @property {Object} startColor
* @default {r: 255, g: 255, b: 255, a: 255}
*/
_startColor: cc.Color.WHITE,
_startColor: null,
startColor: {
get () {
return this._startColor;
},
set (val) {
this._startColor.fromColor(val);
this._vfx.startColor = val;
this._startColor.r = val.r;
this._startColor.g = val.g;
this._startColor.b = val.b;
this._startColor.a = val.a;
}
},
/**
* !#en Variation of the start color.
* !#zh 粒子初始颜色变化范围。
* @property {Color} startColorVar
* @default cc.Color.BLACK
* @property {Object} startColorVar
* @default {r: 0, g: 0, b: 0, a: 0}
*/
_startColorVar: cc.Color.BLACK,
_startColorVar: null,
startColorVar: {
get () {
return this._startColorVar;
},
set (val) {
this._startColorVar.fromColor(val);
this._vfx.startColorVar = val;
this._startColorVar.r = val.r;
this._startColorVar.g = val.g;
this._startColorVar.b = val.b;
this._startColorVar.a = val.a;
}
},
/**
* !#en Ending color of each particle.
* !#zh 粒子结束颜色。
* @property {Color} endColor
* @default new cc.Color(255, 255, 255, 0)
* @property {Object} endColor
* @default {r: 255, g: 255, b: 255, a: 0}
*/
_endColor: cc.color(255, 255, 255, 0),
_endColor: null,
endColor: {
get () {
return this._endColor;
},
set (val) {
this._endColor.fromColor(val);
this._vfx.endColor = val;
this._endColor.r = val.r;
this._endColor.g = val.g;
this._endColor.b = val.b;
this._endColor.a = val.a;
}
},
/**
* !#en Variation of the end color.
* !#zh 粒子结束颜色变化范围。
* @property {Color} endColorVar -
* @default Color.TRANSPARENT
* @property {Object} endColorVar
* @default {r: 0, g: 0, b: 0, a: 0}
*/
_endColorVar: cc.color(0, 0, 0, 0),
_endColorVar: null,
endColorVar: {
get () {
return this._endColorVar;
},
set (val) {
this._endColorVar.fromColor(val);
this._vfx.endColorVar = val;
this._endColorVar.r = val.r;
this._endColorVar.g = val.g;
this._endColorVar.b = val.b;
this._endColorVar.a = val.a;
}
},
@@ -521,64 +497,28 @@ var properties = {
* @property {Number} startSize
* @default 50
*/
_startSize: 50,
startSize: {
get () {
return this._startSize;
},
set (val) {
this._startSize = val;
this._sizeScaleDirty = true;
}
},
startSize: 50,
/**
* !#en Variation of start size in pixels.
* !#zh 粒子初始大小的变化范围。
* @property {Number} startSizeVar
* @default 0
*/
_startSizeVar: 0,
startSizeVar: {
get () {
return this._startSizeVar;
},
set (val) {
this._startSizeVar = val;
this._sizeScaleDirty = true;
}
},
startSizeVar: 0,
/**
* !#en End size in pixels of each particle.
* !#zh 粒子结束时的大小。
* @property {Number} endSize
* @default 0
*/
_endSize: 0,
endSize: {
get () {
return this._endSize;
},
set (val) {
this._endSize = val;
this._sizeScaleDirty = true;
}
},
endSize: 0,
/**
* !#en Variation of end size in pixels.
* !#zh 粒子结束大小的变化范围。
* @property {Number} endSizeVar
* @default 0
*/
_endSizeVar: 0,
endSizeVar: {
get () {
return this._endSizeVar;
},
set (val) {
this._endSizeVar = val;
this._sizeScaleDirty = true;
}
},
endSizeVar: 0,
/**
* !#en Start angle of each particle.
* !#zh 粒子开始自旋角度。
@@ -675,64 +615,28 @@ var properties = {
* @property {Number} tangentialAccel
* @default 80
*/
_tangentialAccel: 80,
tangentialAccel: {
get () {
return this._tangentialAccel;
},
set (val) {
this._tangentialAccel = val;
this._accelScaleDirty = true;
}
},
tangentialAccel: 80,
/**
* !#en Variation of the tangential acceleration.
* !#zh 每个粒子的切向加速度变化范围。
* @property {Number} tangentialAccelVar
* @default 0
*/
_tangentialAccelVar: 0,
tangentialAccelVar: {
get () {
return this._tangentialAccelVar;
},
set (val) {
this._tangentialAccelVar = val;
this._accelScaleDirty = true;
}
},
tangentialAccelVar: 0,
/**
* !#en Acceleration of each particle. Only available in 'Gravity' mode.
* !#zh 粒子径向加速度,即平行于重力方向的加速度,只有在重力模式下可用。
* @property {Number} radialAccel
* @default 0
*/
_radialAccel: 0,
radialAccel: {
get () {
return this._radialAccel;
},
set (val) {
this._radialAccel = val;
this._accelScaleDirty = true;
}
},
radialAccel: 0,
/**
* !#en Variation of the radial acceleration.
* !#zh 粒子径向加速度变化范围。
* @property {Number} radialAccelVar
* @default 0
*/
_radialAccelVar: 0,
radialAccelVar: {
get () {
return this._radialAccelVar;
},
set (val) {
this._radialAccelVar = val;
this._accelScaleDirty = true;
}
},
radialAccelVar: 0,
/**
* !#en Indicate whether the rotation of each particle equals to its direction. Only available in 'Gravity' mode.
@@ -750,64 +654,28 @@ var properties = {
* @property {Number} startRadius
* @default 0
*/
_startRadius: 0,
startRadius: {
get () {
return this._startRadius;
},
set (val) {
this._startRadius = val;
this._radiusScaleDirty = true;
}
},
startRadius: 0,
/**
* !#en Variation of the starting radius.
* !#zh 初始半径变化范围。
* @property {Number} startRadiusVar
* @default 0
*/
_startRadiusVar: 0,
startRadiusVar: {
get () {
return this._startRadiusVar;
},
set (val) {
this._startRadiusVar = val;
this._radiusScaleDirty = true;
}
},
startRadiusVar: 0,
/**
* !#en Ending radius of the particles. Only available in 'Radius' mode.
* !#zh 结束半径,只有在半径模式下可用。
* @property {Number} endRadius
* @default 0
*/
_endRadius: 0,
endRadius: {
get () {
return this._endRadius;
},
set (val) {
this._endRadius = val;
this._radiusScaleDirty = true;
}
},
endRadius: 0,
/**
* !#en Variation of the ending radius.
* !#zh 结束半径变化范围。
* @property {Number} endRadiusVar
* @default 0
*/
_endRadiusVar: 0,
endRadiusVar: {
get () {
return this._endRadiusVar;
},
set (val) {
this._endRadiusVar = val;
this._radiusScaleDirty = true;
}
},
endRadiusVar: 0,
/**
* !#en Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode.
* !#zh 粒子每秒围绕起始点的旋转角度,只有在半径模式下可用。
@@ -883,32 +751,13 @@ var ParticleSystem = cc.Class({
this._willStart = false;
this._texture = null;
// Material update caches
this._uv = {
l: 0.0,
b: 0.0,
r: 0.0,
t: 0.0
};
this._statesize = {
x: 0.0,
y: 0.0
};
this._quadsize = {
x: 0.0,
y: 0.0
};
// vfx handle real particle step process based on GPU shaders
this._vfx = new Particles(cc.renderer.device, cc.renderer._forward, this);
this._vfx.stopSystem();
this._vertexFormat = this._vfx.vertexFormat;
this._simulator = new ParticleSimulator(this);
// Config update flags, vfx constructor has updated with the current config, so not dirty
this._maxParticleDirty = false;
this._sizeScaleDirty = false;
this._radiusScaleDirty = false;
this._accelScaleDirty = false;
// colors
this._startColor = {r: 255, g: 255, b: 255, a: 255};
this._startColorVar = {r: 0, g: 0, b: 0, a: 0};
this._endColor = {r: 255, g: 255, b: 255, a: 0};
this._endColorVar = {r: 0, g: 0, b: 0, a: 0};
},
properties: properties,
@@ -949,60 +798,19 @@ var ParticleSystem = cc.Class({
PositionType: PositionType,
},
// LIFE-CYCLE METHODS
__preload: function () {
if (this._file) {
if (this._custom) {
var missCustomTexture = !this._texture;
if (missCustomTexture) {
this._applyFile();
}
this._applyCustoms();
}
else {
this._applyFile();
}
}
else if (this._custom) {
this._applyCustoms();
}
// auto play
if (!CC_EDITOR || cc.engine.isPlaying) {
if (this.playOnLoad) {
this.resetSystem();
}
}
},
onEnable: function () {
this._super();
// should add render flag after particle loaded
this.disableRender();
this._updateMaterial();
},
onDestroy: function () {
// TODO: do we need to release memory created by vfx
this._vfx = null;
if (this._autoRemoveOnFinish) {
this.autoRemoveOnFinish = false; // already removed
}
this._super();
},
// EDITOR RELATED METHODS
onFocusInEditor: CC_EDITOR && function () {
this._focused = true;
if (this.preview) {
this.resetSystem();
this.markForUpdateRenderData(true);
this.markForRender(true);
this.markForCustomIARender(true);
var self = this;
this._previewTimer = setInterval(function () {
// attemptToReplay
if (self._vfx && !self._willStart && self.particleCount === 0) {
if (!self._willStart && self.particleCount === 0) {
self._willStart = true;
setTimeout(function () {
self._willStart = false;
@@ -1028,6 +836,53 @@ var ParticleSystem = cc.Class({
}
},
// LIFE-CYCLE METHODS
__preload: function () {
if (this._file) {
if (this._custom) {
var missCustomTexture = !this._texture;
if (missCustomTexture) {
this._applyFile();
}
}
else {
this._applyFile();
}
}
// auto play
if (!CC_EDITOR || cc.engine.isPlaying) {
if (this.playOnLoad) {
this.resetSystem();
}
}
},
onLoad () {
ParticleSystem._assembler.createIA(this);
},
onEnable () {
this._super();
// should add render flag after particle loaded
this.disableRender();
this._updateMaterial();
},
onDestroy () {
if (this.autoRemoveOnFinish) {
this.autoRemoveOnFinish = false; // already removed
}
this._super();
},
update (dt) {
if (!this._simulator.finished && this._material) {
this._simulator.step(dt);
}
},
// APIS
/*
@@ -1049,7 +904,8 @@ var ParticleSystem = cc.Class({
* myParticleSystem.stopSystem();
*/
stopSystem: function () {
this._vfx.stopSystem();
this._stopped = true;
this._simulator.stop();
},
/**
@@ -1061,7 +917,9 @@ var ParticleSystem = cc.Class({
* myParticleSystem.resetSystem();
*/
resetSystem: function () {
this._vfx.resetSystem();
this._stopped = false;
this._simulator.reset();
this.markForCustomIARender(true);
},
/**
@@ -1119,19 +977,6 @@ var ParticleSystem = cc.Class({
}
},
_applyCustoms: function () {
// trigger vfx config update after deserialize
this._maxParticleDirty = true;
this._sizeScaleDirty = true;
this._radiusScaleDirty = true;
this._accelScaleDirty = true;
let vfx = this._vfx;
vfx.startColor = this.startColor;
vfx.startColorVar = this.startColorVar;
vfx.endColor = this.endColor;
vfx.endColorVar = this.endColorVar;
},
_initTextureWithDictionary: function (dict) {
var imgPath = cc.path.changeBasename(this._plistFile, dict["textureFileName"]);
// texture
@@ -1227,8 +1072,9 @@ var ParticleSystem = cc.Class({
this.endSizeVar = parseFloat(dict["finishParticleSizeVariance"] || 0);
// position
this.sourcePos.x = parseFloat(dict["sourcePositionx"] || 0);
this.sourcePos.y = parseFloat(dict["sourcePositiony"] || 0);
// for
this.sourcePos.x = 0;
this.sourcePos.y = 0;
this.posVar.x = parseFloat(dict["sourcePositionVariancex"] || 0);
this.posVar.y = parseFloat(dict["sourcePositionVariancey"] || 0);
@@ -1266,12 +1112,12 @@ var ParticleSystem = cc.Class({
var locRotationIsDir = dict["rotationIsDir"] || "";
if (locRotationIsDir !== null) {
locRotationIsDir = locRotationIsDir.toString().toLowerCase();
this._rotationIsDir = (locRotationIsDir === "true" || locRotationIsDir === "1");
this.rotationIsDir = (locRotationIsDir === "true" || locRotationIsDir === "1");
}
else {
this._rotationIsDir = false;
this.rotationIsDir = false;
}
} else if (this._emitterMode === EmitterMode.RADIUS) {
} else if (this.emitterMode === EmitterMode.RADIUS) {
// or Mode B: radius movement
this.startRadius = parseFloat(dict["maxRadius"] || 0);
this.startRadiusVar = parseFloat(dict["maxRadiusVariance"] || 0);
@@ -1315,18 +1161,6 @@ var ParticleSystem = cc.Class({
}
},
_updateMaterialSize: function () {
if (this._material) {
let vfx = this._vfx;
this._statesize.x = vfx.statesize[0];
this._statesize.y = vfx.statesize[1];
this._quadsize.x = vfx.quadsize[0];
this._quadsize.y = vfx.quadsize[1];
this._material.stateSize = this._statesize;
this._material.quadSize = this._quadsize;
}
},
_updateMaterial: function () {
if (!this.enabledInHierarchy) {
this.disableRender();
@@ -1334,7 +1168,7 @@ var ParticleSystem = cc.Class({
}
// cannot be activated if texture not loaded yet
if (!this._texture || !this._texture.loaded) {
this.markForRender(false);
this.markForCustomIARender(false);
if (this._spriteFrame) {
this._applySpriteFrame();
}
@@ -1343,22 +1177,17 @@ var ParticleSystem = cc.Class({
// Get material
if (!this._material) {
this._material = new ParticleMaterial();
// Particle System cannot be batched, so every one use a unique hash id
this._material.updateHash(this._id);
this._material = new renderEngine.SpriteMaterial();
this._material.useTexture = true;
this._material.useModel = true;
this._material.useColor = false;
this._material.texture = this._texture;
}
let vfx = this._vfx;
this._material.texture = this._texture;
this._material.stateMap = this._vfx.textures.state0;
this._material.quadMap = this._vfx.textures.quads;
this._material.z = this.node.z;
this._updateMaterialSize();
this._updateBlendFunc();
this.markForUpdateRenderData(true);
this.markForRender(true);
this.markForCustomIARender(true);
},
_updateBlendFunc: function () {
@@ -1373,11 +1202,12 @@ var ParticleSystem = cc.Class({
gfx.BLEND_FUNC_ADD,
this._srcBlendFactor, this._dstBlendFactor
);
this._material.updateHash();
},
_finishedSimulation: function () {
if (this._autoRemoveOnFinish && this._vfx.stopped) {
this.disableRender();
this.disableRender();
if (this.autoRemoveOnFinish && this._stopped) {
this.node.destroy();
}
}
+1
View File
@@ -25,4 +25,5 @@
require('./CCParticleAsset');
require('./CCParticleSystem');
require('./particle-simulator');
require('./particle-system-assembler');
+398
View File
@@ -0,0 +1,398 @@
/****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
const AffineTrans = require('../core/utils/affine-transform');
const js = require('../core/platform/js');
const misc = require('../core/utils/misc');
const ZERO_VEC2 = cc.v2(0, 0);
let _trans = AffineTrans.create();
let _pos = cc.v2();
let _tpa = cc.v2();
let _tpb = cc.v2();
let _tpc = cc.v2();
let Particle = function () {
this.pos = cc.v2(0, 0);
this.startPos = cc.v2(0, 0);
this.color = cc.color(0, 0, 0, 255);
this.deltaColor = {r: 0, g: 0, b: 0, a: 255};
this.size = 0;
this.deltaSize = 0;
this.rotation = 0;
this.deltaRotation = 0;
this.timeToLive = 0;
this.drawPos = cc.v2(0, 0);
// Mode A
this.dir = cc.v2(0, 0);
this.radialAccel = 0;
this.tangentialAccel = 0;
// Mode B
this.angle = 0;
this.degreesPerSecond = 0;
this.radius = 0;
this.deltaRadius = 0;
}
let pool = new js.Pool(function (par) {
par.pos.set(ZERO_VEC2);
par.startPos.set(ZERO_VEC2);
par.color._val = ((255<<24) >>> 0);
par.deltaColor.r = par.deltaColor.g = par.deltaColor.b = 0;
par.deltaColor.a = 255;
par.size = 0;
par.deltaSize = 0;
par.rotation = 0;
par.deltaRotation = 0;
par.timeToLive = 0;
par.drawPos.set(ZERO_VEC2);
// Mode A
par.dir.set(ZERO_VEC2);
par.radialAccel = 0;
par.tangentialAccel = 0;
// Mode B
par.angle = 0;
par.degreesPerSecond = 0;
par.radius = 0;
par.deltaRadius = 0;
}, 1024);
pool.get = function () {
return this._get() || new Particle();
}
let Simulator = function (system) {
this.sys = system;
this.particles = [];
this.active = false;
this.finished = false;
this.elapsed = 0;
this.emitCounter = 0;
}
Simulator.prototype.stop = function () {
this.active = false;
this.elapsed = this.sys.duration;
this.emitCounter = 0;
}
Simulator.prototype.reset = function () {
this.active = true;
this.elapsed = 0;
this.emitCounter = 0;
this.finished = false;
let particles = this.particles;
for (let id = 0; id < particles.length; ++id)
pool.put(particles[id]);
particles.length = 0;
}
Simulator.prototype.emitParticle = function (pos) {
let psys = this.sys;
let clampf = misc.clampf;
let particle = pool.get();
this.particles.push(particle);
// Init particle
// timeToLive
// no negative life. prevent division by 0
particle.timeToLive = psys.life + psys.lifeVar * (Math.random() - 0.5) * 2;
let timeToLive = particle.timeToLive = Math.max(0, particle.timeToLive);
// position
particle.pos.x = psys.sourcePos.x + psys.posVar.x * (Math.random() - 0.5) * 2;
particle.pos.y = psys.sourcePos.y + psys.posVar.y * (Math.random() - 0.5) * 2;
// Color
let sr, sg, sb, sa;
let startColor = psys._startColor, startColorVar = psys._startColorVar;
let endColor = psys._endColor, endColorVar = psys._endColorVar;
particle.color.r = sr = clampf(startColor.r + startColorVar.r * (Math.random() - 0.5) * 2, 0, 255);
particle.color.g = sg = clampf(startColor.g + startColorVar.g * (Math.random() - 0.5) * 2, 0, 255);
particle.color.b = sb = clampf(startColor.b + startColorVar.b * (Math.random() - 0.5) * 2, 0, 255);
particle.color.a = sa = clampf(startColor.a + startColorVar.a * (Math.random() - 0.5) * 2, 0, 255);
particle.deltaColor.r = (clampf(endColor.r + endColorVar.r * (Math.random() - 0.5) * 2, 0, 255) - sr) / timeToLive;
particle.deltaColor.g = (clampf(endColor.g + endColorVar.g * (Math.random() - 0.5) * 2, 0, 255) - sg) / timeToLive;
particle.deltaColor.b = (clampf(endColor.b + endColorVar.b * (Math.random() - 0.5) * 2, 0, 255) - sb) / timeToLive;
particle.deltaColor.a = (clampf(endColor.a + endColorVar.a * (Math.random() - 0.5) * 2, 0, 255) - sa) / timeToLive;
// size
let startS = psys.startSize + psys.startSizeVar * (Math.random() - 0.5) * 2;
startS = Math.max(0, startS); // No negative value
particle.size = startS;
if (psys.endSize === cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE) {
particle.deltaSize = 0;
} else {
var endS = psys.endSize + psys.endSizeVar * (Math.random() - 0.5) * 2;
endS = Math.max(0, endS); // No negative values
particle.deltaSize = (endS - startS) / timeToLive;
}
// rotation
var startA = psys.startSpin + psys.startSpinVar * (Math.random() - 0.5) * 2;
var endA = psys.endSpin + psys.endSpinVar * (Math.random() - 0.5) * 2;
particle.rotation = startA;
particle.deltaRotation = (endA - startA) / timeToLive;
// position
particle.startPos.x = pos.x;
particle.startPos.y = pos.y;
// direction
let a = misc.degreesToRadians(psys.angle + psys.angleVar * (Math.random() - 0.5) * 2);
// Mode Gravity: A
if (psys.emitterMode === cc.ParticleSystem.EmitterMode.GRAVITY) {
let s = psys.speed + psys.speedVar * (Math.random() - 0.5) * 2;
// direction
particle.dir.x = Math.cos(a);
particle.dir.y = Math.sin(a);
particle.dir.mulSelf(s);
// radial accel
particle.radialAccel = psys.radialAccel + psys.radialAccelVar * (Math.random() - 0.5) * 2;
// tangential accel
particle.tangentialAccel = psys.tangentialAccel + psys.tangentialAccelVar * (Math.random() - 0.5) * 2;
// rotation is dir
if (psys.rotationIsDir) {
particle.rotation = -misc.radiansToDegrees(Math.atan2(particle.dir.y, particle.dir.x));
}
}
// Mode Radius: B
else {
// Set the default diameter of the particle from the source position
var startRadius = psys.startRadius + psys.startRadiusVar * (Math.random() - 0.5) * 2;
var endRadius = psys.endRadius + psys.endRadiusVar * (Math.random() - 0.5) * 2;
particle.radius = startRadius;
particle.deltaRadius = (psys.endRadius === cc.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS) ? 0 : (endRadius - startRadius) / timeToLive;
particle.angle = a;
particle.degreesPerSecond = misc.degreesToRadians(psys.rotatePerS + psys.rotatePerSVar * (Math.random() - 0.5) * 2);
}
};
Simulator.prototype.updateParticleBuffer = function (particle, pos, buffer, offset) {
let vbuf = buffer._vData;
let uintbuf = buffer._uintVData;
let uv = this.sys._spriteFrame.uv;
let x = pos.x, y = pos.y;
let size_2 = particle.size / 2;
// pos
if (particle.rotation) {
let x1 = -size_2, y1 = -size_2;
let x2 = size_2, y2 = size_2;
let rad = -misc.degreesToRadians(particle.rotation);
let cr = Math.cos(rad), sr = Math.sin(rad);
// bl
vbuf[offset] = x1 * cr - y1 * sr + x;
vbuf[offset+1] = x1 * sr + y1 * cr + y;
// br
vbuf[offset+5] = x2 * cr - y1 * sr + x;
vbuf[offset+6] = x2 * sr + y1 * cr + y;
// tl
vbuf[offset+10] = x1 * cr - y2 * sr + x;
vbuf[offset+11] = x1 * sr + y2 * cr + y;
// tr
vbuf[offset+15] = x2 * cr - y2 * sr + x;
vbuf[offset+16] = x2 * sr + y2 * cr + y;
}
else {
// bl
vbuf[offset] = x - size_2;
vbuf[offset+1] = y - size_2;
// br
vbuf[offset+5] = x + size_2;
vbuf[offset+6] = y - size_2;
// tl
vbuf[offset+10] = x - size_2;
vbuf[offset+11] = y + size_2;
// tr
vbuf[offset+15] = x + size_2;
vbuf[offset+16] = y + size_2;
}
// uv
vbuf[offset+2] = uv[0];
vbuf[offset+3] = uv[1];
vbuf[offset+7] = uv[2];
vbuf[offset+8] = uv[3];
vbuf[offset+12] = uv[4];
vbuf[offset+13] = uv[5];
vbuf[offset+17] = uv[6];
vbuf[offset+18] = uv[7];
// color
uintbuf[offset+4] = particle.color._val;
uintbuf[offset+9] = particle.color._val;
uintbuf[offset+14] = particle.color._val;
uintbuf[offset+19] = particle.color._val;
};
Simulator.prototype.step = function (dt) {
let psys = this.sys;
let node = psys.node;
let particles = this.particles;
const FLOAT_PER_PARTICLE = 4 * psys._vertexFormat._bytes / 4;
// Calculate pos
node._updateWorldMatrix();
AffineTrans.fromMat4(_trans, node._worldMatrix);
if (psys.positionType === cc.ParticleSystem.PositionType.FREE) {
AffineTrans.transformVec2(_pos, ZERO_VEC2, _trans);
} else if (psys.positionType === cc.ParticleSystem.PositionType.RELATIVE) {
_pos.x = node._position.x;
_pos.y = node._position.y;
}
// Get world to node trans only once
AffineTrans.invert(_trans, _trans);
let worldToNodeTrans = _trans;
// Emission
if (this.active && psys.emissionRate) {
var rate = 1.0 / psys.emissionRate;
//issue #1201, prevent bursts of particles, due to too high emitCounter
if (particles.length < psys.totalParticles)
this.emitCounter += dt;
while ((particles.length < psys.totalParticles) && (this.emitCounter > rate)) {
this.emitParticle(_pos);
this.emitCounter -= rate;
}
this.elapsed += dt;
if (psys.duration !== -1 && psys.duration < this.elapsed)
psys.stopSystem();
}
// Request buffer for particles
let buffer = psys._buffer;
buffer.reset();
buffer.request(particles.length * 4, particles.length * 6);
// Used to reduce memory allocation / creation within the loop
let particleIdx = 0;
while (particleIdx < particles.length) {
// Reset temporary vectors
_tpa.x = _tpa.y = _tpb.x = _tpb.y = _tpc.x = _tpc.y = 0;
let particle = particles[particleIdx];
// life
particle.timeToLive -= dt;
if (particle.timeToLive > 0) {
// Mode A: gravity, direction, tangential accel & radial accel
if (psys.emitterMode === cc.ParticleSystem.EmitterMode.GRAVITY) {
let tmp = _tpc, radial = _tpa, tangential = _tpb;
// radial acceleration
if (particle.pos.x || particle.pos.y) {
radial.set(particle.pos);
radial.normalizeSelf();
}
tangential.set(radial);
radial.mulSelf(particle.radialAccel);
// tangential acceleration
let newy = tangential.x;
tangential.x = -tangential.y;
tangential.y = newy;
tangential.mulSelf(particle.tangentialAccel);
tmp.set(radial);
tmp.addSelf(tangential);
tmp.addSelf(psys.gravity);
tmp.mulSelf(dt);
particle.dir.addSelf(tmp);
tmp.set(particle.dir);
tmp.mulSelf(dt);
particle.pos.addSelf(tmp);
}
// Mode B: radius movement
else {
// Update the angle and radius of the particle.
particle.angle += particle.degreesPerSecond * dt;
particle.radius += particle.deltaRadius * dt;
particle.pos.x = -Math.cos(particle.angle) * particle.radius;
particle.pos.y = -Math.sin(particle.angle) * particle.radius;
}
// color
particle.color.r += particle.deltaColor.r * dt;
particle.color.g += particle.deltaColor.g * dt;
particle.color.b += particle.deltaColor.b * dt;
particle.color.a += particle.deltaColor.a * dt;
// size
particle.size += particle.deltaSize * dt;
if (particle.size < 0) {
particle.size = 0;
}
// angle
particle.rotation += particle.deltaRotation * dt;
// update values in quad buffer
let newPos = _tpa;
if (psys.positionType === cc.ParticleSystem.PositionType.FREE || psys.positionType === cc.ParticleSystem.PositionType.RELATIVE) {
let diff = _tpb, startPos = _tpc;
// current Position convert To Node Space
AffineTrans.transformVec2(diff, _pos, worldToNodeTrans);
// start Position convert To Node Space
AffineTrans.transformVec2(startPos, particle.startPos, worldToNodeTrans);
diff.subSelf(startPos);
newPos.set(particle.pos);
newPos.subSelf(diff);
} else {
newPos.set(particle.pos);
}
let offset = FLOAT_PER_PARTICLE * particleIdx;
this.updateParticleBuffer(particle, newPos, buffer, offset);
// update particle counter
++particleIdx;
} else {
// life < 0
let deadParticle = particles[particleIdx];
if (particleIdx !== particles.length - 1) {
particles[particleIdx] = particles[particles.length - 1];
}
pool.put(deadParticle);
particles.length--;
if (particles.length === 0) {
this.finished = true;
psys._finishedSimulation();
}
}
}
if (particles.length > 0) {
buffer.uploadData();
psys._ia._count = particles.length * 6;
}
}
module.exports = Simulator;
+21 -99
View File
@@ -25,118 +25,40 @@
const js = require('../core/platform/js');
const ParticleSystem = require('./CCParticleSystem');
const renderer = require('../core/renderer/');
const renderEngine = require('../core/renderer/render-engine');
const vfmtPosUvColor = require('../core/renderer/webgl/vertex-format').vfmtPosUvColor;
const QuadBuffer = require('../core/renderer/webgl/quad-buffer');
const RenderFlow = require('../core/renderer/render-flow');
var particleSystemAssembler = {
useModel: true,
updateUVs (comp) {
let material = comp.getMaterial();
let renderData = comp._renderData;
if (material && renderData) {
let data = renderData._data;
let texture = material.effect.getProperty('texture');
let texw = texture._width,
texh = texture._height;
let frame = comp.spriteFrame;
let rect = frame._rect;
comp._uv.l = texw === 0 ? 0 : (rect.x / texw);
comp._uv.t = texh === 0 ? 0 : (rect.y / texh);
comp._uv.r = texw === 0 ? 0 : (rect.x + rect.width / texw);
comp._uv.b = texh === 0 ? 0 : (rect.y + rect.height / texh);
comp._material.uv = comp._uv;
renderData.uvDirty = false;
}
createIA (comp) {
let device = renderer.device;
// Vertex format defines vertex buffer layout: x, y, u, v color
comp._vertexFormat = vfmtPosUvColor;
// Create quad buffer for vertex and index
comp._buffer = new QuadBuffer(renderer._walker, vfmtPosUvColor);
comp._ia = new renderEngine.InputAssembler();
comp._ia._vertexBuffer = comp._buffer._vb;
comp._ia._indexBuffer = comp._buffer._ib;
comp._ia._start = 0;
comp._ia._count = 0;
},
updateRenderData (comp) {
if (!comp._renderData) {
comp._renderData = comp.requestRenderData();
comp._renderData.dataLength = 0;
comp._renderData = new renderEngine.IARenderData();
comp._renderData.material = comp._material;
comp._renderData.ia = comp._ia;
}
let renderData = comp._renderData;
if (renderData.uvDirty) {
this.updateUVs(comp);
}
let vfx = comp._vfx;
// Update particle configs
if (comp._maxParticleDirty) {
vfx.updateMaxParticle(comp);
comp._updateMaterialSize();
comp._maxParticleDirty = false;
}
if (comp._sizeScaleDirty) {
vfx.updateSizeScale(comp);
comp._sizeScaleDirty = false;
}
if (comp._accelScaleDirty) {
vfx.updateAccelScale(comp);
comp._accelScaleDirty = false;
}
if (comp._radiusScaleDirty) {
vfx.updateRadiusScale(comp);
comp._radiusScaleDirty = false;
}
// Process to generate vertex buffer and index buffer
// TODO: Update vfx parameters, check whether to update other material configs, z etc
let running = !vfx.stopped;
vfx.step(cc.director.getDeltaTime());
// check finish
if (running && vfx.stopped) {
comp.scheduleOnce(comp._finishedSimulation, 0);
}
renderData.vertexCount = vfx.buffers.indexes.length;
renderData.indiceCount = renderData.vertexCount / 2 * 3;
renderData.material = comp.getMaterial();
},
fillBuffers (comp, renderer) {
let verts = comp._vfx.buffers.indexes;
let buffer = renderer.getBuffer('mesh', comp._vertexFormat),
vertexOffset = buffer.byteOffset >> 2,
vbuf = buffer._vData;
let ibuf = buffer._iData,
indiceOffset = buffer.indiceOffset,
vertexId = buffer.vertexOffset;
let quads = verts.length / 4;
let quadsize = comp._vfx.quadsize;
let w = quadsize[0], h = quadsize[1];
buffer.request(verts.length, w/2 * h/2 * 6);
// vertex buffer
for (let i = 0; i < verts.length; i++) {
vbuf[vertexOffset] = verts[i];
vertexOffset++;
}
// index buffer
for (let y = 0; y < h; y+=2) {
for (let x = 0; x < w; x+=2) {
let i = vertexId + y * w + x;
ibuf[indiceOffset + 0] = i;
ibuf[indiceOffset + 1] = i + 1;
ibuf[indiceOffset + 2] = i + w;
ibuf[indiceOffset + 3] = i + 1;
ibuf[indiceOffset + 4] = i + w + 1;
ibuf[indiceOffset + 5] = i + w;
indiceOffset += 6;
}
}
comp.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA;
renderIA (comp, renderer) {
renderer._flushIA(comp._renderData);
}
};