particleSystem.ts 107 KB

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