thinParticleSystem.js 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  1. import { FactorGradient, ColorGradient, Color3Gradient, GradientHelper } from "../Misc/gradients.js";
  2. import { Observable } from "../Misc/observable.js";
  3. import { Vector3, Matrix, Vector4, TmpVectors } from "../Maths/math.vector.js";
  4. import { VertexBuffer, Buffer } from "../Buffers/buffer.js";
  5. import { RawTexture } from "../Materials/Textures/rawTexture.js";
  6. import { EngineStore } from "../Engines/engineStore.js";
  7. import { BaseParticleSystem } from "./baseParticleSystem.js";
  8. import { Particle } from "./particle.js";
  9. import { DrawWrapper } from "../Materials/drawWrapper.js";
  10. import "../Shaders/particles.fragment.js";
  11. import "../Shaders/particles.vertex.js";
  12. import { Color4, Color3, TmpColors } from "../Maths/math.color.js";
  13. import "../Engines/Extensions/engine.alpha.js";
  14. import { addClipPlaneUniforms, prepareStringDefinesForClipPlanes, bindClipPlane } from "../Materials/clipPlaneMaterialHelper.js";
  15. import { BindFogParameters, BindLogDepth } from "../Materials/materialHelper.functions.js";
  16. import { BoxParticleEmitter } from "./EmitterTypes/boxParticleEmitter.js";
  17. import { Clamp, Lerp, RandomRange } from "../Maths/math.scalar.functions.js";
  18. import { PrepareSamplersForImageProcessing, PrepareUniformsForImageProcessing } from "../Materials/imageProcessingConfiguration.functions.js";
  19. /**
  20. * This represents a thin particle system in Babylon.
  21. * 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.
  22. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  23. * This thin version contains a limited subset of the total features in order to provide users with a way to get particles but with a smaller footprint
  24. * @example https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro
  25. */
  26. export class ThinParticleSystem extends BaseParticleSystem {
  27. /**
  28. * Sets a callback that will be triggered when the system is disposed
  29. */
  30. set onDispose(callback) {
  31. if (this._onDisposeObserver) {
  32. this.onDisposeObservable.remove(this._onDisposeObserver);
  33. }
  34. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35. }
  36. /** Gets or sets a boolean indicating that ramp gradients must be used
  37. * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients
  38. */
  39. get useRampGradients() {
  40. return this._useRampGradients;
  41. }
  42. set useRampGradients(value) {
  43. if (this._useRampGradients === value) {
  44. return;
  45. }
  46. this._useRampGradients = value;
  47. this._resetEffect();
  48. }
  49. /**
  50. * Gets the current list of active particles
  51. */
  52. get particles() {
  53. return this._particles;
  54. }
  55. /**
  56. * Gets the number of particles active at the same time.
  57. * @returns The number of active particles.
  58. */
  59. getActiveCount() {
  60. return this._particles.length;
  61. }
  62. /**
  63. * Returns the string "ParticleSystem"
  64. * @returns a string containing the class name
  65. */
  66. getClassName() {
  67. return "ParticleSystem";
  68. }
  69. /**
  70. * Gets a boolean indicating that the system is stopping
  71. * @returns true if the system is currently stopping
  72. */
  73. isStopping() {
  74. return this._stopped && this.isAlive();
  75. }
  76. /**
  77. * Gets the custom effect used to render the particles
  78. * @param blendMode Blend mode for which the effect should be retrieved
  79. * @returns The effect
  80. */
  81. getCustomEffect(blendMode = 0) {
  82. return this._customWrappers[blendMode]?.effect ?? this._customWrappers[0].effect;
  83. }
  84. _getCustomDrawWrapper(blendMode = 0) {
  85. return this._customWrappers[blendMode] ?? this._customWrappers[0];
  86. }
  87. /**
  88. * Sets the custom effect used to render the particles
  89. * @param effect The effect to set
  90. * @param blendMode Blend mode for which the effect should be set
  91. */
  92. setCustomEffect(effect, blendMode = 0) {
  93. this._customWrappers[blendMode] = new DrawWrapper(this._engine);
  94. this._customWrappers[blendMode].effect = effect;
  95. if (this._customWrappers[blendMode].drawContext) {
  96. this._customWrappers[blendMode].drawContext.useInstancing = this._useInstancing;
  97. }
  98. }
  99. /**
  100. * Observable that will be called just before the particles are drawn
  101. */
  102. get onBeforeDrawParticlesObservable() {
  103. if (!this._onBeforeDrawParticlesObservable) {
  104. this._onBeforeDrawParticlesObservable = new Observable();
  105. }
  106. return this._onBeforeDrawParticlesObservable;
  107. }
  108. /**
  109. * Gets the name of the particle vertex shader
  110. */
  111. get vertexShaderName() {
  112. return "particles";
  113. }
  114. /**
  115. * Gets the vertex buffers used by the particle system
  116. */
  117. get vertexBuffers() {
  118. return this._vertexBuffers;
  119. }
  120. /**
  121. * Gets the index buffer used by the particle system (or null if no index buffer is used (if _useInstancing=true))
  122. */
  123. get indexBuffer() {
  124. return this._indexBuffer;
  125. }
  126. /**
  127. * Instantiates a particle system.
  128. * 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.
  129. * @param name The name of the particle system
  130. * @param capacity The max number of particles alive at the same time
  131. * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene
  132. * @param customEffect a custom effect used to change the way particles are rendered by default
  133. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  134. * @param epsilon Offset used to render the particles
  135. */
  136. constructor(name, capacity, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false, epsilon = 0.01) {
  137. super(name);
  138. this._emitterInverseWorldMatrix = Matrix.Identity();
  139. /**
  140. * @internal
  141. */
  142. this._inheritedVelocityOffset = new Vector3();
  143. /**
  144. * An event triggered when the system is disposed
  145. */
  146. this.onDisposeObservable = new Observable();
  147. /**
  148. * An event triggered when the system is stopped
  149. */
  150. this.onStoppedObservable = new Observable();
  151. this._particles = new Array();
  152. this._stockParticles = new Array();
  153. this._newPartsExcess = 0;
  154. this._vertexBuffers = {};
  155. this._scaledColorStep = new Color4(0, 0, 0, 0);
  156. this._colorDiff = new Color4(0, 0, 0, 0);
  157. this._scaledDirection = Vector3.Zero();
  158. this._scaledGravity = Vector3.Zero();
  159. this._currentRenderId = -1;
  160. this._useInstancing = false;
  161. this._started = false;
  162. this._stopped = false;
  163. this._actualFrame = 0;
  164. /** @internal */
  165. this._currentEmitRate1 = 0;
  166. /** @internal */
  167. this._currentEmitRate2 = 0;
  168. /** @internal */
  169. this._currentStartSize1 = 0;
  170. /** @internal */
  171. this._currentStartSize2 = 0;
  172. /** Indicates that the update of particles is done in the animate function */
  173. this.updateInAnimate = true;
  174. this._rawTextureWidth = 256;
  175. this._useRampGradients = false;
  176. /**
  177. * Specifies if the particles are updated in emitter local space or world space
  178. */
  179. this.isLocal = false;
  180. /** Indicates that the particle system is CPU based */
  181. this.isGPU = false;
  182. /** @internal */
  183. this._onBeforeDrawParticlesObservable = null;
  184. /** @internal */
  185. this._emitFromParticle = (particle) => {
  186. // Do nothing
  187. };
  188. // start of sub system methods
  189. /**
  190. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  191. * Its lifetime will start back at 0.
  192. * @param particle
  193. */
  194. this.recycleParticle = (particle) => {
  195. // move particle from activeParticle list to stock particles
  196. const lastParticle = this._particles.pop();
  197. if (lastParticle !== particle) {
  198. lastParticle.copyTo(particle);
  199. }
  200. this._stockParticles.push(lastParticle);
  201. };
  202. this._createParticle = () => {
  203. let particle;
  204. if (this._stockParticles.length !== 0) {
  205. particle = this._stockParticles.pop();
  206. particle._reset();
  207. }
  208. else {
  209. particle = new Particle(this);
  210. }
  211. this._prepareParticle(particle);
  212. return particle;
  213. };
  214. this._capacity = capacity;
  215. this._epsilon = epsilon;
  216. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  217. if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") {
  218. this._scene = sceneOrEngine || EngineStore.LastCreatedScene;
  219. this._engine = this._scene.getEngine();
  220. this.uniqueId = this._scene.getUniqueId();
  221. this._scene.particleSystems.push(this);
  222. }
  223. else {
  224. this._engine = sceneOrEngine;
  225. this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange);
  226. }
  227. if (this._engine.getCaps().vertexArrayObject) {
  228. this._vertexArrayObject = null;
  229. }
  230. // Setup the default processing configuration to the scene.
  231. this._attachImageProcessingConfiguration(null);
  232. // eslint-disable-next-line @typescript-eslint/naming-convention
  233. this._customWrappers = { 0: new DrawWrapper(this._engine) };
  234. this._customWrappers[0].effect = customEffect;
  235. this._drawWrappers = [];
  236. this._useInstancing = this._engine.getCaps().instancedArrays;
  237. this._createIndexBuffer();
  238. this._createVertexBuffers();
  239. // Default emitter type
  240. this.particleEmitterType = new BoxParticleEmitter();
  241. let noiseTextureData = null;
  242. // Update
  243. this.updateFunction = (particles) => {
  244. let noiseTextureSize = null;
  245. if (this.noiseTexture) {
  246. // We need to get texture data back to CPU
  247. noiseTextureSize = this.noiseTexture.getSize();
  248. this.noiseTexture.getContent()?.then((data) => {
  249. noiseTextureData = data;
  250. });
  251. }
  252. const sameParticleArray = particles === this._particles;
  253. for (let index = 0; index < particles.length; index++) {
  254. const particle = particles[index];
  255. let scaledUpdateSpeed = this._scaledUpdateSpeed;
  256. const previousAge = particle.age;
  257. particle.age += scaledUpdateSpeed;
  258. // Evaluate step to death
  259. if (particle.age > particle.lifeTime) {
  260. const diff = particle.age - previousAge;
  261. const oldDiff = particle.lifeTime - previousAge;
  262. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  263. particle.age = particle.lifeTime;
  264. }
  265. const ratio = particle.age / particle.lifeTime;
  266. // Color
  267. if (this._colorGradients && this._colorGradients.length > 0) {
  268. GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
  269. if (currentGradient !== particle._currentColorGradient) {
  270. particle._currentColor1.copyFrom(particle._currentColor2);
  271. nextGradient.getColorToRef(particle._currentColor2);
  272. particle._currentColorGradient = currentGradient;
  273. }
  274. Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  275. });
  276. }
  277. else {
  278. particle.colorStep.scaleToRef(scaledUpdateSpeed, this._scaledColorStep);
  279. particle.color.addInPlace(this._scaledColorStep);
  280. if (particle.color.a < 0) {
  281. particle.color.a = 0;
  282. }
  283. }
  284. // Angular speed
  285. if (this._angularSpeedGradients && this._angularSpeedGradients.length > 0) {
  286. GradientHelper.GetCurrentGradient(ratio, this._angularSpeedGradients, (currentGradient, nextGradient, scale) => {
  287. if (currentGradient !== particle._currentAngularSpeedGradient) {
  288. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  289. particle._currentAngularSpeed2 = nextGradient.getFactor();
  290. particle._currentAngularSpeedGradient = currentGradient;
  291. }
  292. particle.angularSpeed = Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  293. });
  294. }
  295. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  296. // Direction
  297. let directionScale = scaledUpdateSpeed;
  298. /// Velocity
  299. if (this._velocityGradients && this._velocityGradients.length > 0) {
  300. GradientHelper.GetCurrentGradient(ratio, this._velocityGradients, (currentGradient, nextGradient, scale) => {
  301. if (currentGradient !== particle._currentVelocityGradient) {
  302. particle._currentVelocity1 = particle._currentVelocity2;
  303. particle._currentVelocity2 = nextGradient.getFactor();
  304. particle._currentVelocityGradient = currentGradient;
  305. }
  306. directionScale *= Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  307. });
  308. }
  309. particle.direction.scaleToRef(directionScale, this._scaledDirection);
  310. /// Limit velocity
  311. if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {
  312. GradientHelper.GetCurrentGradient(ratio, this._limitVelocityGradients, (currentGradient, nextGradient, scale) => {
  313. if (currentGradient !== particle._currentLimitVelocityGradient) {
  314. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  315. particle._currentLimitVelocity2 = nextGradient.getFactor();
  316. particle._currentLimitVelocityGradient = currentGradient;
  317. }
  318. const limitVelocity = Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  319. const currentVelocity = particle.direction.length();
  320. if (currentVelocity > limitVelocity) {
  321. particle.direction.scaleInPlace(this.limitVelocityDamping);
  322. }
  323. });
  324. }
  325. /// Drag
  326. if (this._dragGradients && this._dragGradients.length > 0) {
  327. GradientHelper.GetCurrentGradient(ratio, this._dragGradients, (currentGradient, nextGradient, scale) => {
  328. if (currentGradient !== particle._currentDragGradient) {
  329. particle._currentDrag1 = particle._currentDrag2;
  330. particle._currentDrag2 = nextGradient.getFactor();
  331. particle._currentDragGradient = currentGradient;
  332. }
  333. const drag = Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  334. this._scaledDirection.scaleInPlace(1.0 - drag);
  335. });
  336. }
  337. if (this.isLocal && particle._localPosition) {
  338. particle._localPosition.addInPlace(this._scaledDirection);
  339. Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position);
  340. }
  341. else {
  342. particle.position.addInPlace(this._scaledDirection);
  343. }
  344. // Noise
  345. if (noiseTextureData && noiseTextureSize && particle._randomNoiseCoordinates1) {
  346. const fetchedColorR = this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  347. const fetchedColorG = this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  348. const fetchedColorB = this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  349. const force = TmpVectors.Vector3[0];
  350. const scaledForce = TmpVectors.Vector3[1];
  351. force.copyFromFloats((2 * fetchedColorR - 1) * this.noiseStrength.x, (2 * fetchedColorG - 1) * this.noiseStrength.y, (2 * fetchedColorB - 1) * this.noiseStrength.z);
  352. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  353. particle.direction.addInPlace(scaledForce);
  354. }
  355. // Gravity
  356. this.gravity.scaleToRef(scaledUpdateSpeed, this._scaledGravity);
  357. particle.direction.addInPlace(this._scaledGravity);
  358. // Size
  359. if (this._sizeGradients && this._sizeGradients.length > 0) {
  360. GradientHelper.GetCurrentGradient(ratio, this._sizeGradients, (currentGradient, nextGradient, scale) => {
  361. if (currentGradient !== particle._currentSizeGradient) {
  362. particle._currentSize1 = particle._currentSize2;
  363. particle._currentSize2 = nextGradient.getFactor();
  364. particle._currentSizeGradient = currentGradient;
  365. }
  366. particle.size = Lerp(particle._currentSize1, particle._currentSize2, scale);
  367. });
  368. }
  369. // Remap data
  370. if (this._useRampGradients) {
  371. if (this._colorRemapGradients && this._colorRemapGradients.length > 0) {
  372. GradientHelper.GetCurrentGradient(ratio, this._colorRemapGradients, (currentGradient, nextGradient, scale) => {
  373. const min = Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  374. const max = Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  375. particle.remapData.x = min;
  376. particle.remapData.y = max - min;
  377. });
  378. }
  379. if (this._alphaRemapGradients && this._alphaRemapGradients.length > 0) {
  380. GradientHelper.GetCurrentGradient(ratio, this._alphaRemapGradients, (currentGradient, nextGradient, scale) => {
  381. const min = Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  382. const max = Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  383. particle.remapData.z = min;
  384. particle.remapData.w = max - min;
  385. });
  386. }
  387. }
  388. if (this._isAnimationSheetEnabled) {
  389. particle.updateCellIndex();
  390. }
  391. // Update the position of the attached sub-emitters to match their attached particle
  392. particle._inheritParticleInfoToSubEmitters();
  393. if (particle.age >= particle.lifeTime) {
  394. // Recycle by swapping with last particle
  395. this._emitFromParticle(particle);
  396. if (particle._attachedSubEmitters) {
  397. particle._attachedSubEmitters.forEach((subEmitter) => {
  398. subEmitter.particleSystem.disposeOnStop = true;
  399. subEmitter.particleSystem.stop();
  400. });
  401. particle._attachedSubEmitters = null;
  402. }
  403. this.recycleParticle(particle);
  404. if (sameParticleArray) {
  405. index--;
  406. }
  407. continue;
  408. }
  409. }
  410. };
  411. }
  412. serialize(serializeTexture) {
  413. throw new Error("Method not implemented.");
  414. }
  415. /**
  416. * Clones the particle system.
  417. * @param name The name of the cloned object
  418. * @param newEmitter The new emitter to use
  419. * @param cloneTexture Also clone the textures if true
  420. */
  421. clone(name, newEmitter, cloneTexture = false) {
  422. throw new Error("Method not implemented.");
  423. }
  424. _addFactorGradient(factorGradients, gradient, factor, factor2) {
  425. const newGradient = new FactorGradient(gradient, factor, factor2);
  426. factorGradients.push(newGradient);
  427. factorGradients.sort((a, b) => {
  428. if (a.gradient < b.gradient) {
  429. return -1;
  430. }
  431. else if (a.gradient > b.gradient) {
  432. return 1;
  433. }
  434. return 0;
  435. });
  436. }
  437. _removeFactorGradient(factorGradients, gradient) {
  438. if (!factorGradients) {
  439. return;
  440. }
  441. let index = 0;
  442. for (const factorGradient of factorGradients) {
  443. if (factorGradient.gradient === gradient) {
  444. factorGradients.splice(index, 1);
  445. break;
  446. }
  447. index++;
  448. }
  449. }
  450. /**
  451. * Adds a new life time gradient
  452. * @param gradient defines the gradient to use (between 0 and 1)
  453. * @param factor defines the life time factor to affect to the specified gradient
  454. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  455. * @returns the current particle system
  456. */
  457. addLifeTimeGradient(gradient, factor, factor2) {
  458. if (!this._lifeTimeGradients) {
  459. this._lifeTimeGradients = [];
  460. }
  461. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  462. return this;
  463. }
  464. /**
  465. * Remove a specific life time gradient
  466. * @param gradient defines the gradient to remove
  467. * @returns the current particle system
  468. */
  469. removeLifeTimeGradient(gradient) {
  470. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  471. return this;
  472. }
  473. /**
  474. * Adds a new size gradient
  475. * @param gradient defines the gradient to use (between 0 and 1)
  476. * @param factor defines the size factor to affect to the specified gradient
  477. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  478. * @returns the current particle system
  479. */
  480. addSizeGradient(gradient, factor, factor2) {
  481. if (!this._sizeGradients) {
  482. this._sizeGradients = [];
  483. }
  484. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  485. return this;
  486. }
  487. /**
  488. * Remove a specific size gradient
  489. * @param gradient defines the gradient to remove
  490. * @returns the current particle system
  491. */
  492. removeSizeGradient(gradient) {
  493. this._removeFactorGradient(this._sizeGradients, gradient);
  494. return this;
  495. }
  496. /**
  497. * Adds a new color remap gradient
  498. * @param gradient defines the gradient to use (between 0 and 1)
  499. * @param min defines the color remap minimal range
  500. * @param max defines the color remap maximal range
  501. * @returns the current particle system
  502. */
  503. addColorRemapGradient(gradient, min, max) {
  504. if (!this._colorRemapGradients) {
  505. this._colorRemapGradients = [];
  506. }
  507. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  508. return this;
  509. }
  510. /**
  511. * Remove a specific color remap gradient
  512. * @param gradient defines the gradient to remove
  513. * @returns the current particle system
  514. */
  515. removeColorRemapGradient(gradient) {
  516. this._removeFactorGradient(this._colorRemapGradients, gradient);
  517. return this;
  518. }
  519. /**
  520. * Adds a new alpha remap gradient
  521. * @param gradient defines the gradient to use (between 0 and 1)
  522. * @param min defines the alpha remap minimal range
  523. * @param max defines the alpha remap maximal range
  524. * @returns the current particle system
  525. */
  526. addAlphaRemapGradient(gradient, min, max) {
  527. if (!this._alphaRemapGradients) {
  528. this._alphaRemapGradients = [];
  529. }
  530. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  531. return this;
  532. }
  533. /**
  534. * Remove a specific alpha remap gradient
  535. * @param gradient defines the gradient to remove
  536. * @returns the current particle system
  537. */
  538. removeAlphaRemapGradient(gradient) {
  539. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  540. return this;
  541. }
  542. /**
  543. * Adds a new angular speed gradient
  544. * @param gradient defines the gradient to use (between 0 and 1)
  545. * @param factor defines the angular speed to affect to the specified gradient
  546. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  547. * @returns the current particle system
  548. */
  549. addAngularSpeedGradient(gradient, factor, factor2) {
  550. if (!this._angularSpeedGradients) {
  551. this._angularSpeedGradients = [];
  552. }
  553. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  554. return this;
  555. }
  556. /**
  557. * Remove a specific angular speed gradient
  558. * @param gradient defines the gradient to remove
  559. * @returns the current particle system
  560. */
  561. removeAngularSpeedGradient(gradient) {
  562. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  563. return this;
  564. }
  565. /**
  566. * Adds a new velocity gradient
  567. * @param gradient defines the gradient to use (between 0 and 1)
  568. * @param factor defines the velocity to affect to the specified gradient
  569. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  570. * @returns the current particle system
  571. */
  572. addVelocityGradient(gradient, factor, factor2) {
  573. if (!this._velocityGradients) {
  574. this._velocityGradients = [];
  575. }
  576. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  577. return this;
  578. }
  579. /**
  580. * Remove a specific velocity gradient
  581. * @param gradient defines the gradient to remove
  582. * @returns the current particle system
  583. */
  584. removeVelocityGradient(gradient) {
  585. this._removeFactorGradient(this._velocityGradients, gradient);
  586. return this;
  587. }
  588. /**
  589. * Adds a new limit velocity gradient
  590. * @param gradient defines the gradient to use (between 0 and 1)
  591. * @param factor defines the limit velocity value to affect to the specified gradient
  592. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  593. * @returns the current particle system
  594. */
  595. addLimitVelocityGradient(gradient, factor, factor2) {
  596. if (!this._limitVelocityGradients) {
  597. this._limitVelocityGradients = [];
  598. }
  599. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  600. return this;
  601. }
  602. /**
  603. * Remove a specific limit velocity gradient
  604. * @param gradient defines the gradient to remove
  605. * @returns the current particle system
  606. */
  607. removeLimitVelocityGradient(gradient) {
  608. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  609. return this;
  610. }
  611. /**
  612. * Adds a new drag gradient
  613. * @param gradient defines the gradient to use (between 0 and 1)
  614. * @param factor defines the drag value to affect to the specified gradient
  615. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  616. * @returns the current particle system
  617. */
  618. addDragGradient(gradient, factor, factor2) {
  619. if (!this._dragGradients) {
  620. this._dragGradients = [];
  621. }
  622. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  623. return this;
  624. }
  625. /**
  626. * Remove a specific drag gradient
  627. * @param gradient defines the gradient to remove
  628. * @returns the current particle system
  629. */
  630. removeDragGradient(gradient) {
  631. this._removeFactorGradient(this._dragGradients, gradient);
  632. return this;
  633. }
  634. /**
  635. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  636. * @param gradient defines the gradient to use (between 0 and 1)
  637. * @param factor defines the emit rate value to affect to the specified gradient
  638. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  639. * @returns the current particle system
  640. */
  641. addEmitRateGradient(gradient, factor, factor2) {
  642. if (!this._emitRateGradients) {
  643. this._emitRateGradients = [];
  644. }
  645. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  646. return this;
  647. }
  648. /**
  649. * Remove a specific emit rate gradient
  650. * @param gradient defines the gradient to remove
  651. * @returns the current particle system
  652. */
  653. removeEmitRateGradient(gradient) {
  654. this._removeFactorGradient(this._emitRateGradients, gradient);
  655. return this;
  656. }
  657. /**
  658. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  659. * @param gradient defines the gradient to use (between 0 and 1)
  660. * @param factor defines the start size value to affect to the specified gradient
  661. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  662. * @returns the current particle system
  663. */
  664. addStartSizeGradient(gradient, factor, factor2) {
  665. if (!this._startSizeGradients) {
  666. this._startSizeGradients = [];
  667. }
  668. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  669. return this;
  670. }
  671. /**
  672. * Remove a specific start size gradient
  673. * @param gradient defines the gradient to remove
  674. * @returns the current particle system
  675. */
  676. removeStartSizeGradient(gradient) {
  677. this._removeFactorGradient(this._startSizeGradients, gradient);
  678. return this;
  679. }
  680. _createRampGradientTexture() {
  681. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture || !this._scene) {
  682. return;
  683. }
  684. const data = new Uint8Array(this._rawTextureWidth * 4);
  685. const tmpColor = TmpColors.Color3[0];
  686. for (let x = 0; x < this._rawTextureWidth; x++) {
  687. const ratio = x / this._rawTextureWidth;
  688. GradientHelper.GetCurrentGradient(ratio, this._rampGradients, (currentGradient, nextGradient, scale) => {
  689. Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  690. data[x * 4] = tmpColor.r * 255;
  691. data[x * 4 + 1] = tmpColor.g * 255;
  692. data[x * 4 + 2] = tmpColor.b * 255;
  693. data[x * 4 + 3] = 255;
  694. });
  695. }
  696. this._rampGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1);
  697. }
  698. /**
  699. * Gets the current list of ramp gradients.
  700. * You must use addRampGradient and removeRampGradient to update this list
  701. * @returns the list of ramp gradients
  702. */
  703. getRampGradients() {
  704. return this._rampGradients;
  705. }
  706. /** Force the system to rebuild all gradients that need to be resync */
  707. forceRefreshGradients() {
  708. this._syncRampGradientTexture();
  709. }
  710. _syncRampGradientTexture() {
  711. if (!this._rampGradients) {
  712. return;
  713. }
  714. this._rampGradients.sort((a, b) => {
  715. if (a.gradient < b.gradient) {
  716. return -1;
  717. }
  718. else if (a.gradient > b.gradient) {
  719. return 1;
  720. }
  721. return 0;
  722. });
  723. if (this._rampGradientsTexture) {
  724. this._rampGradientsTexture.dispose();
  725. this._rampGradientsTexture = null;
  726. }
  727. this._createRampGradientTexture();
  728. }
  729. /**
  730. * Adds a new ramp gradient used to remap particle colors
  731. * @param gradient defines the gradient to use (between 0 and 1)
  732. * @param color defines the color to affect to the specified gradient
  733. * @returns the current particle system
  734. */
  735. addRampGradient(gradient, color) {
  736. if (!this._rampGradients) {
  737. this._rampGradients = [];
  738. }
  739. const rampGradient = new Color3Gradient(gradient, color);
  740. this._rampGradients.push(rampGradient);
  741. this._syncRampGradientTexture();
  742. return this;
  743. }
  744. /**
  745. * Remove a specific ramp gradient
  746. * @param gradient defines the gradient to remove
  747. * @returns the current particle system
  748. */
  749. removeRampGradient(gradient) {
  750. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  751. this._rampGradientsTexture = null;
  752. if (this._rampGradients && this._rampGradients.length > 0) {
  753. this._createRampGradientTexture();
  754. }
  755. return this;
  756. }
  757. /**
  758. * Adds a new color gradient
  759. * @param gradient defines the gradient to use (between 0 and 1)
  760. * @param color1 defines the color to affect to the specified gradient
  761. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  762. * @returns this particle system
  763. */
  764. addColorGradient(gradient, color1, color2) {
  765. if (!this._colorGradients) {
  766. this._colorGradients = [];
  767. }
  768. const colorGradient = new ColorGradient(gradient, color1, color2);
  769. this._colorGradients.push(colorGradient);
  770. this._colorGradients.sort((a, b) => {
  771. if (a.gradient < b.gradient) {
  772. return -1;
  773. }
  774. else if (a.gradient > b.gradient) {
  775. return 1;
  776. }
  777. return 0;
  778. });
  779. return this;
  780. }
  781. /**
  782. * Remove a specific color gradient
  783. * @param gradient defines the gradient to remove
  784. * @returns this particle system
  785. */
  786. removeColorGradient(gradient) {
  787. if (!this._colorGradients) {
  788. return this;
  789. }
  790. let index = 0;
  791. for (const colorGradient of this._colorGradients) {
  792. if (colorGradient.gradient === gradient) {
  793. this._colorGradients.splice(index, 1);
  794. break;
  795. }
  796. index++;
  797. }
  798. return this;
  799. }
  800. /**
  801. * Resets the draw wrappers cache
  802. */
  803. resetDrawCache() {
  804. for (const drawWrappers of this._drawWrappers) {
  805. if (drawWrappers) {
  806. for (const drawWrapper of drawWrappers) {
  807. drawWrapper?.dispose();
  808. }
  809. }
  810. }
  811. this._drawWrappers = [];
  812. }
  813. _fetchR(u, v, width, height, pixels) {
  814. u = Math.abs(u) * 0.5 + 0.5;
  815. v = Math.abs(v) * 0.5 + 0.5;
  816. const wrappedU = (u * width) % width | 0;
  817. const wrappedV = (v * height) % height | 0;
  818. const position = (wrappedU + wrappedV * width) * 4;
  819. return pixels[position] / 255;
  820. }
  821. _reset() {
  822. this._resetEffect();
  823. }
  824. _resetEffect() {
  825. if (this._vertexBuffer) {
  826. this._vertexBuffer.dispose();
  827. this._vertexBuffer = null;
  828. }
  829. if (this._spriteBuffer) {
  830. this._spriteBuffer.dispose();
  831. this._spriteBuffer = null;
  832. }
  833. if (this._vertexArrayObject) {
  834. this._engine.releaseVertexArrayObject(this._vertexArrayObject);
  835. this._vertexArrayObject = null;
  836. }
  837. this._createVertexBuffers();
  838. }
  839. _createVertexBuffers() {
  840. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  841. if (this._isAnimationSheetEnabled) {
  842. this._vertexBufferSize += 1;
  843. }
  844. if (!this._isBillboardBased ||
  845. this.billboardMode === 8 ||
  846. this.billboardMode === 9) {
  847. this._vertexBufferSize += 3;
  848. }
  849. if (this._useRampGradients) {
  850. this._vertexBufferSize += 4;
  851. }
  852. const engine = this._engine;
  853. const vertexSize = this._vertexBufferSize * (this._useInstancing ? 1 : 4);
  854. this._vertexData = new Float32Array(this._capacity * vertexSize);
  855. this._vertexBuffer = new Buffer(engine, this._vertexData, true, vertexSize);
  856. let dataOffset = 0;
  857. const positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  858. this._vertexBuffers[VertexBuffer.PositionKind] = positions;
  859. dataOffset += 3;
  860. const colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  861. this._vertexBuffers[VertexBuffer.ColorKind] = colors;
  862. dataOffset += 4;
  863. const options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  864. this._vertexBuffers["angle"] = options;
  865. dataOffset += 1;
  866. const size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  867. this._vertexBuffers["size"] = size;
  868. dataOffset += 2;
  869. if (this._isAnimationSheetEnabled) {
  870. const cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  871. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  872. dataOffset += 1;
  873. }
  874. if (!this._isBillboardBased ||
  875. this.billboardMode === 8 ||
  876. this.billboardMode === 9) {
  877. const directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  878. this._vertexBuffers["direction"] = directionBuffer;
  879. dataOffset += 3;
  880. }
  881. if (this._useRampGradients) {
  882. const rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  883. this._vertexBuffers["remapData"] = rampDataBuffer;
  884. dataOffset += 4;
  885. }
  886. let offsets;
  887. if (this._useInstancing) {
  888. const spriteData = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
  889. this._spriteBuffer = new Buffer(engine, spriteData, false, 2);
  890. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  891. }
  892. else {
  893. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  894. dataOffset += 2;
  895. }
  896. this._vertexBuffers["offset"] = offsets;
  897. this.resetDrawCache();
  898. }
  899. _createIndexBuffer() {
  900. if (this._useInstancing) {
  901. this._linesIndexBufferUseInstancing = this._engine.createIndexBuffer(new Uint32Array([0, 1, 1, 3, 3, 2, 2, 0, 0, 3]));
  902. return;
  903. }
  904. const indices = [];
  905. const indicesWireframe = [];
  906. let index = 0;
  907. for (let count = 0; count < this._capacity; count++) {
  908. indices.push(index);
  909. indices.push(index + 1);
  910. indices.push(index + 2);
  911. indices.push(index);
  912. indices.push(index + 2);
  913. indices.push(index + 3);
  914. indicesWireframe.push(index, index + 1, index + 1, index + 2, index + 2, index + 3, index + 3, index, index, index + 3);
  915. index += 4;
  916. }
  917. this._indexBuffer = this._engine.createIndexBuffer(indices);
  918. this._linesIndexBuffer = this._engine.createIndexBuffer(indicesWireframe);
  919. }
  920. /**
  921. * Gets the maximum number of particles active at the same time.
  922. * @returns The max number of active particles.
  923. */
  924. getCapacity() {
  925. return this._capacity;
  926. }
  927. /**
  928. * Gets whether there are still active particles in the system.
  929. * @returns True if it is alive, otherwise false.
  930. */
  931. isAlive() {
  932. return this._alive;
  933. }
  934. /**
  935. * Gets if the system has been started. (Note: this will still be true after stop is called)
  936. * @returns True if it has been started, otherwise false.
  937. */
  938. isStarted() {
  939. return this._started;
  940. }
  941. /** @internal */
  942. _preStart() {
  943. // Do nothing
  944. }
  945. /**
  946. * Starts the particle system and begins to emit
  947. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  948. */
  949. start(delay = this.startDelay) {
  950. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  951. // eslint-disable-next-line no-throw-literal
  952. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  953. }
  954. if (delay) {
  955. setTimeout(() => {
  956. this.start(0);
  957. }, delay);
  958. return;
  959. }
  960. this._started = true;
  961. this._stopped = false;
  962. this._actualFrame = 0;
  963. this._preStart();
  964. // Reset emit gradient so it acts the same on every start
  965. if (this._emitRateGradients) {
  966. if (this._emitRateGradients.length > 0) {
  967. this._currentEmitRateGradient = this._emitRateGradients[0];
  968. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  969. this._currentEmitRate2 = this._currentEmitRate1;
  970. }
  971. if (this._emitRateGradients.length > 1) {
  972. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  973. }
  974. }
  975. // Reset start size gradient so it acts the same on every start
  976. if (this._startSizeGradients) {
  977. if (this._startSizeGradients.length > 0) {
  978. this._currentStartSizeGradient = this._startSizeGradients[0];
  979. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  980. this._currentStartSize2 = this._currentStartSize1;
  981. }
  982. if (this._startSizeGradients.length > 1) {
  983. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  984. }
  985. }
  986. if (this.preWarmCycles) {
  987. if (this.emitter?.getClassName().indexOf("Mesh") !== -1) {
  988. this.emitter.computeWorldMatrix(true);
  989. }
  990. const noiseTextureAsProcedural = this.noiseTexture;
  991. if (noiseTextureAsProcedural && noiseTextureAsProcedural.onGeneratedObservable) {
  992. noiseTextureAsProcedural.onGeneratedObservable.addOnce(() => {
  993. setTimeout(() => {
  994. for (let index = 0; index < this.preWarmCycles; index++) {
  995. this.animate(true);
  996. noiseTextureAsProcedural.render();
  997. }
  998. });
  999. });
  1000. }
  1001. else {
  1002. for (let index = 0; index < this.preWarmCycles; index++) {
  1003. this.animate(true);
  1004. }
  1005. }
  1006. }
  1007. // Animations
  1008. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) {
  1009. this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  1010. }
  1011. }
  1012. /**
  1013. * Stops the particle system.
  1014. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. The default value is true.
  1015. */
  1016. stop(stopSubEmitters = true) {
  1017. if (this._stopped) {
  1018. return;
  1019. }
  1020. this.onStoppedObservable.notifyObservers(this);
  1021. this._stopped = true;
  1022. this._postStop(stopSubEmitters);
  1023. }
  1024. /** @internal */
  1025. _postStop(stopSubEmitters) {
  1026. // Do nothing
  1027. }
  1028. // Animation sheet
  1029. /**
  1030. * Remove all active particles
  1031. */
  1032. reset() {
  1033. this._stockParticles.length = 0;
  1034. this._particles.length = 0;
  1035. }
  1036. /**
  1037. * @internal (for internal use only)
  1038. */
  1039. _appendParticleVertex(index, particle, offsetX, offsetY) {
  1040. let offset = index * this._vertexBufferSize;
  1041. this._vertexData[offset++] = particle.position.x + this.worldOffset.x;
  1042. this._vertexData[offset++] = particle.position.y + this.worldOffset.y;
  1043. this._vertexData[offset++] = particle.position.z + this.worldOffset.z;
  1044. this._vertexData[offset++] = particle.color.r;
  1045. this._vertexData[offset++] = particle.color.g;
  1046. this._vertexData[offset++] = particle.color.b;
  1047. this._vertexData[offset++] = particle.color.a;
  1048. this._vertexData[offset++] = particle.angle;
  1049. this._vertexData[offset++] = particle.scale.x * particle.size;
  1050. this._vertexData[offset++] = particle.scale.y * particle.size;
  1051. if (this._isAnimationSheetEnabled) {
  1052. this._vertexData[offset++] = particle.cellIndex;
  1053. }
  1054. if (!this._isBillboardBased) {
  1055. if (particle._initialDirection) {
  1056. let initialDirection = particle._initialDirection;
  1057. if (this.isLocal) {
  1058. Vector3.TransformNormalToRef(initialDirection, this._emitterWorldMatrix, TmpVectors.Vector3[0]);
  1059. initialDirection = TmpVectors.Vector3[0];
  1060. }
  1061. if (initialDirection.x === 0 && initialDirection.z === 0) {
  1062. initialDirection.x = 0.001;
  1063. }
  1064. this._vertexData[offset++] = initialDirection.x;
  1065. this._vertexData[offset++] = initialDirection.y;
  1066. this._vertexData[offset++] = initialDirection.z;
  1067. }
  1068. else {
  1069. let direction = particle.direction;
  1070. if (this.isLocal) {
  1071. Vector3.TransformNormalToRef(direction, this._emitterWorldMatrix, TmpVectors.Vector3[0]);
  1072. direction = TmpVectors.Vector3[0];
  1073. }
  1074. if (direction.x === 0 && direction.z === 0) {
  1075. direction.x = 0.001;
  1076. }
  1077. this._vertexData[offset++] = direction.x;
  1078. this._vertexData[offset++] = direction.y;
  1079. this._vertexData[offset++] = direction.z;
  1080. }
  1081. }
  1082. else if (this.billboardMode === 8 || this.billboardMode === 9) {
  1083. this._vertexData[offset++] = particle.direction.x;
  1084. this._vertexData[offset++] = particle.direction.y;
  1085. this._vertexData[offset++] = particle.direction.z;
  1086. }
  1087. if (this._useRampGradients && particle.remapData) {
  1088. this._vertexData[offset++] = particle.remapData.x;
  1089. this._vertexData[offset++] = particle.remapData.y;
  1090. this._vertexData[offset++] = particle.remapData.z;
  1091. this._vertexData[offset++] = particle.remapData.w;
  1092. }
  1093. if (!this._useInstancing) {
  1094. if (this._isAnimationSheetEnabled) {
  1095. if (offsetX === 0) {
  1096. offsetX = this._epsilon;
  1097. }
  1098. else if (offsetX === 1) {
  1099. offsetX = 1 - this._epsilon;
  1100. }
  1101. if (offsetY === 0) {
  1102. offsetY = this._epsilon;
  1103. }
  1104. else if (offsetY === 1) {
  1105. offsetY = 1 - this._epsilon;
  1106. }
  1107. }
  1108. this._vertexData[offset++] = offsetX;
  1109. this._vertexData[offset++] = offsetY;
  1110. }
  1111. }
  1112. /** @internal */
  1113. _prepareParticle(particle) {
  1114. //Do nothing
  1115. }
  1116. _update(newParticles) {
  1117. // Update current
  1118. this._alive = this._particles.length > 0;
  1119. if (this.emitter.position) {
  1120. const emitterMesh = this.emitter;
  1121. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  1122. }
  1123. else {
  1124. const emitterPosition = this.emitter;
  1125. this._emitterWorldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  1126. }
  1127. this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix);
  1128. this.updateFunction(this._particles);
  1129. // Add new ones
  1130. let particle;
  1131. for (let index = 0; index < newParticles; index++) {
  1132. if (this._particles.length === this._capacity) {
  1133. break;
  1134. }
  1135. particle = this._createParticle();
  1136. this._particles.push(particle);
  1137. // Life time
  1138. if (this.targetStopDuration && this._lifeTimeGradients && this._lifeTimeGradients.length > 0) {
  1139. const ratio = Clamp(this._actualFrame / this.targetStopDuration);
  1140. GradientHelper.GetCurrentGradient(ratio, this._lifeTimeGradients, (currentGradient, nextGradient) => {
  1141. const factorGradient1 = currentGradient;
  1142. const factorGradient2 = nextGradient;
  1143. const lifeTime1 = factorGradient1.getFactor();
  1144. const lifeTime2 = factorGradient2.getFactor();
  1145. const gradient = (ratio - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  1146. particle.lifeTime = Lerp(lifeTime1, lifeTime2, gradient);
  1147. });
  1148. }
  1149. else {
  1150. particle.lifeTime = RandomRange(this.minLifeTime, this.maxLifeTime);
  1151. }
  1152. // Emitter
  1153. const emitPower = RandomRange(this.minEmitPower, this.maxEmitPower);
  1154. if (this.startPositionFunction) {
  1155. this.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal);
  1156. }
  1157. else {
  1158. this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal);
  1159. }
  1160. if (this.isLocal) {
  1161. if (!particle._localPosition) {
  1162. particle._localPosition = particle.position.clone();
  1163. }
  1164. else {
  1165. particle._localPosition.copyFrom(particle.position);
  1166. }
  1167. Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position);
  1168. }
  1169. if (this.startDirectionFunction) {
  1170. this.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal);
  1171. }
  1172. else {
  1173. this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal, this._emitterInverseWorldMatrix);
  1174. }
  1175. if (emitPower === 0) {
  1176. if (!particle._initialDirection) {
  1177. particle._initialDirection = particle.direction.clone();
  1178. }
  1179. else {
  1180. particle._initialDirection.copyFrom(particle.direction);
  1181. }
  1182. }
  1183. else {
  1184. particle._initialDirection = null;
  1185. }
  1186. particle.direction.scaleInPlace(emitPower);
  1187. // Size
  1188. if (!this._sizeGradients || this._sizeGradients.length === 0) {
  1189. particle.size = RandomRange(this.minSize, this.maxSize);
  1190. }
  1191. else {
  1192. particle._currentSizeGradient = this._sizeGradients[0];
  1193. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  1194. particle.size = particle._currentSize1;
  1195. if (this._sizeGradients.length > 1) {
  1196. particle._currentSize2 = this._sizeGradients[1].getFactor();
  1197. }
  1198. else {
  1199. particle._currentSize2 = particle._currentSize1;
  1200. }
  1201. }
  1202. // Size and scale
  1203. particle.scale.copyFromFloats(RandomRange(this.minScaleX, this.maxScaleX), RandomRange(this.minScaleY, this.maxScaleY));
  1204. // Adjust scale by start size
  1205. if (this._startSizeGradients && this._startSizeGradients[0] && this.targetStopDuration) {
  1206. const ratio = this._actualFrame / this.targetStopDuration;
  1207. GradientHelper.GetCurrentGradient(ratio, this._startSizeGradients, (currentGradient, nextGradient, scale) => {
  1208. if (currentGradient !== this._currentStartSizeGradient) {
  1209. this._currentStartSize1 = this._currentStartSize2;
  1210. this._currentStartSize2 = nextGradient.getFactor();
  1211. this._currentStartSizeGradient = currentGradient;
  1212. }
  1213. const value = Lerp(this._currentStartSize1, this._currentStartSize2, scale);
  1214. particle.scale.scaleInPlace(value);
  1215. });
  1216. }
  1217. // Angle
  1218. if (!this._angularSpeedGradients || this._angularSpeedGradients.length === 0) {
  1219. particle.angularSpeed = RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  1220. }
  1221. else {
  1222. particle._currentAngularSpeedGradient = this._angularSpeedGradients[0];
  1223. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  1224. particle._currentAngularSpeed1 = particle.angularSpeed;
  1225. if (this._angularSpeedGradients.length > 1) {
  1226. particle._currentAngularSpeed2 = this._angularSpeedGradients[1].getFactor();
  1227. }
  1228. else {
  1229. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  1230. }
  1231. }
  1232. particle.angle = RandomRange(this.minInitialRotation, this.maxInitialRotation);
  1233. // Velocity
  1234. if (this._velocityGradients && this._velocityGradients.length > 0) {
  1235. particle._currentVelocityGradient = this._velocityGradients[0];
  1236. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  1237. if (this._velocityGradients.length > 1) {
  1238. particle._currentVelocity2 = this._velocityGradients[1].getFactor();
  1239. }
  1240. else {
  1241. particle._currentVelocity2 = particle._currentVelocity1;
  1242. }
  1243. }
  1244. // Limit velocity
  1245. if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {
  1246. particle._currentLimitVelocityGradient = this._limitVelocityGradients[0];
  1247. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  1248. if (this._limitVelocityGradients.length > 1) {
  1249. particle._currentLimitVelocity2 = this._limitVelocityGradients[1].getFactor();
  1250. }
  1251. else {
  1252. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  1253. }
  1254. }
  1255. // Drag
  1256. if (this._dragGradients && this._dragGradients.length > 0) {
  1257. particle._currentDragGradient = this._dragGradients[0];
  1258. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  1259. if (this._dragGradients.length > 1) {
  1260. particle._currentDrag2 = this._dragGradients[1].getFactor();
  1261. }
  1262. else {
  1263. particle._currentDrag2 = particle._currentDrag1;
  1264. }
  1265. }
  1266. // Color
  1267. if (!this._colorGradients || this._colorGradients.length === 0) {
  1268. const step = RandomRange(0, 1.0);
  1269. Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  1270. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  1271. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  1272. }
  1273. else {
  1274. particle._currentColorGradient = this._colorGradients[0];
  1275. particle._currentColorGradient.getColorToRef(particle.color);
  1276. particle._currentColor1.copyFrom(particle.color);
  1277. if (this._colorGradients.length > 1) {
  1278. this._colorGradients[1].getColorToRef(particle._currentColor2);
  1279. }
  1280. else {
  1281. particle._currentColor2.copyFrom(particle.color);
  1282. }
  1283. }
  1284. // Sheet
  1285. if (this._isAnimationSheetEnabled) {
  1286. particle._initialStartSpriteCellID = this.startSpriteCellID;
  1287. particle._initialEndSpriteCellID = this.endSpriteCellID;
  1288. particle._initialSpriteCellLoop = this.spriteCellLoop;
  1289. }
  1290. // Inherited Velocity
  1291. particle.direction.addInPlace(this._inheritedVelocityOffset);
  1292. // Ramp
  1293. if (this._useRampGradients) {
  1294. particle.remapData = new Vector4(0, 1, 0, 1);
  1295. }
  1296. // Noise texture coordinates
  1297. if (this.noiseTexture) {
  1298. if (particle._randomNoiseCoordinates1) {
  1299. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  1300. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  1301. }
  1302. else {
  1303. particle._randomNoiseCoordinates1 = new Vector3(Math.random(), Math.random(), Math.random());
  1304. particle._randomNoiseCoordinates2 = new Vector3(Math.random(), Math.random(), Math.random());
  1305. }
  1306. }
  1307. // Update the position of the attached sub-emitters to match their attached particle
  1308. particle._inheritParticleInfoToSubEmitters();
  1309. }
  1310. }
  1311. /**
  1312. * @internal
  1313. */
  1314. static _GetAttributeNamesOrOptions(isAnimationSheetEnabled = false, isBillboardBased = false, useRampGradients = false) {
  1315. const attributeNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "angle", "offset", "size"];
  1316. if (isAnimationSheetEnabled) {
  1317. attributeNamesOrOptions.push("cellIndex");
  1318. }
  1319. if (!isBillboardBased) {
  1320. attributeNamesOrOptions.push("direction");
  1321. }
  1322. if (useRampGradients) {
  1323. attributeNamesOrOptions.push("remapData");
  1324. }
  1325. return attributeNamesOrOptions;
  1326. }
  1327. /**
  1328. * @internal
  1329. */
  1330. static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false, applyFog = false) {
  1331. const effectCreationOption = ["invView", "view", "projection", "textureMask", "translationPivot", "eyePosition"];
  1332. addClipPlaneUniforms(effectCreationOption);
  1333. if (isAnimationSheetEnabled) {
  1334. effectCreationOption.push("particlesInfos");
  1335. }
  1336. if (useLogarithmicDepth) {
  1337. effectCreationOption.push("logarithmicDepthConstant");
  1338. }
  1339. if (applyFog) {
  1340. effectCreationOption.push("vFogInfos");
  1341. effectCreationOption.push("vFogColor");
  1342. }
  1343. return effectCreationOption;
  1344. }
  1345. /**
  1346. * Fill the defines array according to the current settings of the particle system
  1347. * @param defines Array to be updated
  1348. * @param blendMode blend mode to take into account when updating the array
  1349. */
  1350. fillDefines(defines, blendMode) {
  1351. if (this._scene) {
  1352. prepareStringDefinesForClipPlanes(this, this._scene, defines);
  1353. if (this.applyFog && this._scene.fogEnabled && this._scene.fogMode !== 0) {
  1354. defines.push("#define FOG");
  1355. }
  1356. }
  1357. if (this._isAnimationSheetEnabled) {
  1358. defines.push("#define ANIMATESHEET");
  1359. }
  1360. if (this.useLogarithmicDepth) {
  1361. defines.push("#define LOGARITHMICDEPTH");
  1362. }
  1363. if (blendMode === BaseParticleSystem.BLENDMODE_MULTIPLY) {
  1364. defines.push("#define BLENDMULTIPLYMODE");
  1365. }
  1366. if (this._useRampGradients) {
  1367. defines.push("#define RAMPGRADIENT");
  1368. }
  1369. if (this._isBillboardBased) {
  1370. defines.push("#define BILLBOARD");
  1371. switch (this.billboardMode) {
  1372. case 2:
  1373. defines.push("#define BILLBOARDY");
  1374. break;
  1375. case 8:
  1376. case 9:
  1377. defines.push("#define BILLBOARDSTRETCHED");
  1378. if (this.billboardMode === 9) {
  1379. defines.push("#define BILLBOARDSTRETCHED_LOCAL");
  1380. }
  1381. break;
  1382. case 7:
  1383. defines.push("#define BILLBOARDMODE_ALL");
  1384. break;
  1385. default:
  1386. break;
  1387. }
  1388. }
  1389. if (this._imageProcessingConfiguration) {
  1390. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  1391. defines.push(this._imageProcessingConfigurationDefines.toString());
  1392. }
  1393. }
  1394. /**
  1395. * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system
  1396. * @param uniforms Uniforms array to fill
  1397. * @param attributes Attributes array to fill
  1398. * @param samplers Samplers array to fill
  1399. */
  1400. fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) {
  1401. attributes.push(...ThinParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased &&
  1402. this.billboardMode !== 8 &&
  1403. this.billboardMode !== 9, this._useRampGradients));
  1404. uniforms.push(...ThinParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth, this.applyFog));
  1405. samplers.push("diffuseSampler", "rampSampler");
  1406. if (this._imageProcessingConfiguration) {
  1407. PrepareUniformsForImageProcessing(uniforms, this._imageProcessingConfigurationDefines);
  1408. PrepareSamplersForImageProcessing(samplers, this._imageProcessingConfigurationDefines);
  1409. }
  1410. }
  1411. /**
  1412. * @internal
  1413. */
  1414. _getWrapper(blendMode) {
  1415. const customWrapper = this._getCustomDrawWrapper(blendMode);
  1416. if (customWrapper?.effect) {
  1417. return customWrapper;
  1418. }
  1419. const defines = [];
  1420. this.fillDefines(defines, blendMode);
  1421. // Effect
  1422. const currentRenderPassId = this._engine._features.supportRenderPasses ? this._engine.currentRenderPassId : 0;
  1423. let drawWrappers = this._drawWrappers[currentRenderPassId];
  1424. if (!drawWrappers) {
  1425. drawWrappers = this._drawWrappers[currentRenderPassId] = [];
  1426. }
  1427. let drawWrapper = drawWrappers[blendMode];
  1428. if (!drawWrapper) {
  1429. drawWrapper = new DrawWrapper(this._engine);
  1430. if (drawWrapper.drawContext) {
  1431. drawWrapper.drawContext.useInstancing = this._useInstancing;
  1432. }
  1433. drawWrappers[blendMode] = drawWrapper;
  1434. }
  1435. const join = defines.join("\n");
  1436. if (drawWrapper.defines !== join) {
  1437. const attributesNamesOrOptions = [];
  1438. const effectCreationOption = [];
  1439. const samplers = [];
  1440. this.fillUniformsAttributesAndSamplerNames(effectCreationOption, attributesNamesOrOptions, samplers);
  1441. drawWrapper.setEffect(this._engine.createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join), join);
  1442. }
  1443. return drawWrapper;
  1444. }
  1445. /**
  1446. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  1447. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  1448. */
  1449. animate(preWarmOnly = false) {
  1450. if (!this._started) {
  1451. return;
  1452. }
  1453. if (!preWarmOnly && this._scene) {
  1454. // Check
  1455. if (!this.isReady()) {
  1456. return;
  1457. }
  1458. if (this._currentRenderId === this._scene.getFrameId()) {
  1459. return;
  1460. }
  1461. this._currentRenderId = this._scene.getFrameId();
  1462. }
  1463. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene?.getAnimationRatio() || 1);
  1464. // Determine the number of particles we need to create
  1465. let newParticles;
  1466. if (this.manualEmitCount > -1) {
  1467. newParticles = this.manualEmitCount;
  1468. this._newPartsExcess = 0;
  1469. this.manualEmitCount = 0;
  1470. }
  1471. else {
  1472. let rate = this.emitRate;
  1473. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  1474. const ratio = this._actualFrame / this.targetStopDuration;
  1475. GradientHelper.GetCurrentGradient(ratio, this._emitRateGradients, (currentGradient, nextGradient, scale) => {
  1476. if (currentGradient !== this._currentEmitRateGradient) {
  1477. this._currentEmitRate1 = this._currentEmitRate2;
  1478. this._currentEmitRate2 = nextGradient.getFactor();
  1479. this._currentEmitRateGradient = currentGradient;
  1480. }
  1481. rate = Lerp(this._currentEmitRate1, this._currentEmitRate2, scale);
  1482. });
  1483. }
  1484. newParticles = (rate * this._scaledUpdateSpeed) >> 0;
  1485. this._newPartsExcess += rate * this._scaledUpdateSpeed - newParticles;
  1486. }
  1487. if (this._newPartsExcess > 1.0) {
  1488. newParticles += this._newPartsExcess >> 0;
  1489. this._newPartsExcess -= this._newPartsExcess >> 0;
  1490. }
  1491. this._alive = false;
  1492. if (!this._stopped) {
  1493. this._actualFrame += this._scaledUpdateSpeed;
  1494. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  1495. this.stop();
  1496. }
  1497. }
  1498. else {
  1499. newParticles = 0;
  1500. }
  1501. this._update(newParticles);
  1502. // Stopped?
  1503. if (this._stopped) {
  1504. if (!this._alive) {
  1505. this._started = false;
  1506. if (this.onAnimationEnd) {
  1507. this.onAnimationEnd();
  1508. }
  1509. if (this.disposeOnStop && this._scene) {
  1510. this._scene._toBeDisposed.push(this);
  1511. }
  1512. }
  1513. }
  1514. if (!preWarmOnly) {
  1515. // Update VBO
  1516. let offset = 0;
  1517. for (let index = 0; index < this._particles.length; index++) {
  1518. const particle = this._particles[index];
  1519. this._appendParticleVertices(offset, particle);
  1520. offset += this._useInstancing ? 1 : 4;
  1521. }
  1522. if (this._vertexBuffer) {
  1523. this._vertexBuffer.updateDirectly(this._vertexData, 0, this._particles.length);
  1524. }
  1525. }
  1526. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  1527. this.stop();
  1528. }
  1529. }
  1530. _appendParticleVertices(offset, particle) {
  1531. this._appendParticleVertex(offset++, particle, 0, 0);
  1532. if (!this._useInstancing) {
  1533. this._appendParticleVertex(offset++, particle, 1, 0);
  1534. this._appendParticleVertex(offset++, particle, 1, 1);
  1535. this._appendParticleVertex(offset++, particle, 0, 1);
  1536. }
  1537. }
  1538. /**
  1539. * Rebuilds the particle system.
  1540. */
  1541. rebuild() {
  1542. if (this._engine.getCaps().vertexArrayObject) {
  1543. this._vertexArrayObject = null;
  1544. }
  1545. this._createIndexBuffer();
  1546. this._spriteBuffer?._rebuild();
  1547. this._createVertexBuffers();
  1548. this.resetDrawCache();
  1549. }
  1550. /**
  1551. * Is this system ready to be used/rendered
  1552. * @returns true if the system is ready
  1553. */
  1554. isReady() {
  1555. if (!this.emitter || (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady()) || !this.particleTexture || !this.particleTexture.isReady()) {
  1556. return false;
  1557. }
  1558. if (this.blendMode !== BaseParticleSystem.BLENDMODE_MULTIPLYADD) {
  1559. if (!this._getWrapper(this.blendMode).effect.isReady()) {
  1560. return false;
  1561. }
  1562. }
  1563. else {
  1564. if (!this._getWrapper(BaseParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) {
  1565. return false;
  1566. }
  1567. if (!this._getWrapper(BaseParticleSystem.BLENDMODE_ADD).effect.isReady()) {
  1568. return false;
  1569. }
  1570. }
  1571. return true;
  1572. }
  1573. _render(blendMode) {
  1574. const drawWrapper = this._getWrapper(blendMode);
  1575. const effect = drawWrapper.effect;
  1576. const engine = this._engine;
  1577. // Render
  1578. engine.enableEffect(drawWrapper);
  1579. const viewMatrix = this.defaultViewMatrix ?? this._scene.getViewMatrix();
  1580. effect.setTexture("diffuseSampler", this.particleTexture);
  1581. effect.setMatrix("view", viewMatrix);
  1582. effect.setMatrix("projection", this.defaultProjectionMatrix ?? this._scene.getProjectionMatrix());
  1583. if (this._isAnimationSheetEnabled && this.particleTexture) {
  1584. const baseSize = this.particleTexture.getBaseSize();
  1585. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, this.spriteCellWidth / baseSize.width);
  1586. }
  1587. effect.setVector2("translationPivot", this.translationPivot);
  1588. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  1589. if (this._isBillboardBased && this._scene) {
  1590. const camera = this._scene.activeCamera;
  1591. effect.setVector3("eyePosition", camera.globalPosition);
  1592. }
  1593. if (this._rampGradientsTexture) {
  1594. if (!this._rampGradients || !this._rampGradients.length) {
  1595. this._rampGradientsTexture.dispose();
  1596. this._rampGradientsTexture = null;
  1597. }
  1598. effect.setTexture("rampSampler", this._rampGradientsTexture);
  1599. }
  1600. const defines = effect.defines;
  1601. if (this._scene) {
  1602. bindClipPlane(effect, this, this._scene);
  1603. if (this.applyFog) {
  1604. BindFogParameters(this._scene, undefined, effect);
  1605. }
  1606. }
  1607. if (defines.indexOf("#define BILLBOARDMODE_ALL") >= 0) {
  1608. viewMatrix.invertToRef(TmpVectors.Matrix[0]);
  1609. effect.setMatrix("invView", TmpVectors.Matrix[0]);
  1610. }
  1611. if (this._vertexArrayObject !== undefined) {
  1612. if (this._scene?.forceWireframe) {
  1613. engine.bindBuffers(this._vertexBuffers, this._linesIndexBufferUseInstancing, effect);
  1614. }
  1615. else {
  1616. if (!this._vertexArrayObject) {
  1617. this._vertexArrayObject = this._engine.recordVertexArrayObject(this._vertexBuffers, null, effect);
  1618. }
  1619. this._engine.bindVertexArrayObject(this._vertexArrayObject, this._scene?.forceWireframe ? this._linesIndexBufferUseInstancing : this._indexBuffer);
  1620. }
  1621. }
  1622. else {
  1623. if (!this._indexBuffer) {
  1624. // Use instancing mode
  1625. engine.bindBuffers(this._vertexBuffers, this._scene?.forceWireframe ? this._linesIndexBufferUseInstancing : null, effect);
  1626. }
  1627. else {
  1628. engine.bindBuffers(this._vertexBuffers, this._scene?.forceWireframe ? this._linesIndexBuffer : this._indexBuffer, effect);
  1629. }
  1630. }
  1631. // Log. depth
  1632. if (this.useLogarithmicDepth && this._scene) {
  1633. BindLogDepth(defines, effect, this._scene);
  1634. }
  1635. // image processing
  1636. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  1637. this._imageProcessingConfiguration.bind(effect);
  1638. }
  1639. // Draw order
  1640. switch (blendMode) {
  1641. case BaseParticleSystem.BLENDMODE_ADD:
  1642. engine.setAlphaMode(1);
  1643. break;
  1644. case BaseParticleSystem.BLENDMODE_ONEONE:
  1645. engine.setAlphaMode(6);
  1646. break;
  1647. case BaseParticleSystem.BLENDMODE_STANDARD:
  1648. engine.setAlphaMode(2);
  1649. break;
  1650. case BaseParticleSystem.BLENDMODE_MULTIPLY:
  1651. engine.setAlphaMode(4);
  1652. break;
  1653. }
  1654. if (this._onBeforeDrawParticlesObservable) {
  1655. this._onBeforeDrawParticlesObservable.notifyObservers(effect);
  1656. }
  1657. if (this._useInstancing) {
  1658. if (this._scene?.forceWireframe) {
  1659. engine.drawElementsType(6, 0, 10, this._particles.length);
  1660. }
  1661. else {
  1662. engine.drawArraysType(7, 0, 4, this._particles.length);
  1663. }
  1664. }
  1665. else {
  1666. if (this._scene?.forceWireframe) {
  1667. engine.drawElementsType(1, 0, this._particles.length * 10);
  1668. }
  1669. else {
  1670. engine.drawElementsType(0, 0, this._particles.length * 6);
  1671. }
  1672. }
  1673. return this._particles.length;
  1674. }
  1675. /**
  1676. * Renders the particle system in its current state.
  1677. * @returns the current number of particles
  1678. */
  1679. render() {
  1680. // Check
  1681. if (!this.isReady() || !this._particles.length) {
  1682. return 0;
  1683. }
  1684. const engine = this._engine;
  1685. if (engine.setState) {
  1686. engine.setState(false);
  1687. if (this.forceDepthWrite) {
  1688. engine.setDepthWrite(true);
  1689. }
  1690. }
  1691. let outparticles = 0;
  1692. if (this.blendMode === BaseParticleSystem.BLENDMODE_MULTIPLYADD) {
  1693. outparticles = this._render(BaseParticleSystem.BLENDMODE_MULTIPLY) + this._render(BaseParticleSystem.BLENDMODE_ADD);
  1694. }
  1695. else {
  1696. outparticles = this._render(this.blendMode);
  1697. }
  1698. this._engine.unbindInstanceAttributes();
  1699. this._engine.setAlphaMode(0);
  1700. return outparticles;
  1701. }
  1702. /** @internal */
  1703. _onDispose(disposeAttachedSubEmitters = false, disposeEndSubEmitters = false) {
  1704. // Do Nothing
  1705. }
  1706. /**
  1707. * Disposes the particle system and free the associated resources
  1708. * @param disposeTexture defines if the particle texture must be disposed as well (true by default)
  1709. * @param disposeAttachedSubEmitters defines if the attached sub-emitters must be disposed as well (false by default)
  1710. * @param disposeEndSubEmitters defines if the end type sub-emitters must be disposed as well (false by default)
  1711. */
  1712. dispose(disposeTexture = true, disposeAttachedSubEmitters = false, disposeEndSubEmitters = false) {
  1713. this.resetDrawCache();
  1714. if (this._vertexBuffer) {
  1715. this._vertexBuffer.dispose();
  1716. this._vertexBuffer = null;
  1717. }
  1718. if (this._spriteBuffer) {
  1719. this._spriteBuffer.dispose();
  1720. this._spriteBuffer = null;
  1721. }
  1722. if (this._indexBuffer) {
  1723. this._engine._releaseBuffer(this._indexBuffer);
  1724. this._indexBuffer = null;
  1725. }
  1726. if (this._linesIndexBuffer) {
  1727. this._engine._releaseBuffer(this._linesIndexBuffer);
  1728. this._linesIndexBuffer = null;
  1729. }
  1730. if (this._linesIndexBufferUseInstancing) {
  1731. this._engine._releaseBuffer(this._linesIndexBufferUseInstancing);
  1732. this._linesIndexBufferUseInstancing = null;
  1733. }
  1734. if (this._vertexArrayObject) {
  1735. this._engine.releaseVertexArrayObject(this._vertexArrayObject);
  1736. this._vertexArrayObject = null;
  1737. }
  1738. if (disposeTexture && this.particleTexture) {
  1739. this.particleTexture.dispose();
  1740. this.particleTexture = null;
  1741. }
  1742. if (disposeTexture && this.noiseTexture) {
  1743. this.noiseTexture.dispose();
  1744. this.noiseTexture = null;
  1745. }
  1746. if (this._rampGradientsTexture) {
  1747. this._rampGradientsTexture.dispose();
  1748. this._rampGradientsTexture = null;
  1749. }
  1750. this._onDispose(disposeAttachedSubEmitters, disposeEndSubEmitters);
  1751. if (this._onBeforeDrawParticlesObservable) {
  1752. this._onBeforeDrawParticlesObservable.clear();
  1753. }
  1754. // Remove from scene
  1755. if (this._scene) {
  1756. const index = this._scene.particleSystems.indexOf(this);
  1757. if (index > -1) {
  1758. this._scene.particleSystems.splice(index, 1);
  1759. }
  1760. this._scene._activeParticleSystems.dispose();
  1761. }
  1762. // Callback
  1763. this.onDisposeObservable.notifyObservers(this);
  1764. this.onDisposeObservable.clear();
  1765. this.onStoppedObservable.clear();
  1766. this.reset();
  1767. }
  1768. }
  1769. //# sourceMappingURL=thinParticleSystem.js.map