gpuParticleSystem.ts 62 KB

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