babylon.gpuParticleSystem.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. module BABYLON {
  2. /**
  3. * This represents a GPU particle system in Babylon
  4. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  5. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  6. */
  7. export class GPUParticleSystem implements IDisposable, IParticleSystem, IAnimatable {
  8. /**
  9. * The id of the Particle system.
  10. */
  11. public id: string;
  12. /**
  13. * The friendly name of the Particle system.
  14. */
  15. public name: string;
  16. /**
  17. * The emitter represents the Mesh or position we are attaching the particle system to.
  18. */
  19. public emitter: Nullable<AbstractMesh | Vector3> = null;
  20. /**
  21. * The rendering group used by the Particle system to chose when to render.
  22. */
  23. public renderingGroupId = 0;
  24. /**
  25. * The layer mask we are rendering the particles through.
  26. */
  27. public layerMask: number = 0x0FFFFFFF;
  28. private _capacity: number;
  29. private _activeCount: number;
  30. private _currentActiveCount: number;
  31. private _renderEffect: Effect;
  32. private _updateEffect: Effect;
  33. private _buffer0: Buffer;
  34. private _buffer1: Buffer;
  35. private _spriteBuffer: Buffer;
  36. private _updateVAO: Array<WebGLVertexArrayObject>;
  37. private _renderVAO: Array<WebGLVertexArrayObject>;
  38. private _targetIndex = 0;
  39. private _sourceBuffer: Buffer;
  40. private _targetBuffer: Buffer;
  41. private _scene: Scene;
  42. private _engine: Engine;
  43. private _currentRenderId = -1;
  44. private _started = false;
  45. private _stopped = false;
  46. private _timeDelta = 0;
  47. private _randomTexture: RawTexture;
  48. private readonly _attributesStrideSize = 14;
  49. private _updateEffectOptions: EffectCreationOptions;
  50. private _randomTextureSize: number;
  51. private _actualFrame = 0;
  52. /**
  53. * List of animations used by the particle system.
  54. */
  55. public animations: Animation[] = [];
  56. /**
  57. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  58. */
  59. public static get IsSupported(): boolean {
  60. if (!Engine.LastCreatedEngine) {
  61. return false;
  62. }
  63. return Engine.LastCreatedEngine.webGLVersion > 1;
  64. }
  65. /**
  66. * An event triggered when the system is disposed.
  67. */
  68. public onDisposeObservable = new Observable<GPUParticleSystem>();
  69. /**
  70. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  71. */
  72. public updateSpeed = 0.01;
  73. /**
  74. * The amount of time the particle system is running (depends of the overall update speed).
  75. */
  76. public targetStopDuration = 0;
  77. /**
  78. * The texture used to render each particle. (this can be a spritesheet)
  79. */
  80. public particleTexture: Nullable<Texture>;
  81. /**
  82. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  83. */
  84. public blendMode = ParticleSystem.BLENDMODE_ONEONE;
  85. /**
  86. * Minimum life time of emitting particles.
  87. */
  88. public minLifeTime = 1;
  89. /**
  90. * Maximum life time of emitting particles.
  91. */
  92. public maxLifeTime = 1;
  93. /**
  94. * Minimum Size of emitting particles.
  95. */
  96. public minSize = 1;
  97. /**
  98. * Maximum Size of emitting particles.
  99. */
  100. public maxSize = 1;
  101. /**
  102. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  103. */
  104. public color1 = new Color4(1.0, 1.0, 1.0, 1.0);
  105. /**
  106. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  107. */
  108. public color2 = new Color4(1.0, 1.0, 1.0, 1.0);
  109. /**
  110. * Color the particle will have at the end of its lifetime.
  111. */
  112. public colorDead = new Color4(0, 0, 0, 0);
  113. /**
  114. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  115. */
  116. public emitRate = 100;
  117. /**
  118. * You can use gravity if you want to give an orientation to your particles.
  119. */
  120. public gravity = Vector3.Zero();
  121. /**
  122. * Minimum power of emitting particles.
  123. */
  124. public minEmitPower = 1;
  125. /**
  126. * Maximum power of emitting particles.
  127. */
  128. public maxEmitPower = 1;
  129. /**
  130. * The particle emitter type defines the emitter used by the particle system.
  131. * It can be for example box, sphere, or cone...
  132. */
  133. public particleEmitterType: Nullable<IParticleEmitterType>;
  134. /**
  135. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  136. * This only works when particleEmitterTyps is a BoxParticleEmitter
  137. */
  138. public get direction1(): Vector3 {
  139. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  140. return (<BoxParticleEmitter>this.particleEmitterType).direction1;
  141. }
  142. return Vector3.Zero();
  143. }
  144. public set direction1(value: Vector3) {
  145. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  146. (<BoxParticleEmitter>this.particleEmitterType).direction1 = value;
  147. }
  148. }
  149. /**
  150. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  151. * This only works when particleEmitterTyps is a BoxParticleEmitter
  152. */
  153. public get direction2(): Vector3 {
  154. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  155. return (<BoxParticleEmitter>this.particleEmitterType).direction2;
  156. }
  157. return Vector3.Zero();
  158. }
  159. public set direction2(value: Vector3) {
  160. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  161. (<BoxParticleEmitter>this.particleEmitterType).direction2 = value;
  162. }
  163. }
  164. /**
  165. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  166. * This only works when particleEmitterTyps is a BoxParticleEmitter
  167. */
  168. public get minEmitBox(): Vector3 {
  169. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  170. return (<BoxParticleEmitter>this.particleEmitterType).minEmitBox;
  171. }
  172. return Vector3.Zero();
  173. }
  174. public set minEmitBox(value: Vector3) {
  175. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  176. (<BoxParticleEmitter>this.particleEmitterType).minEmitBox = value;
  177. }
  178. }
  179. /**
  180. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  181. * This only works when particleEmitterTyps is a BoxParticleEmitter
  182. */
  183. public get maxEmitBox(): Vector3 {
  184. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  185. return (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox;
  186. }
  187. return Vector3.Zero();
  188. }
  189. public set maxEmitBox(value: Vector3) {
  190. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  191. (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox = value;
  192. }
  193. }
  194. /**
  195. * Gets the maximum number of particles active at the same time.
  196. * @returns The max number of active particles.
  197. */
  198. public getCapacity(): number {
  199. return this._capacity;
  200. }
  201. /**
  202. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  203. * to override the particles.
  204. */
  205. public forceDepthWrite = false;
  206. /**
  207. * Gets or set the number of active particles
  208. */
  209. public get activeParticleCount(): number {
  210. return this._activeCount;
  211. }
  212. public set activeParticleCount(value: number) {
  213. this._activeCount = Math.min(value, this._capacity);
  214. }
  215. /**
  216. * Is this system ready to be used/rendered
  217. * @return true if the system is ready
  218. */
  219. public isReady(): boolean {
  220. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  221. return false;
  222. }
  223. return true;
  224. }
  225. /**
  226. * Gets Wether the system has been started.
  227. * @returns True if it has been started, otherwise false.
  228. */
  229. public isStarted(): boolean {
  230. return this._started;
  231. }
  232. /**
  233. * Starts the particle system and begins to emit.
  234. */
  235. public start(): void {
  236. this._started = true;
  237. this._stopped = false;
  238. }
  239. /**
  240. * Stops the particle system.
  241. */
  242. public stop(): void {
  243. this._stopped = true;
  244. }
  245. /**
  246. * Remove all active particles
  247. */
  248. public reset(): void {
  249. this._releaseBuffers();
  250. this._releaseVAOs();
  251. this._currentActiveCount = 0;
  252. this._targetIndex = 0;
  253. }
  254. /**
  255. * Returns the string "GPUParticleSystem"
  256. * @returns a string containing the class name
  257. */
  258. public getClassName(): string {
  259. return "GPUParticleSystem";
  260. }
  261. /**
  262. * Instantiates a GPU particle system.
  263. * 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.
  264. * @param name The name of the particle system
  265. * @param capacity The max number of particles alive at the same time
  266. * @param scene The scene the particle system belongs to
  267. */
  268. constructor(name: string, options: Partial<{
  269. capacity: number,
  270. randomTextureSize: number
  271. }>, scene: Scene) {
  272. this.id = name;
  273. this.name = name;
  274. this._scene = scene || Engine.LastCreatedScene;
  275. this._engine = this._scene.getEngine();
  276. let fullOptions = {
  277. capacity: 50000,
  278. randomTextureSize: this._engine.getCaps().maxTextureSize,
  279. ...options
  280. };
  281. this._capacity = fullOptions.capacity;
  282. this._activeCount = fullOptions.capacity;
  283. this._currentActiveCount = 0;
  284. this._scene.particleSystems.push(this);
  285. this._updateEffectOptions = {
  286. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  287. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  288. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  289. uniformBuffersNames: [],
  290. samplers:["randomSampler"],
  291. defines: "",
  292. fallbacks: null,
  293. onCompiled: null,
  294. onError: null,
  295. indexParameters: null,
  296. maxSimultaneousLights: 0,
  297. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  298. };
  299. // Random data
  300. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  301. var d = [];
  302. for (var i = 0; i < maxTextureSize; ++i) {
  303. d.push(Math.random());
  304. d.push(Math.random());
  305. d.push(Math.random());
  306. d.push(Math.random());
  307. }
  308. this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT)
  309. this._randomTexture.wrapU = Texture.WRAP_ADDRESSMODE;
  310. this._randomTexture.wrapV = Texture.WRAP_ADDRESSMODE;
  311. this._randomTextureSize = maxTextureSize;
  312. this.particleEmitterType = new BoxParticleEmitter();
  313. }
  314. private _createUpdateVAO(source: Buffer): WebGLVertexArrayObject {
  315. let updateVertexBuffers: {[key: string]: VertexBuffer} = {};
  316. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  317. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  318. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  319. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  320. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  321. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  322. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  323. let vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  324. this._engine.bindArrayBuffer(null);
  325. return vao;
  326. }
  327. private _createRenderVAO(source: Buffer, spriteSource: Buffer): WebGLVertexArrayObject {
  328. let renderVertexBuffers: {[key: string]: VertexBuffer} = {};
  329. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  330. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  331. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  332. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  333. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  334. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  335. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  336. let vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  337. this._engine.bindArrayBuffer(null);
  338. return vao;
  339. }
  340. private _initialize(force = false): void {
  341. if (this._buffer0 && !force) {
  342. return;
  343. }
  344. let engine = this._scene.getEngine();
  345. var data = new Array<float>();
  346. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  347. // position
  348. data.push(0.0);
  349. data.push(0.0);
  350. data.push(0.0);
  351. // Age and life
  352. data.push(0.0); // create the particle as a dead one to create a new one at start
  353. data.push(0.0);
  354. // Seed
  355. data.push(Math.random());
  356. // Size
  357. data.push(0.0);
  358. // color
  359. data.push(0.0);
  360. data.push(0.0);
  361. data.push(0.0);
  362. data.push(0.0);
  363. // direction
  364. data.push(0.0);
  365. data.push(0.0);
  366. data.push(0.0);
  367. }
  368. // Sprite data
  369. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  370. -0.5, 0.5, 0, 1,
  371. -0.5, -0.5, 0, 0,
  372. 0.5, -0.5, 1, 0]);
  373. // Buffers
  374. this._buffer0 = new Buffer(engine, data, false, this._attributesStrideSize);
  375. this._buffer1 = new Buffer(engine, data, false, this._attributesStrideSize);
  376. this._spriteBuffer = new Buffer(engine, spriteData, false, 4);
  377. // Update VAO
  378. this._updateVAO = [];
  379. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  380. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  381. // Render VAO
  382. this._renderVAO = [];
  383. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  384. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  385. // Links
  386. this._sourceBuffer = this._buffer0;
  387. this._targetBuffer = this._buffer1;
  388. }
  389. /** @ignore */
  390. public _recreateUpdateEffect() {
  391. let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  392. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  393. return;
  394. }
  395. this._updateEffectOptions.defines = defines;
  396. this._updateEffect = new Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  397. }
  398. /** @ignore */
  399. public _recreateRenderEffect() {
  400. let defines = "";
  401. if (this._scene.clipPlane) {
  402. defines = "\n#define CLIPPLANE";
  403. }
  404. if (this._renderEffect && this._renderEffect.defines === defines) {
  405. return;
  406. }
  407. this._renderEffect = new Effect("gpuRenderParticles",
  408. ["position", "age", "life", "size", "color", "offset", "uv"],
  409. ["view", "projection", "colorDead", "invView", "vClipPlane"],
  410. ["textureSampler"], this._scene.getEngine(), defines);
  411. }
  412. /**
  413. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  414. */
  415. public animate(): void {
  416. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  417. this._actualFrame += this._timeDelta;
  418. if (!this._stopped) {
  419. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  420. this.stop();
  421. }
  422. }
  423. }
  424. /**
  425. * Renders the particle system in its current state.
  426. * @returns the current number of particles
  427. */
  428. public render(): number {
  429. if (!this._started) {
  430. return 0;
  431. }
  432. this._recreateUpdateEffect();
  433. this._recreateRenderEffect();
  434. if (!this.isReady()) {
  435. return 0;
  436. }
  437. if (this._currentRenderId === this._scene.getRenderId()) {
  438. return 0;
  439. }
  440. this._currentRenderId = this._scene.getRenderId();
  441. // Get everything ready to render
  442. this. _initialize();
  443. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  444. // Enable update effect
  445. this._engine.enableEffect(this._updateEffect);
  446. this._engine.setState(false);
  447. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  448. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  449. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  450. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  451. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  452. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  453. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  454. this._updateEffect.setDirectColor4("color1", this.color1);
  455. this._updateEffect.setDirectColor4("color2", this.color2);
  456. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  457. this._updateEffect.setVector3("gravity", this.gravity);
  458. if (this.particleEmitterType) {
  459. this.particleEmitterType.applyToShader(this._updateEffect);
  460. }
  461. let emitterWM: Matrix;
  462. if ((<AbstractMesh>this.emitter).position) {
  463. var emitterMesh = (<AbstractMesh>this.emitter);
  464. emitterWM = emitterMesh.getWorldMatrix();
  465. } else {
  466. var emitterPosition = (<Vector3>this.emitter);
  467. emitterWM = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  468. }
  469. this._updateEffect.setMatrix("emitterWM", emitterWM);
  470. // Bind source VAO
  471. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  472. // Update
  473. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  474. this._engine.setRasterizerState(false);
  475. this._engine.beginTransformFeedback();
  476. this._engine.drawArraysType(Material.PointListDrawMode, 0, this._currentActiveCount);
  477. this._engine.endTransformFeedback();
  478. this._engine.setRasterizerState(true);
  479. this._engine.bindTransformFeedbackBuffer(null);
  480. // Enable render effect
  481. this._engine.enableEffect(this._renderEffect);
  482. let viewMatrix = this._scene.getViewMatrix();
  483. this._renderEffect.setMatrix("view", viewMatrix);
  484. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  485. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  486. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  487. if (this._scene.clipPlane) {
  488. var clipPlane = this._scene.clipPlane;
  489. var invView = viewMatrix.clone();
  490. invView.invert();
  491. this._renderEffect.setMatrix("invView", invView);
  492. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  493. }
  494. // Draw order
  495. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  496. this._engine.setAlphaMode(Engine.ALPHA_ONEONE);
  497. } else {
  498. this._engine.setAlphaMode(Engine.ALPHA_COMBINE);
  499. }
  500. if (this.forceDepthWrite) {
  501. this._engine.setDepthWrite(true);
  502. }
  503. // Bind source VAO
  504. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  505. // Render
  506. this._engine.drawArraysType(Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  507. this._engine.setAlphaMode(Engine.ALPHA_DISABLE);
  508. // Switch VAOs
  509. this._targetIndex++;
  510. if (this._targetIndex === 2) {
  511. this._targetIndex = 0;
  512. }
  513. // Switch buffers
  514. let tmpBuffer = this._sourceBuffer;
  515. this._sourceBuffer = this._targetBuffer;
  516. this._targetBuffer = tmpBuffer;
  517. return this._currentActiveCount;
  518. }
  519. /**
  520. * Rebuilds the particle system
  521. */
  522. public rebuild(): void {
  523. this._initialize(true);
  524. }
  525. private _releaseBuffers() {
  526. if (this._buffer0) {
  527. this._buffer0.dispose();
  528. (<any>this._buffer0) = null;
  529. }
  530. if (this._buffer1) {
  531. this._buffer1.dispose();
  532. (<any>this._buffer1) = null;
  533. }
  534. if (this._spriteBuffer) {
  535. this._spriteBuffer.dispose();
  536. (<any>this._spriteBuffer) = null;
  537. }
  538. }
  539. private _releaseVAOs() {
  540. if (!this._updateVAO) {
  541. return;
  542. }
  543. for (var index = 0; index < this._updateVAO.length; index++) {
  544. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  545. }
  546. this._updateVAO = [];
  547. for (var index = 0; index < this._renderVAO.length; index++) {
  548. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  549. }
  550. this._renderVAO = [];
  551. }
  552. /**
  553. * Disposes the particle system and free the associated resources
  554. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  555. */
  556. public dispose(disposeTexture = true): void {
  557. var index = this._scene.particleSystems.indexOf(this);
  558. if (index > -1) {
  559. this._scene.particleSystems.splice(index, 1);
  560. }
  561. this._releaseBuffers();
  562. this._releaseVAOs();
  563. if (this._randomTexture) {
  564. this._randomTexture.dispose();
  565. (<any>this._randomTexture) = null;
  566. }
  567. if (disposeTexture && this.particleTexture) {
  568. this.particleTexture.dispose();
  569. this.particleTexture = null;
  570. }
  571. // Callback
  572. this.onDisposeObservable.notifyObservers(this);
  573. this.onDisposeObservable.clear();
  574. }
  575. /**
  576. * Clones the particle system.
  577. * @param name The name of the cloned object
  578. * @param newEmitter The new emitter to use
  579. * @returns the cloned particle system
  580. */
  581. public clone(name: string, newEmitter: any): Nullable<GPUParticleSystem> {
  582. var result = new GPUParticleSystem(name, {capacity: this._capacity, randomTextureSize: this._randomTextureSize}, this._scene);
  583. Tools.DeepCopy(this, result);
  584. if (newEmitter === undefined) {
  585. newEmitter = this.emitter;
  586. }
  587. result.emitter = newEmitter;
  588. if (this.particleTexture) {
  589. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  590. }
  591. return result;
  592. }
  593. /**
  594. * Serializes the particle system to a JSON object.
  595. * @returns the JSON object
  596. */
  597. public serialize(): any {
  598. var serializationObject: any = {};
  599. serializationObject.name = this.name;
  600. serializationObject.id = this.id;
  601. // Emitter
  602. if ((<AbstractMesh>this.emitter).position) {
  603. var emitterMesh = (<AbstractMesh>this.emitter);
  604. serializationObject.emitterId = emitterMesh.id;
  605. } else {
  606. var emitterPosition = (<Vector3>this.emitter);
  607. serializationObject.emitter = emitterPosition.asArray();
  608. }
  609. serializationObject.capacity = this.getCapacity();
  610. if (this.particleTexture) {
  611. serializationObject.textureName = this.particleTexture.name;
  612. }
  613. // Animations
  614. Animation.AppendSerializedAnimations(this, serializationObject);
  615. // Particle system
  616. serializationObject.activeParticleCount = this.activeParticleCount;
  617. serializationObject.randomTextureSize = this._randomTextureSize;
  618. serializationObject.minSize = this.minSize;
  619. serializationObject.maxSize = this.maxSize;
  620. serializationObject.minEmitPower = this.minEmitPower;
  621. serializationObject.maxEmitPower = this.maxEmitPower;
  622. serializationObject.minLifeTime = this.minLifeTime;
  623. serializationObject.maxLifeTime = this.maxLifeTime;
  624. serializationObject.emitRate = this.emitRate;
  625. serializationObject.gravity = this.gravity.asArray();
  626. serializationObject.color1 = this.color1.asArray();
  627. serializationObject.color2 = this.color2.asArray();
  628. serializationObject.colorDead = this.colorDead.asArray();
  629. serializationObject.updateSpeed = this.updateSpeed;
  630. serializationObject.targetStopDuration = this.targetStopDuration;
  631. serializationObject.blendMode = this.blendMode;
  632. // Emitter
  633. if (this.particleEmitterType) {
  634. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  635. }
  636. return serializationObject;
  637. }
  638. /**
  639. * Parses a JSON object to create a GPU particle system.
  640. * @param parsedParticleSystem The JSON object to parse
  641. * @param scene The scene to create the particle system in
  642. * @param rootUrl The root url to use to load external dependencies like texture
  643. * @returns the parsed GPU particle system
  644. */
  645. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): GPUParticleSystem {
  646. var name = parsedParticleSystem.name;
  647. var particleSystem = new GPUParticleSystem(name, {capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize}, scene);
  648. if (parsedParticleSystem.id) {
  649. particleSystem.id = parsedParticleSystem.id;
  650. }
  651. // Texture
  652. if (parsedParticleSystem.textureName) {
  653. particleSystem.particleTexture = new Texture(rootUrl + parsedParticleSystem.textureName, scene);
  654. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  655. }
  656. // Emitter
  657. if (parsedParticleSystem.emitterId) {
  658. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  659. } else {
  660. particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);
  661. }
  662. // Animations
  663. if (parsedParticleSystem.animations) {
  664. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  665. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  666. particleSystem.animations.push(Animation.Parse(parsedAnimation));
  667. }
  668. }
  669. // Particle system
  670. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  671. particleSystem.minSize = parsedParticleSystem.minSize;
  672. particleSystem.maxSize = parsedParticleSystem.maxSize;
  673. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  674. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  675. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  676. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  677. particleSystem.emitRate = parsedParticleSystem.emitRate;
  678. particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);
  679. particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);
  680. particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);
  681. particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);
  682. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  683. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  684. particleSystem.blendMode = parsedParticleSystem.blendMode;
  685. // Emitter
  686. if (parsedParticleSystem.particleEmitterType) {
  687. let emitterType: IParticleEmitterType;
  688. switch (parsedParticleSystem.particleEmitterType.type) {
  689. case "SphereEmitter":
  690. emitterType = new SphereParticleEmitter();
  691. break;
  692. case "SphereDirectedParticleEmitter":
  693. emitterType = new SphereDirectedParticleEmitter();
  694. break;
  695. case "ConeEmitter":
  696. emitterType = new ConeParticleEmitter();
  697. break;
  698. case "BoxEmitter":
  699. default:
  700. emitterType = new BoxParticleEmitter();
  701. break;
  702. }
  703. emitterType.parse(parsedParticleSystem.particleEmitterType);
  704. particleSystem.particleEmitterType = emitterType;
  705. }
  706. return particleSystem;
  707. }
  708. }
  709. }