gpuParticleSystem.ts 66 KB

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