solidParticleSystem.ts 60 KB

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