babylon.particleSystem.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. module BABYLON {
  2. var randomNumber = (min: number, max: number): number => {
  3. if (min === max) {
  4. return (min);
  5. }
  6. var random = Math.random();
  7. return ((random * (max - min)) + min);
  8. }
  9. export class ParticleSystem implements IDisposable {
  10. // Statics
  11. public static BLENDMODE_ONEONE = 0;
  12. public static BLENDMODE_STANDARD = 1;
  13. // Members
  14. public id: string;
  15. public renderingGroupId = 0;
  16. public emitter = null;
  17. public emitRate = 10;
  18. public manualEmitCount = -1;
  19. public updateSpeed = 0.01;
  20. public targetStopDuration = 0;
  21. public disposeOnStop = false;
  22. public minEmitPower = 1;
  23. public maxEmitPower = 1;
  24. public minLifeTime = 1;
  25. public maxLifeTime = 1;
  26. public minSize = 1;
  27. public maxSize = 1;
  28. public minAngularSpeed = 0;
  29. public maxAngularSpeed = 0;
  30. public particleTexture: Texture;
  31. public layerMask: number = 0x0FFFFFFF;
  32. public onDispose: () => void;
  33. public updateFunction: (particles: Particle[]) => void;
  34. public blendMode = ParticleSystem.BLENDMODE_ONEONE;
  35. public forceDepthWrite = false;
  36. public gravity = Vector3.Zero();
  37. public direction1 = new Vector3(0, 1.0, 0);
  38. public direction2 = new Vector3(0, 1.0, 0);
  39. public minEmitBox = new Vector3(-0.5, -0.5, -0.5);
  40. public maxEmitBox = new Vector3(0.5, 0.5, 0.5);
  41. public color1 = new Color4(1.0, 1.0, 1.0, 1.0);
  42. public color2 = new Color4(1.0, 1.0, 1.0, 1.0);
  43. public colorDead = new Color4(0, 0, 0, 1.0);
  44. public textureMask = new Color4(1.0, 1.0, 1.0, 1.0);
  45. public startDirectionFunction: (emitPower: number, worldMatrix: Matrix, directionToUpdate: Vector3) => void;
  46. public startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3) => void;
  47. private particles = new Array<Particle>();
  48. private _capacity: number;
  49. private _scene: Scene;
  50. private _vertexDeclaration = [3, 4, 4];
  51. private _vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  52. private _stockParticles = new Array<Particle>();
  53. private _newPartsExcess = 0;
  54. private _vertexBuffer: WebGLBuffer;
  55. private _indexBuffer: WebGLBuffer;
  56. private _vertices: Float32Array;
  57. private _effect: Effect;
  58. private _customEffect: Effect;
  59. private _cachedDefines: string;
  60. private _scaledColorStep = new Color4(0, 0, 0, 0);
  61. private _colorDiff = new Color4(0, 0, 0, 0);
  62. private _scaledDirection = Vector3.Zero();
  63. private _scaledGravity = Vector3.Zero();
  64. private _currentRenderId = -1;
  65. private _alive: boolean;
  66. private _started = false;
  67. private _stopped = false;
  68. private _actualFrame = 0;
  69. private _scaledUpdateSpeed: number;
  70. constructor(public name: string, capacity: number, scene: Scene, customEffect?: Effect) {
  71. this.id = name;
  72. this._capacity = capacity;
  73. this._scene = scene;
  74. this._customEffect = customEffect;
  75. scene.particleSystems.push(this);
  76. // VBO
  77. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  78. var indices = [];
  79. var index = 0;
  80. for (var count = 0; count < capacity; count++) {
  81. indices.push(index);
  82. indices.push(index + 1);
  83. indices.push(index + 2);
  84. indices.push(index);
  85. indices.push(index + 2);
  86. indices.push(index + 3);
  87. index += 4;
  88. }
  89. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  90. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  91. // Default behaviors
  92. this.startDirectionFunction = (emitPower: number, worldMatrix: Matrix, directionToUpdate: Vector3): void => {
  93. var randX = randomNumber(this.direction1.x, this.direction2.x);
  94. var randY = randomNumber(this.direction1.y, this.direction2.y);
  95. var randZ = randomNumber(this.direction1.z, this.direction2.z);
  96. Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  97. }
  98. this.startPositionFunction = (worldMatrix: Matrix, positionToUpdate: Vector3): void => {
  99. var randX = randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
  100. var randY = randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
  101. var randZ = randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
  102. Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  103. }
  104. this.updateFunction = (particles: Particle[]): void => {
  105. for (var index = 0; index < particles.length; index++) {
  106. var particle = particles[index];
  107. particle.age += this._scaledUpdateSpeed;
  108. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  109. this.recycleParticle(particle);
  110. index--;
  111. continue;
  112. }
  113. else {
  114. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  115. particle.color.addInPlace(this._scaledColorStep);
  116. if (particle.color.a < 0)
  117. particle.color.a = 0;
  118. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  119. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  120. particle.position.addInPlace(this._scaledDirection);
  121. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  122. particle.direction.addInPlace(this._scaledGravity);
  123. }
  124. }
  125. }
  126. }
  127. public recycleParticle(particle: Particle): void {
  128. var lastParticle = this.particles.pop();
  129. if (lastParticle !== particle) {
  130. lastParticle.copyTo(particle);
  131. this._stockParticles.push(lastParticle);
  132. }
  133. }
  134. public getCapacity(): number {
  135. return this._capacity;
  136. }
  137. public isAlive(): boolean {
  138. return this._alive;
  139. }
  140. public isStarted(): boolean {
  141. return this._started;
  142. }
  143. public start(): void {
  144. this._started = true;
  145. this._stopped = false;
  146. this._actualFrame = 0;
  147. }
  148. public stop(): void {
  149. this._stopped = true;
  150. }
  151. public _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void {
  152. var offset = index * 11;
  153. this._vertices[offset] = particle.position.x;
  154. this._vertices[offset + 1] = particle.position.y;
  155. this._vertices[offset + 2] = particle.position.z;
  156. this._vertices[offset + 3] = particle.color.r;
  157. this._vertices[offset + 4] = particle.color.g;
  158. this._vertices[offset + 5] = particle.color.b;
  159. this._vertices[offset + 6] = particle.color.a;
  160. this._vertices[offset + 7] = particle.angle;
  161. this._vertices[offset + 8] = particle.size;
  162. this._vertices[offset + 9] = offsetX;
  163. this._vertices[offset + 10] = offsetY;
  164. }
  165. private _update(newParticles: number): void {
  166. // Update current
  167. this._alive = this.particles.length > 0;
  168. this.updateFunction(this.particles);
  169. // Add new ones
  170. var worldMatrix;
  171. if (this.emitter.position) {
  172. worldMatrix = this.emitter.getWorldMatrix();
  173. } else {
  174. worldMatrix = Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  175. }
  176. for (var index = 0; index < newParticles; index++) {
  177. if (this.particles.length === this._capacity) {
  178. break;
  179. }
  180. if (this._stockParticles.length !== 0) {
  181. var particle = this._stockParticles.pop();
  182. particle.age = 0;
  183. } else {
  184. particle = new Particle();
  185. }
  186. this.particles.push(particle);
  187. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  188. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  189. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  190. particle.size = randomNumber(this.minSize, this.maxSize);
  191. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  192. this.startPositionFunction(worldMatrix, particle.position);
  193. var step = randomNumber(0, 1.0);
  194. Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  195. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  196. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  197. }
  198. }
  199. private _getEffect(): Effect {
  200. if (this._customEffect) {
  201. return this._customEffect;
  202. };
  203. var defines = [];
  204. if (this._scene.clipPlane) {
  205. defines.push("#define CLIPPLANE");
  206. }
  207. // Effect
  208. var join = defines.join("\n");
  209. if (this._cachedDefines !== join) {
  210. this._cachedDefines = join;
  211. this._effect = this._scene.getEngine().createEffect(
  212. "particles",
  213. ["position", "color", "options"],
  214. ["invView", "view", "projection", "vClipPlane", "textureMask"],
  215. ["diffuseSampler"], join);
  216. }
  217. return this._effect;
  218. }
  219. public animate(): void {
  220. if (!this._started)
  221. return;
  222. var effect = this._getEffect();
  223. // Check
  224. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  225. return;
  226. if (this._currentRenderId === this._scene.getRenderId()) {
  227. return;
  228. }
  229. this._currentRenderId = this._scene.getRenderId();
  230. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  231. // determine the number of particles we need to create
  232. var emitCout;
  233. if (this.manualEmitCount > -1) {
  234. emitCout = this.manualEmitCount;
  235. this.manualEmitCount = 0;
  236. } else {
  237. emitCout = this.emitRate;
  238. }
  239. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  240. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  241. if (this._newPartsExcess > 1.0) {
  242. newParticles += this._newPartsExcess >> 0;
  243. this._newPartsExcess -= this._newPartsExcess >> 0;
  244. }
  245. this._alive = false;
  246. if (!this._stopped) {
  247. this._actualFrame += this._scaledUpdateSpeed;
  248. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  249. this.stop();
  250. } else {
  251. newParticles = 0;
  252. }
  253. this._update(newParticles);
  254. // Stopped?
  255. if (this._stopped) {
  256. if (!this._alive) {
  257. this._started = false;
  258. if (this.disposeOnStop) {
  259. this._scene._toBeDisposed.push(this);
  260. }
  261. }
  262. }
  263. // Update VBO
  264. var offset = 0;
  265. for (var index = 0; index < this.particles.length; index++) {
  266. var particle = this.particles[index];
  267. this._appendParticleVertex(offset++, particle, 0, 0);
  268. this._appendParticleVertex(offset++, particle, 1, 0);
  269. this._appendParticleVertex(offset++, particle, 1, 1);
  270. this._appendParticleVertex(offset++, particle, 0, 1);
  271. }
  272. var engine = this._scene.getEngine();
  273. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  274. }
  275. public render(): number {
  276. var effect = this._getEffect();
  277. // Check
  278. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  279. return 0;
  280. var engine = this._scene.getEngine();
  281. // Render
  282. engine.enableEffect(effect);
  283. engine.setState(false);
  284. var viewMatrix = this._scene.getViewMatrix();
  285. effect.setTexture("diffuseSampler", this.particleTexture);
  286. effect.setMatrix("view", viewMatrix);
  287. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  288. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  289. if (this._scene.clipPlane) {
  290. var clipPlane = this._scene.clipPlane;
  291. var invView = viewMatrix.clone();
  292. invView.invert();
  293. effect.setMatrix("invView", invView);
  294. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  295. }
  296. // VBOs
  297. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  298. // Draw order
  299. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  300. engine.setAlphaMode(Engine.ALPHA_ONEONE);
  301. } else {
  302. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  303. }
  304. if (this.forceDepthWrite) {
  305. engine.setDepthWrite(true);
  306. }
  307. engine.draw(true, 0, this.particles.length * 6);
  308. engine.setAlphaMode(Engine.ALPHA_DISABLE);
  309. return this.particles.length;
  310. }
  311. public dispose(): void {
  312. if (this._vertexBuffer) {
  313. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  314. this._vertexBuffer = null;
  315. }
  316. if (this._indexBuffer) {
  317. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  318. this._indexBuffer = null;
  319. }
  320. if (this.particleTexture) {
  321. this.particleTexture.dispose();
  322. this.particleTexture = null;
  323. }
  324. // Remove from scene
  325. var index = this._scene.particleSystems.indexOf(this);
  326. this._scene.particleSystems.splice(index, 1);
  327. // Callback
  328. if (this.onDispose) {
  329. this.onDispose();
  330. }
  331. }
  332. // Clone
  333. public clone(name: string, newEmitter: any): ParticleSystem {
  334. var result = new ParticleSystem(name, this._capacity, this._scene);
  335. Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  336. if (newEmitter === undefined) {
  337. newEmitter = this.emitter;
  338. }
  339. result.emitter = newEmitter;
  340. if (this.particleTexture) {
  341. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  342. }
  343. result.start();
  344. return result;
  345. }
  346. }
  347. }