babylon.particleSystem.ts 110 KB

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