babylon.particleSystem.ts 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405
  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 extends BaseParticleSystem implements IDisposable, IAnimatable, IParticleSystem {
  9. /**
  10. * This function can be defined to provide custom update for active particles.
  11. * This function will be called instead of regular update (age, position, color, etc.).
  12. * Do not forget that this function will be called on every frame so try to keep it simple and fast :)
  13. */
  14. public updateFunction: (particles: Particle[]) => void;
  15. private _emitterWorldMatrix: Matrix;
  16. /**
  17. * This function can be defined to specify initial direction for every new particle.
  18. * It by default use the emitterType defined function
  19. */
  20. public startDirectionFunction: (worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void;
  21. /**
  22. * This function can be defined to specify initial position for every new particle.
  23. * It by default use the emitterType defined function
  24. */
  25. public startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void;
  26. /**
  27. * @hidden
  28. */
  29. public _inheritedVelocityOffset = new BABYLON.Vector3();
  30. /**
  31. * An event triggered when the system is disposed
  32. */
  33. public onDisposeObservable = new Observable<ParticleSystem>();
  34. private _onDisposeObserver: Nullable<Observer<ParticleSystem>>;
  35. /**
  36. * Sets a callback that will be triggered when the system is disposed
  37. */
  38. public set onDispose(callback: () => void) {
  39. if (this._onDisposeObserver) {
  40. this.onDisposeObservable.remove(this._onDisposeObserver);
  41. }
  42. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43. }
  44. private _particles = new Array<Particle>();
  45. private _epsilon: number;
  46. private _capacity: number;
  47. private _stockParticles = new Array<Particle>();
  48. private _newPartsExcess = 0;
  49. private _vertexData: Float32Array;
  50. private _vertexBuffer: Nullable<Buffer>;
  51. private _vertexBuffers: { [key: string]: VertexBuffer } = {};
  52. private _spriteBuffer: Nullable<Buffer>;
  53. private _indexBuffer: Nullable<WebGLBuffer>;
  54. private _effect: Effect;
  55. private _customEffect: Nullable<Effect>;
  56. private _cachedDefines: string;
  57. private _scaledColorStep = new Color4(0, 0, 0, 0);
  58. private _colorDiff = new Color4(0, 0, 0, 0);
  59. private _scaledDirection = Vector3.Zero();
  60. private _scaledGravity = Vector3.Zero();
  61. private _currentRenderId = -1;
  62. private _alive: boolean;
  63. private _useInstancing = false;
  64. private _started = false;
  65. private _stopped = false;
  66. private _actualFrame = 0;
  67. private _scaledUpdateSpeed: number;
  68. private _vertexBufferSize: number;
  69. /** @hidden */
  70. public _currentEmitRateGradient: Nullable<FactorGradient>;
  71. /** @hidden */
  72. public _currentEmitRate1 = 0;
  73. /** @hidden */
  74. public _currentEmitRate2 = 0;
  75. /** @hidden */
  76. public _currentStartSizeGradient: Nullable<FactorGradient>;
  77. /** @hidden */
  78. public _currentStartSize1 = 0;
  79. /** @hidden */
  80. public _currentStartSize2 = 0;
  81. private readonly _rawTextureWidth = 256;
  82. private _rampGradientsTexture: Nullable<RawTexture>;
  83. private _useRampGradients = false;
  84. /** Gets or sets a boolean indicating that ramp gradients must be used
  85. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  86. */
  87. public get useRampGradients(): boolean {
  88. return this._useRampGradients;
  89. }
  90. public set useRampGradients(value: boolean) {
  91. if (this._useRampGradients === value) {
  92. return;
  93. }
  94. this._useRampGradients = value;
  95. this._resetEffect();
  96. }
  97. // Sub-emitters
  98. /**
  99. * The Sub-emitters templates that will be used to generate the sub particle system to be associated with the system, this property is used by the root particle system only.
  100. * When a particle is spawned, an array will be chosen at random and all the emitters in that array will be attached to the particle. (Default: [])
  101. */
  102. public subEmitters: Array<ParticleSystem | SubEmitter | Array<SubEmitter>>;
  103. // the subEmitters field above converted to a constant type
  104. private _subEmitters: Array<Array<SubEmitter>>;
  105. /**
  106. * @hidden
  107. * If the particle systems emitter should be disposed when the particle system is disposed
  108. */
  109. public _disposeEmitterOnDispose = false;
  110. /**
  111. * The current active Sub-systems, this property is used by the root particle system only.
  112. */
  113. public activeSubSystems: Array<ParticleSystem>;
  114. private _rootParticleSystem: ParticleSystem;
  115. //end of Sub-emitter
  116. /**
  117. * Gets the current list of active particles
  118. */
  119. public get particles(): Particle[] {
  120. return this._particles;
  121. }
  122. /**
  123. * Returns the string "ParticleSystem"
  124. * @returns a string containing the class name
  125. */
  126. public getClassName(): string {
  127. return "ParticleSystem";
  128. }
  129. /**
  130. * Instantiates a particle system.
  131. * 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.
  132. * @param name The name of the particle system
  133. * @param capacity The max number of particles alive at the same time
  134. * @param scene The scene the particle system belongs to
  135. * @param customEffect a custom effect used to change the way particles are rendered by default
  136. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  137. * @param epsilon Offset used to render the particles
  138. */
  139. constructor(name: string, capacity: number, scene: Scene, customEffect: Nullable<Effect> = null, isAnimationSheetEnabled: boolean = false, epsilon: number = 0.01) {
  140. super(name);
  141. this._capacity = capacity;
  142. this._epsilon = epsilon;
  143. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  144. this._scene = scene || Engine.LastCreatedScene;
  145. // Setup the default processing configuration to the scene.
  146. this._attachImageProcessingConfiguration(null);
  147. this._customEffect = customEffect;
  148. this._scene.particleSystems.push(this);
  149. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  150. this._createIndexBuffer();
  151. this._createVertexBuffers();
  152. // Default emitter type
  153. this.particleEmitterType = new BoxParticleEmitter();
  154. this.updateFunction = (particles: Particle[]): void => {
  155. let noiseTextureData: Nullable<Uint8Array> = null;
  156. let noiseTextureSize: Nullable<ISize> = null;
  157. if (this.noiseTexture) { // We need to get texture data back to CPU
  158. noiseTextureData = <Nullable<Uint8Array>>(this.noiseTexture.readPixels());
  159. noiseTextureSize = this.noiseTexture.getSize();
  160. }
  161. for (var index = 0; index < particles.length; index++) {
  162. var particle = particles[index];
  163. particle.age += this._scaledUpdateSpeed;
  164. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  165. this._emitFromParticle(particle);
  166. if (particle._attachedSubEmitters) {
  167. particle._attachedSubEmitters.forEach((subEmitter) => {
  168. subEmitter.particleSystem.disposeOnStop = true;
  169. subEmitter.particleSystem.stop();
  170. });
  171. particle._attachedSubEmitters = null;
  172. }
  173. this.recycleParticle(particle);
  174. index--;
  175. continue;
  176. }
  177. else {
  178. let ratio = particle.age / particle.lifeTime;
  179. // Color
  180. if (this._colorGradients && this._colorGradients.length > 0) {
  181. Tools.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
  182. if (currentGradient !== particle._currentColorGradient) {
  183. particle._currentColor1.copyFrom(particle._currentColor2);
  184. (<ColorGradient>nextGradient).getColorToRef(particle._currentColor2);
  185. particle._currentColorGradient = (<ColorGradient>currentGradient);
  186. }
  187. Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  188. });
  189. }
  190. else {
  191. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  192. particle.color.addInPlace(this._scaledColorStep);
  193. if (particle.color.a < 0) {
  194. particle.color.a = 0;
  195. }
  196. }
  197. // Angular speed
  198. if (this._angularSpeedGradients && this._angularSpeedGradients.length > 0) {
  199. Tools.GetCurrentGradient(ratio, this._angularSpeedGradients, (currentGradient, nextGradient, scale) => {
  200. if (currentGradient !== particle._currentAngularSpeedGradient) {
  201. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  202. particle._currentAngularSpeed2 = (<FactorGradient>nextGradient).getFactor();
  203. particle._currentAngularSpeedGradient = (<FactorGradient>currentGradient);
  204. }
  205. particle.angularSpeed = Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  206. });
  207. }
  208. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  209. // Direction
  210. let directionScale = this._scaledUpdateSpeed;
  211. /// Velocity
  212. if (this._velocityGradients && this._velocityGradients.length > 0) {
  213. Tools.GetCurrentGradient(ratio, this._velocityGradients, (currentGradient, nextGradient, scale) => {
  214. if (currentGradient !== particle._currentVelocityGradient) {
  215. particle._currentVelocity1 = particle._currentVelocity2;
  216. particle._currentVelocity2 = (<FactorGradient>nextGradient).getFactor();
  217. particle._currentVelocityGradient = (<FactorGradient>currentGradient);
  218. }
  219. directionScale *= Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  220. });
  221. }
  222. particle.direction.scaleToRef(directionScale, this._scaledDirection);
  223. /// Limit velocity
  224. if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {
  225. Tools.GetCurrentGradient(ratio, this._limitVelocityGradients, (currentGradient, nextGradient, scale) => {
  226. if (currentGradient !== particle._currentLimitVelocityGradient) {
  227. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  228. particle._currentLimitVelocity2 = (<FactorGradient>nextGradient).getFactor();
  229. particle._currentLimitVelocityGradient = (<FactorGradient>currentGradient);
  230. }
  231. let limitVelocity = Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  232. let currentVelocity = particle.direction.length();
  233. if (currentVelocity > limitVelocity) {
  234. particle.direction.scaleInPlace(this.limitVelocityDamping);
  235. }
  236. });
  237. }
  238. /// Drag
  239. if (this._dragGradients && this._dragGradients.length > 0) {
  240. Tools.GetCurrentGradient(ratio, this._dragGradients, (currentGradient, nextGradient, scale) => {
  241. if (currentGradient !== particle._currentDragGradient) {
  242. particle._currentDrag1 = particle._currentDrag2;
  243. particle._currentDrag2 = (<FactorGradient>nextGradient).getFactor();
  244. particle._currentDragGradient = (<FactorGradient>currentGradient);
  245. }
  246. let drag = Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  247. this._scaledDirection.scaleInPlace(1.0 - drag);
  248. });
  249. }
  250. particle.position.addInPlace(this._scaledDirection);
  251. // Noise
  252. if (noiseTextureData && noiseTextureSize) {
  253. let localPosition = Tmp.Vector3[0];
  254. let emitterPosition = Tmp.Vector3[1];
  255. this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  256. particle.position.subtractToRef(emitterPosition, localPosition);
  257. let fetchedColorR = this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  258. let fetchedColorG = this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  259. let fetchedColorB = this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  260. let force = Tmp.Vector3[0];
  261. let scaledForce = Tmp.Vector3[1];
  262. force.copyFromFloats((2 * fetchedColorR - 1) * this.noiseStrength.x, (2 * fetchedColorG - 1) * this.noiseStrength.y, (2 * fetchedColorB - 1) * this.noiseStrength.z);
  263. force.scaleToRef(this._scaledUpdateSpeed, scaledForce);
  264. particle.direction.addInPlace(scaledForce);
  265. }
  266. // Gravity
  267. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  268. particle.direction.addInPlace(this._scaledGravity);
  269. // Size
  270. if (this._sizeGradients && this._sizeGradients.length > 0) {
  271. Tools.GetCurrentGradient(ratio, this._sizeGradients, (currentGradient, nextGradient, scale) => {
  272. if (currentGradient !== particle._currentSizeGradient) {
  273. particle._currentSize1 = particle._currentSize2;
  274. particle._currentSize2 = (<FactorGradient>nextGradient).getFactor();
  275. particle._currentSizeGradient = (<FactorGradient>currentGradient);
  276. }
  277. particle.size = Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  278. });
  279. }
  280. // Remap data
  281. if (this._useRampGradients) {
  282. if (this._colorRemapGradients && this._colorRemapGradients.length > 0) {
  283. Tools.GetCurrentGradient(ratio, this._colorRemapGradients, (currentGradient, nextGradient, scale) => {
  284. let min = Scalar.Lerp((<FactorGradient>currentGradient).factor1, (<FactorGradient>nextGradient).factor1, scale);
  285. let max = Scalar.Lerp((<FactorGradient>currentGradient).factor2!, (<FactorGradient>nextGradient).factor2!, scale);
  286. particle.remapData.x = min;
  287. particle.remapData.y = max - min;
  288. });
  289. }
  290. if (this._alphaRemapGradients && this._alphaRemapGradients.length > 0) {
  291. Tools.GetCurrentGradient(ratio, this._alphaRemapGradients, (currentGradient, nextGradient, scale) => {
  292. let min = Scalar.Lerp((<FactorGradient>currentGradient).factor1, (<FactorGradient>nextGradient).factor1, scale);
  293. let max = Scalar.Lerp((<FactorGradient>currentGradient).factor2!, (<FactorGradient>nextGradient).factor2!, scale);
  294. particle.remapData.z = min;
  295. particle.remapData.w = max - min;
  296. });
  297. }
  298. }
  299. if (this._isAnimationSheetEnabled) {
  300. particle.updateCellIndex();
  301. }
  302. // Update the position of the attached sub-emitters to match their attached particle
  303. if (particle._attachedSubEmitters && particle._attachedSubEmitters.length > 0) {
  304. particle._attachedSubEmitters.forEach((subEmitter) => {
  305. ParticleSystem._InheritParticleInfoToSubEmitter(subEmitter, particle);
  306. });
  307. }
  308. }
  309. }
  310. }
  311. }
  312. private static _InheritParticleInfoToSubEmitter(subEmitter: SubEmitter, particle: Particle) {
  313. if ((<AbstractMesh>subEmitter.particleSystem.emitter).position) {
  314. var emitterMesh = (<AbstractMesh>subEmitter.particleSystem.emitter);
  315. emitterMesh.position.copyFrom(particle.position);
  316. if (subEmitter.inheritDirection) {
  317. emitterMesh.position.subtractToRef(particle.direction, BABYLON.Tmp.Vector3[0]);
  318. // Look at using Y as forward
  319. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  320. }
  321. } else {
  322. var emitterPosition = (<Vector3>subEmitter.particleSystem.emitter);
  323. emitterPosition.copyFrom(particle.position);
  324. }
  325. // Set inheritedVelocityOffset to be used when new particles are created
  326. particle.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, Tmp.Vector3[0]);
  327. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(Tmp.Vector3[0]);
  328. }
  329. private _addFactorGradient(factorGradients: FactorGradient[], gradient: number, factor: number, factor2?: number) {
  330. let newGradient = new FactorGradient();
  331. newGradient.gradient = gradient;
  332. newGradient.factor1 = factor;
  333. newGradient.factor2 = factor2;
  334. factorGradients.push(newGradient);
  335. factorGradients.sort((a, b) => {
  336. if (a.gradient < b.gradient) {
  337. return -1;
  338. } else if (a.gradient > b.gradient) {
  339. return 1;
  340. }
  341. return 0;
  342. });
  343. }
  344. private _removeFactorGradient(factorGradients: Nullable<FactorGradient[]>, gradient: number) {
  345. if (!factorGradients) {
  346. return;
  347. }
  348. let index = 0;
  349. for (var factorGradient of factorGradients) {
  350. if (factorGradient.gradient === gradient) {
  351. factorGradients.splice(index, 1);
  352. break;
  353. }
  354. index++;
  355. }
  356. }
  357. /**
  358. * Adds a new life time gradient
  359. * @param gradient defines the gradient to use (between 0 and 1)
  360. * @param factor defines the life time factor to affect to the specified gradient
  361. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  362. * @returns the current particle system
  363. */
  364. public addLifeTimeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  365. if (!this._lifeTimeGradients) {
  366. this._lifeTimeGradients = [];
  367. }
  368. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  369. return this;
  370. }
  371. /**
  372. * Remove a specific life time gradient
  373. * @param gradient defines the gradient to remove
  374. * @returns the current particle system
  375. */
  376. public removeLifeTimeGradient(gradient: number): IParticleSystem {
  377. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  378. return this;
  379. }
  380. /**
  381. * Adds a new size gradient
  382. * @param gradient defines the gradient to use (between 0 and 1)
  383. * @param factor defines the size factor to affect to the specified gradient
  384. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  385. * @returns the current particle system
  386. */
  387. public addSizeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  388. if (!this._sizeGradients) {
  389. this._sizeGradients = [];
  390. }
  391. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  392. return this;
  393. }
  394. /**
  395. * Remove a specific size gradient
  396. * @param gradient defines the gradient to remove
  397. * @returns the current particle system
  398. */
  399. public removeSizeGradient(gradient: number): IParticleSystem {
  400. this._removeFactorGradient(this._sizeGradients, gradient);
  401. return this;
  402. }
  403. /**
  404. * Adds a new color remap gradient
  405. * @param gradient defines the gradient to use (between 0 and 1)
  406. * @param min defines the color remap minimal range
  407. * @param max defines the color remap maximal range
  408. * @returns the current particle system
  409. */
  410. public addColorRemapGradient(gradient: number, min: number, max: number): IParticleSystem {
  411. if (!this._colorRemapGradients) {
  412. this._colorRemapGradients = [];
  413. }
  414. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  415. return this;
  416. }
  417. /**
  418. * Remove a specific color remap gradient
  419. * @param gradient defines the gradient to remove
  420. * @returns the current particle system
  421. */
  422. public removeColorRemapGradient(gradient: number): IParticleSystem {
  423. this._removeFactorGradient(this._colorRemapGradients, gradient);
  424. return this;
  425. }
  426. /**
  427. * Adds a new alpha remap gradient
  428. * @param gradient defines the gradient to use (between 0 and 1)
  429. * @param min defines the alpha remap minimal range
  430. * @param max defines the alpha remap maximal range
  431. * @returns the current particle system
  432. */
  433. public addAlphaRemapGradient(gradient: number, min: number, max: number): IParticleSystem {
  434. if (!this._alphaRemapGradients) {
  435. this._alphaRemapGradients = [];
  436. }
  437. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  438. return this;
  439. }
  440. /**
  441. * Remove a specific alpha remap gradient
  442. * @param gradient defines the gradient to remove
  443. * @returns the current particle system
  444. */
  445. public removeAlphaRemapGradient(gradient: number): IParticleSystem {
  446. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  447. return this;
  448. }
  449. /**
  450. * Adds a new angular speed gradient
  451. * @param gradient defines the gradient to use (between 0 and 1)
  452. * @param factor defines the angular speed to affect to the specified gradient
  453. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  454. * @returns the current particle system
  455. */
  456. public addAngularSpeedGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  457. if (!this._angularSpeedGradients) {
  458. this._angularSpeedGradients = [];
  459. }
  460. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  461. return this;
  462. }
  463. /**
  464. * Remove a specific angular speed gradient
  465. * @param gradient defines the gradient to remove
  466. * @returns the current particle system
  467. */
  468. public removeAngularSpeedGradient(gradient: number): IParticleSystem {
  469. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  470. return this;
  471. }
  472. /**
  473. * Adds a new velocity gradient
  474. * @param gradient defines the gradient to use (between 0 and 1)
  475. * @param factor defines the velocity to affect to the specified gradient
  476. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  477. * @returns the current particle system
  478. */
  479. public addVelocityGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  480. if (!this._velocityGradients) {
  481. this._velocityGradients = [];
  482. }
  483. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  484. return this;
  485. }
  486. /**
  487. * Remove a specific velocity gradient
  488. * @param gradient defines the gradient to remove
  489. * @returns the current particle system
  490. */
  491. public removeVelocityGradient(gradient: number): IParticleSystem {
  492. this._removeFactorGradient(this._velocityGradients, gradient);
  493. return this;
  494. }
  495. /**
  496. * Adds a new limit velocity gradient
  497. * @param gradient defines the gradient to use (between 0 and 1)
  498. * @param factor defines the limit velocity value to affect to the specified gradient
  499. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  500. * @returns the current particle system
  501. */
  502. public addLimitVelocityGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  503. if (!this._limitVelocityGradients) {
  504. this._limitVelocityGradients = [];
  505. }
  506. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  507. return this;
  508. }
  509. /**
  510. * Remove a specific limit velocity gradient
  511. * @param gradient defines the gradient to remove
  512. * @returns the current particle system
  513. */
  514. public removeLimitVelocityGradient(gradient: number): IParticleSystem {
  515. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  516. return this;
  517. }
  518. /**
  519. * Adds a new drag gradient
  520. * @param gradient defines the gradient to use (between 0 and 1)
  521. * @param factor defines the drag value to affect to the specified gradient
  522. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  523. * @returns the current particle system
  524. */
  525. public addDragGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  526. if (!this._dragGradients) {
  527. this._dragGradients = [];
  528. }
  529. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  530. return this;
  531. }
  532. /**
  533. * Remove a specific drag gradient
  534. * @param gradient defines the gradient to remove
  535. * @returns the current particle system
  536. */
  537. public removeDragGradient(gradient: number): IParticleSystem {
  538. this._removeFactorGradient(this._dragGradients, gradient);
  539. return this;
  540. }
  541. /**
  542. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  543. * @param gradient defines the gradient to use (between 0 and 1)
  544. * @param factor defines the emit rate value to affect to the specified gradient
  545. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  546. * @returns the current particle system
  547. */
  548. public addEmitRateGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  549. if (!this._emitRateGradients) {
  550. this._emitRateGradients = [];
  551. }
  552. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  553. if (!this._currentEmitRateGradient) {
  554. this._currentEmitRateGradient = this._emitRateGradients[0];
  555. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  556. this._currentEmitRate2 = this._currentEmitRate1;
  557. }
  558. if (this._emitRateGradients.length === 2) {
  559. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  560. }
  561. return this;
  562. }
  563. /**
  564. * Remove a specific emit rate gradient
  565. * @param gradient defines the gradient to remove
  566. * @returns the current particle system
  567. */
  568. public removeEmitRateGradient(gradient: number): IParticleSystem {
  569. this._removeFactorGradient(this._emitRateGradients, gradient);
  570. return this;
  571. }
  572. /**
  573. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  574. * @param gradient defines the gradient to use (between 0 and 1)
  575. * @param factor defines the start size value to affect to the specified gradient
  576. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  577. * @returns the current particle system
  578. */
  579. public addStartSizeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  580. if (!this._startSizeGradients) {
  581. this._startSizeGradients = [];
  582. }
  583. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  584. if (!this._currentStartSizeGradient) {
  585. this._currentStartSizeGradient = this._startSizeGradients[0];
  586. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  587. this._currentStartSize2 = this._currentStartSize1;
  588. }
  589. if (this._startSizeGradients.length === 2) {
  590. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  591. }
  592. return this;
  593. }
  594. /**
  595. * Remove a specific start size gradient
  596. * @param gradient defines the gradient to remove
  597. * @returns the current particle system
  598. */
  599. public removeStartSizeGradient(gradient: number): IParticleSystem {
  600. this._removeFactorGradient(this._emitRateGradients, gradient);
  601. return this;
  602. }
  603. private _createRampGradientTexture() {
  604. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  605. return;
  606. }
  607. let data = new Uint8Array(this._rawTextureWidth * 4);
  608. let tmpColor = Tmp.Color3[0];
  609. for (var x = 0; x < this._rawTextureWidth; x++) {
  610. var ratio = x / this._rawTextureWidth;
  611. Tools.GetCurrentGradient(ratio, this._rampGradients, (currentGradient, nextGradient, scale) => {
  612. Color3.LerpToRef((<Color3Gradient>currentGradient).color, (<Color3Gradient>nextGradient).color, scale, tmpColor);
  613. data[x * 4] = tmpColor.r * 255;
  614. data[x * 4 + 1] = tmpColor.g * 255;
  615. data[x * 4 + 2] = tmpColor.b * 255;
  616. data[x * 4 + 3] = 255;
  617. });
  618. }
  619. this._rampGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE);
  620. }
  621. /**
  622. * Gets the current list of ramp gradients.
  623. * You must use addRampGradient and removeRampGradient to udpate this list
  624. * @returns the list of ramp gradients
  625. */
  626. public getRampGradients(): Nullable<Array<Color3Gradient>> {
  627. return this._rampGradients;
  628. }
  629. /**
  630. * Adds a new ramp gradient used to remap particle colors
  631. * @param gradient defines the gradient to use (between 0 and 1)
  632. * @param color defines the color to affect to the specified gradient
  633. * @returns the current particle system
  634. */
  635. public addRampGradient(gradient: number, color: Color3): ParticleSystem {
  636. if (!this._rampGradients) {
  637. this._rampGradients = [];
  638. }
  639. let rampGradient = new Color3Gradient();
  640. rampGradient.gradient = gradient;
  641. rampGradient.color = color;
  642. this._rampGradients.push(rampGradient);
  643. this._rampGradients.sort((a, b) => {
  644. if (a.gradient < b.gradient) {
  645. return -1;
  646. } else if (a.gradient > b.gradient) {
  647. return 1;
  648. }
  649. return 0;
  650. });
  651. if (this._rampGradientsTexture) {
  652. this._rampGradientsTexture.dispose();
  653. (<any>this._rampGradientsTexture) = null;
  654. }
  655. this._createRampGradientTexture();
  656. return this;
  657. }
  658. /**
  659. * Remove a specific ramp gradient
  660. * @param gradient defines the gradient to remove
  661. * @returns the current particle system
  662. */
  663. public removeRampGradient(gradient: number): ParticleSystem {
  664. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  665. (<any>this._rampGradientsTexture) = null;
  666. if (this._rampGradients && this._rampGradients.length > 0) {
  667. this._createRampGradientTexture();
  668. }
  669. return this;
  670. }
  671. /**
  672. * Adds a new color gradient
  673. * @param gradient defines the gradient to use (between 0 and 1)
  674. * @param color defines the color to affect to the specified gradient
  675. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  676. */
  677. public addColorGradient(gradient: number, color: Color4, color2?: Color4): IParticleSystem {
  678. if (!this._colorGradients) {
  679. this._colorGradients = [];
  680. }
  681. let colorGradient = new ColorGradient();
  682. colorGradient.gradient = gradient;
  683. colorGradient.color1 = color;
  684. colorGradient.color2 = color2;
  685. this._colorGradients.push(colorGradient);
  686. this._colorGradients.sort((a, b) => {
  687. if (a.gradient < b.gradient) {
  688. return -1;
  689. } else if (a.gradient > b.gradient) {
  690. return 1;
  691. }
  692. return 0;
  693. });
  694. return this;
  695. }
  696. /**
  697. * Remove a specific color gradient
  698. * @param gradient defines the gradient to remove
  699. */
  700. public removeColorGradient(gradient: number): IParticleSystem {
  701. if (!this._colorGradients) {
  702. return this;
  703. }
  704. let index = 0;
  705. for (var colorGradient of this._colorGradients) {
  706. if (colorGradient.gradient === gradient) {
  707. this._colorGradients.splice(index, 1);
  708. break;
  709. }
  710. index++;
  711. }
  712. return this;
  713. }
  714. private _fetchR(u: number, v: number, width: number, height: number, pixels: Uint8Array): number {
  715. u = Math.abs(u) * 0.5 + 0.5;
  716. v = Math.abs(v) * 0.5 + 0.5;
  717. let wrappedU = ((u * width) % width) | 0;
  718. let wrappedV = ((v * height) % height) | 0;
  719. let position = (wrappedU + wrappedV * width) * 4;
  720. return pixels[position] / 255;
  721. }
  722. protected _reset() {
  723. this._resetEffect();
  724. }
  725. private _resetEffect() {
  726. if (this._vertexBuffer) {
  727. this._vertexBuffer.dispose();
  728. this._vertexBuffer = null;
  729. }
  730. if (this._spriteBuffer) {
  731. this._spriteBuffer.dispose();
  732. this._spriteBuffer = null;
  733. }
  734. this._createVertexBuffers();
  735. }
  736. private _createVertexBuffers() {
  737. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  738. if (this._isAnimationSheetEnabled) {
  739. this._vertexBufferSize += 1;
  740. }
  741. if (!this._isBillboardBased) {
  742. this._vertexBufferSize += 3;
  743. }
  744. if (this._useRampGradients) {
  745. this._vertexBufferSize += 4;
  746. }
  747. let engine = this._scene.getEngine();
  748. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  749. this._vertexBuffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  750. let dataOffset = 0;
  751. var positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  752. this._vertexBuffers[VertexBuffer.PositionKind] = positions;
  753. dataOffset += 3;
  754. var colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  755. this._vertexBuffers[VertexBuffer.ColorKind] = colors;
  756. dataOffset += 4;
  757. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  758. this._vertexBuffers["angle"] = options;
  759. dataOffset += 1;
  760. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  761. this._vertexBuffers["size"] = size;
  762. dataOffset += 2;
  763. if (this._isAnimationSheetEnabled) {
  764. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  765. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  766. dataOffset += 1;
  767. }
  768. if (!this._isBillboardBased) {
  769. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  770. this._vertexBuffers["direction"] = directionBuffer;
  771. dataOffset += 3;
  772. }
  773. if (this._useRampGradients) {
  774. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  775. this._vertexBuffers["remapData"] = rampDataBuffer;
  776. dataOffset += 4;
  777. }
  778. var offsets: VertexBuffer;
  779. if (this._useInstancing) {
  780. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  781. this._spriteBuffer = new Buffer(engine, spriteData, false, 2);
  782. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  783. } else {
  784. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  785. dataOffset += 2;
  786. }
  787. this._vertexBuffers["offset"] = offsets;
  788. }
  789. private _createIndexBuffer() {
  790. if (this._useInstancing) {
  791. return;
  792. }
  793. var indices = [];
  794. var index = 0;
  795. for (var count = 0; count < this._capacity; count++) {
  796. indices.push(index);
  797. indices.push(index + 1);
  798. indices.push(index + 2);
  799. indices.push(index);
  800. indices.push(index + 2);
  801. indices.push(index + 3);
  802. index += 4;
  803. }
  804. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  805. }
  806. /**
  807. * Gets the maximum number of particles active at the same time.
  808. * @returns The max number of active particles.
  809. */
  810. public getCapacity(): number {
  811. return this._capacity;
  812. }
  813. /**
  814. * Gets whether there are still active particles in the system.
  815. * @returns True if it is alive, otherwise false.
  816. */
  817. public isAlive(): boolean {
  818. return this._alive;
  819. }
  820. /**
  821. * Gets if the system has been started. (Note: this will still be true after stop is called)
  822. * @returns True if it has been started, otherwise false.
  823. */
  824. public isStarted(): boolean {
  825. return this._started;
  826. }
  827. /**
  828. * Starts the particle system and begins to emit
  829. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  830. */
  831. public start(delay = 0): void {
  832. if(!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()){
  833. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  834. }
  835. if (delay) {
  836. setTimeout(() => {
  837. this.start(0);
  838. }, delay);
  839. return;
  840. }
  841. // Convert the subEmitters field to the constant type field _subEmitters
  842. this._subEmitters = new Array<Array<SubEmitter>>();
  843. if (this.subEmitters) {
  844. this.subEmitters.forEach((subEmitter) => {
  845. if (subEmitter instanceof ParticleSystem) {
  846. this._subEmitters.push([new SubEmitter(subEmitter)]);
  847. } else if (subEmitter instanceof SubEmitter) {
  848. this._subEmitters.push([subEmitter]);
  849. } else if (subEmitter instanceof Array) {
  850. this._subEmitters.push(subEmitter);
  851. }
  852. this._subEmitters[this._subEmitters.length-1].forEach((se)=>{
  853. if (!(se.particleSystem.emitter instanceof AbstractMesh) && se.inheritDirection) {
  854. Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  855. }
  856. })
  857. });
  858. }
  859. this._started = true;
  860. this._stopped = false;
  861. this._actualFrame = 0;
  862. if (this._subEmitters && this._subEmitters.length != 0) {
  863. this.activeSubSystems = new Array<ParticleSystem>();
  864. }
  865. if (this.preWarmCycles) {
  866. for (var index = 0; index < this.preWarmCycles; index++) {
  867. this.animate(true);
  868. }
  869. }
  870. }
  871. /**
  872. * Stops the particle system.
  873. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  874. */
  875. public stop(stopSubEmitters = true): void {
  876. this._stopped = true;
  877. if (stopSubEmitters) {
  878. this._stopSubEmitters();
  879. }
  880. }
  881. // animation sheet
  882. /**
  883. * Remove all active particles
  884. */
  885. public reset(): void {
  886. this._stockParticles = [];
  887. this._particles = [];
  888. }
  889. /**
  890. * @hidden (for internal use only)
  891. */
  892. public _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void {
  893. var offset = index * this._vertexBufferSize;
  894. this._vertexData[offset++] = particle.position.x;
  895. this._vertexData[offset++] = particle.position.y;
  896. this._vertexData[offset++] = particle.position.z;
  897. this._vertexData[offset++] = particle.color.r;
  898. this._vertexData[offset++] = particle.color.g;
  899. this._vertexData[offset++] = particle.color.b;
  900. this._vertexData[offset++] = particle.color.a;
  901. this._vertexData[offset++] = particle.angle;
  902. this._vertexData[offset++] = particle.scale.x * particle.size;
  903. this._vertexData[offset++] = particle.scale.y * particle.size;
  904. if (this._isAnimationSheetEnabled) {
  905. this._vertexData[offset++] = particle.cellIndex;
  906. }
  907. if (!this._isBillboardBased) {
  908. if (particle._initialDirection) {
  909. this._vertexData[offset++] = particle._initialDirection.x;
  910. this._vertexData[offset++] = particle._initialDirection.y;
  911. this._vertexData[offset++] = particle._initialDirection.z;
  912. } else {
  913. this._vertexData[offset++] = particle.direction.x;
  914. this._vertexData[offset++] = particle.direction.y;
  915. this._vertexData[offset++] = particle.direction.z;
  916. }
  917. }
  918. if (this._useRampGradients) {
  919. this._vertexData[offset++] = particle.remapData.x;
  920. this._vertexData[offset++] = particle.remapData.y;
  921. this._vertexData[offset++] = particle.remapData.z;
  922. this._vertexData[offset++] = particle.remapData.w;
  923. }
  924. if (!this._useInstancing) {
  925. if (this._isAnimationSheetEnabled) {
  926. if (offsetX === 0)
  927. offsetX = this._epsilon;
  928. else if (offsetX === 1)
  929. offsetX = 1 - this._epsilon;
  930. if (offsetY === 0)
  931. offsetY = this._epsilon;
  932. else if (offsetY === 1)
  933. offsetY = 1 - this._epsilon;
  934. }
  935. this._vertexData[offset++] = offsetX;
  936. this._vertexData[offset++] = offsetY;
  937. }
  938. }
  939. // start of sub system methods
  940. /**
  941. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  942. * Its lifetime will start back at 0.
  943. */
  944. public recycleParticle: (particle: Particle) => void = (particle) => {
  945. // move particle from activeParticle list to stock particles
  946. var lastParticle = <Particle>this._particles.pop();
  947. if (lastParticle !== particle) {
  948. lastParticle.copyTo(particle);
  949. }
  950. this._stockParticles.push(lastParticle);
  951. };
  952. private _stopSubEmitters(): void {
  953. if (!this.activeSubSystems) {
  954. return;
  955. }
  956. this.activeSubSystems.forEach(subSystem => {
  957. subSystem.stop(true);
  958. });
  959. this.activeSubSystems = new Array<ParticleSystem>();
  960. }
  961. private _createParticle: () => Particle = () => {
  962. var particle: Particle;
  963. if (this._stockParticles.length !== 0) {
  964. particle = <Particle>this._stockParticles.pop();
  965. particle._reset();
  966. } else {
  967. particle = new Particle(this);
  968. }
  969. // Attach emitters
  970. if (this._subEmitters && this._subEmitters.length > 0) {
  971. var subEmitters = this._subEmitters[Math.floor(Math.random() * this._subEmitters.length)];
  972. particle._attachedSubEmitters = [];
  973. subEmitters.forEach((subEmitter) => {
  974. if (subEmitter.type === SubEmitterType.ATTACHED) {
  975. var newEmitter = subEmitter.clone();
  976. (<Array<SubEmitter>>particle._attachedSubEmitters).push(newEmitter);
  977. newEmitter.particleSystem.start();
  978. }
  979. })
  980. }
  981. return particle;
  982. }
  983. private _removeFromRoot(): void {
  984. if (!this._rootParticleSystem) {
  985. return;
  986. }
  987. let index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  988. if (index !== -1) {
  989. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  990. }
  991. }
  992. private _emitFromParticle: (particle: Particle) => void = (particle) => {
  993. if (!this._subEmitters || this._subEmitters.length === 0) {
  994. return;
  995. }
  996. var templateIndex = Math.floor(Math.random() * this._subEmitters.length);
  997. this._subEmitters[templateIndex].forEach((subEmitter) => {
  998. if (subEmitter.type === SubEmitterType.END) {
  999. var subSystem = subEmitter.clone();
  1000. ParticleSystem._InheritParticleInfoToSubEmitter(subSystem, particle);
  1001. subSystem.particleSystem._rootParticleSystem = this;
  1002. this.activeSubSystems.push(subSystem.particleSystem);
  1003. subSystem.particleSystem.start();
  1004. }
  1005. })
  1006. }
  1007. // End of sub system methods
  1008. private _update(newParticles: number): void {
  1009. // Update current
  1010. this._alive = this._particles.length > 0;
  1011. if ((<AbstractMesh>this.emitter).position) {
  1012. var emitterMesh = (<AbstractMesh>this.emitter);
  1013. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  1014. } else {
  1015. var emitterPosition = (<Vector3>this.emitter);
  1016. this._emitterWorldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  1017. }
  1018. this.updateFunction(this._particles);
  1019. // Add new ones
  1020. var particle: Particle;
  1021. for (var index = 0; index < newParticles; index++) {
  1022. if (this._particles.length === this._capacity) {
  1023. break;
  1024. }
  1025. particle = this._createParticle();
  1026. this._particles.push(particle);
  1027. // Emitter
  1028. let emitPower = Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  1029. if (this.startPositionFunction) {
  1030. this.startPositionFunction(this._emitterWorldMatrix, particle.position, particle);
  1031. }
  1032. else {
  1033. this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix, particle.position, particle);
  1034. }
  1035. if (this.startDirectionFunction) {
  1036. this.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle);
  1037. }
  1038. else {
  1039. this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle);
  1040. }
  1041. if (emitPower === 0) {
  1042. if (!particle._initialDirection) {
  1043. particle._initialDirection = particle.direction.clone();
  1044. } else {
  1045. particle._initialDirection.copyFrom(particle.direction);
  1046. }
  1047. } else {
  1048. particle._initialDirection = null;
  1049. }
  1050. particle.direction.scaleInPlace(emitPower);
  1051. // Life time
  1052. if (this.targetStopDuration && this._lifeTimeGradients && this._lifeTimeGradients.length > 0) {
  1053. let ratio = Scalar.Clamp(this._actualFrame / this.targetStopDuration);
  1054. Tools.GetCurrentGradient(ratio, this._lifeTimeGradients, (currentGradient, nextGradient, scale) => {
  1055. let factorGradient1 = (<FactorGradient>currentGradient);
  1056. let factorGradient2 = (<FactorGradient>nextGradient);
  1057. let lifeTime1 = factorGradient1.getFactor();
  1058. let lifeTime2 = factorGradient2.getFactor();
  1059. let gradient = (ratio - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  1060. particle.lifeTime = Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  1061. });
  1062. } else {
  1063. particle.lifeTime = Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  1064. }
  1065. // Size
  1066. if (!this._sizeGradients || this._sizeGradients.length === 0) {
  1067. particle.size = Scalar.RandomRange(this.minSize, this.maxSize);
  1068. } else {
  1069. particle._currentSizeGradient = this._sizeGradients[0];
  1070. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  1071. particle.size = particle._currentSize1;
  1072. if (this._sizeGradients.length > 1) {
  1073. particle._currentSize2 = this._sizeGradients[1].getFactor();
  1074. } else {
  1075. particle._currentSize2 = particle._currentSize1;
  1076. }
  1077. }
  1078. // Size and scale
  1079. particle.scale.copyFromFloats(Scalar.RandomRange(this.minScaleX, this.maxScaleX), Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  1080. // Adjust scale by start size
  1081. if (this._startSizeGradients && this._startSizeGradients[0] && this.targetStopDuration) {
  1082. const ratio = this._actualFrame / this.targetStopDuration;
  1083. Tools.GetCurrentGradient(ratio, this._startSizeGradients, (currentGradient, nextGradient, scale) => {
  1084. if (currentGradient !== this._currentStartSizeGradient) {
  1085. this._currentStartSize1 = this._currentStartSize2;
  1086. this._currentStartSize2 = (<FactorGradient>nextGradient).getFactor();
  1087. this._currentStartSizeGradient = (<FactorGradient>currentGradient);
  1088. }
  1089. var value = Scalar.Lerp(this._currentStartSize1, this._currentStartSize2, scale);
  1090. particle.scale.scaleInPlace(value);
  1091. });
  1092. }
  1093. // Angle
  1094. if (!this._angularSpeedGradients || this._angularSpeedGradients.length === 0) {
  1095. particle.angularSpeed = Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  1096. } else {
  1097. particle._currentAngularSpeedGradient = this._angularSpeedGradients[0];
  1098. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  1099. particle._currentAngularSpeed1 = particle.angularSpeed;
  1100. if (this._angularSpeedGradients.length > 1) {
  1101. particle._currentAngularSpeed2 = this._angularSpeedGradients[1].getFactor();
  1102. } else {
  1103. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  1104. }
  1105. }
  1106. particle.angle = Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  1107. // Velocity
  1108. if (this._velocityGradients && this._velocityGradients.length > 0) {
  1109. particle._currentVelocityGradient = this._velocityGradients[0];
  1110. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  1111. if (this._velocityGradients.length > 1) {
  1112. particle._currentVelocity2 = this._velocityGradients[1].getFactor();
  1113. } else {
  1114. particle._currentVelocity2 = particle._currentVelocity1;
  1115. }
  1116. }
  1117. // Limit velocity
  1118. if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {
  1119. particle._currentLimitVelocityGradient = this._limitVelocityGradients[0];
  1120. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  1121. if (this._limitVelocityGradients.length > 1) {
  1122. particle._currentLimitVelocity2 = this._limitVelocityGradients[1].getFactor();
  1123. } else {
  1124. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  1125. }
  1126. }
  1127. // Drag
  1128. if (this._dragGradients && this._dragGradients.length > 0) {
  1129. particle._currentDragGradient = this._dragGradients[0];
  1130. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  1131. if (this._dragGradients.length > 1) {
  1132. particle._currentDrag2 = this._dragGradients[1].getFactor();
  1133. } else {
  1134. particle._currentDrag2 = particle._currentDrag1;
  1135. }
  1136. }
  1137. // Color
  1138. if (!this._colorGradients || this._colorGradients.length === 0) {
  1139. var step = Scalar.RandomRange(0, 1.0);
  1140. Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  1141. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  1142. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  1143. } else {
  1144. particle._currentColorGradient = this._colorGradients[0];
  1145. particle._currentColorGradient.getColorToRef(particle.color);
  1146. particle._currentColor1.copyFrom(particle.color);
  1147. if (this._colorGradients.length > 1) {
  1148. this._colorGradients[1].getColorToRef(particle._currentColor2);
  1149. } else {
  1150. particle._currentColor2.copyFrom(particle.color);
  1151. }
  1152. }
  1153. // Sheet
  1154. if (this._isAnimationSheetEnabled) {
  1155. particle._initialStartSpriteCellID = this.startSpriteCellID;
  1156. particle._initialEndSpriteCellID = this.endSpriteCellID;
  1157. }
  1158. // Inherited Velocity
  1159. particle.direction.addInPlace(this._inheritedVelocityOffset);
  1160. // Ramp
  1161. if (this._useRampGradients) {
  1162. particle.remapData = new Vector4(0, 1, 0, 1);
  1163. }
  1164. }
  1165. }
  1166. /** @hidden */
  1167. public static _GetAttributeNamesOrOptions(isAnimationSheetEnabled = false, isBillboardBased = false, useRampGradients = false): string[] {
  1168. var attributeNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "angle", "offset", "size"]
  1169. if (isAnimationSheetEnabled) {
  1170. attributeNamesOrOptions.push("cellIndex");
  1171. }
  1172. if (!isBillboardBased) {
  1173. attributeNamesOrOptions.push("direction");
  1174. }
  1175. if (useRampGradients) {
  1176. attributeNamesOrOptions.push("remapData");
  1177. }
  1178. return attributeNamesOrOptions;
  1179. }
  1180. public static _GetEffectCreationOptions(isAnimationSheetEnabled = false): string[] {
  1181. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  1182. if (isAnimationSheetEnabled) {
  1183. effectCreationOption.push("particlesInfos")
  1184. }
  1185. return effectCreationOption;
  1186. }
  1187. private _getEffect(blendMode: number): Effect {
  1188. if (this._customEffect) {
  1189. return this._customEffect;
  1190. };
  1191. var defines = [];
  1192. if (this._scene.clipPlane) {
  1193. defines.push("#define CLIPPLANE");
  1194. }
  1195. if (this._scene.clipPlane2) {
  1196. defines.push("#define CLIPPLANE2");
  1197. }
  1198. if (this._scene.clipPlane3) {
  1199. defines.push("#define CLIPPLANE3");
  1200. }
  1201. if (this._scene.clipPlane4) {
  1202. defines.push("#define CLIPPLANE4");
  1203. }
  1204. if (this._isAnimationSheetEnabled) {
  1205. defines.push("#define ANIMATESHEET");
  1206. }
  1207. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  1208. defines.push("#define BLENDMULTIPLYMODE");
  1209. }
  1210. if (this._useRampGradients) {
  1211. defines.push("#define RAMPGRADIENT");
  1212. }
  1213. if (this._isBillboardBased) {
  1214. defines.push("#define BILLBOARD");
  1215. switch (this.billboardMode) {
  1216. case AbstractMesh.BILLBOARDMODE_Y:
  1217. defines.push("#define BILLBOARDY");
  1218. break;
  1219. case AbstractMesh.BILLBOARDMODE_ALL:
  1220. default:
  1221. break;
  1222. }
  1223. }
  1224. if (this._imageProcessingConfiguration) {
  1225. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  1226. defines.push(this._imageProcessingConfigurationDefines.toString());
  1227. }
  1228. // Effect
  1229. var join = defines.join("\n");
  1230. if (this._cachedDefines !== join) {
  1231. this._cachedDefines = join;
  1232. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased, this._useRampGradients);
  1233. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  1234. var samplers = ["diffuseSampler", "rampSampler"];
  1235. if (ImageProcessingConfiguration) {
  1236. ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  1237. ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  1238. }
  1239. this._effect = this._scene.getEngine().createEffect(
  1240. "particles",
  1241. attributesNamesOrOptions,
  1242. effectCreationOption,
  1243. samplers, join);
  1244. }
  1245. return this._effect;
  1246. }
  1247. /**
  1248. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  1249. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  1250. */
  1251. public animate(preWarmOnly = false): void {
  1252. if (!this._started)
  1253. return;
  1254. if (!preWarmOnly) {
  1255. // Check
  1256. if (!this.isReady())
  1257. return;
  1258. if (this._currentRenderId === this._scene.getRenderId()) {
  1259. return;
  1260. }
  1261. this._currentRenderId = this._scene.getRenderId();
  1262. }
  1263. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  1264. // Determine the number of particles we need to create
  1265. var newParticles;
  1266. if (this.manualEmitCount > -1) {
  1267. newParticles = this.manualEmitCount;
  1268. this._newPartsExcess = 0;
  1269. this.manualEmitCount = 0;
  1270. } else {
  1271. let rate = this.emitRate;
  1272. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  1273. const ratio = this._actualFrame / this.targetStopDuration;
  1274. Tools.GetCurrentGradient(ratio, this._emitRateGradients, (currentGradient, nextGradient, scale) => {
  1275. if (currentGradient !== this._currentEmitRateGradient) {
  1276. this._currentEmitRate1 = this._currentEmitRate2;
  1277. this._currentEmitRate2 = (<FactorGradient>nextGradient).getFactor();
  1278. this._currentEmitRateGradient = (<FactorGradient>currentGradient);
  1279. }
  1280. rate = Scalar.Lerp(this._currentEmitRate1, this._currentEmitRate2, scale);
  1281. });
  1282. }
  1283. newParticles = ((rate * this._scaledUpdateSpeed) >> 0);
  1284. this._newPartsExcess += rate * this._scaledUpdateSpeed - newParticles;
  1285. }
  1286. if (this._newPartsExcess > 1.0) {
  1287. newParticles += this._newPartsExcess >> 0;
  1288. this._newPartsExcess -= this._newPartsExcess >> 0;
  1289. }
  1290. this._alive = false;
  1291. if (!this._stopped) {
  1292. this._actualFrame += this._scaledUpdateSpeed;
  1293. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  1294. this.stop();
  1295. } else {
  1296. newParticles = 0;
  1297. }
  1298. this._update(newParticles);
  1299. // Stopped?
  1300. if (this._stopped) {
  1301. if (!this._alive) {
  1302. this._started = false;
  1303. if (this.onAnimationEnd) {
  1304. this.onAnimationEnd();
  1305. }
  1306. if (this.disposeOnStop) {
  1307. this._scene._toBeDisposed.push(this);
  1308. }
  1309. }
  1310. }
  1311. if (!preWarmOnly) {
  1312. // Update VBO
  1313. var offset = 0;
  1314. for (var index = 0; index < this._particles.length; index++) {
  1315. var particle = this._particles[index];
  1316. this._appendParticleVertices(offset, particle);
  1317. offset += this._useInstancing ? 1 : 4;
  1318. }
  1319. if (this._vertexBuffer) {
  1320. this._vertexBuffer.update(this._vertexData);
  1321. }
  1322. }
  1323. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  1324. this.stop();
  1325. }
  1326. }
  1327. private _appendParticleVertices(offset: number, particle: Particle) {
  1328. this._appendParticleVertex(offset++, particle, 0, 0);
  1329. if (!this._useInstancing) {
  1330. this._appendParticleVertex(offset++, particle, 1, 0);
  1331. this._appendParticleVertex(offset++, particle, 1, 1);
  1332. this._appendParticleVertex(offset++, particle, 0, 1);
  1333. }
  1334. }
  1335. /**
  1336. * Rebuilds the particle system.
  1337. */
  1338. public rebuild(): void {
  1339. this._createIndexBuffer();
  1340. if (this._vertexBuffer) {
  1341. this._vertexBuffer._rebuild();
  1342. }
  1343. }
  1344. /**
  1345. * Is this system ready to be used/rendered
  1346. * @return true if the system is ready
  1347. */
  1348. public isReady(): boolean {
  1349. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  1350. return false;
  1351. }
  1352. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  1353. if (!this._getEffect(this.blendMode).isReady()) {
  1354. return false;
  1355. }
  1356. } else {
  1357. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  1358. return false;
  1359. }
  1360. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  1361. return false;
  1362. }
  1363. }
  1364. return true;
  1365. }
  1366. private _render(blendMode: number) {
  1367. var effect = this._getEffect(blendMode);
  1368. var engine = this._scene.getEngine();
  1369. // Render
  1370. engine.enableEffect(effect);
  1371. var viewMatrix = this._scene.getViewMatrix();
  1372. effect.setTexture("diffuseSampler", this.particleTexture);
  1373. effect.setMatrix("view", viewMatrix);
  1374. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  1375. if (this._isAnimationSheetEnabled && this.particleTexture) {
  1376. var baseSize = this.particleTexture.getBaseSize();
  1377. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  1378. }
  1379. effect.setVector2("translationPivot", this.translationPivot);
  1380. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  1381. if (this._isBillboardBased) {
  1382. var camera = this._scene.activeCamera!;
  1383. effect.setVector3("eyePosition", camera.globalPosition);
  1384. }
  1385. if (this._rampGradientsTexture) {
  1386. effect.setTexture("rampSampler", this._rampGradientsTexture);
  1387. }
  1388. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  1389. var invView = viewMatrix.clone();
  1390. invView.invert();
  1391. effect.setMatrix("invView", invView);
  1392. MaterialHelper.BindClipPlane(effect, this._scene);
  1393. }
  1394. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  1395. // image processing
  1396. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  1397. this._imageProcessingConfiguration.bind(effect);
  1398. }
  1399. // Draw order
  1400. switch (blendMode) {
  1401. case ParticleSystem.BLENDMODE_ADD:
  1402. engine.setAlphaMode(Engine.ALPHA_ADD);
  1403. break;
  1404. case ParticleSystem.BLENDMODE_ONEONE:
  1405. engine.setAlphaMode(Engine.ALPHA_ONEONE);
  1406. break;
  1407. case ParticleSystem.BLENDMODE_STANDARD:
  1408. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  1409. break;
  1410. case ParticleSystem.BLENDMODE_MULTIPLY:
  1411. engine.setAlphaMode(Engine.ALPHA_MULTIPLY);
  1412. break;
  1413. }
  1414. if (this._useInstancing) {
  1415. engine.drawArraysType(Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  1416. } else {
  1417. engine.drawElementsType(Material.TriangleFillMode, 0, this._particles.length * 6);
  1418. }
  1419. return this._particles.length;
  1420. }
  1421. /**
  1422. * Renders the particle system in its current state.
  1423. * @returns the current number of particles
  1424. */
  1425. public render(): number {
  1426. // Check
  1427. if (!this.isReady() || !this._particles.length) {
  1428. return 0;
  1429. }
  1430. var engine = this._scene.getEngine();
  1431. engine.setState(false);
  1432. if (this.forceDepthWrite) {
  1433. engine.setDepthWrite(true);
  1434. }
  1435. let outparticles = 0;
  1436. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  1437. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  1438. }
  1439. outparticles = this._render(this.blendMode);
  1440. engine.unbindInstanceAttributes();
  1441. engine.setAlphaMode(Engine.ALPHA_DISABLE);
  1442. return outparticles;
  1443. }
  1444. /**
  1445. * Disposes the particle system and free the associated resources
  1446. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  1447. */
  1448. public dispose(disposeTexture = true): void {
  1449. if (this._vertexBuffer) {
  1450. this._vertexBuffer.dispose();
  1451. this._vertexBuffer = null;
  1452. }
  1453. if (this._spriteBuffer) {
  1454. this._spriteBuffer.dispose();
  1455. this._spriteBuffer = null;
  1456. }
  1457. if (this._indexBuffer) {
  1458. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  1459. this._indexBuffer = null;
  1460. }
  1461. if (disposeTexture && this.particleTexture) {
  1462. this.particleTexture.dispose();
  1463. this.particleTexture = null;
  1464. }
  1465. if (disposeTexture && this.noiseTexture) {
  1466. this.noiseTexture.dispose();
  1467. this.noiseTexture = null;
  1468. }
  1469. if (this._rampGradientsTexture) {
  1470. this._rampGradientsTexture.dispose();
  1471. this._rampGradientsTexture = null;
  1472. }
  1473. this._removeFromRoot();
  1474. if (this._disposeEmitterOnDispose && this.emitter && (this.emitter as AbstractMesh).dispose) {
  1475. (<AbstractMesh>this.emitter).dispose(true);
  1476. }
  1477. // Remove from scene
  1478. var index = this._scene.particleSystems.indexOf(this);
  1479. if (index > -1) {
  1480. this._scene.particleSystems.splice(index, 1);
  1481. }
  1482. // Callback
  1483. this.onDisposeObservable.notifyObservers(this);
  1484. this.onDisposeObservable.clear();
  1485. }
  1486. // Clone
  1487. /**
  1488. * Clones the particle system.
  1489. * @param name The name of the cloned object
  1490. * @param newEmitter The new emitter to use
  1491. * @returns the cloned particle system
  1492. */
  1493. public clone(name: string, newEmitter: any): ParticleSystem {
  1494. var custom: Nullable<Effect> = null;
  1495. var program: any = null;
  1496. if (this.customShader != null) {
  1497. program = this.customShader;
  1498. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  1499. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  1500. } else if (this._customEffect) {
  1501. custom = this._customEffect;
  1502. }
  1503. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  1504. result.customShader = program;
  1505. Tools.DeepCopy(this, result, ["particles", "customShader"]);
  1506. if (newEmitter === undefined) {
  1507. newEmitter = this.emitter;
  1508. }
  1509. result.emitter = newEmitter;
  1510. if (this.particleTexture) {
  1511. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  1512. }
  1513. // Clone gradients
  1514. if (this._colorGradients) {
  1515. this._colorGradients.forEach((v) => {
  1516. result.addColorGradient(v.gradient, v.color1, v.color2);
  1517. });
  1518. }
  1519. if (this._dragGradients) {
  1520. this._dragGradients.forEach((v) => {
  1521. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  1522. });
  1523. }
  1524. if (this._angularSpeedGradients) {
  1525. this._angularSpeedGradients.forEach((v) => {
  1526. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  1527. });
  1528. }
  1529. if (this._emitRateGradients) {
  1530. this._emitRateGradients.forEach((v) => {
  1531. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  1532. });
  1533. }
  1534. if (this._lifeTimeGradients) {
  1535. this._lifeTimeGradients.forEach((v) => {
  1536. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  1537. });
  1538. }
  1539. if (this._limitVelocityGradients) {
  1540. this._limitVelocityGradients.forEach((v) => {
  1541. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  1542. });
  1543. }
  1544. if (this._sizeGradients) {
  1545. this._sizeGradients.forEach((v) => {
  1546. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  1547. });
  1548. }
  1549. if (this._startSizeGradients) {
  1550. this._startSizeGradients.forEach((v) => {
  1551. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  1552. });
  1553. }
  1554. if (this._velocityGradients) {
  1555. this._velocityGradients.forEach((v) => {
  1556. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  1557. });
  1558. }
  1559. if (this._rampGradients) {
  1560. this._rampGradients.forEach((v) => {
  1561. result.addRampGradient(v.gradient, v.color);
  1562. });
  1563. }
  1564. if (this._colorRemapGradients) {
  1565. this._colorRemapGradients.forEach((v) => {
  1566. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2!);
  1567. });
  1568. }
  1569. if (this._alphaRemapGradients) {
  1570. this._alphaRemapGradients.forEach((v) => {
  1571. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2!);
  1572. });
  1573. }
  1574. if (!this.preventAutoStart) {
  1575. result.start();
  1576. }
  1577. return result;
  1578. }
  1579. /**
  1580. * Serializes the particle system to a JSON object.
  1581. * @returns the JSON object
  1582. */
  1583. public serialize(): any {
  1584. var serializationObject: any = {};
  1585. ParticleSystem._Serialize(serializationObject, this);
  1586. serializationObject.textureMask = this.textureMask.asArray();
  1587. serializationObject.customShader = this.customShader;
  1588. serializationObject.preventAutoStart = this.preventAutoStart;
  1589. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  1590. return serializationObject;
  1591. }
  1592. /** @hidden */
  1593. public static _Serialize(serializationObject: any, particleSystem: IParticleSystem) {
  1594. serializationObject.name = particleSystem.name;
  1595. serializationObject.id = particleSystem.id;
  1596. serializationObject.capacity = particleSystem.getCapacity();
  1597. // Emitter
  1598. if ((<AbstractMesh>particleSystem.emitter).position) {
  1599. var emitterMesh = (<AbstractMesh>particleSystem.emitter);
  1600. serializationObject.emitterId = emitterMesh.id;
  1601. } else {
  1602. var emitterPosition = (<Vector3>particleSystem.emitter);
  1603. serializationObject.emitter = emitterPosition.asArray();
  1604. }
  1605. // Emitter
  1606. if (particleSystem.particleEmitterType) {
  1607. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  1608. }
  1609. if (particleSystem.particleTexture) {
  1610. serializationObject.textureName = particleSystem.particleTexture.name;
  1611. }
  1612. // Animations
  1613. Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  1614. // Particle system
  1615. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  1616. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  1617. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  1618. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  1619. serializationObject.minSize = particleSystem.minSize;
  1620. serializationObject.maxSize = particleSystem.maxSize;
  1621. serializationObject.minScaleX = particleSystem.minScaleX;
  1622. serializationObject.maxScaleX = particleSystem.maxScaleX;
  1623. serializationObject.minScaleY = particleSystem.minScaleY;
  1624. serializationObject.maxScaleY = particleSystem.maxScaleY;
  1625. serializationObject.minEmitPower = particleSystem.minEmitPower;
  1626. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  1627. serializationObject.minLifeTime = particleSystem.minLifeTime;
  1628. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  1629. serializationObject.emitRate = particleSystem.emitRate;
  1630. serializationObject.gravity = particleSystem.gravity.asArray();
  1631. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  1632. serializationObject.color1 = particleSystem.color1.asArray();
  1633. serializationObject.color2 = particleSystem.color2.asArray();
  1634. serializationObject.colorDead = particleSystem.colorDead.asArray();
  1635. serializationObject.updateSpeed = particleSystem.updateSpeed;
  1636. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  1637. serializationObject.blendMode = particleSystem.blendMode;
  1638. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  1639. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  1640. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  1641. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  1642. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  1643. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  1644. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  1645. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  1646. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  1647. let colorGradients = particleSystem.getColorGradients();
  1648. if (colorGradients) {
  1649. serializationObject.colorGradients = [];
  1650. for (var colorGradient of colorGradients) {
  1651. var serializedGradient: any = {
  1652. gradient: colorGradient.gradient,
  1653. color1: colorGradient.color1.asArray()
  1654. };
  1655. if (colorGradient.color2) {
  1656. serializedGradient.color2 = colorGradient.color2.asArray();
  1657. }
  1658. serializationObject.colorGradients.push(serializedGradient);
  1659. }
  1660. }
  1661. let rampGradients = particleSystem.getRampGradients();
  1662. if (rampGradients) {
  1663. serializationObject.rampGradients = [];
  1664. for (var rampGradient of rampGradients) {
  1665. var serializedGradient: any = {
  1666. gradient: rampGradient.gradient,
  1667. color: rampGradient.color.asArray()
  1668. };
  1669. serializationObject.rampGradients.push(serializedGradient);
  1670. }
  1671. }
  1672. let colorRemapGradients = particleSystem.getColorRemapGradients();
  1673. if (colorRemapGradients) {
  1674. serializationObject.colorRemapGradients = [];
  1675. for (var colorRemapGradient of colorRemapGradients) {
  1676. var serializedGradient: any = {
  1677. gradient: colorRemapGradient.gradient,
  1678. factor1: colorRemapGradient.factor1
  1679. };
  1680. if (colorRemapGradient.factor2 !== undefined) {
  1681. serializedGradient.factor2 = colorRemapGradient.factor2;
  1682. }
  1683. serializationObject.colorRemapGradients.push(serializedGradient);
  1684. }
  1685. }
  1686. let alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  1687. if (alphaRemapGradients) {
  1688. serializationObject.alphaRemapGradients = [];
  1689. for (var alphaRemapGradient of alphaRemapGradients) {
  1690. var serializedGradient: any = {
  1691. gradient: alphaRemapGradient.gradient,
  1692. factor1: alphaRemapGradient.factor1
  1693. };
  1694. if (alphaRemapGradient.factor2 !== undefined) {
  1695. serializedGradient.factor2 = alphaRemapGradient.factor2;
  1696. }
  1697. serializationObject.alphaRemapGradients.push(serializedGradient);
  1698. }
  1699. }
  1700. let sizeGradients = particleSystem.getSizeGradients();
  1701. if (sizeGradients) {
  1702. serializationObject.sizeGradients = [];
  1703. for (var sizeGradient of sizeGradients) {
  1704. var serializedGradient: any = {
  1705. gradient: sizeGradient.gradient,
  1706. factor1: sizeGradient.factor1
  1707. };
  1708. if (sizeGradient.factor2 !== undefined) {
  1709. serializedGradient.factor2 = sizeGradient.factor2;
  1710. }
  1711. serializationObject.sizeGradients.push(serializedGradient);
  1712. }
  1713. }
  1714. let angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  1715. if (angularSpeedGradients) {
  1716. serializationObject.angularSpeedGradients = [];
  1717. for (var angularSpeedGradient of angularSpeedGradients) {
  1718. var serializedGradient: any = {
  1719. gradient: angularSpeedGradient.gradient,
  1720. factor1: angularSpeedGradient.factor1
  1721. };
  1722. if (angularSpeedGradient.factor2 !== undefined) {
  1723. serializedGradient.factor2 = angularSpeedGradient.factor2;
  1724. }
  1725. serializationObject.angularSpeedGradients.push(serializedGradient);
  1726. }
  1727. }
  1728. let velocityGradients = particleSystem.getVelocityGradients();
  1729. if (velocityGradients) {
  1730. serializationObject.velocityGradients = [];
  1731. for (var velocityGradient of velocityGradients) {
  1732. var serializedGradient: any = {
  1733. gradient: velocityGradient.gradient,
  1734. factor1: velocityGradient.factor1
  1735. };
  1736. if (velocityGradient.factor2 !== undefined) {
  1737. serializedGradient.factor2 = velocityGradient.factor2;
  1738. }
  1739. serializationObject.velocityGradients.push(serializedGradient);
  1740. }
  1741. }
  1742. let dragGradients = particleSystem.getDragGradients();
  1743. if (dragGradients) {
  1744. serializationObject.dragyGradients = [];
  1745. for (var dragGradient of dragGradients) {
  1746. var serializedGradient: any = {
  1747. gradient: dragGradient.gradient,
  1748. factor1: dragGradient.factor1
  1749. };
  1750. if (dragGradient.factor2 !== undefined) {
  1751. serializedGradient.factor2 = dragGradient.factor2;
  1752. }
  1753. serializationObject.dragGradients.push(serializedGradient);
  1754. }
  1755. }
  1756. let emitRateGradients = particleSystem.getEmitRateGradients();
  1757. if (emitRateGradients) {
  1758. serializationObject.emitRateGradients = [];
  1759. for (var emitRateGradient of emitRateGradients) {
  1760. var serializedGradient: any = {
  1761. gradient: emitRateGradient.gradient,
  1762. factor1: emitRateGradient.factor1
  1763. };
  1764. if (emitRateGradient.factor2 !== undefined) {
  1765. serializedGradient.factor2 = emitRateGradient.factor2;
  1766. }
  1767. serializationObject.emitRateGradients.push(serializedGradient);
  1768. }
  1769. }
  1770. let startSizeGradients = particleSystem.getStartSizeGradients();
  1771. if (startSizeGradients) {
  1772. serializationObject.startSizeGradients = [];
  1773. for (var startSizeGradient of startSizeGradients) {
  1774. var serializedGradient: any = {
  1775. gradient: startSizeGradient.gradient,
  1776. factor1: startSizeGradient.factor1
  1777. };
  1778. if (startSizeGradient.factor2 !== undefined) {
  1779. serializedGradient.factor2 = startSizeGradient.factor2;
  1780. }
  1781. serializationObject.startSizeGradients.push(serializedGradient);
  1782. }
  1783. }
  1784. let limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  1785. if (limitVelocityGradients) {
  1786. serializationObject.limitVelocityGradients = [];
  1787. for (var limitVelocityGradient of limitVelocityGradients) {
  1788. var serializedGradient: any = {
  1789. gradient: limitVelocityGradient.gradient,
  1790. factor1: limitVelocityGradient.factor1
  1791. };
  1792. if (limitVelocityGradient.factor2 !== undefined) {
  1793. serializedGradient.factor2 = limitVelocityGradient.factor2;
  1794. }
  1795. serializationObject.limitVelocityGradients.push(serializedGradient);
  1796. }
  1797. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  1798. }
  1799. if (ProceduralTexture && particleSystem.noiseTexture && particleSystem.noiseTexture instanceof ProceduralTexture) {
  1800. const noiseTexture = particleSystem.noiseTexture as ProceduralTexture;
  1801. serializationObject.noiseTexture = noiseTexture.serialize();
  1802. }
  1803. }
  1804. /** @hidden */
  1805. public static _Parse(parsedParticleSystem: any, particleSystem: IParticleSystem, scene: Scene, rootUrl: string) {
  1806. // Texture
  1807. if (parsedParticleSystem.textureName) {
  1808. particleSystem.particleTexture = new Texture(rootUrl + parsedParticleSystem.textureName, scene);
  1809. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  1810. }
  1811. // Emitter
  1812. if (parsedParticleSystem.emitterId === undefined) {
  1813. particleSystem.emitter = Vector3.Zero();
  1814. }
  1815. else if (parsedParticleSystem.emitterId) {
  1816. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  1817. } else {
  1818. particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);
  1819. }
  1820. // Misc.
  1821. if (parsedParticleSystem.renderingGroupId !== undefined) {
  1822. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  1823. }
  1824. if (parsedParticleSystem.isBillboardBased !== undefined) {
  1825. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  1826. }
  1827. // Animations
  1828. if (parsedParticleSystem.animations) {
  1829. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  1830. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  1831. particleSystem.animations.push(Animation.Parse(parsedAnimation));
  1832. }
  1833. }
  1834. if (parsedParticleSystem.autoAnimate) {
  1835. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  1836. }
  1837. // Particle system
  1838. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  1839. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  1840. particleSystem.minSize = parsedParticleSystem.minSize;
  1841. particleSystem.maxSize = parsedParticleSystem.maxSize;
  1842. if (parsedParticleSystem.minScaleX) {
  1843. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  1844. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  1845. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  1846. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  1847. }
  1848. if (parsedParticleSystem.preWarmCycles !== undefined) {
  1849. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  1850. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  1851. }
  1852. if (parsedParticleSystem.minInitialRotation !== undefined) {
  1853. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  1854. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  1855. }
  1856. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  1857. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  1858. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  1859. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  1860. particleSystem.emitRate = parsedParticleSystem.emitRate;
  1861. particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);
  1862. if (parsedParticleSystem.noiseStrength) {
  1863. particleSystem.noiseStrength = Vector3.FromArray(parsedParticleSystem.noiseStrength);
  1864. }
  1865. particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);
  1866. particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);
  1867. particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);
  1868. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  1869. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  1870. particleSystem.blendMode = parsedParticleSystem.blendMode;
  1871. if (parsedParticleSystem.colorGradients) {
  1872. for (var colorGradient of parsedParticleSystem.colorGradients) {
  1873. particleSystem.addColorGradient(colorGradient.gradient, Color4.FromArray(colorGradient.color1), colorGradient.color2 ? Color4.FromArray(colorGradient.color2) : undefined);
  1874. }
  1875. }
  1876. if (parsedParticleSystem.rampGradients) {
  1877. for (var rampGradient of parsedParticleSystem.rampGradients) {
  1878. particleSystem.addRampGradient(rampGradient.gradient, Color3.FromArray(rampGradient.color1));
  1879. }
  1880. }
  1881. if (parsedParticleSystem.colorRemapGradients) {
  1882. for (var colorRemapGradient of parsedParticleSystem.colorRemapGradients) {
  1883. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  1884. }
  1885. }
  1886. if (parsedParticleSystem.alphaRemapGradients) {
  1887. for (var alphaRemapGradient of parsedParticleSystem.alphaRemapGradients) {
  1888. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  1889. }
  1890. }
  1891. if (parsedParticleSystem.sizeGradients) {
  1892. for (var sizeGradient of parsedParticleSystem.sizeGradients) {
  1893. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  1894. }
  1895. }
  1896. if (parsedParticleSystem.sizeGradients) {
  1897. for (var sizeGradient of parsedParticleSystem.sizeGradients) {
  1898. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  1899. }
  1900. }
  1901. if (parsedParticleSystem.angularSpeedGradients) {
  1902. for (var angularSpeedGradient of parsedParticleSystem.angularSpeedGradients) {
  1903. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  1904. }
  1905. }
  1906. if (parsedParticleSystem.velocityGradients) {
  1907. for (var velocityGradient of parsedParticleSystem.velocityGradients) {
  1908. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  1909. }
  1910. }
  1911. if (parsedParticleSystem.dragGradients) {
  1912. for (var dragGradient of parsedParticleSystem.dragGradients) {
  1913. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  1914. }
  1915. }
  1916. if (parsedParticleSystem.emitRateGradients) {
  1917. for (var emitRateGradient of parsedParticleSystem.emitRateGradients) {
  1918. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  1919. }
  1920. }
  1921. if (parsedParticleSystem.startSizeGradients) {
  1922. for (var startSizeGradient of parsedParticleSystem.startSizeGradients) {
  1923. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  1924. }
  1925. }
  1926. if (parsedParticleSystem.limitVelocityGradients) {
  1927. for (var limitVelocityGradient of parsedParticleSystem.limitVelocityGradients) {
  1928. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  1929. }
  1930. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  1931. }
  1932. if (parsedParticleSystem.noiseTexture) {
  1933. particleSystem.noiseTexture = ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  1934. }
  1935. // Emitter
  1936. let emitterType: IParticleEmitterType;
  1937. if (parsedParticleSystem.particleEmitterType) {
  1938. switch (parsedParticleSystem.particleEmitterType.type) {
  1939. case "SphereParticleEmitter":
  1940. emitterType = new SphereParticleEmitter();
  1941. break;
  1942. case "SphereDirectedParticleEmitter":
  1943. emitterType = new SphereDirectedParticleEmitter();
  1944. break;
  1945. case "ConeEmitter":
  1946. case "ConeParticleEmitter":
  1947. emitterType = new ConeParticleEmitter();
  1948. break;
  1949. case "BoxEmitter":
  1950. case "BoxParticleEmitter":
  1951. default:
  1952. emitterType = new BoxParticleEmitter();
  1953. break;
  1954. }
  1955. emitterType.parse(parsedParticleSystem.particleEmitterType);
  1956. } else {
  1957. emitterType = new BoxParticleEmitter();
  1958. emitterType.parse(parsedParticleSystem);
  1959. }
  1960. particleSystem.particleEmitterType = emitterType;
  1961. // Animation sheet
  1962. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  1963. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  1964. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  1965. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  1966. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  1967. }
  1968. /**
  1969. * Parses a JSON object to create a particle system.
  1970. * @param parsedParticleSystem The JSON object to parse
  1971. * @param scene The scene to create the particle system in
  1972. * @param rootUrl The root url to use to load external dependencies like texture
  1973. * @returns the Parsed particle system
  1974. */
  1975. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem {
  1976. var name = parsedParticleSystem.name;
  1977. var custom: Nullable<Effect> = null;
  1978. var program: any = null;
  1979. if (parsedParticleSystem.customShader) {
  1980. program = parsedParticleSystem.customShader;
  1981. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  1982. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  1983. }
  1984. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  1985. particleSystem.customShader = program;
  1986. if (parsedParticleSystem.id) {
  1987. particleSystem.id = parsedParticleSystem.id;
  1988. }
  1989. // Auto start
  1990. if (parsedParticleSystem.preventAutoStart) {
  1991. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  1992. }
  1993. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  1994. particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask);
  1995. if (!particleSystem.preventAutoStart) {
  1996. particleSystem.start();
  1997. }
  1998. return particleSystem;
  1999. }
  2000. }
  2001. }