particleSystem.ts 112 KB

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