babylon.gpuParticleSystem.ts 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  1. module BABYLON {
  2. /**
  3. * This represents a GPU particle system in Babylon
  4. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  5. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  6. */
  7. export class GPUParticleSystem extends BaseParticleSystem implements IDisposable, IParticleSystem, IAnimatable {
  8. /**
  9. * The layer mask we are rendering the particles through.
  10. */
  11. public layerMask: number = 0x0FFFFFFF;
  12. private _capacity: number;
  13. private _activeCount: number;
  14. private _currentActiveCount: number;
  15. private _accumulatedCount = 0;
  16. private _renderEffect: Effect;
  17. private _updateEffect: Effect;
  18. private _buffer0: Buffer;
  19. private _buffer1: Buffer;
  20. private _spriteBuffer: Buffer;
  21. private _updateVAO: Array<WebGLVertexArrayObject>;
  22. private _renderVAO: Array<WebGLVertexArrayObject>;
  23. private _targetIndex = 0;
  24. private _sourceBuffer: Buffer;
  25. private _targetBuffer: Buffer;
  26. private _engine: Engine;
  27. private _currentRenderId = -1;
  28. private _started = false;
  29. private _stopped = false;
  30. private _timeDelta = 0;
  31. private _randomTexture: RawTexture;
  32. private _randomTexture2: RawTexture;
  33. private _attributesStrideSize = 21;
  34. private _updateEffectOptions: EffectCreationOptions;
  35. private _randomTextureSize: number;
  36. private _actualFrame = 0;
  37. private readonly _rawTextureWidth = 256;
  38. /**
  39. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  40. */
  41. public static get IsSupported(): boolean {
  42. if (!Engine.LastCreatedEngine) {
  43. return false;
  44. }
  45. return Engine.LastCreatedEngine.webGLVersion > 1;
  46. }
  47. /**
  48. * An event triggered when the system is disposed.
  49. */
  50. public onDisposeObservable = new Observable<GPUParticleSystem>();
  51. /**
  52. * Gets the maximum number of particles active at the same time.
  53. * @returns The max number of active particles.
  54. */
  55. public getCapacity(): number {
  56. return this._capacity;
  57. }
  58. /**
  59. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60. * to override the particles.
  61. */
  62. public forceDepthWrite = false;
  63. /**
  64. * Gets or set the number of active particles
  65. */
  66. public get activeParticleCount(): number {
  67. return this._activeCount;
  68. }
  69. public set activeParticleCount(value: number) {
  70. this._activeCount = Math.min(value, this._capacity);
  71. }
  72. private _preWarmDone = false;
  73. /**
  74. * Is this system ready to be used/rendered
  75. * @return true if the system is ready
  76. */
  77. public isReady(): boolean {
  78. if (!this._updateEffect) {
  79. this._recreateUpdateEffect();
  80. this._recreateRenderEffect();
  81. return false;
  82. }
  83. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  84. return false;
  85. }
  86. return true;
  87. }
  88. /**
  89. * Gets if the system has been started. (Note: this will still be true after stop is called)
  90. * @returns True if it has been started, otherwise false.
  91. */
  92. public isStarted(): boolean {
  93. return this._started;
  94. }
  95. /**
  96. * Starts the particle system and begins to emit
  97. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  98. */
  99. public start(delay = 0): void {
  100. if (delay) {
  101. setTimeout(()=> {
  102. this.start(0);
  103. }, delay);
  104. return;
  105. }
  106. this._started = true;
  107. this._stopped = false;
  108. this._preWarmDone = false;
  109. }
  110. /**
  111. * Stops the particle system.
  112. */
  113. public stop(): void {
  114. this._stopped = true;
  115. }
  116. /**
  117. * Remove all active particles
  118. */
  119. public reset(): void {
  120. this._releaseBuffers();
  121. this._releaseVAOs();
  122. this._currentActiveCount = 0;
  123. this._targetIndex = 0;
  124. }
  125. /**
  126. * Returns the string "GPUParticleSystem"
  127. * @returns a string containing the class name
  128. */
  129. public getClassName(): string {
  130. return "GPUParticleSystem";
  131. }
  132. private _colorGradientsTexture: RawTexture;
  133. protected _removeGradientAndTexture(gradient: number, gradients: Nullable<IValueGradient[]>, texture: RawTexture): BaseParticleSystem {
  134. super._removeGradientAndTexture(gradient, gradients, texture);
  135. this._releaseBuffers();
  136. return this;
  137. }
  138. /**
  139. * Adds a new color gradient
  140. * @param gradient defines the gradient to use (between 0 and 1)
  141. * @param color defines the color to affect to the specified gradient
  142. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  143. * @returns the current particle system
  144. */
  145. public addColorGradient(gradient: number, color1: Color4, color2?: Color4): GPUParticleSystem {
  146. if (!this._colorGradients) {
  147. this._colorGradients = [];
  148. }
  149. let colorGradient = new ColorGradient();
  150. colorGradient.gradient = gradient;
  151. colorGradient.color1 = color1;
  152. this._colorGradients.push(colorGradient);
  153. this._colorGradients.sort((a, b) => {
  154. if (a.gradient < b.gradient) {
  155. return -1;
  156. } else if (a.gradient > b.gradient) {
  157. return 1;
  158. }
  159. return 0;
  160. });
  161. if (this._colorGradientsTexture) {
  162. this._colorGradientsTexture.dispose();
  163. (<any>this._colorGradientsTexture) = null;
  164. }
  165. this._releaseBuffers();
  166. return this;
  167. }
  168. /**
  169. * Remove a specific color gradient
  170. * @param gradient defines the gradient to remove
  171. * @returns the current particle system
  172. */
  173. public removeColorGradient(gradient: number): GPUParticleSystem {
  174. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  175. (<any>this._colorGradientsTexture) = null;
  176. return this;
  177. }
  178. private _angularSpeedGradientsTexture: RawTexture;
  179. private _sizeGradientsTexture: RawTexture;
  180. private _velocityGradientsTexture: RawTexture;
  181. private _limitVelocityGradientsTexture: RawTexture;
  182. private _dragGradientsTexture: RawTexture;
  183. private _addFactorGradient(factorGradients: FactorGradient[], gradient: number, factor: number) {
  184. let valueGradient = new FactorGradient();
  185. valueGradient.gradient = gradient;
  186. valueGradient.factor1 = factor;
  187. factorGradients.push(valueGradient);
  188. factorGradients.sort((a, b) => {
  189. if (a.gradient < b.gradient) {
  190. return -1;
  191. } else if (a.gradient > b.gradient) {
  192. return 1;
  193. }
  194. return 0;
  195. });
  196. this._releaseBuffers();
  197. }
  198. /**
  199. * Adds a new size gradient
  200. * @param gradient defines the gradient to use (between 0 and 1)
  201. * @param factor defines the size factor to affect to the specified gradient
  202. * @returns the current particle system
  203. */
  204. public addSizeGradient(gradient: number, factor: number): GPUParticleSystem {
  205. if (!this._sizeGradients) {
  206. this._sizeGradients = [];
  207. }
  208. this._addFactorGradient(this._sizeGradients, gradient, factor);
  209. if (this._sizeGradientsTexture) {
  210. this._sizeGradientsTexture.dispose();
  211. (<any>this._sizeGradientsTexture) = null;
  212. }
  213. this._releaseBuffers();
  214. return this;
  215. }
  216. /**
  217. * Remove a specific size gradient
  218. * @param gradient defines the gradient to remove
  219. * @returns the current particle system
  220. */
  221. public removeSizeGradient(gradient: number): GPUParticleSystem {
  222. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  223. (<any>this._sizeGradientsTexture) = null;
  224. return this;
  225. }
  226. /**
  227. * Adds a new angular speed gradient
  228. * @param gradient defines the gradient to use (between 0 and 1)
  229. * @param factor defines the angular speed to affect to the specified gradient
  230. * @returns the current particle system
  231. */
  232. public addAngularSpeedGradient(gradient: number, factor: number): GPUParticleSystem {
  233. if (!this._angularSpeedGradients) {
  234. this._angularSpeedGradients = [];
  235. }
  236. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  237. if (this._angularSpeedGradientsTexture) {
  238. this._angularSpeedGradientsTexture.dispose();
  239. (<any>this._angularSpeedGradientsTexture) = null;
  240. }
  241. this._releaseBuffers();
  242. return this;
  243. }
  244. /**
  245. * Remove a specific angular speed gradient
  246. * @param gradient defines the gradient to remove
  247. * @returns the current particle system
  248. */
  249. public removeAngularSpeedGradient(gradient: number): GPUParticleSystem {
  250. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  251. (<any>this._angularSpeedGradientsTexture) = null;
  252. return this;
  253. }
  254. /**
  255. * Adds a new velocity gradient
  256. * @param gradient defines the gradient to use (between 0 and 1)
  257. * @param factor defines the velocity to affect to the specified gradient
  258. * @returns the current particle system
  259. */
  260. public addVelocityGradient(gradient: number, factor: number): GPUParticleSystem {
  261. if (!this._velocityGradients) {
  262. this._velocityGradients = [];
  263. }
  264. this._addFactorGradient(this._velocityGradients, gradient, factor);
  265. if (this._velocityGradientsTexture) {
  266. this._velocityGradientsTexture.dispose();
  267. (<any>this._velocityGradientsTexture) = null;
  268. }
  269. this._releaseBuffers();
  270. return this;
  271. }
  272. /**
  273. * Remove a specific velocity gradient
  274. * @param gradient defines the gradient to remove
  275. * @returns the current particle system
  276. */
  277. public removeVelocityGradient(gradient: number): GPUParticleSystem {
  278. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  279. (<any>this._velocityGradientsTexture) = null;
  280. return this;
  281. }
  282. /**
  283. * Adds a new limit velocity gradient
  284. * @param gradient defines the gradient to use (between 0 and 1)
  285. * @param factor defines the limit velocity value to affect to the specified gradient
  286. * @returns the current particle system
  287. */
  288. public addLimitVelocityGradient(gradient: number, factor: number): GPUParticleSystem {
  289. if (!this._limitVelocityGradients) {
  290. this._limitVelocityGradients = [];
  291. }
  292. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  293. if (this._limitVelocityGradientsTexture) {
  294. this._limitVelocityGradientsTexture.dispose();
  295. (<any>this._limitVelocityGradientsTexture) = null;
  296. }
  297. this._releaseBuffers();
  298. return this;
  299. }
  300. /**
  301. * Remove a specific limit velocity gradient
  302. * @param gradient defines the gradient to remove
  303. * @returns the current particle system
  304. */
  305. public removeLimitVelocityGradient(gradient: number): GPUParticleSystem {
  306. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  307. (<any>this._limitVelocityGradientsTexture) = null;
  308. return this;
  309. }
  310. /**
  311. * Adds a new drag gradient
  312. * @param gradient defines the gradient to use (between 0 and 1)
  313. * @param factor defines the drag value to affect to the specified gradient
  314. * @returns the current particle system
  315. */
  316. public addDragGradient(gradient: number, factor: number): GPUParticleSystem {
  317. if (!this._dragGradients) {
  318. this._dragGradients = [];
  319. }
  320. this._addFactorGradient(this._dragGradients, gradient, factor);
  321. if (this._dragGradientsTexture) {
  322. this._dragGradientsTexture.dispose();
  323. (<any>this._dragGradientsTexture) = null;
  324. }
  325. this._releaseBuffers();
  326. return this;
  327. }
  328. /**
  329. * Remove a specific drag gradient
  330. * @param gradient defines the gradient to remove
  331. * @returns the current particle system
  332. */
  333. public removeDragGradient(gradient: number): GPUParticleSystem {
  334. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  335. (<any>this._dragGradientsTexture) = null;
  336. return this;
  337. }
  338. /**
  339. * Not supported by GPUParticleSystem
  340. * @param gradient defines the gradient to use (between 0 and 1)
  341. * @param factor defines the emit rate value to affect to the specified gradient
  342. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  343. * @returns the current particle system
  344. */
  345. public addEmitRateGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  346. // Do nothing as emit rate is not supported by GPUParticleSystem
  347. return this;
  348. }
  349. /**
  350. * Not supported by GPUParticleSystem
  351. * @param gradient defines the gradient to remove
  352. * @returns the current particle system
  353. */
  354. public removeEmitRateGradient(gradient: number): IParticleSystem {
  355. // Do nothing as emit rate is not supported by GPUParticleSystem
  356. return this;
  357. }
  358. /**
  359. * Not supported by GPUParticleSystem
  360. * @param gradient defines the gradient to use (between 0 and 1)
  361. * @param factor defines the start size value to affect to the specified gradient
  362. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  363. * @returns the current particle system
  364. */
  365. public addStartSizeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  366. // Do nothing as start size is not supported by GPUParticleSystem
  367. return this;
  368. }
  369. /**
  370. * Not supported by GPUParticleSystem
  371. * @param gradient defines the gradient to remove
  372. * @returns the current particle system
  373. */
  374. public removeStartSizeGradient(gradient: number): IParticleSystem {
  375. // Do nothing as start size is not supported by GPUParticleSystem
  376. return this;
  377. }
  378. /**
  379. * Not supported by GPUParticleSystem
  380. * @param gradient defines the gradient to use (between 0 and 1)
  381. * @param min defines the color remap minimal range
  382. * @param max defines the color remap maximal range
  383. * @returns the current particle system
  384. */
  385. public addColorRemapGradient(gradient: number, min: number, max: number): IParticleSystem {
  386. // Do nothing as start size is not supported by GPUParticleSystem
  387. return this;
  388. }
  389. /**
  390. * Not supported by GPUParticleSystem
  391. * @param gradient defines the gradient to remove
  392. * @returns the current particle system
  393. */
  394. public removeColorRemapGradient(gradient: number): IParticleSystem {
  395. // Do nothing as start size is not supported by GPUParticleSystem
  396. return this;
  397. }
  398. /**
  399. * Not supported by GPUParticleSystem
  400. * @param gradient defines the gradient to use (between 0 and 1)
  401. * @param min defines the alpha remap minimal range
  402. * @param max defines the alpha remap maximal range
  403. * @returns the current particle system
  404. */
  405. public addAlphaRemapGradient(gradient: number, min: number, max: number): IParticleSystem {
  406. // Do nothing as start size is not supported by GPUParticleSystem
  407. return this;
  408. }
  409. /**
  410. * Not supported by GPUParticleSystem
  411. * @param gradient defines the gradient to remove
  412. * @returns the current particle system
  413. */
  414. public removeAlphaRemapGradient(gradient: number): IParticleSystem {
  415. // Do nothing as start size is not supported by GPUParticleSystem
  416. return this;
  417. }
  418. /**
  419. * Not supported by GPUParticleSystem
  420. * @param gradient defines the gradient to use (between 0 and 1)
  421. * @param color defines the color to affect to the specified gradient
  422. * @returns the current particle system
  423. */
  424. public addRampGradient(gradient: number, color: Color4): IParticleSystem {
  425. //Not supported by GPUParticleSystem
  426. return this;
  427. }
  428. /**
  429. * Not supported by GPUParticleSystem
  430. * @param gradient defines the gradient to remove
  431. * @returns the current particle system
  432. */
  433. public removeRampGradient(gradient: number): IParticleSystem {
  434. //Not supported by GPUParticleSystem
  435. return this;
  436. }
  437. /**
  438. * Not supported by GPUParticleSystem
  439. * @returns the list of ramp gradients
  440. */
  441. public getRampGradients(): Nullable<Array<ColorGradient>> {
  442. return null;
  443. }
  444. /**
  445. * Instantiates a GPU particle system.
  446. * 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.
  447. * @param name The name of the particle system
  448. * @param options The options used to create the system
  449. * @param scene The scene the particle system belongs to
  450. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  451. */
  452. constructor(name: string, options: Partial<{
  453. capacity: number,
  454. randomTextureSize: number
  455. }>, scene: Scene, isAnimationSheetEnabled: boolean = false) {
  456. super(name);
  457. this._scene = scene || Engine.LastCreatedScene;
  458. // Setup the default processing configuration to the scene.
  459. this._attachImageProcessingConfiguration(null);
  460. this._engine = this._scene.getEngine();
  461. if (!options.randomTextureSize) {
  462. delete options.randomTextureSize;
  463. }
  464. let fullOptions = {
  465. capacity: 50000,
  466. randomTextureSize: this._engine.getCaps().maxTextureSize,
  467. ...options
  468. };
  469. var optionsAsNumber = <number>options;
  470. if (isFinite(optionsAsNumber)) {
  471. fullOptions.capacity = optionsAsNumber;
  472. }
  473. this._capacity = fullOptions.capacity;
  474. this._activeCount = fullOptions.capacity;
  475. this._currentActiveCount = 0;
  476. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  477. this._scene.particleSystems.push(this);
  478. this._updateEffectOptions = {
  479. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset"],
  480. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange","gravity", "emitPower",
  481. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  482. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  483. uniformBuffersNames: [],
  484. samplers:["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  485. defines: "",
  486. fallbacks: null,
  487. onCompiled: null,
  488. onError: null,
  489. indexParameters: null,
  490. maxSimultaneousLights: 0,
  491. transformFeedbackVaryings: []
  492. };
  493. this.particleEmitterType = new BoxParticleEmitter();
  494. // Random data
  495. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  496. var d = [];
  497. for (var i = 0; i < maxTextureSize; ++i) {
  498. d.push(Math.random());
  499. d.push(Math.random());
  500. d.push(Math.random());
  501. d.push(Math.random());
  502. }
  503. this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);
  504. this._randomTexture.wrapU = Texture.WRAP_ADDRESSMODE;
  505. this._randomTexture.wrapV = Texture.WRAP_ADDRESSMODE;
  506. d = [];
  507. for (var i = 0; i < maxTextureSize; ++i) {
  508. d.push(Math.random());
  509. d.push(Math.random());
  510. d.push(Math.random());
  511. d.push(Math.random());
  512. }
  513. this._randomTexture2 = new RawTexture(new Float32Array(d), maxTextureSize, 1, Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);
  514. this._randomTexture2.wrapU = Texture.WRAP_ADDRESSMODE;
  515. this._randomTexture2.wrapV = Texture.WRAP_ADDRESSMODE;
  516. this._randomTextureSize = maxTextureSize;
  517. }
  518. protected _reset() {
  519. this._releaseBuffers();
  520. }
  521. private _createUpdateVAO(source: Buffer): WebGLVertexArrayObject {
  522. let updateVertexBuffers: {[key: string]: VertexBuffer} = {};
  523. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  524. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  525. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  526. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  527. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  528. let offset = 12;
  529. if (!this._colorGradientsTexture) {
  530. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  531. offset += 4;
  532. }
  533. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  534. offset += 3
  535. if (!this._isBillboardBased) {
  536. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  537. offset += 3;
  538. }
  539. if (this._angularSpeedGradientsTexture) {
  540. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  541. offset += 1;
  542. } else {
  543. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  544. offset += 2;
  545. }
  546. if (this._isAnimationSheetEnabled) {
  547. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  548. offset += 1;
  549. if (this.spriteRandomStartCell) {
  550. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  551. offset += 1;
  552. }
  553. }
  554. let vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  555. this._engine.bindArrayBuffer(null);
  556. return vao;
  557. }
  558. private _createRenderVAO(source: Buffer, spriteSource: Buffer): WebGLVertexArrayObject {
  559. let renderVertexBuffers: {[key: string]: VertexBuffer} = {};
  560. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  561. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  562. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  563. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  564. let offset = 12;
  565. if (!this._colorGradientsTexture) {
  566. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  567. offset += 4;
  568. }
  569. offset += 3; // Direction
  570. if (!this._isBillboardBased) {
  571. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  572. offset += 3;
  573. }
  574. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  575. if (this._angularSpeedGradientsTexture) {
  576. offset++;
  577. } else {
  578. offset += 2;
  579. }
  580. if (this._isAnimationSheetEnabled) {
  581. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  582. offset += 1;
  583. if (this.spriteRandomStartCell) {
  584. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  585. offset += 1;
  586. }
  587. }
  588. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  589. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  590. let vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  591. this._engine.bindArrayBuffer(null);
  592. return vao;
  593. }
  594. private _initialize(force = false): void {
  595. if (this._buffer0 && !force) {
  596. return;
  597. }
  598. let engine = this._scene.getEngine();
  599. var data = new Array<float>();
  600. if (!this.isBillboardBased) {
  601. this._attributesStrideSize += 3;
  602. }
  603. if (this._colorGradientsTexture) {
  604. this._attributesStrideSize -= 4;
  605. }
  606. if (this._angularSpeedGradientsTexture) {
  607. this._attributesStrideSize -= 1;
  608. }
  609. if (this._isAnimationSheetEnabled) {
  610. this._attributesStrideSize += 1;
  611. if (this.spriteRandomStartCell) {
  612. this._attributesStrideSize += 1;
  613. }
  614. }
  615. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  616. // position
  617. data.push(0.0);
  618. data.push(0.0);
  619. data.push(0.0);
  620. // Age and life
  621. data.push(0.0); // create the particle as a dead one to create a new one at start
  622. data.push(0.0);
  623. // Seed
  624. data.push(Math.random());
  625. data.push(Math.random());
  626. data.push(Math.random());
  627. data.push(Math.random());
  628. // Size
  629. data.push(0.0);
  630. data.push(0.0);
  631. data.push(0.0);
  632. if (!this._colorGradientsTexture) {
  633. // color
  634. data.push(0.0);
  635. data.push(0.0);
  636. data.push(0.0);
  637. data.push(0.0);
  638. }
  639. // direction
  640. data.push(0.0);
  641. data.push(0.0);
  642. data.push(0.0);
  643. if (!this.isBillboardBased) {
  644. // initialDirection
  645. data.push(0.0);
  646. data.push(0.0);
  647. data.push(0.0);
  648. }
  649. // angle
  650. data.push(0.0);
  651. if (!this._angularSpeedGradientsTexture) {
  652. data.push(0.0);
  653. }
  654. if (this._isAnimationSheetEnabled) {
  655. data.push(0.0);
  656. if (this.spriteRandomStartCell) {
  657. data.push(0.0);
  658. }
  659. }
  660. }
  661. // Sprite data
  662. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  663. -0.5, 0.5, 0, 1,
  664. -0.5, -0.5, 0, 0,
  665. 0.5, -0.5, 1, 0]);
  666. // Buffers
  667. this._buffer0 = new Buffer(engine, data, false, this._attributesStrideSize);
  668. this._buffer1 = new Buffer(engine, data, false, this._attributesStrideSize);
  669. this._spriteBuffer = new Buffer(engine, spriteData, false, 4);
  670. // Update VAO
  671. this._updateVAO = [];
  672. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  673. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  674. // Render VAO
  675. this._renderVAO = [];
  676. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  677. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  678. // Links
  679. this._sourceBuffer = this._buffer0;
  680. this._targetBuffer = this._buffer1;
  681. }
  682. /** @hidden */
  683. public _recreateUpdateEffect() {
  684. let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  685. if (this._isBillboardBased) {
  686. defines += "\n#define BILLBOARD";
  687. }
  688. if (this._colorGradientsTexture) {
  689. defines += "\n#define COLORGRADIENTS";
  690. }
  691. if (this._sizeGradientsTexture) {
  692. defines += "\n#define SIZEGRADIENTS";
  693. }
  694. if (this._angularSpeedGradientsTexture) {
  695. defines += "\n#define ANGULARSPEEDGRADIENTS";
  696. }
  697. if (this._velocityGradientsTexture) {
  698. defines += "\n#define VELOCITYGRADIENTS";
  699. }
  700. if (this._limitVelocityGradientsTexture) {
  701. defines += "\n#define LIMITVELOCITYGRADIENTS";
  702. }
  703. if (this._dragGradientsTexture) {
  704. defines += "\n#define DRAGGRADIENTS";
  705. }
  706. if (this.isAnimationSheetEnabled) {
  707. defines += "\n#define ANIMATESHEET";
  708. if (this.spriteRandomStartCell) {
  709. defines += "\n#define ANIMATESHEETRANDOMSTART";
  710. }
  711. }
  712. if (this.noiseTexture) {
  713. defines += "\n#define NOISE";
  714. }
  715. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  716. return;
  717. }
  718. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  719. if (!this._colorGradientsTexture) {
  720. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  721. }
  722. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  723. if (!this._isBillboardBased) {
  724. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  725. }
  726. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  727. if (this.isAnimationSheetEnabled) {
  728. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  729. if (this.spriteRandomStartCell) {
  730. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  731. }
  732. }
  733. this._updateEffectOptions.defines = defines;
  734. this._updateEffect = new Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  735. }
  736. /** @hidden */
  737. public _recreateRenderEffect() {
  738. let defines = "";
  739. if (this._scene.clipPlane) {
  740. defines = "\n#define CLIPPLANE";
  741. }
  742. if (this._scene.clipPlane2) {
  743. defines = "\n#define CLIPPLANE2";
  744. }
  745. if (this._scene.clipPlane3) {
  746. defines = "\n#define CLIPPLANE3";
  747. }
  748. if (this._scene.clipPlane4) {
  749. defines = "\n#define CLIPPLANE4";
  750. }
  751. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  752. defines = "\n#define BLENDMULTIPLYMODE";
  753. }
  754. if (this._isBillboardBased) {
  755. defines += "\n#define BILLBOARD";
  756. switch (this.billboardMode) {
  757. case AbstractMesh.BILLBOARDMODE_Y:
  758. defines += "\n#define BILLBOARDY";
  759. break;
  760. case AbstractMesh.BILLBOARDMODE_ALL:
  761. default:
  762. break;
  763. }
  764. }
  765. if (this._colorGradientsTexture) {
  766. defines += "\n#define COLORGRADIENTS";
  767. }
  768. if (this.isAnimationSheetEnabled) {
  769. defines += "\n#define ANIMATESHEET";
  770. }
  771. if (this._imageProcessingConfiguration) {
  772. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  773. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  774. }
  775. if (this._renderEffect && this._renderEffect.defines === defines) {
  776. return;
  777. }
  778. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  779. var samplers = ["textureSampler", "colorGradientSampler"];
  780. if (ImageProcessingConfiguration) {
  781. ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  782. ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  783. }
  784. this._renderEffect = new Effect("gpuRenderParticles",
  785. ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"],
  786. uniforms,
  787. samplers, this._scene.getEngine(), defines);
  788. }
  789. /**
  790. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  791. * @param preWarm defines if we are in the pre-warmimg phase
  792. */
  793. public animate(preWarm = false): void {
  794. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  795. this._actualFrame += this._timeDelta;
  796. if (!this._stopped) {
  797. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  798. this.stop();
  799. }
  800. }
  801. }
  802. private _createFactorGradientTexture(factorGradients: Nullable<IValueGradient[]>, textureName: string) {
  803. let texture:RawTexture = (<any>this)[textureName];
  804. if (!factorGradients || !factorGradients.length || texture) {
  805. return;
  806. }
  807. let data = new Float32Array(this._rawTextureWidth);
  808. for (var x = 0; x < this._rawTextureWidth; x++) {
  809. var ratio = x / this._rawTextureWidth;
  810. Tools.GetCurrentGradient(ratio, factorGradients, (currentGradient, nextGradient, scale) => {
  811. data[x] = Scalar.Lerp((<FactorGradient>currentGradient).factor1, (<FactorGradient>nextGradient).factor1, scale);
  812. });
  813. }
  814. (<any>this)[textureName] = RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE);
  815. }
  816. private _createSizeGradientTexture() {
  817. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  818. }
  819. private _createAngularSpeedGradientTexture() {
  820. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  821. }
  822. private _createVelocityGradientTexture() {
  823. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  824. }
  825. private _createLimitVelocityGradientTexture() {
  826. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  827. }
  828. private _createDragGradientTexture() {
  829. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  830. }
  831. private _createColorGradientTexture() {
  832. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  833. return;
  834. }
  835. let data = new Uint8Array(this._rawTextureWidth * 4);
  836. let tmpColor = Tmp.Color4[0];
  837. for (var x = 0; x < this._rawTextureWidth; x++) {
  838. var ratio = x / this._rawTextureWidth;
  839. Tools.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
  840. Color4.LerpToRef((<ColorGradient>currentGradient).color1, (<ColorGradient>nextGradient).color1, scale, tmpColor);
  841. data[x * 4] = tmpColor.r * 255;
  842. data[x * 4 + 1] = tmpColor.g * 255;
  843. data[x * 4 + 2] = tmpColor.b * 255;
  844. data[x * 4 + 3] = tmpColor.a * 255;
  845. });
  846. }
  847. this._colorGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE);
  848. }
  849. /**
  850. * Renders the particle system in its current state
  851. * @param preWarm defines if the system should only update the particles but not render them
  852. * @returns the current number of particles
  853. */
  854. public render(preWarm = false): number {
  855. if (!this._started) {
  856. return 0;
  857. }
  858. this._createColorGradientTexture();
  859. this._createSizeGradientTexture();
  860. this._createAngularSpeedGradientTexture();
  861. this._createVelocityGradientTexture();
  862. this._createLimitVelocityGradientTexture();
  863. this._createDragGradientTexture();
  864. this._recreateUpdateEffect();
  865. this._recreateRenderEffect();
  866. if (!this.isReady()) {
  867. return 0;
  868. }
  869. if (!preWarm) {
  870. if (!this._preWarmDone && this.preWarmCycles) {
  871. for (var index = 0; index < this.preWarmCycles; index++) {
  872. this.animate(true);
  873. this.render(true);
  874. }
  875. this._preWarmDone = true;
  876. }
  877. if (this._currentRenderId === this._scene.getRenderId()) {
  878. return 0;
  879. }
  880. this._currentRenderId = this._scene.getRenderId();
  881. }
  882. // Get everything ready to render
  883. this._initialize();
  884. this._accumulatedCount += this.emitRate * this._timeDelta;
  885. if (this._accumulatedCount > 1) {
  886. var intPart = this._accumulatedCount | 0;
  887. this._accumulatedCount -= intPart;
  888. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  889. }
  890. if (!this._currentActiveCount) {
  891. return 0;
  892. }
  893. // Enable update effect
  894. this._engine.enableEffect(this._updateEffect);
  895. this._engine.setState(false);
  896. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  897. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  898. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  899. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  900. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  901. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  902. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  903. if (!this._colorGradientsTexture) {
  904. this._updateEffect.setDirectColor4("color1", this.color1);
  905. this._updateEffect.setDirectColor4("color2", this.color2);
  906. }
  907. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  908. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  909. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  910. this._updateEffect.setVector3("gravity", this.gravity);
  911. if (this._sizeGradientsTexture) {
  912. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  913. }
  914. if (this._angularSpeedGradientsTexture) {
  915. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  916. }
  917. if (this._velocityGradientsTexture) {
  918. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  919. }
  920. if (this._limitVelocityGradientsTexture) {
  921. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  922. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  923. }
  924. if (this._dragGradientsTexture) {
  925. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  926. }
  927. if (this.particleEmitterType) {
  928. this.particleEmitterType.applyToShader(this._updateEffect);
  929. }
  930. if (this._isAnimationSheetEnabled) {
  931. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  932. }
  933. if (this.noiseTexture) {
  934. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  935. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  936. }
  937. let emitterWM: Matrix;
  938. if ((<AbstractMesh>this.emitter).position) {
  939. var emitterMesh = (<AbstractMesh>this.emitter);
  940. emitterWM = emitterMesh.getWorldMatrix();
  941. } else {
  942. var emitterPosition = (<Vector3>this.emitter);
  943. emitterWM = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  944. }
  945. this._updateEffect.setMatrix("emitterWM", emitterWM);
  946. // Bind source VAO
  947. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  948. // Update
  949. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  950. this._engine.setRasterizerState(false);
  951. this._engine.beginTransformFeedback(true);
  952. this._engine.drawArraysType(Material.PointListDrawMode, 0, this._currentActiveCount);
  953. this._engine.endTransformFeedback();
  954. this._engine.setRasterizerState(true);
  955. this._engine.bindTransformFeedbackBuffer(null);
  956. if (!preWarm) {
  957. // Enable render effect
  958. this._engine.enableEffect(this._renderEffect);
  959. let viewMatrix = this._scene.getViewMatrix();
  960. this._renderEffect.setMatrix("view", viewMatrix);
  961. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  962. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  963. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  964. if (this._colorGradientsTexture) {
  965. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  966. } else {
  967. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  968. }
  969. if (this._isAnimationSheetEnabled && this.particleTexture) {
  970. let baseSize = this.particleTexture.getBaseSize();
  971. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  972. }
  973. if (this._isBillboardBased) {
  974. var camera = this._scene.activeCamera!;
  975. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  976. }
  977. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  978. var invView = viewMatrix.clone();
  979. invView.invert();
  980. this._renderEffect.setMatrix("invView", invView);
  981. MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  982. }
  983. // image processing
  984. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  985. this._imageProcessingConfiguration.bind(this._renderEffect);
  986. }
  987. // Draw order
  988. switch(this.blendMode)
  989. {
  990. case ParticleSystem.BLENDMODE_ADD:
  991. this._engine.setAlphaMode(Engine.ALPHA_ADD);
  992. break;
  993. case ParticleSystem.BLENDMODE_ONEONE:
  994. this._engine.setAlphaMode(Engine.ALPHA_ONEONE);
  995. break;
  996. case ParticleSystem.BLENDMODE_STANDARD:
  997. this._engine.setAlphaMode(Engine.ALPHA_COMBINE);
  998. break;
  999. case ParticleSystem.BLENDMODE_MULTIPLY:
  1000. this._engine.setAlphaMode(Engine.ALPHA_MULTIPLY);
  1001. break;
  1002. }
  1003. if (this.forceDepthWrite) {
  1004. this._engine.setDepthWrite(true);
  1005. }
  1006. // Bind source VAO
  1007. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  1008. // Render
  1009. this._engine.drawArraysType(Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  1010. this._engine.setAlphaMode(Engine.ALPHA_DISABLE);
  1011. }
  1012. // Switch VAOs
  1013. this._targetIndex++;
  1014. if (this._targetIndex === 2) {
  1015. this._targetIndex = 0;
  1016. }
  1017. // Switch buffers
  1018. let tmpBuffer = this._sourceBuffer;
  1019. this._sourceBuffer = this._targetBuffer;
  1020. this._targetBuffer = tmpBuffer;
  1021. return this._currentActiveCount;
  1022. }
  1023. /**
  1024. * Rebuilds the particle system
  1025. */
  1026. public rebuild(): void {
  1027. this._initialize(true);
  1028. }
  1029. private _releaseBuffers() {
  1030. if (this._buffer0) {
  1031. this._buffer0.dispose();
  1032. (<any>this._buffer0) = null;
  1033. }
  1034. if (this._buffer1) {
  1035. this._buffer1.dispose();
  1036. (<any>this._buffer1) = null;
  1037. }
  1038. if (this._spriteBuffer) {
  1039. this._spriteBuffer.dispose();
  1040. (<any>this._spriteBuffer) = null;
  1041. }
  1042. }
  1043. private _releaseVAOs() {
  1044. if (!this._updateVAO) {
  1045. return;
  1046. }
  1047. for (var index = 0; index < this._updateVAO.length; index++) {
  1048. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  1049. }
  1050. this._updateVAO = [];
  1051. for (var index = 0; index < this._renderVAO.length; index++) {
  1052. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  1053. }
  1054. this._renderVAO = [];
  1055. }
  1056. /**
  1057. * Disposes the particle system and free the associated resources
  1058. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  1059. */
  1060. public dispose(disposeTexture = true): void {
  1061. var index = this._scene.particleSystems.indexOf(this);
  1062. if (index > -1) {
  1063. this._scene.particleSystems.splice(index, 1);
  1064. }
  1065. this._releaseBuffers();
  1066. this._releaseVAOs();
  1067. if (this._colorGradientsTexture) {
  1068. this._colorGradientsTexture.dispose();
  1069. (<any>this._colorGradientsTexture) = null;
  1070. }
  1071. if (this._sizeGradientsTexture) {
  1072. this._sizeGradientsTexture.dispose();
  1073. (<any>this._sizeGradientsTexture) = null;
  1074. }
  1075. if (this._angularSpeedGradientsTexture) {
  1076. this._angularSpeedGradientsTexture.dispose();
  1077. (<any>this._angularSpeedGradientsTexture) = null;
  1078. }
  1079. if (this._velocityGradientsTexture) {
  1080. this._velocityGradientsTexture.dispose();
  1081. (<any>this._velocityGradientsTexture) = null;
  1082. }
  1083. if (this._limitVelocityGradientsTexture) {
  1084. this._limitVelocityGradientsTexture.dispose();
  1085. (<any>this._limitVelocityGradientsTexture) = null;
  1086. }
  1087. if (this._dragGradientsTexture) {
  1088. this._dragGradientsTexture.dispose();
  1089. (<any>this._dragGradientsTexture) = null;
  1090. }
  1091. if (this._randomTexture) {
  1092. this._randomTexture.dispose();
  1093. (<any>this._randomTexture) = null;
  1094. }
  1095. if (this._randomTexture2) {
  1096. this._randomTexture2.dispose();
  1097. (<any>this._randomTexture2) = null;
  1098. }
  1099. if (disposeTexture && this.particleTexture) {
  1100. this.particleTexture.dispose();
  1101. this.particleTexture = null;
  1102. }
  1103. if (disposeTexture && this.noiseTexture) {
  1104. this.noiseTexture.dispose();
  1105. this.noiseTexture = null;
  1106. }
  1107. // Callback
  1108. this.onDisposeObservable.notifyObservers(this);
  1109. this.onDisposeObservable.clear();
  1110. }
  1111. /**
  1112. * Clones the particle system.
  1113. * @param name The name of the cloned object
  1114. * @param newEmitter The new emitter to use
  1115. * @returns the cloned particle system
  1116. */
  1117. public clone(name: string, newEmitter: any): GPUParticleSystem {
  1118. var result = new GPUParticleSystem(name, {capacity: this._capacity, randomTextureSize: this._randomTextureSize}, this._scene);
  1119. Tools.DeepCopy(this, result);
  1120. if (newEmitter === undefined) {
  1121. newEmitter = this.emitter;
  1122. }
  1123. result.emitter = newEmitter;
  1124. if (this.particleTexture) {
  1125. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  1126. }
  1127. return result;
  1128. }
  1129. /**
  1130. * Serializes the particle system to a JSON object.
  1131. * @returns the JSON object
  1132. */
  1133. public serialize(): any {
  1134. var serializationObject: any = {};
  1135. ParticleSystem._Serialize(serializationObject, this);
  1136. serializationObject.activeParticleCount = this.activeParticleCount;
  1137. return serializationObject;
  1138. }
  1139. /**
  1140. * Parses a JSON object to create a GPU particle system.
  1141. * @param parsedParticleSystem The JSON object to parse
  1142. * @param scene The scene to create the particle system in
  1143. * @param rootUrl The root url to use to load external dependencies like texture
  1144. * @returns the parsed GPU particle system
  1145. */
  1146. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): GPUParticleSystem {
  1147. var name = parsedParticleSystem.name;
  1148. var particleSystem = new GPUParticleSystem(name, {capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize}, scene);
  1149. if (parsedParticleSystem.activeParticleCount) {
  1150. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  1151. }
  1152. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  1153. return particleSystem;
  1154. }
  1155. }
  1156. }