babylon.gpuParticleSystem.ts 61 KB

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