babylon.particleSystem.ts 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. module BABYLON {
  2. /**
  3. * This represents a particle system in Babylon.
  4. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  5. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  6. * @example https://doc.babylonjs.com/babylon101/particles
  7. */
  8. export class ParticleSystem implements IDisposable, IAnimatable, IParticleSystem {
  9. /**
  10. * Source color is added to the destination color without alpha affecting the result.
  11. */
  12. public static BLENDMODE_ONEONE = 0;
  13. /**
  14. * Blend current color and particle color using particle’s alpha.
  15. */
  16. public static BLENDMODE_STANDARD = 1;
  17. /**
  18. * List of animations used by the particle system.
  19. */
  20. public animations: Animation[] = [];
  21. /**
  22. * The id of the Particle system.
  23. */
  24. public id: string;
  25. /**
  26. * The friendly name of the Particle system.
  27. */
  28. public name: string;
  29. /**
  30. * The rendering group used by the Particle system to chose when to render.
  31. */
  32. public renderingGroupId = 0;
  33. /**
  34. * The emitter represents the Mesh or position we are attaching the particle system to.
  35. */
  36. public emitter: Nullable<AbstractMesh | Vector3> = null;
  37. /**
  38. * The maximum number of particles to emit per frame
  39. */
  40. public emitRate = 10;
  41. /**
  42. * If you want to launch only a few particles at once, that can be done, as well.
  43. */
  44. public manualEmitCount = -1;
  45. /**
  46. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  47. */
  48. public updateSpeed = 0.01;
  49. /**
  50. * The amount of time the particle system is running (depends of the overall update speed).
  51. */
  52. public targetStopDuration = 0;
  53. /**
  54. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55. */
  56. public disposeOnStop = false;
  57. /**
  58. * Minimum power of emitting particles.
  59. */
  60. public minEmitPower = 1;
  61. /**
  62. * Maximum power of emitting particles.
  63. */
  64. public maxEmitPower = 1;
  65. /**
  66. * Minimum life time of emitting particles.
  67. */
  68. public minLifeTime = 1;
  69. /**
  70. * Maximum life time of emitting particles.
  71. */
  72. public maxLifeTime = 1;
  73. /**
  74. * Minimum Size of emitting particles.
  75. */
  76. public minSize = 1;
  77. /**
  78. * Maximum Size of emitting particles.
  79. */
  80. public maxSize = 1;
  81. /**
  82. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  83. */
  84. public minAngularSpeed = 0;
  85. /**
  86. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  87. */
  88. public maxAngularSpeed = 0;
  89. /**
  90. * The texture used to render each particle. (this can be a spritesheet)
  91. */
  92. public particleTexture: Nullable<Texture>;
  93. /**
  94. * The layer mask we are rendering the particles through.
  95. */
  96. public layerMask: number = 0x0FFFFFFF;
  97. /**
  98. * This can help using your own shader to render the particle system.
  99. * The according effect will be created
  100. */
  101. public customShader: any = null;
  102. /**
  103. * By default particle system starts as soon as they are created. This prevents the
  104. * automatic start to happen and let you decide when to start emitting particles.
  105. */
  106. public preventAutoStart: boolean = false;
  107. /**
  108. * This function can be defined to provide custom update for active particles.
  109. * This function will be called instead of regular update (age, position, color, etc.).
  110. * Do not forget that this function will be called on every frame so try to keep it simple and fast :)
  111. */
  112. public updateFunction: (particles: Particle[]) => void;
  113. /**
  114. * Callback triggered when the particle animation is ending.
  115. */
  116. public onAnimationEnd: Nullable<() => void> = null;
  117. /**
  118. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  119. */
  120. public blendMode = ParticleSystem.BLENDMODE_ONEONE;
  121. /**
  122. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  123. * to override the particles.
  124. */
  125. public forceDepthWrite = false;
  126. /**
  127. * You can use gravity if you want to give an orientation to your particles.
  128. */
  129. public gravity = Vector3.Zero();
  130. /**
  131. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  132. * This only works when particleEmitterTyps is a BoxParticleEmitter
  133. */
  134. public get direction1(): Vector3 {
  135. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  136. return (<BoxParticleEmitter>this.particleEmitterType).direction1;
  137. }
  138. return Vector3.Zero();
  139. }
  140. public set direction1(value: Vector3) {
  141. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  142. (<BoxParticleEmitter>this.particleEmitterType).direction1 = value;
  143. }
  144. }
  145. /**
  146. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  147. * This only works when particleEmitterTyps is a BoxParticleEmitter
  148. */
  149. public get direction2(): Vector3 {
  150. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  151. return (<BoxParticleEmitter>this.particleEmitterType).direction2;
  152. }
  153. return Vector3.Zero();
  154. }
  155. public set direction2(value: Vector3) {
  156. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  157. (<BoxParticleEmitter>this.particleEmitterType).direction2 = value;
  158. }
  159. }
  160. /**
  161. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  162. * This only works when particleEmitterTyps is a BoxParticleEmitter
  163. */
  164. public get minEmitBox(): Vector3 {
  165. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  166. return (<BoxParticleEmitter>this.particleEmitterType).minEmitBox;
  167. }
  168. return Vector3.Zero();
  169. }
  170. public set minEmitBox(value: Vector3) {
  171. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  172. (<BoxParticleEmitter>this.particleEmitterType).minEmitBox = value;
  173. }
  174. }
  175. /**
  176. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  177. * This only works when particleEmitterTyps is a BoxParticleEmitter
  178. */
  179. public get maxEmitBox(): Vector3 {
  180. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  181. return (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox;
  182. }
  183. return Vector3.Zero();
  184. }
  185. public set maxEmitBox(value: Vector3) {
  186. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  187. (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox = value;
  188. }
  189. }
  190. /**
  191. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  192. */
  193. public color1 = new Color4(1.0, 1.0, 1.0, 1.0);
  194. /**
  195. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  196. */
  197. public color2 = new Color4(1.0, 1.0, 1.0, 1.0);
  198. /**
  199. * Color the particle will have at the end of its lifetime.
  200. */
  201. public colorDead = new Color4(0, 0, 0, 1.0);
  202. /**
  203. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  204. */
  205. public textureMask = new Color4(1.0, 1.0, 1.0, 1.0);
  206. /**
  207. * The particle emitter type defines the emitter used by the particle system.
  208. * It can be for example box, sphere, or cone...
  209. */
  210. public particleEmitterType: IParticleEmitterType;
  211. /**
  212. * This function can be defined to specify initial direction for every new particle.
  213. * It by default use the emitterType defined function.
  214. */
  215. public startDirectionFunction: (emitPower: number, worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void;
  216. /**
  217. * This function can be defined to specify initial position for every new particle.
  218. * It by default use the emitterType defined function.
  219. */
  220. public startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void;
  221. /**
  222. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  223. */
  224. public spriteCellLoop = true;
  225. /**
  226. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  227. */
  228. public spriteCellChangeSpeed = 0;
  229. /**
  230. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  231. */
  232. public startSpriteCellID = 0;
  233. /**
  234. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  235. */
  236. public endSpriteCellID = 0;
  237. /**
  238. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  239. */
  240. public spriteCellWidth = 0;
  241. /**
  242. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  243. */
  244. public spriteCellHeight = 0;
  245. /**
  246. * An event triggered when the system is disposed.
  247. */
  248. public onDisposeObservable = new Observable<ParticleSystem>();
  249. private _onDisposeObserver: Nullable<Observer<ParticleSystem>>;
  250. /**
  251. * Sets a callback that will be triggered when the system is disposed.
  252. */
  253. public set onDispose(callback: () => void) {
  254. if (this._onDisposeObserver) {
  255. this.onDisposeObservable.remove(this._onDisposeObserver);
  256. }
  257. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  258. }
  259. /**
  260. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  261. */
  262. public get isAnimationSheetEnabled(): Boolean {
  263. return this._isAnimationSheetEnabled;
  264. }
  265. private _particles = new Array<Particle>();
  266. private _epsilon: number;
  267. private _capacity: number;
  268. private _scene: Scene;
  269. private _stockParticles = new Array<Particle>();
  270. private _newPartsExcess = 0;
  271. private _vertexData: Float32Array;
  272. private _vertexBuffer: Nullable<Buffer>;
  273. private _vertexBuffers: { [key: string]: VertexBuffer } = {};
  274. private _indexBuffer: Nullable<WebGLBuffer>;
  275. private _effect: Effect;
  276. private _customEffect: Nullable<Effect>;
  277. private _cachedDefines: string;
  278. private _scaledColorStep = new Color4(0, 0, 0, 0);
  279. private _colorDiff = new Color4(0, 0, 0, 0);
  280. private _scaledDirection = Vector3.Zero();
  281. private _scaledGravity = Vector3.Zero();
  282. private _currentRenderId = -1;
  283. private _alive: boolean;
  284. private _started = false;
  285. private _stopped = false;
  286. private _actualFrame = 0;
  287. private _scaledUpdateSpeed: number;
  288. private _vertexBufferSize = 11;
  289. private _isAnimationSheetEnabled: boolean;
  290. /**
  291. * Gets the current list of active particles
  292. */
  293. public get particles(): Particle[] {
  294. return this._particles;
  295. }
  296. /**
  297. * Returns the string "ParticleSystem"
  298. * @returns a string containing the class name
  299. */
  300. public getClassName(): string {
  301. return "ParticleSystem";
  302. }
  303. /**
  304. * Instantiates a particle system.
  305. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  306. * @param name The name of the particle system
  307. * @param capacity The max number of particles alive at the same time
  308. * @param scene The scene the particle system belongs to
  309. * @param customEffect a custom effect used to change the way particles are rendered by default
  310. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  311. * @param epsilon Offset used to render the particles
  312. */
  313. constructor(name: string, capacity: number, scene: Scene, customEffect: Nullable<Effect> = null, isAnimationSheetEnabled: boolean = false, epsilon: number = 0.01) {
  314. this.id = name;
  315. this.name = name;
  316. this._capacity = capacity;
  317. this._epsilon = epsilon;
  318. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  319. if (isAnimationSheetEnabled) {
  320. this._vertexBufferSize = 12;
  321. }
  322. this._scene = scene || Engine.LastCreatedScene;
  323. this._customEffect = customEffect;
  324. scene.particleSystems.push(this);
  325. this._createIndexBuffer();
  326. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  327. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  328. this._vertexBuffer = new Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  329. var positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 3);
  330. var colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, 3, 4);
  331. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  332. if (this._isAnimationSheetEnabled) {
  333. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  334. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  335. }
  336. this._vertexBuffers[VertexBuffer.PositionKind] = positions;
  337. this._vertexBuffers[VertexBuffer.ColorKind] = colors;
  338. this._vertexBuffers["options"] = options;
  339. // Default emitter type
  340. this.particleEmitterType = new BoxParticleEmitter();
  341. this.updateFunction = (particles: Particle[]): void => {
  342. for (var index = 0; index < particles.length; index++) {
  343. var particle = particles[index];
  344. particle.age += this._scaledUpdateSpeed;
  345. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  346. this.recycleParticle(particle);
  347. index--;
  348. continue;
  349. }
  350. else {
  351. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  352. particle.color.addInPlace(this._scaledColorStep);
  353. if (particle.color.a < 0)
  354. particle.color.a = 0;
  355. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  356. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  357. particle.position.addInPlace(this._scaledDirection);
  358. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  359. particle.direction.addInPlace(this._scaledGravity);
  360. if (this._isAnimationSheetEnabled) {
  361. particle.updateCellIndex(this._scaledUpdateSpeed);
  362. }
  363. }
  364. }
  365. }
  366. }
  367. private _createIndexBuffer() {
  368. var indices = [];
  369. var index = 0;
  370. for (var count = 0; count < this._capacity; count++) {
  371. indices.push(index);
  372. indices.push(index + 1);
  373. indices.push(index + 2);
  374. indices.push(index);
  375. indices.push(index + 2);
  376. indices.push(index + 3);
  377. index += 4;
  378. }
  379. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  380. }
  381. /**
  382. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  383. * Its lifetime will start back at 0.
  384. * @param particle The particle to recycle
  385. */
  386. public recycleParticle(particle: Particle): void {
  387. var lastParticle = <Particle>this._particles.pop();
  388. if (lastParticle !== particle) {
  389. lastParticle.copyTo(particle);
  390. this._stockParticles.push(lastParticle);
  391. }
  392. }
  393. /**
  394. * Gets the maximum number of particles active at the same time.
  395. * @returns The max number of active particles.
  396. */
  397. public getCapacity(): number {
  398. return this._capacity;
  399. }
  400. /**
  401. * Gets Wether there are still active particles in the system.
  402. * @returns True if it is alive, otherwise false.
  403. */
  404. public isAlive(): boolean {
  405. return this._alive;
  406. }
  407. /**
  408. * Gets Wether the system has been started.
  409. * @returns True if it has been started, otherwise false.
  410. */
  411. public isStarted(): boolean {
  412. return this._started;
  413. }
  414. /**
  415. * Starts the particle system and begins to emit.
  416. */
  417. public start(): void {
  418. this._started = true;
  419. this._stopped = false;
  420. this._actualFrame = 0;
  421. }
  422. /**
  423. * Stops the particle system.
  424. */
  425. public stop(): void {
  426. this._stopped = true;
  427. }
  428. /**
  429. * Remove all active particles
  430. */
  431. public reset(): void {
  432. this._stockParticles = [];
  433. this._particles = [];
  434. }
  435. /**
  436. * @ignore (for internal use only)
  437. */
  438. public _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void {
  439. var offset = index * this._vertexBufferSize;
  440. this._vertexData[offset] = particle.position.x;
  441. this._vertexData[offset + 1] = particle.position.y;
  442. this._vertexData[offset + 2] = particle.position.z;
  443. this._vertexData[offset + 3] = particle.color.r;
  444. this._vertexData[offset + 4] = particle.color.g;
  445. this._vertexData[offset + 5] = particle.color.b;
  446. this._vertexData[offset + 6] = particle.color.a;
  447. this._vertexData[offset + 7] = particle.angle;
  448. this._vertexData[offset + 8] = particle.size;
  449. this._vertexData[offset + 9] = offsetX;
  450. this._vertexData[offset + 10] = offsetY;
  451. }
  452. /**
  453. * @ignore (for internal use only)
  454. */
  455. public _appendParticleVertexWithAnimation(index: number, particle: Particle, offsetX: number, offsetY: number): void {
  456. if (offsetX === 0)
  457. offsetX = this._epsilon;
  458. else if (offsetX === 1)
  459. offsetX = 1 - this._epsilon;
  460. if (offsetY === 0)
  461. offsetY = this._epsilon;
  462. else if (offsetY === 1)
  463. offsetY = 1 - this._epsilon;
  464. var offset = index * this._vertexBufferSize;
  465. this._vertexData[offset] = particle.position.x;
  466. this._vertexData[offset + 1] = particle.position.y;
  467. this._vertexData[offset + 2] = particle.position.z;
  468. this._vertexData[offset + 3] = particle.color.r;
  469. this._vertexData[offset + 4] = particle.color.g;
  470. this._vertexData[offset + 5] = particle.color.b;
  471. this._vertexData[offset + 6] = particle.color.a;
  472. this._vertexData[offset + 7] = particle.angle;
  473. this._vertexData[offset + 8] = particle.size;
  474. this._vertexData[offset + 9] = offsetX;
  475. this._vertexData[offset + 10] = offsetY;
  476. this._vertexData[offset + 11] = particle.cellIndex;
  477. }
  478. private _update(newParticles: number): void {
  479. // Update current
  480. this._alive = this._particles.length > 0;
  481. this.updateFunction(this._particles);
  482. // Add new ones
  483. var worldMatrix;
  484. if ((<AbstractMesh>this.emitter).position) {
  485. var emitterMesh = (<AbstractMesh>this.emitter);
  486. worldMatrix = emitterMesh.getWorldMatrix();
  487. } else {
  488. var emitterPosition = (<Vector3>this.emitter);
  489. worldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  490. }
  491. var particle: Particle;
  492. for (var index = 0; index < newParticles; index++) {
  493. if (this._particles.length === this._capacity) {
  494. break;
  495. }
  496. if (this._stockParticles.length !== 0) {
  497. particle = <Particle>this._stockParticles.pop();
  498. particle.age = 0;
  499. particle.cellIndex = this.startSpriteCellID;
  500. } else {
  501. particle = new Particle(this);
  502. }
  503. this._particles.push(particle);
  504. var emitPower = Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  505. if (this.startPositionFunction) {
  506. this.startPositionFunction(worldMatrix, particle.position, particle);
  507. }
  508. else {
  509. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  510. }
  511. if (this.startDirectionFunction) {
  512. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  513. }
  514. else {
  515. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  516. }
  517. particle.lifeTime = Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  518. particle.size = Scalar.RandomRange(this.minSize, this.maxSize);
  519. particle.angularSpeed = Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  520. var step = Scalar.RandomRange(0, 1.0);
  521. Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  522. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  523. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  524. }
  525. }
  526. private _getEffect(): Effect {
  527. if (this._customEffect) {
  528. return this._customEffect;
  529. };
  530. var defines = [];
  531. if (this._scene.clipPlane) {
  532. defines.push("#define CLIPPLANE");
  533. }
  534. if (this._isAnimationSheetEnabled) {
  535. defines.push("#define ANIMATESHEET");
  536. }
  537. // Effect
  538. var join = defines.join("\n");
  539. if (this._cachedDefines !== join) {
  540. this._cachedDefines = join;
  541. var attributesNamesOrOptions: any;
  542. var effectCreationOption: any;
  543. if (this._isAnimationSheetEnabled) {
  544. attributesNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "options", "cellIndex"];
  545. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  546. }
  547. else {
  548. attributesNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "options"];
  549. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"]
  550. }
  551. this._effect = this._scene.getEngine().createEffect(
  552. "particles",
  553. attributesNamesOrOptions,
  554. effectCreationOption,
  555. ["diffuseSampler"], join);
  556. }
  557. return this._effect;
  558. }
  559. /**
  560. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  561. */
  562. public animate(): void {
  563. if (!this._started)
  564. return;
  565. var effect = this._getEffect();
  566. // Check
  567. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  568. return;
  569. if (this._currentRenderId === this._scene.getRenderId()) {
  570. return;
  571. }
  572. this._currentRenderId = this._scene.getRenderId();
  573. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  574. // determine the number of particles we need to create
  575. var newParticles;
  576. if (this.manualEmitCount > -1) {
  577. newParticles = this.manualEmitCount;
  578. this._newPartsExcess = 0;
  579. this.manualEmitCount = 0;
  580. } else {
  581. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  582. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  583. }
  584. if (this._newPartsExcess > 1.0) {
  585. newParticles += this._newPartsExcess >> 0;
  586. this._newPartsExcess -= this._newPartsExcess >> 0;
  587. }
  588. this._alive = false;
  589. if (!this._stopped) {
  590. this._actualFrame += this._scaledUpdateSpeed;
  591. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  592. this.stop();
  593. } else {
  594. newParticles = 0;
  595. }
  596. this._update(newParticles);
  597. // Stopped?
  598. if (this._stopped) {
  599. if (!this._alive) {
  600. this._started = false;
  601. if (this.onAnimationEnd) {
  602. this.onAnimationEnd();
  603. }
  604. if (this.disposeOnStop) {
  605. this._scene._toBeDisposed.push(this);
  606. }
  607. }
  608. }
  609. // Animation sheet
  610. if (this._isAnimationSheetEnabled) {
  611. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  612. }
  613. else {
  614. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  615. }
  616. // Update VBO
  617. var offset = 0;
  618. for (var index = 0; index < this._particles.length; index++) {
  619. var particle = this._particles[index];
  620. this._appendParticleVertexes(offset, particle);
  621. offset += 4;
  622. }
  623. if (this._vertexBuffer) {
  624. this._vertexBuffer.update(this._vertexData);
  625. }
  626. }
  627. private _appendParticleVertexes: Nullable<(offset: number, particle: Particle) => void> = null;
  628. private _appenedParticleVertexesWithSheet(offset: number, particle: Particle) {
  629. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  630. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  631. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  632. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  633. }
  634. private _appenedParticleVertexesNoSheet(offset: number, particle: Particle) {
  635. this._appendParticleVertex(offset++, particle, 0, 0);
  636. this._appendParticleVertex(offset++, particle, 1, 0);
  637. this._appendParticleVertex(offset++, particle, 1, 1);
  638. this._appendParticleVertex(offset++, particle, 0, 1);
  639. }
  640. /**
  641. * Rebuilds the particle system.
  642. */
  643. public rebuild(): void {
  644. this._createIndexBuffer();
  645. if (this._vertexBuffer) {
  646. this._vertexBuffer._rebuild();
  647. }
  648. }
  649. /**
  650. * Renders the particle system in its current state.
  651. * @returns the current number of particles
  652. */
  653. public render(): number {
  654. var effect = this._getEffect();
  655. // Check
  656. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  657. return 0;
  658. }
  659. var engine = this._scene.getEngine();
  660. // Render
  661. engine.enableEffect(effect);
  662. engine.setState(false);
  663. var viewMatrix = this._scene.getViewMatrix();
  664. effect.setTexture("diffuseSampler", this.particleTexture);
  665. effect.setMatrix("view", viewMatrix);
  666. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  667. if (this._isAnimationSheetEnabled) {
  668. var baseSize = this.particleTexture.getBaseSize();
  669. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  670. }
  671. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  672. if (this._scene.clipPlane) {
  673. var clipPlane = this._scene.clipPlane;
  674. var invView = viewMatrix.clone();
  675. invView.invert();
  676. effect.setMatrix("invView", invView);
  677. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  678. }
  679. // VBOs
  680. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  681. // Draw order
  682. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  683. engine.setAlphaMode(Engine.ALPHA_ONEONE);
  684. } else {
  685. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  686. }
  687. if (this.forceDepthWrite) {
  688. engine.setDepthWrite(true);
  689. }
  690. engine.drawElementsType(Material.TriangleFillMode, 0, this._particles.length * 6);
  691. engine.setAlphaMode(Engine.ALPHA_DISABLE);
  692. return this._particles.length;
  693. }
  694. /**
  695. * Disposes the particle system and free the associated resources
  696. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  697. */
  698. public dispose(disposeTexture = true): void {
  699. if (this._vertexBuffer) {
  700. this._vertexBuffer.dispose();
  701. this._vertexBuffer = null;
  702. }
  703. if (this._indexBuffer) {
  704. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  705. this._indexBuffer = null;
  706. }
  707. if (disposeTexture && this.particleTexture) {
  708. this.particleTexture.dispose();
  709. this.particleTexture = null;
  710. }
  711. // Remove from scene
  712. var index = this._scene.particleSystems.indexOf(this);
  713. if (index > -1) {
  714. this._scene.particleSystems.splice(index, 1);
  715. }
  716. // Callback
  717. this.onDisposeObservable.notifyObservers(this);
  718. this.onDisposeObservable.clear();
  719. }
  720. /**
  721. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  722. * @param radius The radius of the sphere to emit from
  723. * @returns the emitter
  724. */
  725. public createSphereEmitter(radius = 1): SphereParticleEmitter {
  726. var particleEmitter = new SphereParticleEmitter(radius);
  727. this.particleEmitterType = particleEmitter;
  728. return particleEmitter;
  729. }
  730. /**
  731. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  732. * @param radius The radius of the sphere to emit from
  733. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  734. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  735. * @returns the emitter
  736. */
  737. public createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)): SphereDirectedParticleEmitter {
  738. var particleEmitter = new SphereDirectedParticleEmitter(radius, direction1, direction2)
  739. this.particleEmitterType = particleEmitter;
  740. return particleEmitter;
  741. }
  742. /**
  743. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  744. * @param radius The radius of the cone to emit from
  745. * @param angle The base angle of the cone
  746. * @returns the emitter
  747. */
  748. public createConeEmitter(radius = 1, angle = Math.PI / 4): ConeParticleEmitter {
  749. var particleEmitter = new ConeParticleEmitter(radius, angle);
  750. this.particleEmitterType = particleEmitter;
  751. return particleEmitter;
  752. }
  753. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  754. /**
  755. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  756. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  757. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  758. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  759. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  760. * @returns the emitter
  761. */
  762. public createBoxEmitter(direction1: Vector3, direction2: Vector3, minEmitBox: Vector3, maxEmitBox: Vector3): BoxParticleEmitter {
  763. var particleEmitter = new BoxParticleEmitter();
  764. this.direction1 = direction1;
  765. this.direction2 = direction2;
  766. this.minEmitBox = minEmitBox;
  767. this.maxEmitBox = maxEmitBox;
  768. this.particleEmitterType = particleEmitter;
  769. return particleEmitter;
  770. }
  771. /**
  772. * Clones the particle system.
  773. * @param name The name of the cloned object
  774. * @param newEmitter The new emitter to use
  775. * @returns the cloned particle system
  776. */
  777. public clone(name: string, newEmitter: any): ParticleSystem {
  778. var custom: Nullable<Effect> = null;
  779. var program: any = null;
  780. if (this.customShader != null) {
  781. program = this.customShader;
  782. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  783. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  784. }
  785. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  786. result.customShader = program;
  787. Tools.DeepCopy(this, result, ["particles", "customShader"]);
  788. if (newEmitter === undefined) {
  789. newEmitter = this.emitter;
  790. }
  791. result.emitter = newEmitter;
  792. if (this.particleTexture) {
  793. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  794. }
  795. if (!this.preventAutoStart) {
  796. result.start();
  797. }
  798. return result;
  799. }
  800. /**
  801. * Serializes the particle system to a JSON object.
  802. * @returns the JSON object
  803. */
  804. public serialize(): any {
  805. var serializationObject: any = {};
  806. serializationObject.name = this.name;
  807. serializationObject.id = this.id;
  808. // Emitter
  809. if ((<AbstractMesh>this.emitter).position) {
  810. var emitterMesh = (<AbstractMesh>this.emitter);
  811. serializationObject.emitterId = emitterMesh.id;
  812. } else {
  813. var emitterPosition = (<Vector3>this.emitter);
  814. serializationObject.emitter = emitterPosition.asArray();
  815. }
  816. serializationObject.capacity = this.getCapacity();
  817. if (this.particleTexture) {
  818. serializationObject.textureName = this.particleTexture.name;
  819. }
  820. // Animations
  821. Animation.AppendSerializedAnimations(this, serializationObject);
  822. // Particle system
  823. serializationObject.minAngularSpeed = this.minAngularSpeed;
  824. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  825. serializationObject.minSize = this.minSize;
  826. serializationObject.maxSize = this.maxSize;
  827. serializationObject.minEmitPower = this.minEmitPower;
  828. serializationObject.maxEmitPower = this.maxEmitPower;
  829. serializationObject.minLifeTime = this.minLifeTime;
  830. serializationObject.maxLifeTime = this.maxLifeTime;
  831. serializationObject.emitRate = this.emitRate;
  832. serializationObject.minEmitBox = this.minEmitBox.asArray();
  833. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  834. serializationObject.gravity = this.gravity.asArray();
  835. serializationObject.direction1 = this.direction1.asArray();
  836. serializationObject.direction2 = this.direction2.asArray();
  837. serializationObject.color1 = this.color1.asArray();
  838. serializationObject.color2 = this.color2.asArray();
  839. serializationObject.colorDead = this.colorDead.asArray();
  840. serializationObject.updateSpeed = this.updateSpeed;
  841. serializationObject.targetStopDuration = this.targetStopDuration;
  842. serializationObject.textureMask = this.textureMask.asArray();
  843. serializationObject.blendMode = this.blendMode;
  844. serializationObject.customShader = this.customShader;
  845. serializationObject.preventAutoStart = this.preventAutoStart;
  846. serializationObject.startSpriteCellID = this.startSpriteCellID;
  847. serializationObject.endSpriteCellID = this.endSpriteCellID;
  848. serializationObject.spriteCellLoop = this.spriteCellLoop;
  849. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  850. serializationObject.spriteCellWidth = this.spriteCellWidth;
  851. serializationObject.spriteCellHeight = this.spriteCellHeight;
  852. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  853. // Emitter
  854. if (this.particleEmitterType) {
  855. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  856. }
  857. return serializationObject;
  858. }
  859. /**
  860. * Parses a JSON object to create a particle system.
  861. * @param parsedParticleSystem The JSON object to parse
  862. * @param scene The scene to create the particle system in
  863. * @param rootUrl The root url to use to load external dependencies like texture
  864. * @returns the Parsed particle system
  865. */
  866. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem {
  867. var name = parsedParticleSystem.name;
  868. var custom: Nullable<Effect> = null;
  869. var program: any = null;
  870. if (parsedParticleSystem.customShader) {
  871. program = parsedParticleSystem.customShader;
  872. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  873. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  874. }
  875. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  876. particleSystem.customShader = program;
  877. if (parsedParticleSystem.id) {
  878. particleSystem.id = parsedParticleSystem.id;
  879. }
  880. // Auto start
  881. if (parsedParticleSystem.preventAutoStart) {
  882. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  883. }
  884. // Texture
  885. if (parsedParticleSystem.textureName) {
  886. particleSystem.particleTexture = new Texture(rootUrl + parsedParticleSystem.textureName, scene);
  887. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  888. }
  889. // Emitter
  890. if (parsedParticleSystem.emitterId) {
  891. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  892. } else {
  893. particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);
  894. }
  895. // Animations
  896. if (parsedParticleSystem.animations) {
  897. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  898. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  899. particleSystem.animations.push(Animation.Parse(parsedAnimation));
  900. }
  901. }
  902. if (parsedParticleSystem.autoAnimate) {
  903. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  904. }
  905. // Particle system
  906. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  907. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  908. particleSystem.minSize = parsedParticleSystem.minSize;
  909. particleSystem.maxSize = parsedParticleSystem.maxSize;
  910. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  911. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  912. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  913. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  914. particleSystem.emitRate = parsedParticleSystem.emitRate;
  915. particleSystem.minEmitBox = Vector3.FromArray(parsedParticleSystem.minEmitBox);
  916. particleSystem.maxEmitBox = Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  917. particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);
  918. particleSystem.direction1 = Vector3.FromArray(parsedParticleSystem.direction1);
  919. particleSystem.direction2 = Vector3.FromArray(parsedParticleSystem.direction2);
  920. particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);
  921. particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);
  922. particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);
  923. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  924. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  925. particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask);
  926. particleSystem.blendMode = parsedParticleSystem.blendMode;
  927. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  928. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  929. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  930. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  931. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  932. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  933. if (!particleSystem.preventAutoStart) {
  934. particleSystem.start();
  935. }
  936. return particleSystem;
  937. }
  938. }
  939. }