babylon.particleSystem.ts 102 KB

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