babylon.particleSystem.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var randomNumber = function (min, max) {
  4. if (min === max) {
  5. return (min);
  6. }
  7. var random = Math.random();
  8. return ((random * (max - min)) + min);
  9. };
  10. var ParticleSystem = (function () {
  11. function ParticleSystem(name, capacity, scene, customEffect) {
  12. var _this = this;
  13. this.name = name;
  14. this.renderingGroupId = 0;
  15. this.emitter = null;
  16. this.emitRate = 10;
  17. this.manualEmitCount = -1;
  18. this.updateSpeed = 0.01;
  19. this.targetStopDuration = 0;
  20. this.disposeOnStop = false;
  21. this.minEmitPower = 1;
  22. this.maxEmitPower = 1;
  23. this.minLifeTime = 1;
  24. this.maxLifeTime = 1;
  25. this.minSize = 1;
  26. this.maxSize = 1;
  27. this.minAngularSpeed = 0;
  28. this.maxAngularSpeed = 0;
  29. this.layerMask = 0x0FFFFFFF;
  30. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  31. this.forceDepthWrite = false;
  32. this.gravity = BABYLON.Vector3.Zero();
  33. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  34. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  35. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  36. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  37. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  40. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  41. this.particles = new Array();
  42. this._vertexDeclaration = [3, 4, 4];
  43. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  44. this._stockParticles = new Array();
  45. this._newPartsExcess = 0;
  46. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  47. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  48. this._scaledDirection = BABYLON.Vector3.Zero();
  49. this._scaledGravity = BABYLON.Vector3.Zero();
  50. this._currentRenderId = -1;
  51. this._started = false;
  52. this._stopped = false;
  53. this._actualFrame = 0;
  54. this.id = name;
  55. this._capacity = capacity;
  56. this._scene = scene;
  57. this._customEffect = customEffect;
  58. scene.particleSystems.push(this);
  59. // VBO
  60. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  61. var indices = [];
  62. var index = 0;
  63. for (var count = 0; count < capacity; count++) {
  64. indices.push(index);
  65. indices.push(index + 1);
  66. indices.push(index + 2);
  67. indices.push(index);
  68. indices.push(index + 2);
  69. indices.push(index + 3);
  70. index += 4;
  71. }
  72. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  73. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  74. // Default behaviors
  75. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  76. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  77. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  78. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  79. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  80. };
  81. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  82. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  83. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  84. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  85. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  86. };
  87. this.updateFunction = function (particles) {
  88. for (var index = 0; index < particles.length; index++) {
  89. var particle = particles[index];
  90. particle.age += _this._scaledUpdateSpeed;
  91. if (particle.age >= particle.lifeTime) {
  92. _this.recycleParticle(particle);
  93. index--;
  94. continue;
  95. }
  96. else {
  97. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  98. particle.color.addInPlace(_this._scaledColorStep);
  99. if (particle.color.a < 0)
  100. particle.color.a = 0;
  101. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  102. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  103. particle.position.addInPlace(_this._scaledDirection);
  104. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  105. particle.direction.addInPlace(_this._scaledGravity);
  106. }
  107. }
  108. };
  109. }
  110. ParticleSystem.prototype.recycleParticle = function (particle) {
  111. var lastParticle = this.particles.pop();
  112. if (lastParticle !== particle) {
  113. lastParticle.copyTo(particle);
  114. this._stockParticles.push(lastParticle);
  115. }
  116. };
  117. ParticleSystem.prototype.getCapacity = function () {
  118. return this._capacity;
  119. };
  120. ParticleSystem.prototype.isAlive = function () {
  121. return this._alive;
  122. };
  123. ParticleSystem.prototype.isStarted = function () {
  124. return this._started;
  125. };
  126. ParticleSystem.prototype.start = function () {
  127. this._started = true;
  128. this._stopped = false;
  129. this._actualFrame = 0;
  130. };
  131. ParticleSystem.prototype.stop = function () {
  132. this._stopped = true;
  133. };
  134. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  135. var offset = index * 11;
  136. this._vertices[offset] = particle.position.x;
  137. this._vertices[offset + 1] = particle.position.y;
  138. this._vertices[offset + 2] = particle.position.z;
  139. this._vertices[offset + 3] = particle.color.r;
  140. this._vertices[offset + 4] = particle.color.g;
  141. this._vertices[offset + 5] = particle.color.b;
  142. this._vertices[offset + 6] = particle.color.a;
  143. this._vertices[offset + 7] = particle.angle;
  144. this._vertices[offset + 8] = particle.size;
  145. this._vertices[offset + 9] = offsetX;
  146. this._vertices[offset + 10] = offsetY;
  147. };
  148. ParticleSystem.prototype._update = function (newParticles) {
  149. // Update current
  150. this._alive = this.particles.length > 0;
  151. this.updateFunction(this.particles);
  152. // Add new ones
  153. var worldMatrix;
  154. if (this.emitter.position) {
  155. worldMatrix = this.emitter.getWorldMatrix();
  156. }
  157. else {
  158. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  159. }
  160. var particle;
  161. for (var index = 0; index < newParticles; index++) {
  162. if (this.particles.length === this._capacity) {
  163. break;
  164. }
  165. if (this._stockParticles.length !== 0) {
  166. particle = this._stockParticles.pop();
  167. particle.age = 0;
  168. }
  169. else {
  170. particle = new BABYLON.Particle();
  171. }
  172. this.particles.push(particle);
  173. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  174. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  175. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  176. particle.size = randomNumber(this.minSize, this.maxSize);
  177. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  178. this.startPositionFunction(worldMatrix, particle.position, particle);
  179. var step = randomNumber(0, 1.0);
  180. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  181. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  182. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  183. }
  184. };
  185. ParticleSystem.prototype._getEffect = function () {
  186. if (this._customEffect) {
  187. return this._customEffect;
  188. }
  189. ;
  190. var defines = [];
  191. if (this._scene.clipPlane) {
  192. defines.push("#define CLIPPLANE");
  193. }
  194. // Effect
  195. var join = defines.join("\n");
  196. if (this._cachedDefines !== join) {
  197. this._cachedDefines = join;
  198. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  199. }
  200. return this._effect;
  201. };
  202. ParticleSystem.prototype.animate = function () {
  203. if (!this._started)
  204. return;
  205. var effect = this._getEffect();
  206. // Check
  207. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  208. return;
  209. if (this._currentRenderId === this._scene.getRenderId()) {
  210. return;
  211. }
  212. this._currentRenderId = this._scene.getRenderId();
  213. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  214. // determine the number of particles we need to create
  215. var emitCout;
  216. if (this.manualEmitCount > -1) {
  217. emitCout = this.manualEmitCount;
  218. this.manualEmitCount = 0;
  219. }
  220. else {
  221. emitCout = this.emitRate;
  222. }
  223. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  224. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  225. if (this._newPartsExcess > 1.0) {
  226. newParticles += this._newPartsExcess >> 0;
  227. this._newPartsExcess -= this._newPartsExcess >> 0;
  228. }
  229. this._alive = false;
  230. if (!this._stopped) {
  231. this._actualFrame += this._scaledUpdateSpeed;
  232. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  233. this.stop();
  234. }
  235. else {
  236. newParticles = 0;
  237. }
  238. this._update(newParticles);
  239. // Stopped?
  240. if (this._stopped) {
  241. if (!this._alive) {
  242. this._started = false;
  243. if (this.disposeOnStop) {
  244. this._scene._toBeDisposed.push(this);
  245. }
  246. }
  247. }
  248. // Update VBO
  249. var offset = 0;
  250. for (var index = 0; index < this.particles.length; index++) {
  251. var particle = this.particles[index];
  252. this._appendParticleVertex(offset++, particle, 0, 0);
  253. this._appendParticleVertex(offset++, particle, 1, 0);
  254. this._appendParticleVertex(offset++, particle, 1, 1);
  255. this._appendParticleVertex(offset++, particle, 0, 1);
  256. }
  257. var engine = this._scene.getEngine();
  258. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  259. };
  260. ParticleSystem.prototype.render = function () {
  261. var effect = this._getEffect();
  262. // Check
  263. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  264. return 0;
  265. var engine = this._scene.getEngine();
  266. // Render
  267. engine.enableEffect(effect);
  268. engine.setState(false);
  269. var viewMatrix = this._scene.getViewMatrix();
  270. effect.setTexture("diffuseSampler", this.particleTexture);
  271. effect.setMatrix("view", viewMatrix);
  272. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  273. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  274. if (this._scene.clipPlane) {
  275. var clipPlane = this._scene.clipPlane;
  276. var invView = viewMatrix.clone();
  277. invView.invert();
  278. effect.setMatrix("invView", invView);
  279. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  280. }
  281. // VBOs
  282. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  283. // Draw order
  284. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  285. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  286. }
  287. else {
  288. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  289. }
  290. if (this.forceDepthWrite) {
  291. engine.setDepthWrite(true);
  292. }
  293. engine.draw(true, 0, this.particles.length * 6);
  294. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  295. return this.particles.length;
  296. };
  297. ParticleSystem.prototype.dispose = function () {
  298. if (this._vertexBuffer) {
  299. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  300. this._vertexBuffer = null;
  301. }
  302. if (this._indexBuffer) {
  303. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  304. this._indexBuffer = null;
  305. }
  306. if (this.particleTexture) {
  307. this.particleTexture.dispose();
  308. this.particleTexture = null;
  309. }
  310. // Remove from scene
  311. var index = this._scene.particleSystems.indexOf(this);
  312. this._scene.particleSystems.splice(index, 1);
  313. // Callback
  314. if (this.onDispose) {
  315. this.onDispose();
  316. }
  317. };
  318. // Clone
  319. ParticleSystem.prototype.clone = function (name, newEmitter) {
  320. var result = new ParticleSystem(name, this._capacity, this._scene);
  321. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  322. if (newEmitter === undefined) {
  323. newEmitter = this.emitter;
  324. }
  325. result.emitter = newEmitter;
  326. if (this.particleTexture) {
  327. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  328. }
  329. result.start();
  330. return result;
  331. };
  332. ParticleSystem.prototype.serialize = function () {
  333. var serializationObject = {};
  334. serializationObject.emitterId = this.emitter.id;
  335. serializationObject.capacity = this.getCapacity();
  336. if (this.particleTexture) {
  337. serializationObject.textureName = this.particleTexture.name;
  338. }
  339. serializationObject.minAngularSpeed = this.minAngularSpeed;
  340. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  341. serializationObject.minSize = this.minSize;
  342. serializationObject.maxSize = this.maxSize;
  343. serializationObject.minLifeTime = this.minLifeTime;
  344. serializationObject.maxLifeTime = this.maxLifeTime;
  345. serializationObject.emitRate = this.emitRate;
  346. serializationObject.minEmitBox = this.minEmitBox.asArray();
  347. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  348. serializationObject.gravity = this.gravity.asArray();
  349. serializationObject.direction1 = this.direction1.asArray();
  350. serializationObject.direction2 = this.direction2.asArray();
  351. serializationObject.color1 = this.color1.asArray();
  352. serializationObject.color2 = this.color2.asArray();
  353. serializationObject.colorDead = this.colorDead.asArray();
  354. serializationObject.updateSpeed = this.updateSpeed;
  355. serializationObject.targetStopDuration = this.targetStopDuration;
  356. serializationObject.textureMask = this.textureMask.asArray();
  357. serializationObject.blendMode = this.blendMode;
  358. return serializationObject;
  359. };
  360. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  361. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  362. var particleSystem = new ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  363. if (parsedParticleSystem.textureName) {
  364. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  365. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  366. }
  367. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  368. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  369. particleSystem.minSize = parsedParticleSystem.minSize;
  370. particleSystem.maxSize = parsedParticleSystem.maxSize;
  371. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  372. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  373. particleSystem.emitter = emitter;
  374. particleSystem.emitRate = parsedParticleSystem.emitRate;
  375. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  376. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  377. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  378. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  379. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  380. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  381. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  382. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  383. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  384. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  385. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  386. particleSystem.blendMode = parsedParticleSystem.blendMode;
  387. particleSystem.start();
  388. return particleSystem;
  389. };
  390. // Statics
  391. ParticleSystem.BLENDMODE_ONEONE = 0;
  392. ParticleSystem.BLENDMODE_STANDARD = 1;
  393. return ParticleSystem;
  394. })();
  395. BABYLON.ParticleSystem = ParticleSystem;
  396. })(BABYLON || (BABYLON = {}));