babylon.particleSystem.ts 105 KB

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