solidParticleSystem.ts 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. import { Nullable, IndicesArray, FloatArray } from "../types";
  2. import { Color4, Vector3, Matrix, Tmp, Quaternion, Axis } from "../Maths/math";
  3. import { VertexBuffer } from "../Meshes/buffer";
  4. import { VertexData } from "../Meshes/mesh.vertexData";
  5. import { Mesh } from "../Meshes/mesh";
  6. import { MeshBuilder } from "../Meshes/meshBuilder";
  7. import { EngineStore } from "../Engines/engineStore";
  8. import { Scene, IDisposable } from "../scene";
  9. import { DepthSortedParticle, SolidParticle, ModelShape } from "./solidParticle";
  10. import { TargetCamera } from "../Cameras/targetCamera";
  11. import { BoundingInfo } from "../Culling/boundingInfo";
  12. const depthSortFunction = (p1: DepthSortedParticle, p2: DepthSortedParticle) => p2.sqDistance - p1.sqDistance;
  13. /**
  14. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  15. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  16. * The SPS is also a particle system. It provides some methods to manage the particles.
  17. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  18. *
  19. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  20. */
  21. export class SolidParticleSystem implements IDisposable {
  22. /**
  23. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  24. * Example : var p = SPS.particles[i];
  25. */
  26. public particles: SolidParticle[] = new Array<SolidParticle>();
  27. /**
  28. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  29. */
  30. public nbParticles: number = 0;
  31. /**
  32. * If the particles must ever face the camera (default false). Useful for planar particles.
  33. */
  34. public billboard: boolean = false;
  35. /**
  36. * Recompute normals when adding a shape
  37. */
  38. public recomputeNormals: boolean = true;
  39. /**
  40. * This a counter ofr your own usage. It's not set by any SPS functions.
  41. */
  42. public counter: number = 0;
  43. /**
  44. * The SPS name. This name is also given to the underlying mesh.
  45. */
  46. public name: string;
  47. /**
  48. * The SPS mesh. It's a standard BJS Mesh, so all the methods from the Mesh class are avalaible.
  49. */
  50. public mesh: Mesh;
  51. /**
  52. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54. */
  55. public vars: any = {};
  56. /**
  57. * This array is populated when the SPS is set as 'pickable'.
  58. * Each key of this array is a `faceId` value that you can get from a pickResult object.
  59. * Each element of this array is an object `{idx: int, faceId: int}`.
  60. * `idx` is the picked particle index in the `SPS.particles` array
  61. * `faceId` is the picked face index counted within this particle.
  62. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#pickable-particles
  63. */
  64. public pickedParticles: { idx: number; faceId: number }[];
  65. /**
  66. * This array is populated when `enableDepthSort` is set to true.
  67. * Each element of this array is an instance of the class DepthSortedParticle.
  68. */
  69. public depthSortedParticles: DepthSortedParticle[];
  70. /**
  71. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  72. * @hidden
  73. */
  74. public _bSphereOnly: boolean = false;
  75. /**
  76. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  77. * @hidden
  78. */
  79. public _bSphereRadiusFactor: number = 1.0;
  80. private _scene: Scene;
  81. private _positions: number[] = new Array<number>();
  82. private _indices: number[] = new Array<number>();
  83. private _normals: number[] = new Array<number>();
  84. private _colors: number[] = new Array<number>();
  85. private _uvs: number[] = new Array<number>();
  86. private _indices32: IndicesArray; // used as depth sorted array if depth sort enabled, else used as typed indices
  87. private _positions32: Float32Array; // updated positions for the VBO
  88. private _normals32: Float32Array; // updated normals for the VBO
  89. private _fixedNormal32: Float32Array; // initial normal references
  90. private _colors32: Float32Array;
  91. private _uvs32: Float32Array;
  92. private _index: number = 0; // indices index
  93. private _updatable: boolean = true;
  94. private _pickable: boolean = false;
  95. private _isVisibilityBoxLocked = false;
  96. private _alwaysVisible: boolean = false;
  97. private _depthSort: boolean = false;
  98. private _shapeCounter: number = 0;
  99. private _copy: SolidParticle = new SolidParticle(0, 0, 0, null, 0, 0, this);
  100. private _color: Color4 = new Color4(0, 0, 0, 0);
  101. private _computeParticleColor: boolean = true;
  102. private _computeParticleTexture: boolean = true;
  103. private _computeParticleRotation: boolean = true;
  104. private _computeParticleVertex: boolean = false;
  105. private _computeBoundingBox: boolean = false;
  106. private _depthSortParticles: boolean = true;
  107. private _camera: TargetCamera;
  108. private _mustUnrotateFixedNormals = false;
  109. private _particlesIntersect: boolean = false;
  110. private _needs32Bits: boolean = false;
  111. /**
  112. * Creates a SPS (Solid Particle System) object.
  113. * @param name (String) is the SPS name, this will be the underlying mesh name.
  114. * @param scene (Scene) is the scene in which the SPS is added.
  115. * @param options defines the options of the sps e.g.
  116. * * updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  117. * * isPickable (optional boolean, default false) : if the solid particles must be pickable.
  118. * * enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  119. * * particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  120. * * boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  121. * * bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  122. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  123. */
  124. constructor(name: string, scene: Scene, options?: { updatable?: boolean; isPickable?: boolean; enableDepthSort?: boolean; particleIntersection?: boolean; boundingSphereOnly?: boolean; bSphereRadiusFactor?: number }) {
  125. this.name = name;
  126. this._scene = scene || EngineStore.LastCreatedScene;
  127. this._camera = <TargetCamera>scene.activeCamera;
  128. this._pickable = options ? <boolean>options.isPickable : false;
  129. this._depthSort = options ? <boolean>options.enableDepthSort : false;
  130. this._particlesIntersect = options ? <boolean>options.particleIntersection : false;
  131. this._bSphereOnly = options ? <boolean>options.boundingSphereOnly : false;
  132. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  133. if (options && options.updatable !== undefined) {
  134. this._updatable = options.updatable;
  135. } else {
  136. this._updatable = true;
  137. }
  138. if (this._pickable) {
  139. this.pickedParticles = [];
  140. }
  141. if (this._depthSort) {
  142. this.depthSortedParticles = [];
  143. }
  144. }
  145. /**
  146. * Builds the SPS underlying mesh. Returns a standard Mesh.
  147. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  148. * @returns the created mesh
  149. */
  150. public buildMesh(): Mesh {
  151. if (this.nbParticles === 0) {
  152. var triangle = MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  153. this.addShape(triangle, 1);
  154. triangle.dispose();
  155. }
  156. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  157. this._positions32 = new Float32Array(this._positions);
  158. this._uvs32 = new Float32Array(this._uvs);
  159. this._colors32 = new Float32Array(this._colors);
  160. if (this.recomputeNormals) {
  161. VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  162. }
  163. this._normals32 = new Float32Array(this._normals);
  164. this._fixedNormal32 = new Float32Array(this._normals);
  165. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  166. this._unrotateFixedNormals();
  167. }
  168. var vertexData = new VertexData();
  169. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  170. vertexData.set(this._positions32, VertexBuffer.PositionKind);
  171. vertexData.set(this._normals32, VertexBuffer.NormalKind);
  172. if (this._uvs32.length > 0) {
  173. vertexData.set(this._uvs32, VertexBuffer.UVKind);
  174. }
  175. if (this._colors32.length > 0) {
  176. vertexData.set(this._colors32, VertexBuffer.ColorKind);
  177. }
  178. var mesh = new Mesh(this.name, this._scene);
  179. vertexData.applyToMesh(mesh, this._updatable);
  180. this.mesh = mesh;
  181. this.mesh.isPickable = this._pickable;
  182. // free memory
  183. if (!this._depthSort) {
  184. (<any>this._indices) = null;
  185. }
  186. (<any>this._positions) = null;
  187. (<any>this._normals) = null;
  188. (<any>this._uvs) = null;
  189. (<any>this._colors) = null;
  190. if (!this._updatable) {
  191. this.particles.length = 0;
  192. }
  193. return mesh;
  194. }
  195. /**
  196. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  197. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  198. * Thus the particles generated from `digest()` have their property `position` set yet.
  199. * @param mesh ( Mesh ) is the mesh to be digested
  200. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  201. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  202. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  203. * @returns the current SPS
  204. */
  205. public digest(mesh: Mesh, options?: { facetNb?: number; number?: number; delta?: number }): SolidParticleSystem {
  206. var size: number = (options && options.facetNb) || 1;
  207. var number: number = (options && options.number) || 0;
  208. var delta: number = (options && options.delta) || 0;
  209. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  210. var meshInd = <IndicesArray>mesh.getIndices();
  211. var meshUV = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  212. var meshCol = <FloatArray>mesh.getVerticesData(VertexBuffer.ColorKind);
  213. var meshNor = <FloatArray>mesh.getVerticesData(VertexBuffer.NormalKind);
  214. var f: number = 0; // facet counter
  215. var totalFacets: number = meshInd.length / 3; // a facet is a triangle, so 3 indices
  216. // compute size from number
  217. if (number) {
  218. number = (number > totalFacets) ? totalFacets : number;
  219. size = Math.round(totalFacets / number);
  220. delta = 0;
  221. } else {
  222. size = (size > totalFacets) ? totalFacets : size;
  223. }
  224. var facetPos: number[] = []; // submesh positions
  225. var facetInd: number[] = []; // submesh indices
  226. var facetUV: number[] = []; // submesh UV
  227. var facetCol: number[] = []; // submesh colors
  228. var barycenter: Vector3 = Vector3.Zero();
  229. var sizeO: number = size;
  230. while (f < totalFacets) {
  231. size = sizeO + Math.floor((1 + delta) * Math.random());
  232. if (f > totalFacets - size) {
  233. size = totalFacets - f;
  234. }
  235. // reset temp arrays
  236. facetPos.length = 0;
  237. facetInd.length = 0;
  238. facetUV.length = 0;
  239. facetCol.length = 0;
  240. // iterate over "size" facets
  241. var fi: number = 0;
  242. for (var j = f * 3; j < (f + size) * 3; j++) {
  243. facetInd.push(fi);
  244. var i: number = meshInd[j];
  245. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  246. if (meshUV) {
  247. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  248. }
  249. if (meshCol) {
  250. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  251. }
  252. fi++;
  253. }
  254. // create a model shape for each single particle
  255. var idx: number = this.nbParticles;
  256. var shape: Vector3[] = this._posToShape(facetPos);
  257. var shapeUV: number[] = this._uvsToShapeUV(facetUV);
  258. // compute the barycenter of the shape
  259. var v: number;
  260. for (v = 0; v < shape.length; v++) {
  261. barycenter.addInPlace(shape[v]);
  262. }
  263. barycenter.scaleInPlace(1 / shape.length);
  264. // shift the shape from its barycenter to the origin
  265. for (v = 0; v < shape.length; v++) {
  266. shape[v].subtractInPlace(barycenter);
  267. }
  268. var bInfo;
  269. if (this._particlesIntersect) {
  270. bInfo = new BoundingInfo(barycenter, barycenter);
  271. }
  272. var modelShape = new ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  273. // add the particle in the SPS
  274. var currentPos = this._positions.length;
  275. var currentInd = this._indices.length;
  276. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  277. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  278. // initialize the particle position
  279. this.particles[this.nbParticles].position.addInPlace(barycenter);
  280. this._index += shape.length;
  281. idx++;
  282. this.nbParticles++;
  283. this._shapeCounter++;
  284. f += size;
  285. }
  286. return this;
  287. }
  288. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  289. private _unrotateFixedNormals() {
  290. var index = 0;
  291. var idx = 0;
  292. const tmpNormal = Tmp.Vector3[0];
  293. const quaternion = Tmp.Quaternion[0];
  294. const invertedRotMatrix = Tmp.Matrix[0];
  295. for (var p = 0; p < this.particles.length; p++) {
  296. const particle = this.particles[p];
  297. const shape = particle._model._shape;
  298. // computing the inverse of the rotation matrix from the quaternion
  299. // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion
  300. if (particle.rotationQuaternion) {
  301. particle.rotationQuaternion.conjugateToRef(quaternion);
  302. }
  303. else {
  304. const rotation = particle.rotation;
  305. Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  306. quaternion.conjugateInPlace();
  307. }
  308. quaternion.toRotationMatrix(invertedRotMatrix);
  309. for (var pt = 0; pt < shape.length; pt++) {
  310. idx = index + pt * 3;
  311. Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);
  312. tmpNormal.toArray(this._fixedNormal32, idx);
  313. }
  314. index = idx + 3;
  315. }
  316. }
  317. //reset copy
  318. private _resetCopy() {
  319. const copy = this._copy;
  320. copy.position.setAll(0);
  321. copy.rotation.setAll(0);
  322. copy.rotationQuaternion = null;
  323. copy.scaling.setAll(1);
  324. copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);
  325. copy.color = null;
  326. copy.translateFromPivot = false;
  327. }
  328. // _meshBuilder : inserts the shape model in the global SPS mesh
  329. private _meshBuilder(p: number, shape: Vector3[], positions: number[], meshInd: IndicesArray, indices: number[], meshUV: number[] | Float32Array, uvs: number[], meshCol: number[] | Float32Array, colors: number[], meshNor: number[] | Float32Array, normals: number[], idx: number, idxInShape: number, options: any): SolidParticle {
  330. var i;
  331. var u = 0;
  332. var c = 0;
  333. var n = 0;
  334. this._resetCopy();
  335. const copy = this._copy;
  336. if (options && options.positionFunction) { // call to custom positionFunction
  337. options.positionFunction(copy, idx, idxInShape);
  338. this._mustUnrotateFixedNormals = true;
  339. }
  340. const rotMatrix = Tmp.Matrix[0];
  341. const tmpVertex = Tmp.Vector3[0];
  342. const tmpRotated = Tmp.Vector3[1];
  343. const pivotBackTranslation = Tmp.Vector3[2];
  344. const scaledPivot = Tmp.Vector3[3];
  345. copy.getRotationMatrix(rotMatrix);
  346. copy.pivot.multiplyToRef(copy.scaling, scaledPivot);
  347. if (copy.translateFromPivot) {
  348. pivotBackTranslation.setAll(0.0);
  349. }
  350. else {
  351. pivotBackTranslation.copyFrom(scaledPivot);
  352. }
  353. for (i = 0; i < shape.length; i++) {
  354. tmpVertex.copyFrom(shape[i]);
  355. if (options && options.vertexFunction) {
  356. options.vertexFunction(copy, tmpVertex, i);
  357. }
  358. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  359. Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  360. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);
  361. positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);
  362. if (meshUV) {
  363. const copyUvs = copy.uvs;
  364. uvs.push((copyUvs.z - copyUvs.x) * meshUV[u] + copyUvs.x, (copyUvs.w - copyUvs.y) * meshUV[u + 1] + copyUvs.y);
  365. u += 2;
  366. }
  367. if (copy.color) {
  368. this._color = copy.color;
  369. } else {
  370. const color = this._color;
  371. if (meshCol && meshCol[c] !== undefined) {
  372. color.r = meshCol[c];
  373. color.g = meshCol[c + 1];
  374. color.b = meshCol[c + 2];
  375. color.a = meshCol[c + 3];
  376. } else {
  377. color.r = 1.0;
  378. color.g = 1.0;
  379. color.b = 1.0;
  380. color.a = 1.0;
  381. }
  382. }
  383. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  384. c += 4;
  385. if (!this.recomputeNormals && meshNor) {
  386. tmpVertex.x = meshNor[n];
  387. tmpVertex.y = meshNor[n + 1];
  388. tmpVertex.z = meshNor[n + 2];
  389. Vector3.TransformNormalToRef(tmpVertex, rotMatrix, tmpVertex);
  390. normals.push(tmpVertex.x, tmpVertex.y, tmpVertex.z);
  391. n += 3;
  392. }
  393. }
  394. for (i = 0; i < meshInd.length; i++) {
  395. var current_ind = p + meshInd[i];
  396. indices.push(current_ind);
  397. if (current_ind > 65535) {
  398. this._needs32Bits = true;
  399. }
  400. }
  401. if (this._pickable) {
  402. var nbfaces = meshInd.length / 3;
  403. for (i = 0; i < nbfaces; i++) {
  404. this.pickedParticles.push({ idx: idx, faceId: i });
  405. }
  406. }
  407. if (this._depthSort) {
  408. this.depthSortedParticles.push(new DepthSortedParticle());
  409. }
  410. return copy;
  411. }
  412. // returns a shape array from positions array
  413. private _posToShape(positions: number[] | Float32Array): Vector3[] {
  414. var shape = [];
  415. for (var i = 0; i < positions.length; i += 3) {
  416. shape.push(Vector3.FromArray(positions, i));
  417. }
  418. return shape;
  419. }
  420. // returns a shapeUV array from a Vector4 uvs
  421. private _uvsToShapeUV(uvs: number[] | Float32Array): number[] {
  422. var shapeUV = [];
  423. if (uvs) {
  424. for (var i = 0; i < uvs.length; i++) {
  425. shapeUV.push(uvs[i]);
  426. }
  427. }
  428. return shapeUV;
  429. }
  430. // adds a new particle object in the particles array
  431. private _addParticle(idx: number, idxpos: number, idxind: number, model: ModelShape, shapeId: number, idxInShape: number, bInfo: Nullable<BoundingInfo> = null): SolidParticle {
  432. var sp = new SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  433. this.particles.push(sp);
  434. return sp;
  435. }
  436. /**
  437. * Adds some particles to the SPS from the model shape. Returns the shape id.
  438. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  439. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  440. * @param nb (positive integer) the number of particles to be created from this model
  441. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  442. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  443. * @returns the number of shapes in the system
  444. */
  445. public addShape(mesh: Mesh, nb: number, options?: { positionFunction?: any; vertexFunction?: any }): number {
  446. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  447. var meshInd = <IndicesArray>mesh.getIndices();
  448. var meshUV = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  449. var meshCol = <FloatArray>mesh.getVerticesData(VertexBuffer.ColorKind);
  450. var meshNor = <FloatArray>mesh.getVerticesData(VertexBuffer.NormalKind);
  451. var bbInfo;
  452. if (this._particlesIntersect) {
  453. bbInfo = mesh.getBoundingInfo();
  454. }
  455. var shape = this._posToShape(meshPos);
  456. var shapeUV = this._uvsToShapeUV(meshUV);
  457. var posfunc = options ? options.positionFunction : null;
  458. var vtxfunc = options ? options.vertexFunction : null;
  459. var modelShape = new ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  460. // particles
  461. var sp;
  462. var currentCopy;
  463. var idx = this.nbParticles;
  464. for (var i = 0; i < nb; i++) {
  465. var currentPos = this._positions.length;
  466. var currentInd = this._indices.length;
  467. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  468. if (this._updatable) {
  469. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  470. sp.position.copyFrom(currentCopy.position);
  471. sp.rotation.copyFrom(currentCopy.rotation);
  472. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  473. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  474. }
  475. if (currentCopy.color && sp.color) {
  476. sp.color.copyFrom(currentCopy.color);
  477. }
  478. sp.scaling.copyFrom(currentCopy.scaling);
  479. sp.uvs.copyFrom(currentCopy.uvs);
  480. }
  481. this._index += shape.length;
  482. idx++;
  483. }
  484. this.nbParticles += nb;
  485. this._shapeCounter++;
  486. return this._shapeCounter - 1;
  487. }
  488. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  489. private _rebuildParticle(particle: SolidParticle): void {
  490. this._resetCopy();
  491. const copy = this._copy;
  492. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  493. particle._model._positionFunction(copy, particle.idx, particle.idxInShape);
  494. }
  495. const rotMatrix = Tmp.Matrix[0];
  496. const tmpVertex = Tmp.Vector3[0];
  497. const tmpRotated = Tmp.Vector3[1];
  498. const pivotBackTranslation = Tmp.Vector3[2];
  499. const scaledPivot = Tmp.Vector3[3];
  500. copy.getRotationMatrix(rotMatrix);
  501. particle.pivot.multiplyToRef(particle.scaling, scaledPivot);
  502. if (copy.translateFromPivot) {
  503. pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  504. }
  505. else {
  506. pivotBackTranslation.copyFrom(scaledPivot);
  507. }
  508. const shape = particle._model._shape;
  509. for (var pt = 0; pt < shape.length; pt++) {
  510. tmpVertex.copyFrom(shape[pt]);
  511. if (particle._model._vertexFunction) {
  512. particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction
  513. }
  514. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  515. Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  516. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position).toArray(this._positions32, particle._pos + pt * 3);
  517. }
  518. particle.position.setAll(0.0);
  519. particle.rotation.setAll(0.0);
  520. particle.rotationQuaternion = null;
  521. particle.scaling.setAll(1.0);
  522. particle.uvs.setAll(0.0);
  523. particle.pivot.setAll(0.0);
  524. particle.translateFromPivot = false;
  525. particle.parentId = null;
  526. }
  527. /**
  528. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  529. * @returns the SPS.
  530. */
  531. public rebuildMesh(): SolidParticleSystem {
  532. for (var p = 0; p < this.particles.length; p++) {
  533. this._rebuildParticle(this.particles[p]);
  534. }
  535. this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false);
  536. return this;
  537. }
  538. /**
  539. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  540. * This method calls `updateParticle()` for each particle of the SPS.
  541. * For an animated SPS, it is usually called within the render loop.
  542. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  543. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  544. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  545. * @returns the SPS.
  546. */
  547. public setParticles(start: number = 0, end: number = this.nbParticles - 1, update: boolean = true): SolidParticleSystem {
  548. if (!this._updatable) {
  549. return this;
  550. }
  551. // custom beforeUpdate
  552. this.beforeUpdateParticles(start, end, update);
  553. const rotMatrix = Tmp.Matrix[0];
  554. const invertedMatrix = Tmp.Matrix[1];
  555. const mesh = this.mesh;
  556. const colors32 = this._colors32;
  557. const positions32 = this._positions32;
  558. const normals32 = this._normals32;
  559. const uvs32 = this._uvs32;
  560. const indices32 = this._indices32;
  561. const indices = this._indices;
  562. const fixedNormal32 = this._fixedNormal32;
  563. const tempVectors = Tmp.Vector3;
  564. const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  565. const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  566. const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  567. const minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  568. const maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  569. const camInvertedPosition = tempVectors[10].setAll(0);
  570. // cases when the World Matrix is to be computed first
  571. if (this.billboard || this._depthSort) {
  572. this.mesh.computeWorldMatrix(true);
  573. this.mesh._worldMatrix.invertToRef(invertedMatrix);
  574. }
  575. // if the particles will always face the camera
  576. if (this.billboard) {
  577. // compute the camera position and un-rotate it by the current mesh rotation
  578. const tmpVertex = tempVectors[0];
  579. this._camera.getDirectionToRef(Axis.Z, tmpVertex);
  580. Vector3.TransformNormalToRef(tmpVertex, invertedMatrix, camAxisZ);
  581. camAxisZ.normalize();
  582. // same for camera up vector extracted from the cam view matrix
  583. var view = this._camera.getViewMatrix(true);
  584. Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);
  585. Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);
  586. camAxisY.normalize();
  587. camAxisX.normalize();
  588. }
  589. // if depthSort, compute the camera global position in the mesh local system
  590. if (this._depthSort) {
  591. Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera
  592. }
  593. Matrix.IdentityToRef(rotMatrix);
  594. var idx = 0; // current position index in the global array positions32
  595. var index = 0; // position start index in the global array positions32 of the current particle
  596. var colidx = 0; // current color index in the global array colors32
  597. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  598. var uvidx = 0; // current uv index in the global array uvs32
  599. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  600. var pt = 0; // current index in the particle model shape
  601. if (this.mesh.isFacetDataEnabled) {
  602. this._computeBoundingBox = true;
  603. }
  604. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  605. if (this._computeBoundingBox) {
  606. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  607. const boundingInfo = this.mesh._boundingInfo;
  608. if (boundingInfo) {
  609. minimum.copyFrom(boundingInfo.minimum);
  610. maximum.copyFrom(boundingInfo.maximum);
  611. }
  612. }
  613. }
  614. // particle loop
  615. index = this.particles[start]._pos;
  616. const vpos = (index / 3) | 0;
  617. colorIndex = vpos * 4;
  618. uvIndex = vpos * 2;
  619. for (var p = start; p <= end; p++) {
  620. const particle = this.particles[p];
  621. // call to custom user function to update the particle properties
  622. this.updateParticle(particle);
  623. const shape = particle._model._shape;
  624. const shapeUV = particle._model._shapeUV;
  625. const particleRotationMatrix = particle._rotationMatrix;
  626. const particlePosition = particle.position;
  627. const particleRotation = particle.rotation;
  628. const particleScaling = particle.scaling;
  629. const particleGlobalPosition = particle._globalPosition;
  630. // camera-particle distance for depth sorting
  631. if (this._depthSort && this._depthSortParticles) {
  632. var dsp = this.depthSortedParticles[p];
  633. dsp.ind = particle._ind;
  634. dsp.indicesLength = particle._model._indicesLength;
  635. dsp.sqDistance = Vector3.DistanceSquared(particle.position, camInvertedPosition);
  636. }
  637. // skip the computations for inactive or already invisible particles
  638. if (!particle.alive || (particle._stillInvisible && !particle.isVisible)) {
  639. // increment indexes for the next particle
  640. pt = shape.length;
  641. index += pt * 3;
  642. colorIndex += pt * 4;
  643. uvIndex += pt * 2;
  644. continue;
  645. }
  646. if (particle.isVisible) {
  647. particle._stillInvisible = false; // un-mark permanent invisibility
  648. const scaledPivot = tempVectors[12];
  649. particle.pivot.multiplyToRef(particleScaling, scaledPivot);
  650. // particle rotation matrix
  651. if (this.billboard) {
  652. particleRotation.x = 0.0;
  653. particleRotation.y = 0.0;
  654. }
  655. if (this._computeParticleRotation || this.billboard) {
  656. particle.getRotationMatrix(rotMatrix);
  657. }
  658. const particleHasParent = (particle.parentId !== null);
  659. if (particleHasParent) {
  660. const parent = this.particles[particle.parentId!];
  661. const parentRotationMatrix = parent._rotationMatrix;
  662. const parentGlobalPosition = parent._globalPosition;
  663. const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  664. const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  665. const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  666. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  667. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  668. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  669. if (this._computeParticleRotation || this.billboard) {
  670. const rotMatrixValues = rotMatrix.m;
  671. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  672. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  673. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  674. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  675. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  676. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  677. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  678. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  679. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  680. }
  681. }
  682. else {
  683. particleGlobalPosition.x = particlePosition.x;
  684. particleGlobalPosition.y = particlePosition.y;
  685. particleGlobalPosition.z = particlePosition.z;
  686. if (this._computeParticleRotation || this.billboard) {
  687. const rotMatrixValues = rotMatrix.m;
  688. particleRotationMatrix[0] = rotMatrixValues[0];
  689. particleRotationMatrix[1] = rotMatrixValues[1];
  690. particleRotationMatrix[2] = rotMatrixValues[2];
  691. particleRotationMatrix[3] = rotMatrixValues[4];
  692. particleRotationMatrix[4] = rotMatrixValues[5];
  693. particleRotationMatrix[5] = rotMatrixValues[6];
  694. particleRotationMatrix[6] = rotMatrixValues[8];
  695. particleRotationMatrix[7] = rotMatrixValues[9];
  696. particleRotationMatrix[8] = rotMatrixValues[10];
  697. }
  698. }
  699. const pivotBackTranslation = tempVectors[11];
  700. if (particle.translateFromPivot) {
  701. pivotBackTranslation.setAll(0.0);
  702. }
  703. else {
  704. pivotBackTranslation.copyFrom(scaledPivot);
  705. }
  706. // particle vertex loop
  707. for (pt = 0; pt < shape.length; pt++) {
  708. idx = index + pt * 3;
  709. colidx = colorIndex + pt * 4;
  710. uvidx = uvIndex + pt * 2;
  711. const tmpVertex = tempVectors[0];
  712. tmpVertex.copyFrom(shape[pt]);
  713. if (this._computeParticleVertex) {
  714. this.updateParticleVertex(particle, tmpVertex, pt);
  715. }
  716. // positions
  717. const vertexX = tmpVertex.x * particleScaling.x - scaledPivot.x;
  718. const vertexY = tmpVertex.y * particleScaling.y - scaledPivot.y;
  719. const vertexZ = tmpVertex.z * particleScaling.z - scaledPivot.z;
  720. let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  721. let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  722. let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  723. rotatedX += pivotBackTranslation.x;
  724. rotatedY += pivotBackTranslation.y;
  725. rotatedZ += pivotBackTranslation.z;
  726. const px = positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  727. const py = positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  728. const pz = positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  729. if (this._computeBoundingBox) {
  730. minimum.minimizeInPlaceFromFloats(px, py, pz);
  731. maximum.maximizeInPlaceFromFloats(px, py, pz);
  732. }
  733. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  734. if (!this._computeParticleVertex) {
  735. const normalx = fixedNormal32[idx];
  736. const normaly = fixedNormal32[idx + 1];
  737. const normalz = fixedNormal32[idx + 2];
  738. const rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];
  739. const rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];
  740. const rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];
  741. normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;
  742. normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;
  743. normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;
  744. }
  745. if (this._computeParticleColor && particle.color) {
  746. const color = particle.color;
  747. const colors32 = this._colors32;
  748. colors32[colidx] = color.r;
  749. colors32[colidx + 1] = color.g;
  750. colors32[colidx + 2] = color.b;
  751. colors32[colidx + 3] = color.a;
  752. }
  753. if (this._computeParticleTexture) {
  754. const uvs = particle.uvs;
  755. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  756. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  757. }
  758. }
  759. }
  760. // particle just set invisible : scaled to zero and positioned at the origin
  761. else {
  762. particle._stillInvisible = true; // mark the particle as invisible
  763. for (pt = 0; pt < shape.length; pt++) {
  764. idx = index + pt * 3;
  765. colidx = colorIndex + pt * 4;
  766. uvidx = uvIndex + pt * 2;
  767. positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;
  768. normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;
  769. if (this._computeParticleColor && particle.color) {
  770. const color = particle.color;
  771. colors32[colidx] = color.r;
  772. colors32[colidx + 1] = color.g;
  773. colors32[colidx + 2] = color.b;
  774. colors32[colidx + 3] = color.a;
  775. }
  776. if (this._computeParticleTexture) {
  777. const uvs = particle.uvs;
  778. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  779. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  780. }
  781. }
  782. }
  783. // if the particle intersections must be computed : update the bbInfo
  784. if (this._particlesIntersect) {
  785. const bInfo = particle._boundingInfo;
  786. const bBox = bInfo.boundingBox;
  787. const bSphere = bInfo.boundingSphere;
  788. const modelBoundingInfo = particle._modelBoundingInfo;
  789. if (!this._bSphereOnly) {
  790. // place, scale and rotate the particle bbox within the SPS local system, then update it
  791. const modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;
  792. const tempMin = tempVectors[1];
  793. const tempMax = tempVectors[2];
  794. tempMin.setAll(Number.MAX_VALUE);
  795. tempMax.setAll(-Number.MAX_VALUE);
  796. for (var b = 0; b < 8; b++) {
  797. const scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;
  798. const scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;
  799. const scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;
  800. const rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];
  801. const rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];
  802. const rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];
  803. const x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  804. const y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  805. const z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  806. tempMin.minimizeInPlaceFromFloats(x, y, z);
  807. tempMax.maximizeInPlaceFromFloats(x, y, z);
  808. }
  809. bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);
  810. }
  811. // place and scale the particle bouding sphere in the SPS local system, then update it
  812. const minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);
  813. const maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);
  814. const bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5).addInPlace(particleGlobalPosition);
  815. const halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);
  816. const bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);
  817. const bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);
  818. bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);
  819. }
  820. // increment indexes for the next particle
  821. index = idx + 3;
  822. colorIndex = colidx + 4;
  823. uvIndex = uvidx + 2;
  824. }
  825. // if the VBO must be updated
  826. if (update) {
  827. if (this._computeParticleColor) {
  828. mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false);
  829. }
  830. if (this._computeParticleTexture) {
  831. mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false);
  832. }
  833. mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false);
  834. if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {
  835. if (this._computeParticleVertex || mesh.isFacetDataEnabled) {
  836. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  837. var params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;
  838. VertexData.ComputeNormals(positions32, indices32, normals32, params);
  839. for (var i = 0; i < normals32.length; i++) {
  840. fixedNormal32[i] = normals32[i];
  841. }
  842. }
  843. if (!mesh.areNormalsFrozen) {
  844. mesh.updateVerticesData(VertexBuffer.NormalKind, normals32, false, false);
  845. }
  846. }
  847. if (this._depthSort && this._depthSortParticles) {
  848. const depthSortedParticles = this.depthSortedParticles;
  849. depthSortedParticles.sort(depthSortFunction);
  850. const dspl = depthSortedParticles.length;
  851. let sid = 0;
  852. for (let sorted = 0; sorted < dspl; sorted++) {
  853. const lind = depthSortedParticles[sorted].indicesLength;
  854. const sind = depthSortedParticles[sorted].ind;
  855. for (var i = 0; i < lind; i++) {
  856. indices32[sid] = indices[sind + i];
  857. sid++;
  858. }
  859. }
  860. mesh.updateIndices(indices32);
  861. }
  862. }
  863. if (this._computeBoundingBox) {
  864. if (mesh._boundingInfo) {
  865. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  866. }
  867. else {
  868. mesh._boundingInfo = new BoundingInfo(minimum, maximum, mesh._worldMatrix);
  869. }
  870. }
  871. this.afterUpdateParticles(start, end, update);
  872. return this;
  873. }
  874. /**
  875. * Disposes the SPS.
  876. */
  877. public dispose(): void {
  878. this.mesh.dispose();
  879. this.vars = null;
  880. // drop references to internal big arrays for the GC
  881. (<any>this._positions) = null;
  882. (<any>this._indices) = null;
  883. (<any>this._normals) = null;
  884. (<any>this._uvs) = null;
  885. (<any>this._colors) = null;
  886. (<any>this._indices32) = null;
  887. (<any>this._positions32) = null;
  888. (<any>this._normals32) = null;
  889. (<any>this._fixedNormal32) = null;
  890. (<any>this._uvs32) = null;
  891. (<any>this._colors32) = null;
  892. (<any>this.pickedParticles) = null;
  893. }
  894. /**
  895. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  896. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  897. * @returns the SPS.
  898. */
  899. public refreshVisibleSize(): SolidParticleSystem {
  900. if (!this._isVisibilityBoxLocked) {
  901. this.mesh.refreshBoundingInfo();
  902. }
  903. return this;
  904. }
  905. /**
  906. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  907. * @param size the size (float) of the visibility box
  908. * note : this doesn't lock the SPS mesh bounding box.
  909. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  910. */
  911. public setVisibilityBox(size: number): void {
  912. var vis = size / 2;
  913. this.mesh._boundingInfo = new BoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));
  914. }
  915. /**
  916. * Gets whether the SPS as always visible or not
  917. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  918. */
  919. public get isAlwaysVisible(): boolean {
  920. return this._alwaysVisible;
  921. }
  922. /**
  923. * Sets the SPS as always visible or not
  924. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  925. */
  926. public set isAlwaysVisible(val: boolean) {
  927. this._alwaysVisible = val;
  928. this.mesh.alwaysSelectAsActiveMesh = val;
  929. }
  930. /**
  931. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  932. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  933. */
  934. public set isVisibilityBoxLocked(val: boolean) {
  935. this._isVisibilityBoxLocked = val;
  936. let boundingInfo = this.mesh.getBoundingInfo();
  937. boundingInfo.isLocked = val;
  938. }
  939. /**
  940. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  941. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  942. */
  943. public get isVisibilityBoxLocked(): boolean {
  944. return this._isVisibilityBoxLocked;
  945. }
  946. /**
  947. * Tells to `setParticles()` to compute the particle rotations or not.
  948. * Default value : true. The SPS is faster when it's set to false.
  949. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  950. */
  951. public set computeParticleRotation(val: boolean) {
  952. this._computeParticleRotation = val;
  953. }
  954. /**
  955. * Tells to `setParticles()` to compute the particle colors or not.
  956. * Default value : true. The SPS is faster when it's set to false.
  957. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  958. */
  959. public set computeParticleColor(val: boolean) {
  960. this._computeParticleColor = val;
  961. }
  962. public set computeParticleTexture(val: boolean) {
  963. this._computeParticleTexture = val;
  964. }
  965. /**
  966. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  967. * Default value : false. The SPS is faster when it's set to false.
  968. * Note : the particle custom vertex positions aren't stored values.
  969. */
  970. public set computeParticleVertex(val: boolean) {
  971. this._computeParticleVertex = val;
  972. }
  973. /**
  974. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  975. */
  976. public set computeBoundingBox(val: boolean) {
  977. this._computeBoundingBox = val;
  978. }
  979. /**
  980. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  981. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  982. * Default : `true`
  983. */
  984. public set depthSortParticles(val: boolean) {
  985. this._depthSortParticles = val;
  986. }
  987. /**
  988. * Gets if `setParticles()` computes the particle rotations or not.
  989. * Default value : true. The SPS is faster when it's set to false.
  990. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  991. */
  992. public get computeParticleRotation(): boolean {
  993. return this._computeParticleRotation;
  994. }
  995. /**
  996. * Gets if `setParticles()` computes the particle colors or not.
  997. * Default value : true. The SPS is faster when it's set to false.
  998. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  999. */
  1000. public get computeParticleColor(): boolean {
  1001. return this._computeParticleColor;
  1002. }
  1003. /**
  1004. * Gets if `setParticles()` computes the particle textures or not.
  1005. * Default value : true. The SPS is faster when it's set to false.
  1006. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  1007. */
  1008. public get computeParticleTexture(): boolean {
  1009. return this._computeParticleTexture;
  1010. }
  1011. /**
  1012. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  1013. * Default value : false. The SPS is faster when it's set to false.
  1014. * Note : the particle custom vertex positions aren't stored values.
  1015. */
  1016. public get computeParticleVertex(): boolean {
  1017. return this._computeParticleVertex;
  1018. }
  1019. /**
  1020. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  1021. */
  1022. public get computeBoundingBox(): boolean {
  1023. return this._computeBoundingBox;
  1024. }
  1025. /**
  1026. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  1027. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  1028. * Default : `true`
  1029. */
  1030. public get depthSortParticles(): boolean {
  1031. return this._depthSortParticles;
  1032. }
  1033. // =======================================================================
  1034. // Particle behavior logic
  1035. // these following methods may be overwritten by the user to fit his needs
  1036. /**
  1037. * This function does nothing. It may be overwritten to set all the particle first values.
  1038. * The SPS doesn't call this function, you may have to call it by your own.
  1039. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  1040. */
  1041. public initParticles(): void {
  1042. }
  1043. /**
  1044. * This function does nothing. It may be overwritten to recycle a particle.
  1045. * The SPS doesn't call this function, you may have to call it by your own.
  1046. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  1047. * @param particle The particle to recycle
  1048. * @returns the recycled particle
  1049. */
  1050. public recycleParticle(particle: SolidParticle): SolidParticle {
  1051. return particle;
  1052. }
  1053. /**
  1054. * Updates a particle : this function should be overwritten by the user.
  1055. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  1056. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  1057. * @example : just set a particle position or velocity and recycle conditions
  1058. * @param particle The particle to update
  1059. * @returns the updated particle
  1060. */
  1061. public updateParticle(particle: SolidParticle): SolidParticle {
  1062. return particle;
  1063. }
  1064. /**
  1065. * Updates a vertex of a particle : it can be overwritten by the user.
  1066. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  1067. * @param particle the current particle
  1068. * @param vertex the current index of the current particle
  1069. * @param pt the index of the current vertex in the particle shape
  1070. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  1071. * @example : just set a vertex particle position
  1072. * @returns the updated vertex
  1073. */
  1074. public updateParticleVertex(particle: SolidParticle, vertex: Vector3, pt: number): Vector3 {
  1075. return vertex;
  1076. }
  1077. /**
  1078. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  1079. * This does nothing and may be overwritten by the user.
  1080. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1081. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1082. * @param update the boolean update value actually passed to setParticles()
  1083. */
  1084. public beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  1085. }
  1086. /**
  1087. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  1088. * This will be passed three parameters.
  1089. * This does nothing and may be overwritten by the user.
  1090. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1091. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1092. * @param update the boolean update value actually passed to setParticles()
  1093. */
  1094. public afterUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  1095. }
  1096. }