solidParticleSystem.ts 64 KB

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