babylon.particleSystem.ts 110 KB

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