gpuParticleSystem.ts 60 KB

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